Programs & Examples On #Garmin

Garmin is a company which develops and sells products relating to Global Positioning System (GPS) systems.

ALTER COLUMN in sqlite

SQLite supports a limited subset of ALTER TABLE. The ALTER TABLE command in SQLite allows the user to rename a table or to add a new column to an existing table. It is not possible to rename a column, remove a column, or add or remove constraints from a table. But you can alter table column datatype or other property by the following steps.

  1. BEGIN TRANSACTION;
  2. CREATE TEMPORARY TABLE t1_backup(a,b);
  3. INSERT INTO t1_backup SELECT a,b FROM t1;
  4. DROP TABLE t1;
  5. CREATE TABLE t1(a,b);
  6. INSERT INTO t1 SELECT a,b FROM t1_backup;
  7. DROP TABLE t1_backup;
  8. COMMIT

For more detail you can refer the link.

How to generate the "create table" sql statement for an existing table in postgreSQL

This is the variation that works for me:

pg_dump -U user_viktor -h localhost unit_test_database -t floorplanpreferences_table --schema-only

In addition, if you're using schemas, you'll of course need to specify that as well:

pg_dump -U user_viktor -h localhost unit_test_database -t "949766e0-e81e-11e3-b325-1cc1de32fcb6".floorplanpreferences_table --schema-only

You will get an output that you can use to create the table again, just run that output in psql.

HttpServlet cannot be resolved to a type .... is this a bug in eclipse?

You have to set the runtime for your web project to the Tomcat installation you are using; you can do it in the "Targeted runtimes" section of the project configuration.

In this way you will allow Eclipse to add Tomcat's Java EE Web Profile jars to the build path.

Remember that the HttpServlet class isn't in a JRE, but at least in an Enterprise Web Profile (e.g. a servlet container runtime /lib folder).

Convert YYYYMMDD to DATE

In your case it should be:

Select convert(datetime,convert(varchar(10),GRADUATION_DATE,120)) as
'GRADUATION_DATE' from mydb

Video 100% width and height

use this css for height

height: calc(100vh) !important;

This will make the video to have 100% vertical height available.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

The same problem when I export the library httclient-4.3.5 in Android Studio 0.8.6 I need include this:

packagingOptions{
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/LICENSE.txt'
}

The library zip content the next jar:

commons-codec-1.6.jar
commons-logging-1.1.3.jar
fluent-hc-4.3.5.jar
httpclient-4.3.5.jar
httpclient-cache-4.3.5.jar
httpcore-4.3.2.jar
httpmime-4.3.5.jar

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Why does "pip install" inside Python raise a SyntaxError?

you need to type it in cmd not in the IDLE. becuse IDLE is not an command prompt if you want to install something from IDLE type this

>>>from pip.__main__ import _main as main
>>>main(#args splitted by space in list example:['install', 'requests'])

this is calling pip like pip <commands> in terminal. The commands will be seperated by spaces that you are doing there to.

How do I use raw_input in Python 3

Timmerman's solution works great when running the code, but if you don't want to get Undefined name errors when using pyflakes or a similar linter you could use the following instead:

try:
    import __builtin__
    input = getattr(__builtin__, 'raw_input')
except (ImportError, AttributeError):
    pass

How do I make CMake output into a 'bin' dir?

Regardless of whether I define this in the main CMakeLists.txt or in the individual ones, it still assumes I want all the libs and bins off the main path, which is the least useful assumption of all.

Conversion hex string into ascii in bash command line

You can use something like this.

$ cat test_file.txt
54 68 69 73 20 69 73 20 74 65 78 74 20 64 61 74 61 2e 0a 4f 6e 65 20 6d 6f 72 65 20 6c 69 6e 65 20 6f 66 20 74 65 73 74 20 64 61 74 61 2e

$ for c in `cat test_file.txt`; do printf "\x$c"; done;
This is text data.
One more line of test data.

Delete certain lines in a txt file via a batch file

You can accomplish the same solution as @paxdiablo's using just findstr by itself. There's no need to pipe multiple commands together:

findstr /V "ERROR REFERENCE" infile.txt > outfile.txt

Details of how this works:

  • /v finds lines that don't match the search string (same switch @paxdiablo uses)
  • if the search string is in quotes, it performs an OR search, using each word (separator is a space)
  • findstr can take an input file, you don't need to feed it the text using the "type" command
  • "> outfile.txt" will send the results to the file outfile.txt instead printing them to your console. (Note that it will overwrite the file if it exists. Use ">> outfile.txt" instead if you want to append.)
  • You might also consider adding the /i switch to do a case-insensitive match.

C#: HttpClient with POST parameters

As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )

The querystring (get) parameters included in your url probably will not do anything.

Try this:

string url = "http://myserver/method";    
string content = "param1=1&param2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);

HTH,

bovako

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Update: It looks like the manual has been updated and the example I was referring to has been removed. See the edit to @flainez's answer above.

Original: Using @objc is the right way to do it even if you're not interoperating with Obj-C. It ensures that your protocol is being applied to a class and not an enum or struct. See "Checking for Protocol Conformance" in the manual.

How to split a single column values to multiple column values?

Here is how I did this on a SQLite database:

SELECT SUBSTR(name, 1,INSTR(name, " ")-1) as Firstname,
SUBSTR(name, INSTR(name," ")+1, LENGTH(name)) as Lastname
FROM YourTable;

Hope it helps.

Relative imports in Python 3

I ran into this issue. A hack workaround is importing via an if/else block like follows:

#!/usr/bin/env python3
#myothermodule

if __name__ == '__main__':
    from mymodule import as_int
else:
    from .mymodule import as_int


# Exported function
def add(a, b):
    return as_int(a) + as_int(b)

# Test function for module  
def _test():
    assert add('1', '1') == 2

if __name__ == '__main__':
    _test()

Generating an MD5 checksum of a file

You can use hashlib.md5()

Note that sometimes you won't be able to fit the whole file in memory. In that case, you'll have to read chunks of 4096 bytes sequentially and feed them to the md5 method:

import hashlib
def md5(fname):
    hash_md5 = hashlib.md5()
    with open(fname, "rb") as f:
        for chunk in iter(lambda: f.read(4096), b""):
            hash_md5.update(chunk)
    return hash_md5.hexdigest()

Note: hash_md5.hexdigest() will return the hex string representation for the digest, if you just need the packed bytes use return hash_md5.digest(), so you don't have to convert back.

How to read a single char from the console in Java (as the user types it)?

I have written a Java class RawConsoleInput that uses JNA to call operating system functions of Windows and Unix/Linux.

  • On Windows it uses _kbhit() and _getwch() from msvcrt.dll.
  • On Unix it uses tcsetattr() to switch the console to non-canonical mode, System.in.available() to check whether data is available and System.in.read() to read bytes from the console. A CharsetDecoder is used to convert bytes to characters.

It supports non-blocking input and mixing raw mode and normal line mode input.

Running Java gives "Error: could not open `C:\Program Files\Java\jre6\lib\amd64\jvm.cfg'"

If this was working before, it means the PATH isn't correct anymore.

That can happen when the PATH becomes too long and gets truncated.
All posts (like this one) suggest updating the PATH, which you can test first in a separate DOS session, by setting a minimal path and see if java works again there.


Finally the OP Highland Mark concludes:

Finally fixed by uninstalling java, removing all references to it from the registry, and then re-installing.

scary ;)

How do I set browser width and height in Selenium WebDriver?

Try something like this:

IWebDriver _driver = new FirefoxDriver();
_driver.Manage().Window.Position = new Point(0, 0);
_driver.Manage().Window.Size = new Size(1024, 768);

Not sure if it'll resize after being launched though, so maybe it's not what you want

How to correctly display .csv files within Excel 2013?

Another possible problem is that the csv file contains a byte order mark "FEFF". The byte order mark is intended to detect whether the file has been moved from a system using big endian or little endian byte ordering to a system of the opposite endianness. https://en.wikipedia.org/wiki/Byte_order_mark

Removing the "FEFF" byte order mark using a hex editor should allow Excel to read the file.

Angular2 module has no exported member

For my case, I restarted the server and it worked.

How to run multiple .BAT files within a .BAT file

Looking at your filenames, have you considered using a build tool like NAnt or Ant (the Java version). You'll get a lot more control than with bat files.

How to make a drop down list in yii2?

If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:

 $items = Standard::find()->select(['name'])->indexBy('s_id')->column();

How to make shadow on border-bottom?

use box-shadow with no horizontal offset.

http://www.css3.info/preview/box-shadow/

eg.

_x000D_
_x000D_
div {_x000D_
  -webkit-box-shadow: 0 10px 5px #888888;_x000D_
  -moz-box-shadow: 0 10px 5px #888888;_x000D_
  box-shadow: 0 10px 5px #888888;_x000D_
}
_x000D_
<div>wefwefwef</div>
_x000D_
_x000D_
_x000D_

There will be a slight shadow on the sides with a large blur radius (5px in above example)

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

How do I parse an ISO 8601-formatted date?

What is the exact error you get? Is it like the following?

>>> datetime.datetime.strptime("2008-08-12T12:20:30.656234Z", "%Y-%m-%dT%H:%M:%S.Z")
ValueError: time data did not match format:  data=2008-08-12T12:20:30.656234Z  fmt=%Y-%m-%dT%H:%M:%S.Z

If yes, you can split your input string on ".", and then add the microseconds to the datetime you got.

Try this:

>>> def gt(dt_str):
        dt, _, us= dt_str.partition(".")
        dt= datetime.datetime.strptime(dt, "%Y-%m-%dT%H:%M:%S")
        us= int(us.rstrip("Z"), 10)
        return dt + datetime.timedelta(microseconds=us)

>>> gt("2008-08-12T12:20:30.656234Z")
datetime.datetime(2008, 8, 12, 12, 20, 30, 656234)

Is it valid to replace http:// with // in a <script src="http://...">?

Yes, this is documented in RFC 3986, section 5.2:

(edit: Oops, my RFC reference was outdated).

Django development IDE

I really like E Text Editor as it's pretty much a "port" of TextMate to Windows. Obviously Django being based on Python, the support for auto-completion is limited (there's nothing like intellisense that would require a dedicated IDE with knowledge of the intricacies of each library), but the use of snippets and "word-completion" helps a lot. Also, it has support for both Django Python files and the template files, and CSS, HTML, etc.

I've been using E Text Editor for a long time now, and I can tell you that it beats both PyDev and Komodo Edit hands down when it comes to working with Django. For other kinds of projects, PyDev and Komodo might be more adequate though.

How can I get a user's media from Instagram without authenticating as a user?

Here's a rails solutions. It's kind of back-door, which is actually the front door.

# create a headless browser
b = Watir::Browser.new :phantomjs
uri = 'https://www.instagram.com/explore/tags/' + query
uri = 'https://www.instagram.com/' + query if type == 'user'

b.goto uri

# all data are stored on this page-level object.
o = b.execute_script( 'return window._sharedData;')

b.close

The object you get back varies depending on whether or not it's a user search or a tag search. I get the data like this:

if type == 'user'
  data = o[ 'entry_data' ][ 'ProfilePage' ][ 0 ][ 'user' ][ 'media' ][ 'nodes' ]
  page_info = o[ 'entry_data' ][ 'ProfilePage' ][ 0 ][ 'user' ][ 'media' ][ 'page_info' ]
  max_id = page_info[ 'end_cursor' ]
  has_next_page = page_info[ 'has_next_page' ]
else
  data = o[ 'entry_data' ][ 'TagPage' ][ 0 ][ 'tag' ][ 'media' ][ 'nodes' ]
  page_info = o[ 'entry_data' ][ 'TagPage' ][ 0 ][ 'tag' ][ 'media' ][ 'page_info' ]
  max_id = page_info[ 'end_cursor' ]
  has_next_page = page_info[ 'has_next_page' ]
end

I then get another page of results by constructing a url in the following way:

  uri = 'https://www.instagram.com/explore/tags/' + query_string.to_s\
    + '?&max_id=' + max_id.to_s
  uri = 'https://www.instagram.com/' + query_string.to_s + '?&max_id='\
    + max_id.to_s if type === 'user'

What is the difference between id and class in CSS, and when should I use them?

  • Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.

    Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.

    Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)

    Examples of class names are: tag, comment, toolbar-button, warning-message, or email.

  • Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.

    Examples of ids are: main-content, header, footer, or left-sidebar.

A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.

How to make the checkbox unchecked by default always

If you have a checkbox with an id checkbox_id.You can set its state with JS with prop('checked', false) or prop('checked', true)

 $('#checkbox_id').prop('checked', false);

XmlSerializer giving FileNotFoundException at constructor

This exception can also be trapped by a managed debugging assistant (MDA) called BindingFailure.

This MDA is useful if your application is designed to ship with pre-build serialization assemblies. We do this to increase performance for our application. It allows us to make sure that the pre-built serialization assemblies are being properly built by our build process, and loaded by the application without being re-built on the fly.

It's really not useful except in this scenario, because as other posters have said, when a binding error is trapped by the Serializer constructor, the serialization assembly is re-built at runtime. So you can usually turn it off.

Append values to query string

You could use the HttpUtility.ParseQueryString method and an UriBuilder which provides a nice way to work with query string parameters without worrying about things like parsing, url encoding, ...:

string longurl = "http://somesite.com/news.php?article=1&lang=en";
var uriBuilder = new UriBuilder(longurl);
var query = HttpUtility.ParseQueryString(uriBuilder.Query);
query["action"] = "login1";
query["attempts"] = "11";
uriBuilder.Query = query.ToString();
longurl = uriBuilder.ToString();
// "http://somesite.com:80/news.php?article=1&lang=en&action=login1&attempts=11"

Can I get JSON to load into an OrderedDict?

Yes, you can. By specifying the object_pairs_hook argument to JSONDecoder. In fact, this is the exact example given in the documentation.

>>> json.JSONDecoder(object_pairs_hook=collections.OrderedDict).decode('{"foo":1, "bar": 2}')
OrderedDict([('foo', 1), ('bar', 2)])
>>> 

You can pass this parameter to json.loads (if you don't need a Decoder instance for other purposes) like so:

>>> import json
>>> from collections import OrderedDict
>>> data = json.loads('{"foo":1, "bar": 2}', object_pairs_hook=OrderedDict)
>>> print json.dumps(data, indent=4)
{
    "foo": 1,
    "bar": 2
}
>>> 

Using json.load is done in the same way:

>>> data = json.load(open('config.json'), object_pairs_hook=OrderedDict)

IPython Notebook save location

To add to Victor's answer, I was able to change the save directory on Windows using...

c.NotebookApp.notebook_dir = 'C:\\Users\\User\\Folder'

What is the correct way to read from NetworkStream in .NET

Setting the underlying socket ReceiveTimeout property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout. You can read the docs for more information.

Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.

I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  var bytes = 0;
  client.Client.ReceiveTimeout = 20;
  do
  {
      try
      {
          bytes = stm.Read(resp, 0, resp.Length);
          memStream.Write(resp, 0, bytes);
      }
      catch (IOException ex)
      {
          // if the ReceiveTimeout is reached an IOException will be raised...
          // with an InnerException of type SocketException and ErrorCode 10060
          var socketExept = ex.InnerException as SocketException;
          if (socketExept == null || socketExept.ErrorCode != 10060)
              // if it's not the "expected" exception, let's not hide the error
              throw ex;
          // if it is the receive timeout, then reading ended
          bytes = 0;
      }
  } while (bytes > 0);
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

nginx: [emerg] "server" directive is not allowed here

The path to the nginx.conf file which is the primary Configuration file for Nginx - which is also the file which shall INCLUDE the Path for other Nginx Config files as and when required is /etc/nginx/nginx.conf.

You may access and edit this file by typing this at the terminal

cd /etc/nginx

/etc/nginx$ sudo nano nginx.conf

Further in this file you may Include other files - which can have a SERVER directive as an independent SERVER BLOCK - which need not be within the HTTP or HTTPS blocks, as is clarified in the accepted answer above.

I repeat - if you need a SERVER BLOCK to be defined within the PRIMARY Config file itself than that SERVER BLOCK will have to be defined within an enclosing HTTP or HTTPS block in the /etc/nginx/nginx.conf file which is the primary Configuration file for Nginx.

Also note -its OK if you define , a SERVER BLOCK directly not enclosing it within a HTTP or HTTPS block , in a file located at path /etc/nginx/conf.d . Also to make this work you will need to include the path of this file in the PRIMARY Config file as seen below :-

http{
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

Further to this you may comment out from the PRIMARY Config file , the line

http{
    #include /etc/nginx/sites-available/some_file.conf; # Comment Out 
    include /etc/nginx/conf.d/*.conf; #includes all files of file type.conf
}

and need not keep any Config Files in /etc/nginx/sites-available/ and also no need to SYMBOLIC Link them to /etc/nginx/sites-enabled/ , kindly note this works for me - in case anyone think it doesnt for them or this kind of config is illegal etc etc , pls do leave a comment so that i may correct myself - thanks .

EDIT :- According to the latest version of the Official Nginx CookBook , we need not create any Configs within - /etc/nginx/sites-enabled/ , this was the older practice and is DEPRECIATED now .

Thus No need for the INCLUDE DIRECTIVE include /etc/nginx/sites-available/some_file.conf; .

Quote from Nginx CookBook page - 5 .

"In some package repositories, this folder is named sites-enabled, and configuration files are linked from a folder named site-available; this convention is depre- cated."

How to add composite primary key to table

If using Sql Server Management Studio Designer just select both rows (Shift+Click) and Set Primary Key.

enter image description here

Java rounding up to an int using Math.ceil

int total = (int) Math.ceil((double)157/32);

What does $ mean before a string?

Note that you can also combine the two, which is pretty cool (although it looks a bit odd):

// simple interpolated verbatim string
WriteLine($@"Path ""C:\Windows\{file}"" not found.");

php get values from json encode

json_decode will return the same array that was originally encoded. For instanse, if you

$array = json_decode($json, true);
echo $array['countryId'];

OR

$obj= json_decode($json);

echo $obj->countryId;

These both will echo 84. I think json_encode and json_decode function names are self-explanatory...

Command to delete all pods in all kubernetes namespaces

K8s completely works on the fundamental of the namespace. if you like to release all the resource related to specified namespace.

you can use the below mentioned :

kubectl delete namespace k8sdemo-app

How does the ARM architecture differ from x86?

Neither has anything specific to keyboard or mobile, other than the fact that for years ARM has had a pretty substantial advantage in terms of power consumption, which made it attractive for all sorts of battery operated devices.

As far as the actual differences: ARM has more registers, supported predication for most instructions long before Intel added it, and has long incorporated all sorts of techniques (call them "tricks", if you prefer) to save power almost everywhere it could.

There's also a considerable difference in how the two encode instructions. Intel uses a fairly complex variable-length encoding in which an instruction can occupy anywhere from 1 up to 15 byte. This allows programs to be quite small, but makes instruction decoding relatively difficult (as in: decoding instructions fast in parallel is more like a complete nightmare).

ARM has two different instruction encoding modes: ARM and THUMB. In ARM mode, you get access to all instructions, and the encoding is extremely simple and fast to decode. Unfortunately, ARM mode code tends to be fairly large, so it's fairly common for a program to occupy around twice as much memory as Intel code would. Thumb mode attempts to mitigate that. It still uses quite a regular instruction encoding, but reduces most instructions from 32 bits to 16 bits, such as by reducing the number of registers, eliminating predication from most instructions, and reducing the range of branches. At least in my experience, this still doesn't usually give quite as dense of coding as x86 code can get, but it's fairly close, and decoding is still fairly simple and straightforward. Lower code density means you generally need at least a little more memory and (generally more seriously) a larger cache to get equivalent performance.

At one time Intel put a lot more emphasis on speed than power consumption. They started emphasizing power consumption primarily on the context of laptops. For laptops their typical power goal was on the order of 6 watts for a fairly small laptop. More recently (much more recently) they've started to target mobile devices (phones, tablets, etc.) For this market, they're looking at a couple of watts or so at most. They seem to be doing pretty well at that, though their approach has been substantially different from ARM's, emphasizing fabrication technology where ARM has mostly emphasized micro-architecture (not surprising, considering that ARM sells designs, and leaves fabrication to others).

Depending on the situation, a CPU's energy consumption is often more important than its power consumption though. At least as I'm using the terms, power consumption refers to power usage on a (more or less) instantaneous basis. Energy consumption, however, normalizes for speed, so if (for example) CPU A consumes 1 watt for 2 seconds to do a job, and CPU B consumes 2 watts for 1 second to do the same job, both CPUs consume the same total amount of energy (two watt seconds) to do that job--but with CPU B, you get results twice as fast.

ARM processors tend to do very well in terms of power consumption. So if you need something that needs a processor's "presence" almost constantly, but isn't really doing much work, they can work out pretty well. For example, if you're doing video conferencing, you gather a few milliseconds of data, compress it, send it, receive data from others, decompress it, play it back, and repeat. Even a really fast processor can't spend much time sleeping, so for tasks like this, ARM does really well.

Intel's processors (especially their Atom processors, which are actually intended for low power applications) are extremely competitive in terms of energy consumption. While they're running close to their full speed, they will consume more power than most ARM processors--but they also finish work quickly, so they can go back to sleep sooner. As a result, they can combine good battery life with good performance.

So, when comparing the two, you have to be careful about what you measure, to be sure that it reflects what you honestly care about. ARM does very well at power consumption, but depending on the situation you may easily care more about energy consumption than instantaneous power consumption.

Add a prefix string to beginning of each line

If you need to prepend a text at the beginning of each line that has a certain string, try following. In the following example, I am adding # at the beginning of each line that has the word "rock" in it.

sed -i -e 's/^.*rock.*/#&/' file_name

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Use jQuery to scroll to the bottom of a div with lots of text

_x000D_
_x000D_
$(function() {_x000D_
  var wtf    = $('#scroll');_x000D_
  var height = wtf[0].scrollHeight;_x000D_
  wtf.scrollTop(height);_x000D_
});
_x000D_
 #scroll {_x000D_
   width: 200px;_x000D_
   height: 300px;_x000D_
   overflow-y: scroll;_x000D_
 }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="scroll">_x000D_
    <br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/>blah<br/>halb<br/> <center><b>Voila!! You have already reached the bottom :)<b></center>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to recover MySQL database from .myd, .myi, .frm files

I found a solution for converting the files to a .sql file (you can then import the .sql file to a server and recover the database), without needing to access the /var directory, therefore you do not need to be a server admin to do this either.

It does require XAMPP or MAMP installed on your computer.

  • After you have installed XAMPP, navigate to the install directory (Usually C:\XAMPP), and the the sub-directory mysql\data. The full path should be C:\XAMPP\mysql\data
  • Inside you will see folders of any other databases you have created. Copy & Paste the folder full of .myd, .myi and .frm files into there. The path to that folder should be

    C:\XAMPP\mysql\data\foldername\.mydfiles

  • Then visit localhost/phpmyadmin in a browser. Select the database you have just pasted into the mysql\data folder, and click on Export in the navigation bar. Chooses the export it as a .sql file. It will then pop up asking where the save the file

And that is it! You (should) now have a .sql file containing the database that was originally .myd, .myi and .frm files. You can then import it to another server through phpMyAdmin by creating a new database and pressing 'Import' in the navigation bar, then following the steps to import it

What exactly is the meaning of an API?

In layman's terms, I've always said an API is like a translator between two people who speak different languages. In software, data can be consumed or distributed using an API (or translator) so that two different kinds of software can communicate. Good software has a strong translator (API) that follows rules and protocols for security and data cleanliness.

I"m a Marketer, not a coder. This all might not be quite right, but it's what I"ve tried to express for about 10 years now...

How to install Visual Studio 2015 on a different drive

I use Xamarin with Visual Studio, and I prefer to move only some large android to another directory with(copy these folders to destination before create hardlinks):

mklink \J "C:\Users\yourUser\.android" "E:\yourFolder\.android"

mklink \J "C:\Program Files (x86)\Android" "E:\yourFolder\Android"

Detect if page has finished loading

jQuery(window).load(function () {
    alert('page is loaded');

    setTimeout(function () {
        alert('page is loaded and 1 minute has passed');   
    }, 60000);

});

Or http://jsfiddle.net/tangibleJ/fLLrs/1/

See also http://api.jquery.com/load-event/ for an explanation on the jQuery(window).load.

Update

A detailed explanation on how javascript loading works and the two events DOMContentLoaded and OnLoad can be found on this page.

DOMContentLoaded: When the DOM is ready to be manipulated. jQuery's way of capturing this event is with jQuery(document).ready(function () {});.

OnLoad: When the DOM is ready and all assets - this includes images, iframe, fonts, etc - have been loaded and the spinning wheel / hour class disappear. jQuery's way of capturing this event is the above mentioned jQuery(window).load.

Controlling Spacing Between Table Cells

To get the job done, use

<table cellspacing=12>

If you’d rather “be right” than get things done, you can instead use the CSS property border-spacing, which is supported by some browsers.

Is there any JSON Web Token (JWT) example in C#?

Here is the list of classes and functions:

open System
open System.Collections.Generic
open System.Linq
open System.Threading.Tasks
open Microsoft.AspNetCore.Mvc
open Microsoft.Extensions.Logging
open Microsoft.AspNetCore.Authorization
open Microsoft.AspNetCore.Authentication
open Microsoft.AspNetCore.Authentication.JwtBearer
open Microsoft.IdentityModel.Tokens
open System.IdentityModel.Tokens
open System.IdentityModel.Tokens.Jwt
open Microsoft.IdentityModel.JsonWebTokens
open System.Text
open Newtonsoft.Json
open System.Security.Claims
    let theKey = "VerySecretKeyVerySecretKeyVerySecretKey"
    let securityKey = SymmetricSecurityKey(Encoding.UTF8.GetBytes(theKey))
    let credentials = SigningCredentials(securityKey, SecurityAlgorithms.RsaSsaPssSha256)
    let expires = DateTime.UtcNow.AddMinutes(123.0) |> Nullable
    let token = JwtSecurityToken(
                    "lahoda-pro-issuer", 
                    "lahoda-pro-audience",
                    claims = null,
                    expires =  expires,
                    signingCredentials = credentials
        )

    let tokenString = JwtSecurityTokenHandler().WriteToken(token)

How to include Javascript file in Asp.Net page

ScriptManager control can also be used to reference javascript files. One catch is that the ScriptManager control needs to be place inside the form tag. I myself prefer ScriptManager control and generally place it just above the closing form tag.

<asp:ScriptManager ID="sm" runat="server">
    <Scripts>
        <asp:ScriptReference Path="~/Scripts/yourscript.min.js" />
    </Scripts>
</asp:ScriptManager>

How to get the Google Map based on Latitude on Longitude?

Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests

Checking during array iteration, if the current element is the last element

Why not this very simple method:

$i = 0; //a counter to track which element we are at
foreach($array as $index => $value) {
    $i++;
    if( $i == sizeof($array) ){
        //we are at the last element of the array
    }
}

what's the default value of char?

its tempting say as white space or integer 0 as per below proof

char c1 = '\u0000';
System.out.println("*"+c1+"*");
System.out.println((int)c1);

but i wouldn't say so because, it might differ it different platforms or in future. What i really care is i ll never use this default value, so before using any char just check it is \u0000 or not, then use it to avoid misconceptions in programs. Its as simple as that.

Eclipse: Syntax Error, parameterized types are only if source level is 1.5

Yes. Regardless of what anyone else says, Eclipse contains some bug(s) that sometimes causes the workspace setting (e.g. 1.6 compliant) to be ignored. This is even when the per-project settings are disabled, the workspace settings are correct (1.6), the JRE is correctly set, there is only a 1.6 JRE defined, etc., all the things that people generally recommend when questions about this issue are posted to various forums (as they often are).

We hit this irregularly, but often, and typically when there is some unrelated issue with build-time dependencies or other project issues. It seems to fall into the general category of "unable to get Eclipse to recognize reality" issues that I always attribute, rightly or wrongly, to refresh issues with Eclipse' extensive metadata. Eclipse metadata is a blessing and a curse; when all is working well, it makes the tool exceedingly powerful and fast. But when there are problems, the extensive caching makes straightening out the issues more difficult - sometimes much more difficult - than with other tools.

Center-align a HTML table

<table align="center"></table>

This works for me.

Calculate the display width of a string in Java

It doesn't always need to be toolkit-dependent or one doesn't always need use the FontMetrics approach since it requires one to first obtain a graphics object which is absent in a web container or in a headless enviroment.

I have tested this in a web servlet and it does calculate the text width.

import java.awt.Font;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

...

String text = "Hello World";
AffineTransform affinetransform = new AffineTransform();     
FontRenderContext frc = new FontRenderContext(affinetransform,true,true);     
Font font = new Font("Tahoma", Font.PLAIN, 12);
int textwidth = (int)(font.getStringBounds(text, frc).getWidth());
int textheight = (int)(font.getStringBounds(text, frc).getHeight());

Add the necessary values to these dimensions to create any required margin.

Best way to check if object exists in Entity Framework?

I had some trouble with this - my EntityKey consists of three properties (PK with 3 columns) and I didn't want to check each of the columns because that would be ugly. I thought about a solution that works all time with all entities.

Another reason for this is I don't like to catch UpdateExceptions every time.

A little bit of Reflection is needed to get the values of the key properties.

The code is implemented as an extension to simplify the usage as:

context.EntityExists<MyEntityType>(item);

Have a look:

public static bool EntityExists<T>(this ObjectContext context, T entity)
        where T : EntityObject
    {
        object value;
        var entityKeyValues = new List<KeyValuePair<string, object>>();
        var objectSet = context.CreateObjectSet<T>().EntitySet;
        foreach (var member in objectSet.ElementType.KeyMembers)
        {
            var info = entity.GetType().GetProperty(member.Name);
            var tempValue = info.GetValue(entity, null);
            var pair = new KeyValuePair<string, object>(member.Name, tempValue);
            entityKeyValues.Add(pair);
        }
        var key = new EntityKey(objectSet.EntityContainer.Name + "." + objectSet.Name, entityKeyValues);
        if (context.TryGetObjectByKey(key, out value))
        {
            return value != null;
        }
        return false;
    }

How can a add a row to a data frame in R?

There is a simpler way to append a record from one dataframe to another IF you know that the two dataframes share the same columns and types. To append one row from xx to yy just do the following where i is the i'th row in xx.

yy[nrow(yy)+1,] <- xx[i,]

Simple as that. No messy binds. If you need to append all of xx to yy, then either call a loop or take advantage of R's sequence abilities and do this:

zz[(nrow(zz)+1):(nrow(zz)+nrow(yy)),] <- yy[1:nrow(yy),]

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

datatable jquery - table header width not aligned with body width

I fixed, Work for me.

var table = $('#example').DataTable();
$('#container').css( 'display', 'block' );
table.columns.adjust().draw();

Or

var table = $('#example').DataTable();
table.columns.adjust().draw();

Reference: https://datatables.net/reference/api/columns.adjust()

Multiple input in JOptionPane.showInputDialog

this is my solution

JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Binning column with python pandas

You can use pandas.cut:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

Or numpy.searchsorted:

bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and then value_counts or groupby and aggregate size:

s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

By default cut return categorical.

Series methods like Series.value_counts() will use all categories, even if some categories are not present in the data, operations in categorical.

How to get source code of a Windows executable?

For Any *.Exe file written in any language .You can view the source code with hiew (otherwise Hackers view). You can download it at www.hiew.ru. It will be the demo version but still can view the code.

After this follow these steps:

  1. Press alt+f2 to navigate to the file.

  2. Press enter to see its assembly / c++ code.

How to create NSIndexPath for TableView

For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)

Git command to display HEAD commit id?

Old thread, still for future reference...:) even following works

git show-ref --head

by default HEAD is filtered out. Be careful about following though ; plural "heads" with a 's' at the end. The following command shows branches under "refs/heads"

 git show-ref --heads

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

When saving, how can you check if a field has changed?

A modification to @ivanperelivskiy's answer:

@property
def _dict(self):
    ret = {}
    for field in self._meta.get_fields():
        if isinstance(field, ForeignObjectRel):
            # foreign objects might not have corresponding objects in the database.
            if hasattr(self, field.get_accessor_name()):
                ret[field.get_accessor_name()] = getattr(self, field.get_accessor_name())
            else:
                ret[field.get_accessor_name()] = None
        else:
            ret[field.attname] = getattr(self, field.attname)
    return ret

This uses django 1.10's public method get_fields instead. This makes the code more future proof, but more importantly also includes foreign keys and fields where editable=False.

For reference, here is the implementation of .fields

@cached_property
def fields(self):
    """
    Returns a list of all forward fields on the model and its parents,
    excluding ManyToManyFields.

    Private API intended only to be used by Django itself; get_fields()
    combined with filtering of field properties is the public API for
    obtaining this field list.
    """
    # For legacy reasons, the fields property should only contain forward
    # fields that are not private or with a m2m cardinality. Therefore we
    # pass these three filters as filters to the generator.
    # The third lambda is a longwinded way of checking f.related_model - we don't
    # use that property directly because related_model is a cached property,
    # and all the models may not have been loaded yet; we don't want to cache
    # the string reference to the related_model.
    def is_not_an_m2m_field(f):
        return not (f.is_relation and f.many_to_many)

    def is_not_a_generic_relation(f):
        return not (f.is_relation and f.one_to_many)

    def is_not_a_generic_foreign_key(f):
        return not (
            f.is_relation and f.many_to_one and not (hasattr(f.remote_field, 'model') and f.remote_field.model)
        )

    return make_immutable_fields_list(
        "fields",
        (f for f in self._get_fields(reverse=False)
         if is_not_an_m2m_field(f) and is_not_a_generic_relation(f) and is_not_a_generic_foreign_key(f))
    )

Duplicate Symbols for Architecture arm64

From the errors, it would appear that the FacebookSDK.framework already includes the Bolts.framework classes. Try removing the additional Bolts.framework from the project.

Python handling socket.error: [Errno 104] Connection reset by peer

There is a way to catch the error directly in the except clause with ConnectionResetError, better to isolate the right error. This example also catches the timeout.

from urllib.request import urlopen 
from socket import timeout

url = "http://......"
try: 
    string = urlopen(url, timeout=5).read()
except ConnectionResetError:
    print("==> ConnectionResetError")
    pass
except timeout: 
    print("==> Timeout")
    pass

How to dynamically allocate memory space for a string and get that string from user?

First, define a new function to read the input (according to the structure of your input) and store the string, which means the memory in stack used. Set the length of string to be enough for your input.

Second, use strlen to measure the exact used length of string stored before, and malloc to allocate memory in heap, whose length is defined by strlen. The code is shown below.

int strLength = strlen(strInStack);
if (strLength == 0) {
    printf("\"strInStack\" is empty.\n");
}
else {
    char *strInHeap = (char *)malloc((strLength+1) * sizeof(char));
    strcpy(strInHeap, strInStack);
}
return strInHeap;

Finally, copy the value of strInStack to strInHeap using strcpy, and return the pointer to strInHeap. The strInStack will be freed automatically because it only exits in this sub-function.

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

sorting integers in order lowest to highest java

For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.

So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....

Binding to static property

In .NET 4.5 it's possible to bind to static properties, read more

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:

public static event EventHandler MyPropertyChanged; 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 

Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.

Is there a way to view past mysql queries with phpmyadmin?

There is a Console tab at the bottom of the SQL (query) screen. By default it is not expanded, but once clicked on it should expose tabs for Options, History and Clear. Click on history.

The Query history length is set from within Page Related Settings which found by clicking on the gear wheel at the top right of screen.

This is correct for PHP version 4.5.1-1

Changing the sign of a number in PHP?

How about something trivial like:

  • inverting:

    $num = -$num;
    
  • converting only positive into negative:

    if ($num > 0) $num = -$num;
    
  • converting only negative into positive:

    if ($num < 0) $num = -$num;
    

Having links relative to root?

To give a URL to an image tag which locates images/ directory in the root like

`logo.png`

you should give src URL starting with / as follows:

<img src="/images/logo.png"/>

This code works in any directories without any troubles even if you are in branches/europe/about.php still the logo can be seen right there.

Check if space is in a string

There are a lot of ways to do that :

t = s.split(" ")
if len(t) > 1:
  print "several tokens"

To be sure it matches every kind of space, you can use re module :

import re
if re.search(r"\s", your_string):
  print "several words"

Creating a "logical exclusive or" operator in Java

This is an example of using XOR(^), from this answer

byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };

byte[] array_3 = new byte[6];

int i = 0;
for (byte b : array_1)
    array_3[i] = b ^ array_2[i++];

Output

0 0 1 1 1 0

Using Font Awesome icon for bullet points, with a single list item element

My solution using standard <ul> and <i> inside <li>

  <ul>
    <li><i class="fab fa-cc-paypal"></i> <div>Paypal</div></li>
    <li><i class="fab fa-cc-apple-pay"></i> <div>Apple Pay</div></li>
    <li><i class="fab fa-cc-stripe"></i> <div>Stripe</div></li>
    <li><i class="fab fa-cc-visa"></i> <div>VISA</div></li>
  </ul>

enter image description here

DEMO HERE

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A slightly more concise example that builds on top of the other answers here. I leveraged the code generation that is shipped with Visual Studio to remove most of the extra invocation code and replaced it with typed objects instead.

    using System;
    using System.Management;

    namespace Utils
    {
        class NetworkManagement
        {
            /// <summary>
            /// Returns a list of all the network interface class names that are currently enabled in the system
            /// </summary>
            /// <returns>list of nic names</returns>
            public static string[] GetAllNicDescriptions()
            {
                List<string> nics = new List<string>();

                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                           .Where(mo => (bool)mo["IPEnabled"])
                                                                           .Select(x=> new NetworkAdapterConfiguration(x)))
                        {
                            nics.Add(config.Description);
                        }
                    }
                }

                return nics.ToArray();
            }

            /// <summary>
            /// Set's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static bool SetNameservers(string nicDescription, string[] dnsServers, bool restart = false)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                        {
                            // NAC class was generated by opening a developer console and entering:
                            // mgmtclassgen Win32_NetworkAdapterConfiguration -p NetworkAdapterConfiguration.cs
                            // See: http://blog.opennetcf.com/2008/06/24/disableenable-network-connections-under-vista/

                            using (NetworkAdapterConfiguration config = new NetworkAdapterConfiguration(mboDNS))
                            {
                                if (config.SetDNSServerSearchOrder(dnsServers) == 0)
                                {
                                    RestartNetworkAdapter(nicDescription);
                                }
                            }
                        }
                    }
                }

                return false;
            }

            /// <summary>
            /// Restarts a given Network adapter
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static void RestartNetworkAdapter(string nicDescription)
            {
                using (ManagementClass networkConfigMng = new ManagementClass("Win32_NetworkAdapter"))
                {
                    using (ManagementObjectCollection networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (ManagementObject mboDNS in networkConfigs.Cast<ManagementObject>().Where(mo=> (string)mo["Description"] == nicDescription))
                        {
                            // NA class was generated by opening dev console and entering
                            // mgmtclassgen Win32_NetworkAdapter -p NetworkAdapter.cs
                            using (NetworkAdapter adapter = new NetworkAdapter(mboDNS))
                            {
                                adapter.Disable();
                                adapter.Enable();
                                Thread.Sleep(4000); // Wait a few secs until exiting, this will give the NIC enough time to re-connect
                                return;
                            }
                        }
                    }
                }
            }

            /// <summary>
            /// Get's the DNS Server of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            public static string[] GetNameservers(string nicDescription)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config  in networkConfigs.Cast<ManagementObject>()
                                                              .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                              .Select( x => new NetworkAdapterConfiguration(x)))
                        {
                            return config.DNSServerSearchOrder;
                        }
                    }
                }

                return null;
            }

            /// <summary>
            /// Set's a new IP Address and it's Submask of the local machine
            /// </summary>
            /// <param name="nicDescription">The full description of the network interface class</param>
            /// <param name="ipAddresses">The IP Address</param>
            /// <param name="subnetMask">The Submask IP Address</param>
            /// <param name="gateway">The gateway.</param>
            /// <remarks>Requires a reference to the System.Management namespace</remarks>
            public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
            {
                using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
                {
                    using (var networkConfigs = networkConfigMng.GetInstances())
                    {
                        foreach (var config in networkConfigs.Cast<ManagementObject>()
                                                                       .Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription)
                                                                       .Select( x=> new NetworkAdapterConfiguration(x)))
                        {
                            // Set the new IP and subnet masks if needed
                            config.EnableStatic(ipAddresses, Array.ConvertAll(ipAddresses, _ => subnetMask));

                            // Set mew gateway if needed
                            if (!String.IsNullOrEmpty(gateway))
                            {
                                config.SetGateways(new[] {gateway}, new ushort[] {1});
                            }
                        }
                    }
                }
            }

        }
    }

Full source: https://github.com/sverrirs/DnsHelper/blob/master/src/DnsHelperUI/NetworkManagement.cs

Error: [ng:areq] from angular controller

There's also another way this could happen.

In my app I have a main module that takes care of the ui-router state management, config, and things like that. The actual functionality is all defined in other modules.

I had defined a module

angular.module('account', ['services']);

that had a controller 'DashboardController' in it, but had forgotten to inject it into the main module where I had a state that referenced the DashboardController.

Since the DashboardController wasn't available because of the missing injection, it threw this error.

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

You need to create own PCH file
Add New file -> Other-> PCH file

Then add the path of this PCH file to your build setting->prefix header->path

($(SRCROOT)/filename.pch)

enter image description here

Drop-down box dependent on the option selected in another drop-down box

I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script language="javascript" type="text/javascript">
    function dynamicdropdown(listindex)
    {
        switch (listindex)
        {
        case "manual" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            break;
        case "online" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
            break;
        }
        return true;
    }
    </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
    <div class="category_div" id="category_div">Source:
        <select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
        <option value="">Select source</option>
        <option value="manual">MANUAL</option>
        <option value="online">ONLINE</option>
        </select>
    </div>
    <div class="sub_category_div" id="sub_category_div">Status:
        <script type="text/javascript" language="JavaScript">
        document.write('<select name="status" id="status"><option value="">Select status</option></select>')
        </script>
        <noscript>
        <select id="status" name="status">
            <option value="open">OPEN</option>
            <option value="delivered">DELIVERED</option>
        </select>
        </noscript>
    </div>
    </body>
</html>

For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Homebrew install specific version of formula?

Based on the workflow described by @tschundeee and @Debilski’s update 1, I automated the procedure and added cleanup in this script.

Download it, put it in your path and brewv <formula_name> <wanted_version>. For the specific OP, it would be:

cd path/to/downloaded/script/
./brewv postgresql 8.4.4

:)

What is the use of BindingResult interface in spring MVC?

BindingResult is used for validation..

Example:-

 public @ResponseBody String nutzer(@ModelAttribute(value="nutzer") Nutzer nutzer, BindingResult ergebnis){
        String ergebnisText;
        if(!ergebnis.hasErrors()){
            nutzerList.add(nutzer);
            ergebnisText = "Anzahl: " + nutzerList.size();
        }else{
            ergebnisText = "Error!!!!!!!!!!!";
        }
        return ergebnisText;
    }

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

Create a nonclustered non-unique index within the CREATE TABLE statement with SQL Server

The accepted answer of how to create an Index inline a Table creation script did not work for me. This did:

CREATE TABLE [dbo].[TableToBeCreated]
(
    [Id] BIGINT IDENTITY(1, 1) NOT NULL PRIMARY KEY
    ,[ForeignKeyId] BIGINT NOT NULL
    ,CONSTRAINT [FK_TableToBeCreated_ForeignKeyId_OtherTable_Id] FOREIGN KEY ([ForeignKeyId]) REFERENCES [dbo].[OtherTable]([Id])
    ,INDEX [IX_TableToBeCreated_ForeignKeyId] NONCLUSTERED ([ForeignKeyId])
)

Remember, Foreign Keys do not create Indexes, so it is good practice to index them as you will more than likely be joining on them.

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

A CSS selector to get last visible div

Try

div:not([style*="display: none"])

When should you use constexpr capability in C++11?

Suppose it does something a little more complicated.

constexpr int MeaningOfLife ( int a, int b ) { return a * b; }

const int meaningOfLife = MeaningOfLife( 6, 7 );

Now you have something that can be evaluated down to a constant while maintaining good readability and allowing slightly more complex processing than just setting a constant to a number.

It basically provides a good aid to maintainability as it becomes more obvious what you are doing. Take max( a, b ) for example:

template< typename Type > constexpr Type max( Type a, Type b ) { return a < b ? b : a; }

Its a pretty simple choice there but it does mean that if you call max with constant values it is explicitly calculated at compile time and not at runtime.

Another good example would be a DegreesToRadians function. Everyone finds degrees easier to read than radians. While you may know that 180 degrees is 3.14159265 (Pi) in radians it is much clearer written as follows:

const float oneeighty = DegreesToRadians( 180.0f );

Lots of good info here:

http://en.cppreference.com/w/cpp/language/constexpr

UTC Date/Time String to Timezone

PHP's DateTime object is pretty flexible.

$UTC = new DateTimeZone("UTC");
$newTZ = new DateTimeZone("America/New_York");
$date = new DateTime( "2011-01-01 15:00:00", $UTC );
$date->setTimezone( $newTZ );
echo $date->format('Y-m-d H:i:s');

Failed to connect to 127.0.0.1:27017, reason: errno:111 Connection refused

There are changes in mongod.conf file in the latest MongoDB v 3.6.5 +

Here is how I fixed this issue on mac os High Sierra v 10.12.3

Note: I assume that you have installed/upgrade MongoDB using homebrew

mongo --version

MongoDB shell version v3.6.5 
git version: a20ecd3e3a174162052ff99913bc2ca9a839d618 
OpenSSL version: OpenSSL 1.0.2o  27 Mar 2018 
allocator: system modules: none build environment:
distarch: x86_64
target_arch: x86_64
  1. find mongod.conf file

     sudo find / -name mongod.conf` 
    

    /usr/local/etc/mongod.conf > first result .

  2. open mongod.conf file

    sudo vi /usr/local/etc/mongod.conf
    
  3. edit in the file for remote access under net: section

     port: 27017  
     bindIpAll: true 
     #bindIp: 127.0.0.1 // comment this out
    
  4. restart mongodb

    if you have installed using brew than

    brew services stop mongodb
    
    brew services start mongodb
    

otherwise, kill the process.

   sudo kill -9 <procssID>

How could I create a function with a completion handler in Swift?

Say you have a download function to download a file from network, and want to be notified when download task has finished.

typealias CompletionHandler = (success:Bool) -> Void

func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {

    // download code.

    let flag = true // true if download succeed,false otherwise

    completionHandler(success: flag)
}

// How to use it.

downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in

    // When download completes,control flow goes here.
    if success {
        // download success
    } else {
        // download fail
    }
})

Hope it helps.

Simplest way to have a configuration file in a Windows Forms C# application

From a quick read of the previous answers, they look correct, but it doesn't look like anyone mentioned the new configuration facilities in Visual Studio 2008. It still uses app.config (copied at compile time to YourAppName.exe.config), but there is a UI widget to set properties and specify their types. Double-click Settings.settings in your project's "Properties" folder.

The best part is that accessing this property from code is typesafe - the compiler will catch obvious mistakes like mistyping the property name. For example, a property called MyConnectionString in app.config would be accessed like:

string s = Properties.Settings.Default.MyConnectionString;

Java: get greatest common divisor

As far as I know, there isn't any built-in method for primitives. But something as simple as this should do the trick:

public int gcd(int a, int b) {
   if (b==0) return a;
   return gcd(b,a%b);
}

You can also one-line it if you're into that sort of thing:

public int gcd(int a, int b) { return b==0 ? a : gcd(b, a%b); }

It should be noted that there is absolutely no difference between the two as they compile to the same byte code.

Why are the Level.FINE logging messages not showing?

Loggers only log the message, i.e. they create the log records (or logging requests). They do not publish the messages to the destinations, which is taken care of by the Handlers. Setting the level of a logger, only causes it to create log records matching that level or higher.

You might be using a ConsoleHandler (I couldn't infer where your output is System.err or a file, but I would assume that it is the former), which defaults to publishing log records of the level Level.INFO. You will have to configure this handler, to publish log records of level Level.FINER and higher, for the desired outcome.

I would recommend reading the Java Logging Overview guide, in order to understand the underlying design. The guide covers the difference between the concept of a Logger and a Handler.

Editing the handler level

1. Using the Configuration file

The java.util.logging properties file (by default, this is the logging.properties file in JRE_HOME/lib) can be modified to change the default level of the ConsoleHandler:

java.util.logging.ConsoleHandler.level = FINER

2. Creating handlers at runtime

This is not recommended, for it would result in overriding the global configuration. Using this throughout your code base will result in a possibly unmanageable logger configuration.

Handler consoleHandler = new ConsoleHandler();
consoleHandler.setLevel(Level.FINER);
Logger.getAnonymousLogger().addHandler(consoleHandler);

When to use <span> instead <p>?

<span> is an inline tag, a <p> is a block tag, used for paragraphs. Browsers will render a blank line below a paragraph, whereas <span>s will render on the same line.

How do I change TextView Value inside Java Code?

First we need to find a Button:

Button mButton = (Button) findViewById(R.id.my_button);

After that, you must implement View.OnClickListener and there you should find the TextView and execute the method setText:

mButton.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
        final TextView mTextView = (TextView) findViewById(R.id.my_text_view);
        mTextView.setText("Some Text");
    }
});

How to manually install a pypi module without pip/easy_install?

Even though Sheena's answer does the job, pip doesn't stop just there.

From Sheena's answer:

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contained herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

At the end of this, you'll end up with a .egg file in site-packages. As a user, this shouldn't bother you. You can import and uninstall the package normally. However, if you want to do it the pip way, you can continue the following steps.

In the site-packages directory,

  1. unzip <.egg file>
  2. rename the EGG-INFO directory as <pkg>-<version>.dist-info
  3. Now you'll see a separate directory with the package name, <pkg-directory>
  4. find <pkg-directory> > <pkg>-<version>.dist-info/RECORD
  5. find <pkg>-<version>.dist-info >> <pkg>-<version>.dist-info/RECORD. The >> is to prevent overwrite.

Now, looking at the site-packages directory, you'll never realize you installed without pip. To uninstall, just do the usual pip uninstall <pkg>.

Ruby: How to get the first character of a string

In Rails

name = 'Smith'
name.first 

SQL Server: Multiple table joins with a WHERE clause

try this

DECLARE @Application TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Application ( Id, NAME )
VALUES  ( 1,'Word' ), ( 2,'Excel' ), ( 3,'PowerPoint' )
DECLARE @software TABLE(Id INT PRIMARY KEY, ApplicationId INT, Version INT)
INSERT @software ( Id, ApplicationId, Version )
VALUES  ( 1,1, 2003 ), ( 2,1,2007 ), ( 3,2, 2003 ), ( 4,2,2007 ),( 5,3, 2003 ), ( 6,3,2007 )

DECLARE @Computer TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Computer ( Id, NAME )
VALUES  ( 1,'Name1' ), ( 2,'Name2' )

DECLARE @Software_Computer  TABLE(Id INT PRIMARY KEY, SoftwareId int, ComputerId int)
INSERT @Software_Computer ( Id, SoftwareId, ComputerId )
VALUES  ( 1,1, 1 ), ( 2,4,1 ), ( 3,2, 2 ), ( 4,5,2 )

SELECT Computer.Name ComputerName, Application.Name ApplicationName, MAX(Software2.Version) Version
FROM @Application Application 
JOIN @Software Software
    ON Application.ID = Software.ApplicationID
CROSS JOIN @Computer Computer
LEFT JOIN @Software_Computer Software_Computer
    ON Software_Computer.ComputerId = Computer.Id AND Software_Computer.SoftwareId = Software.Id
LEFT JOIN @Software Software2
    ON Software2.ID = Software_Computer.SoftwareID
WHERE Computer.ID = 1 
GROUP BY Computer.Name, Application.Name

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

Could not load the Tomcat server configuration

Had the same issue with Kepler (after trying to add a Tomcat 7 server).

Whilst adding the server I opted to install the Tomcat binary using the download/install feature inside Eclipse. I added the server without adding any apps. After the install I tried adding an app and got the error.

I immediately deleted the Tomcat 7 server from Eclipse then repeated the same steps to add Tomcat 7 back in (obviously skipping the download/install step as the binary was downloaded first time around).

After adding Tomcat 7 a second time I tried adding / publishing an app and it worked fine. Didn't bother with any further RCA, it started working and that was good enough for me.

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

In drawable assets there was an image format which was an unsupported image. When i removed the image every thing started working fine.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
  Name
  <input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
  Username
  <input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
  Password
  <input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
  <input type="submit" name= "submit" value="Update">
</form>

look into this

How to check the multiple permission at single request in Android M?

       // **For multiple permission you can use this code :**

       // **First:**
//Write down in onCreate method.

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    requestPermissions(new String[]{
                                    android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                    android.Manifest.permission.CAMERA},
                            MY_PERMISSIONS_REQUEST);

         }

        //**Second:**
    //Write down in a activity.
     @Override
        public void onRequestPermissionsResult(int requestCode,
                                               String permissions[], int[] grantResults) {
            switch (requestCode) {
                case MY_PERMISSIONS_REQUEST:

                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setVisibility(View.GONE);
                                Intent i = new Intent(SplashActivity.this,
                                        HomeActivity.class);
                                startActivity(i);
                                finish();
                            }
                        }, SPLASH_DISPLAY_LENGTH);

                    } else {
                        finish();
                    }
                    return;
            }
        }

How to update a menu item shown in the ActionBar?

in my case: invalidateOptionsMenu just re-setted the text to the original one, but directly accessing the menu item and re-writing the desire text worked without problems:

if (mnuTopMenuActionBar_ != null) {
    MenuItem mnuPageIndex = mnuTopMenuActionBar_
        .findItem(R.id.menu_magazin_pageOfPage_text);

    if (mnuPageIndex != null) {
        if (getScreenOrientation() == 1) {
            mnuPageIndex.setTitle((i + 1) + " von " + pages);
        }
        else {
            mnuPageIndex.setTitle(
                (i + 1) + " + " + (i + 2) + " " + " von " + pages);
        }
        // invalidateOptionsMenu();
    }
}

due to the comment below, I was able to access the menu item via the following code:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.magazine_swipe_activity, menu);
    mnuTopMenuActionBar_ = menu;
    return true;
}

How do I prevent Eclipse from hanging on startup?

My freeze on startup issue seemed to be related to the proxy settings. I saw the username\password dialog on startup, but Eclipse froze whenever I tried to click ok, cancel, or even just click away from the dialog. For a time, I was seeing this authentication pop-up with no freeze issue.

To fix it, I started eclipse using a different workspace, which thankfully didn't freeze on me. Then I went to Window --> Preferences --> General --> Network Connections. I edited my HTTP Proxy entry and unchecked "Requires Authentication". Then I started my original problematic workspace, which launched this time without freezing. Success!

I had no further issues when I re-opened my workspace, and was able to re-enable authentication without having a problem. I didn't see the username\password pop-up anymore on start-up, so there's a chance my authentication info was FUBAR at the time.

Using: MyEclipse, Version: 2016 CI 7, Build id: 14.0.0-20160923

Correct way to delete cookies server-side

Sending the same cookie value with ; expires appended will not destroy the cookie.

Invalidate the cookie by setting an empty value and include an expires field as well:

Set-Cookie: token=deleted; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT

Note that you cannot force all browsers to delete a cookie. The client can configure the browser in such a way that the cookie persists, even if it's expired. Setting the value as described above would solve this problem.

How to temporarily disable a click handler in jQuery?

If #button_id implies a standard HTML button (like a submit button) you can use the 'disabled' attribute to make the button inactive to the browser.

$("#button_id").click(function() {
    $('#button_id').attr('disabled', 'true');

    //do something

     $('#button_id').removeAttr('disabled');
});   

What you may need to be careful with, however, is the order in which these things may happen. If you are using the jquery hide command, you may want to include the "$('#button_id').removeAttr('disabled');" as part of a call back, so that it does not happen until the hide is complete.

[edit] example of function using a callback:

$("#button_id").click(function() {
    $('#button_id').attr('disabled', 'true');
    $('#myDiv').hide(function() { $('#button_id').removeAttr('disabled'); });
});   

how to avoid a new line with p tag?

Use the display: inline CSS property.

Ideal: In the stylesheet:

#container p { display: inline }

Bad/Extreme situation: Inline:

<p style="display:inline">...</p>

How do I connect to a specific Wi-Fi network in Android programmatically?

I broke my head to understand why your answers for WPA/WPA2 don't work...after hours of tries I found what you are missing:

conf.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);

is REQUIRED for WPA networks!!!!

Now, it works :)

How to see the CREATE VIEW code for a view in PostgreSQL?

Kept having to return here to look up pg_get_viewdef (how to remember that!!), so searched for a more memorable command... and got it:

\d+ viewname

You can see similar sorts of commands by typing \? at the pgsql command line.

Bonus tip: The emacs command sql-postgres makes pgsql a lot more pleasant (edit, copy, paste, command history).

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

I don't want to have to enable a reference library as I need my scripts to be portable. The Dim foo As New VBScript_RegExp_55.RegExp line caused User Defined Type Not Defined errors, but I found a solution that worked for me.

Update RE comments w/ @chrisneilsen :

I was under the impression that enabling a reference library was tied to the local computers settings, but it is in fact, tied directly to the workbook. So, you can enable a reference library, share a macro enabled workbook and the end user wouldn't have to enable the library as well. Caveat: The advantage to Late Binding is that the developer does not have to worry about the wrong version of an object library being installed on the user's computer. This likely would not be an issue w/ the VBScript_RegExp_55.RegExp library, but I'm not sold that the "performance" benifit is worth it for me at this time, as we are talking imperceptible milliseconds in my code. I felt this deserved an update to help others understand. If you enable the reference library, you can use "early bind", but if you don't, as far as I can tell, the code will work fine, but you need to "late bind" and loose on some performance/debugging features.

Source: https://peltiertech.com/Excel/EarlyLateBinding.html

What you'll want to do is put an example string in cell A1, then test your strPattern. Once that's working adjust then rng as desired.

Public Sub RegExSearch()
'https://stackoverflow.com/questions/22542834/how-to-use-regular-expressions-regex-in-microsoft-excel-both-in-cell-and-loops
'https://wellsr.com/vba/2018/excel/vba-regex-regular-expressions-guide/
'https://www.vitoshacademy.com/vba-regex-in-excel/
    Dim regexp As Object
    'Dim regex As New VBScript_RegExp_55.regexp 'Caused "User Defined Type Not Defined" Error
    Dim rng As Range, rcell As Range
    Dim strInput As String, strPattern As String
    
    Set regexp = CreateObject("vbscript.regexp")
    Set rng = ActiveSheet.Range("A1:A1")
        
    strPattern = "([a-z]{2})([0-9]{8})"
    'Search for 2 Letters then 8 Digits Eg: XY12345678 = Matched

    With regexp
        .Global = False
        .MultiLine = False
        .ignoreCase = True
        .Pattern = strPattern
    End With

    For Each rcell In rng.Cells

        If strPattern <> "" Then
            strInput = rcell.Value

            If regexp.test(strInput) Then
                MsgBox rcell & " Matched in Cell " & rcell.Address
            Else
                MsgBox "No Matches!"
            End If
        End If
    Next
End Sub

Import numpy on pycharm

It seems that each project may have a separate collection of python libraries in a project specific computing environment. To get this working with numpy I went to the terminal at the bottom of the pycharm window and ran pip install numpy and once the process finished running the install and indexing my python project was able to import numpy from the line of code import numpy as np. It seems you may need to do this for each project you setup in numpy.

The name 'ConfigurationManager' does not exist in the current context

You may also get this error if you add a reference to a different, unrelated project by mistake. Check if that applies to you.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

Both Activity and View have method dispatchTouchEvent() and onTouchEvent.The ViewGroup have this methods too, but have another method called onInterceptTouchEvent. The return type of those methods are boolean, you can control the dispatch route through the return value.

The event dispatch in Android starts from Activity->ViewGroup->View.

How do I download NLTK data?

This worked for me:

nltk.set_proxy('http://user:[email protected]:8080')
nltk.download()

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

Or you could do this from NuGet Package Manager Console

 Install-Package Microsoft.AspNet.WebApi -Version 5.0.0

And then you will be able to add the reference to System.Web.Http.WebHost 5.0

PostgreSQL database default location on Linux

The "directory where postgresql will keep all databases" (and configuration) is called "data directory" and corresponds to what PostgreSQL calls (a little confusingly) a "database cluster", which is not related to distributed computing, it just means a group of databases and related objects managed by a PostgreSQL server.

The location of the data directory depends on the distribution. If you install from source, the default is /usr/local/pgsql/data:

In file system terms, a database cluster will be a single directory under which all data will be stored. We call this the data directory or data area. It is completely up to you where you choose to store your data. There is no default, although locations such as /usr/local/pgsql/data or /var/lib/pgsql/data are popular. (ref)

Besides, an instance of a running PostgreSQL server is associated to one cluster; the location of its data directory can be passed to the server daemon ("postmaster" or "postgres") in the -D command line option, or by the PGDATA environment variable (usually in the scope of the running user, typically postgres). You can usually see the running server with something like this:

[root@server1 ~]# ps auxw |  grep postgres | grep -- -D
postgres  1535  0.0  0.1  39768  1584 ?        S    May17   0:23 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data

Note that it is possible, though not very frequent, to run two instances of the same PostgreSQL server (same binaries, different processes) that serve different "clusters" (data directories). Of course, each instance would listen on its own TCP/IP port.

Create table with jQuery - append

Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Masterpage</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

        <script type="text/javascript">
            function nav() {
                var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
                $('#menu').append(menuHTML);
            }
        </script>

        <style type="text/css">
        </style>
    </head>
    <body onload="nav()">
        <div id="menu"></div>
    </body>
    </html>

How to convert CLOB to VARCHAR2 inside oracle pl/sql

ALTER TABLE TABLE_NAME ADD (COLUMN_NAME_NEW varchar2(4000 char));
update TABLE_NAME set COLUMN_NAME_NEW = COLUMN_NAME;

ALTER TABLE TABLE_NAME DROP COLUMN COLUMN_NAME;
ALTER TABLE TABLE_NAME rename column COLUMN_NAME_NEW to COLUMN_NAME;

Where is virtualenvwrapper.sh after pip install?

Have you installed it using sudo? Was the error in my case.

What does set -e mean in a bash script?

This is an old question, but none of the answers here discuss the use of set -e aka set -o errexit in Debian package handling scripts. The use of this option is mandatory in these scripts, per Debian policy; the intent is apparently to avoid any possibility of an unhandled error condition.

What this means in practice is that you have to understand under what conditions the commands you run could return an error, and handle each of those errors explicitly.

Common gotchas are e.g. diff (returns an error when there is a difference) and grep (returns an error when there is no match). You can avoid the errors with explicit handling:

diff this that ||
  echo "$0: there was a difference" >&2
grep cat food ||
  echo "$0: no cat in the food" >&2

(Notice also how we take care to include the current script's name in the message, and writing diagnostic messages to standard error instead of standard output.)

If no explicit handling is really necessary or useful, explicitly do nothing:

diff this that || true
grep cat food || :

(The use of the shell's : no-op command is slightly obscure, but fairly commonly seen.)

Just to reiterate,

something || other

is shorthand for

if something; then
    : nothing
else
    other
fi

i.e. we explicitly say other should be run if and only if something fails. The longhand if (and other shell flow control statements like while, until) is also a valid way to handle an error (indeed, if it weren't, shell scripts with set -e could never contain flow control statements!)

And also, just to be explicit, in the absence of a handler like this, set -e would cause the entire script to immediately fail with an error if diff found a difference, or if grep didn't find a match.

On the other hand, some commands don't produce an error exit status when you'd want them to. Commonly problematic commands are find (exit status does not reflect whether files were actually found) and sed (exit status won't reveal whether the script received any input or actually performed any commands successfully). A simple guard in some scenarios is to pipe to a command which does scream if there is no output:

find things | grep .
sed -e 's/o/me/' stuff | grep ^

It should be noted that the exit status of a pipeline is the exit status of the last command in that pipeline. So the above commands actually completely mask the status of find and sed, and only tell you whether grep finally succeeded.

(Bash, of course, has set -o pipefail; but Debian package scripts cannot use Bash features. The policy firmly dictates the use of POSIX sh for these scripts, though this was not always the case.)

In many situations, this is something to separately watch out for when coding defensively. Sometimes you have to e.g. go through a temporary file so you can see whether the command which produced that output finished successfully, even when idiom and convenience would otherwise direct you to use a shell pipeline.

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

The results of the execution time directly contradict the results of the Query Cost, but I'm having difficulty determining what "Query Cost" actually means.

Query cost is what optimizer thinks of how long your query will take (relative to total batch time).

The optimizer tries to choose the optimal query plan by looking at your query and statistics of your data, trying several execution plans and selecting the least costly of them.

Here you may read in more detail about how does it try to do this.

As you can see, this may differ significantly of what you actually get.

The only real query perfomance metric is, of course, how long does the query actually take.

Case-insensitive search in Rails model

You might want to use the following:

validates_uniqueness_of :name, :case_sensitive => false

Please note that by default the setting is :case_sensitive => false, so you don't even need to write this option if you haven't changed other ways.

Find more at: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#method-i-validates_uniqueness_of

What is the function of the push / pop instructions used on registers in x86 assembly?

Where is it pushed on?

esp - 4. More precisely:

  • esp gets subtracted by 4
  • the value is pushed to esp

pop reverses this.

The System V ABI tells Linux to make rsp point to a sensible stack location when the program starts running: What is default register state when program launches (asm, linux)? which is what you should usually use.

How can you push a register?

Minimal GNU GAS example:

.data
    /* .long takes 4 bytes each. */
    val1:
        /* Store bytes 0x 01 00 00 00 here. */
        .long 1
    val2:
        /* 0x 02 00 00 00 */
        .long 2
.text
    /* Make esp point to the address of val2.
     * Unusual, but totally possible. */
    mov $val2, %esp

    /* eax = 3 */
    mov $3, %ea 

    push %eax
    /*
    Outcome:
    - esp == val1
    - val1 == 3
    esp was changed to point to val1,
    and then val1 was modified.
    */

    pop %ebx
    /*
    Outcome:
    - esp == &val2
    - ebx == 3
    Inverses push: ebx gets the value of val1 (first)
    and then esp is increased back to point to val2.
    */

The above on GitHub with runnable assertions.

Why is this needed?

It is true that those instructions could be easily implemented via mov, add and sub.

They reason they exist, is that those combinations of instructions are so frequent, that Intel decided to provide them for us.

The reason why those combinations are so frequent, is that they make it easy to save and restore the values of registers to memory temporarily so they don't get overwritten.

To understand the problem, try compiling some C code by hand.

A major difficulty, is to decide where each variable will be stored.

Ideally, all variables would fit into registers, which is the fastest memory to access (currently about 100x faster than RAM).

But of course, we can easily have more variables than registers, specially for the arguments of nested functions, so the only solution is to write to memory.

We could write to any memory address, but since the local variables and arguments of function calls and returns fit into a nice stack pattern, which prevents memory fragmentation, that is the best way to deal with it. Compare that with the insanity of writing a heap allocator.

Then we let compilers optimize the register allocation for us, since that is NP complete, and one of the hardest parts of writing a compiler. This problem is called register allocation, and it is isomorphic to graph coloring.

When the compiler's allocator is forced to store things in memory instead of just registers, that is known as a spill.

Does this boil down to a single processor instruction or is it more complex?

All we know for sure is that Intel documents a push and a pop instruction, so they are one instruction in that sense.

Internally, it could be expanded to multiple microcodes, one to modify esp and one to do the memory IO, and take multiple cycles.

But it is also possible that a single push is faster than an equivalent combination of other instructions, since it is more specific.

This is mostly un(der)documented:

PHP Warning Permission denied (13) on session_start()

I have had this issue before, you need more than the standard 755 or 644 permission to store the $_SESSION information. You need to be able to write to that file as that is how it remembers.

AngularJS - add HTML element to dom in directive without jQuery

Why not to try simple (but powerful) html() method:

iElement.html('<svg width="600" height="100" class="svg"></svg>');

Or append as an alternative:

iElement.append('<svg width="600" height="100" class="svg"></svg>');

And , of course , more cleaner way:

 var svg = angular.element('<svg width="600" height="100" class="svg"></svg>');
 iElement.append(svg);

Fiddle: http://jsfiddle.net/cherniv/AgGwK/

Display UIViewController as Popup in iPhone

You can do this to add any other subview to the view controller. First set the status bar to None for the ViewController which you want to add as subview so that you can resize to whatever you want. Then create a button in Present View controller and a method for button click. In the method:

- (IBAction)btnLogin:(id)sender {
    SubView *sub = [[SubView alloc] initWithNibName:@"SubView" bundle:nil];
    sub.view.frame = CGRectMake(20, 100, sub.view.frame.size.width, sub.view.frame.size.height);
    [self.view addSubview:sub.view];
}

Hope this helps, feel free to ask if any queries...

matplotlib savefig() plots different from show()

I have fixed this in my matplotlib source, but it's not a pretty fix. However, if you, like me, are very particular about how the graph looks, it's worth it.

The issue seems to be in the rendering backends; they each get the correct values for linewidth, font size, etc., but that comes out slightly larger when rendered as a PDF or PNG than when rendered with show().

I added a few lines to the source for PNG generation, in the file matplotlib/backends/backend_agg.py. You could make similar changes for each backend you use, or find a way to make a more clever change in a single location ;)

Added to my matplotlib/backends/backend_agg.py file:

    # The top of the file, added lines 42 - 44
42  # @warning: CHANGED FROM SOURCE to draw thinner lines
43  PATH_SCALAR = .8
44  FONT_SCALAR = .95

    # In the draw_markers method, added lines 90 - 91
89  def draw_markers(self, *kl, **kw):
90      # @warning: CHANGED FROM SOURCE to draw thinner lines
91      kl[0].set_linewidth(kl[0].get_linewidth()*PATH_SCALAR)
92      return self._renderer.draw_markers(*kl, **kw)

    # At the bottom of the draw_path method, added lines 131 - 132:
130 else:
131     # @warning: CHANGED FROM SOURCE to draw thinner lines
132     gc.set_linewidth(gc.get_linewidth()*PATH_SCALAR)
133     self._renderer.draw_path(gc, path, transform, rgbFace)

    # At the bottom of the _get_agg_font method, added line 242 and the *FONT_SCALAR
241     font.clear()
242     # @warning: CHANGED FROM SOURCE to draw thinner lines
243     size = prop.get_size_in_points()*FONT_SCALAR
244     font.set_size(size, self.dpi)

So that suits my needs for now, but, depending on what you're doing, you may want to implement similar changes in other methods. Or find a better way to do the same without so many line changes!

Update: After posting an issue to the matplotlib project at Github, I was able to track down the source of my problem: I had changed the figure.dpi setting in the matplotlibrc file. If that value is different than the default, my savefig() images come out different, even if I set the savefig dpi to be the same as the figure dpi. So, instead of changing the source as above, I just kept the figure.dpi setting as the default 80, and was able to generate images with savefig() that looked like images from show().

Leon, had you also changed that setting?

Java "user.dir" property - what exactly does it mean?

System.getProperty("user.dir") fetches the directory or path of the workspace for the current project

Apache2: 'AH01630: client denied by server configuration'

Ensure that any user-specific configs are included!

If none of the other answers on this page for you work, here's what I ran into after hours of floundering around.

I used user-specific configurations, with Sites specified as my UserDir in /private/etc/apache2/extra/httpd-userdir.conf. However, I was forbidden access to the endpoint http://localhost/~jwork/.

I could see in /var/log/apache2/error_log that access to /Users/jwork/Sites/ was being blocked. However, I was permitted to access the DocumentRoot, via http://localhost/. This suggested that I didn't have rights to view the ~jwork user. But as far as I could tell by ps aux | egrep '(apache|httpd)' and lsof -i :80, Apache was running for the jwork user, so something was clearly not write with my user configuration.

Given a user named jwork, here was my config file:

/private/etc/apache2/users/jwork.conf

<Directory "/Users/jwork/Sites/">
    Require all granted
</Directory>

This config is perfectly valid. However, I found that my user config wasn't being included:

/private/etc/apache2/extra/httpd-userdir.conf

## Note how it's commented out by default.
## Just remove the comment to enable your user conf.
#Include /private/etc/apache2/users/*.conf

Note that this is the default path to the userdir conf file, but as you'll see below, it's configurable in httpd.conf. Ensure that the following lines are enabled:

/private/etc/apache2/httpd.conf

Include /private/etc/apache2/extra/httpd-userdir.conf

# ...

LoadModule userdir_module libexec/apache2/mod_userdir.so

Default behavior of "git push" without a branch specified

You can change that default behavior in your .gitconfig, for example:

[push]
  default = current

To check the current settings, run:

git config --global --get push.default

Encapsulation vs Abstraction?

in a simple sentence, I cay say: The essence of abstraction is to extract essential properties while omitting inessential details. But why should we omit inessential details? The key motivator is preventing the risk of change. You might consider abstraction is same as encapsulation. But encapsulation means the act of enclosing one or more items within a container, not hiding details. If you make the argument that "everything that was encapsulated was also hidden." This is obviously not true. For example, even though information may be encapsulated within record structures and arrays, this information is usually not hidden (unless hidden via some other mechanism).

How to increase the vertical split window size in Vim

This is what I am using as of now:

nnoremap <silent> <Leader>= :exe "resize " . (winheight(0) * 3/2)<CR>
nnoremap <silent> <Leader>- :exe "resize " . (winheight(0) * 2/3)<CR>
nnoremap <silent> <Leader>0 :exe "vertical resize " . (winwidth(0) * 3/2)<CR>
nnoremap <silent> <Leader>9 :exe "vertical resize " . (winwidth(0) * 2/3)<CR>

How can I make a countdown with NSTimer?

For use in Playground for fellow newbies, in Swift 5, Xcode 11:

Import UIKit

var secondsRemaining = 10
    
Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { (Timer) in
    if secondsRemaining > 0 {
        print ("\(secondsRemaining) seconds")
        secondsRemaining -= 1
    } else {
        Timer.invalidate()
    }
}

How to set thousands separator in Java?

For decimals:

DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(' ');
DecimalFormat dfDecimal = new DecimalFormat("###########0.00###");
dfDecimal.setDecimalFormatSymbols(symbols);
dfDecimal.setGroupingSize(3);
dfDecimal.setGroupingUsed(true);
System.out.println(dfDecimal.format(number));

Fetching distinct values on a column using Spark DataFrame

Well to obtain all different values in a Dataframe you can use distinct. As you can see in the documentation that method returns another DataFrame. After that you can create a UDF in order to transform each record.

For example:

val df = sc.parallelize(Array((1, 2), (3, 4), (1, 6))).toDF("age", "salary")

// I obtain all different values. If you show you must see only {1, 3}
val distinctValuesDF = df.select(df("age")).distinct

// Define your udf. In this case I defined a simple function, but they can get complicated.
val myTransformationUDF = udf(value => value / 10)

// Run that transformation "over" your DataFrame
val afterTransformationDF = distinctValuesDF.select(myTransformationUDF(col("age")))

How to vertically align an image inside a div

There is a super easy solution with flexbox!

.frame {
    display: flex;
    align-items: center;
}

PHP 7: Missing VCRUNTIME140.dll

I had the same issue, I changed the ports, restarted the services but in vein, only worked for me when I updated the Microsoft Visual c++ filesFrom There yoy can modify MVC

Override hosts variable of Ansible playbook from the command line

Here's a cool solution I came up to safely specify hosts via the --limit option. In this example, the play will end if the playbook was executed without any hosts specified via the --limit option.

This was tested on Ansible version 2.7.10

---
- name: Playbook will fail if hosts not specified via --limit option.
  # Hosts must be set via limit. 
  hosts: "{{ play_hosts }}"
  connection: local
  gather_facts: false
  tasks:
  - set_fact:
      inventory_hosts: []
  - set_fact:
      inventory_hosts: "{{inventory_hosts + [item]}}"
    with_items: "{{hostvars.keys()|list}}"

  - meta: end_play
    when: "(play_hosts|length) == (inventory_hosts|length)"

  - debug:
      msg: "About to execute tasks/roles for {{inventory_hostname}}"

Inserting an image with PHP and FPDF

I figured it out, and it's actually pretty straight forward.

Set your variable:

$image1 = "img/products/image1.jpg";

Then ceate a cell, position it, then rather than setting where the image is, use the variable you created above with the following:

$this->Cell( 40, 40, $pdf->Image($image1, $pdf->GetX(), $pdf->GetY(), 33.78), 0, 0, 'L', false );

Now the cell will move up and down with content if other cells around it move.

Hope this helps others in the same boat.

Replace String in all files in Eclipse

If you want to replace two lines of code with one line, then this does not work. It works in notepad++. I end up open all files in notepad++ and replaced all.

How do I separate an integer into separate digits in an array in JavaScript?

It's very simple, first convert the number to string using the toString() method in JavaScript and then use split() method to convert the string to an array of individual characters.

For example, the number is num, then

const numberDigits = num.toString().split('');

IntelliJ does not show project folders

As I had the same issue and none of the above worked for me, this is what I did! I know it is a grumpy solution but at least it finally worked! I am not sure why only this method worked. It should be some weird cache in my PC?

  1. I did close IntelliJ
  2. I did completely remove the .idea folder from my project
  3. I did move the folder demo-project to demo-project-temp
  4. I did create a new empty folder demo-project
  5. I did open this empty folder with intelliJ
  6. I did move all the content demo-project-temp. Don't forget to also move the hidden files
  7. Press right click "Synchronize" to your project
  8. You should see all the files and folders now!
  9. Now you can also safely remove the folder demo-project-temp. If you are on linux or MAC do it with rmdir demo-project-temp just to make sure that your folder is empty

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

There is a new ISO8601DateFormatter class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.

Swift 3.0

extension Date {
    var iso8601: String {
        if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
            return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
        } else {
            var buffer = [CChar](repeating: 0, count: 25)
            var time = time_t(self.timeIntervalSince1970)
            strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
            return String(cString: buffer)
        }
    }
}

Bash write to file without echo?

The way to do this in bash is

zsh <<< '> test <<< "Hello World!"'

This is one of the interesting differences between zsh and bash: given an unchained > or >>, zsh has the good sense to hook it up to stdin, while bash does not. It would be downright useful - if it were only standard. I tried to use this to send & append my ssh key over ssh to a remote authorized_keys file, but the remote host was bash, of course, and quietly did nothing.

And that's why you should just use cat.

What's the difference between import java.util.*; and import java.util.Date; ?

import java.util.*;

imports everything within java.util including the Date class.

import java.util.Date;

just imports the Date class.

Doing either of these could not make any difference.

Check if application is on its first run

This might help you

public class FirstActivity extends Activity {

    SharedPreferences sharedPreferences = null;
    Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        sharedPreferences = getSharedPreferences("com.myAppName", MODE_PRIVATE);
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (sharedPreferences.getBoolean("firstRun", true)) {
         //You can perform anything over here. This will call only first time
                 editor = sharedPreferences.edit();
                 editor.putBoolean("firstRun", false)
                 editor.commit();

        }
    }
}

How to call window.alert("message"); from C#?

Do you mean, a message box?

MessageBox.Show("Error Message", "Error Title", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

More information here: http://msdn.microsoft.com/en-us/library/system.windows.forms.messagebox(v=VS.100).aspx

GCM with PHP (Google Cloud Messaging)

Here's a library I forked from CodeMonkeysRU.

The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

I've also updated it to support iOS.

https://github.com/stevetauber/php-gcm-queue

React: "this" is undefined inside a component function

I ran into a similar bind in a render function and ended up passing the context of this in the following way:

{someList.map(function(listItem) {
  // your code
}, this)}

I've also used:

{someList.map((listItem, index) =>
    <div onClick={this.someFunction.bind(this, listItem)} />
)}

How to multiply duration by integer?

It's nice that Go has a Duration type -- having explicitly defined units can prevent real-world problems.

And because of Go's strict type rules, you can't multiply a Duration by an integer -- you must use a cast in order to multiply common types.

/*
MultiplyDuration Hide semantically invalid duration math behind a function
*/
func MultiplyDuration(factor int64, d time.Duration) time.Duration {
    return time.Duration(factor) * d        // method 1 -- multiply in 'Duration'
 // return time.Duration(factor * int64(d)) // method 2 -- multiply in 'int64'
}

The official documentation demonstrates using method #1:

To convert an integer number of units to a Duration, multiply:

seconds := 10
fmt.Print(time.Duration(seconds)*time.Second) // prints 10s

But, of course, multiplying a duration by a duration should not produce a duration -- that's nonsensical on the face of it. Case in point, 5 milliseconds times 5 milliseconds produces 6h56m40s. Attempting to square 5 seconds results in an overflow (and won't even compile if done with constants).

By the way, the int64 representation of Duration in nanoseconds "limits the largest representable duration to approximately 290 years", and this indicates that Duration, like int64, is treated as a signed value: (1<<(64-1))/(1e9*60*60*24*365.25) ~= 292, and that's exactly how it is implemented:

// A Duration represents the elapsed time between two instants
// as an int64 nanosecond count. The representation limits the
// largest representable duration to approximately 290 years.
type Duration int64

So, because we know that the underlying representation of Duration is an int64, performing the cast between int64 and Duration is a sensible NO-OP -- required only to satisfy language rules about mixing types, and it has no effect on the subsequent multiplication operation.

If you don't like the the casting for reasons of purity, bury it in a function call as I have shown above.

Why isn't .ico file defined when setting window's icon?

You need to have favicon.ico in the same folder or dictionary as your script because python only searches in the current dictionary or you could put in the full pathname. For example, this works:

from tkinter import *
root = Tk()

root.iconbitmap(r'c:\Python32\DLLs\py.ico')
root.mainloop()

But this blows up with your same error:

from tkinter import *
root = Tk()

root.iconbitmap('py.ico')
root.mainloop()

Create two threads, one display odd & other even numbers

package p.Threads;

public class PrintEvenAndOddNum  {

    private  Object obj = new Object();

    private static final PrintEvenAndOddNum peon = new PrintEvenAndOddNum();

    private PrintEvenAndOddNum(){}

    public static PrintEvenAndOddNum getInstance(){
        return peon;
    }

    public  void printOddNum()  {
        for(int i=1;i<10;i++){
            if(i%2 != 0){
                synchronized (obj) {
                    System.out.println(i);

                    try {
                        System.out.println("oddNum going into waiting state ....");
                        obj.wait();

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("resume....");
                    obj.notify();
                }
            }
        }
    }

    public  void printEvenNum()  {
        for(int i=1;i<11;i++){
            if(i%2 == 0){
                synchronized(obj){
                    System.out.println(i);
                    obj.notify();
                    try {
                        System.out.println("evenNum going into waiting state ....");
                        obj.wait();
                        System.out.println("Notifying waiting thread ....");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }   
}

How to convert NSData to byte array in iPhone?

You can't declare an array using a variable so Byte byteData[len]; won't work. If you want to copy the data from a pointer, you also need to memcpy (which will go through the data pointed to by the pointer and copy each byte up to a specified length).

Try:

NSData *data = [NSData dataWithContentsOfFile:filePath];
NSUInteger len = [data length];
Byte *byteData = (Byte*)malloc(len);
memcpy(byteData, [data bytes], len);

This code will dynamically allocate the array to the correct size (you must free(byteData) when you're done) and copy the bytes into it.

You could also use getBytes:length: as indicated by others if you want to use a fixed length array. This avoids malloc/free but is less extensible and more prone to buffer overflow issues so I rarely ever use it.

shift a std_logic_vector of n bit to right or left

I would not suggest to use sll or srl with std_logic_vector.

During simulation sll gave me 'U' value for those bits, where I expected 0's.

Use shift_left(), shift_right() functions.

For example:

OP1 : in std_logic_vector(7 downto 0); signal accum: std_logic_vector(7 downto 0);

accum <= std_logic_vector(shift_left(unsigned(accum), to_integer(unsigned(OP1)))); accum <= std_logic_vector(shift_right(unsigned(accum), to_integer(unsigned(OP1))));

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

Go to Xcode's breakpoints tab. Use the button at the bottom to add an exception breakpoint. Now you'll see what code is invoking setValue:forKey: and the associated stack. With luck that'll point you straight at the problem's source.

Odd that your class is LoginScreen, yet the error is saying someone is using "LoginScreen" as a key. Check that LoginScreen.m is part of your target.

enter image description here


Footnote: with Swift a common problem arises if you change the name of a class (so, you rename it everywhere in your code). Storyboard struggles with this, and you usually have to re-drag any connections involving that class. And in particular, re-enter the name of the class anywhere used in IdentityInspector tab on the right. (In the picture example I deliberately misspelled the class name. But the same thing often happens when you rename a class; even though it's seemingly correct in IdentityInspector, you need to enter the name again; it will correctly autocomplete and you're good to go.)

Room persistance library. Delete all

As of Room 1.1.0 you can use clearAllTables() which:

Deletes all rows from all the tables that are registered to this database as entities().

RecyclerView - How to smooth scroll to top of item on a certain position?

  1. Extend "LinearLayout" class and override the necessary functions
  2. Create an instance of the above class in your fragment or activity
  3. Call "recyclerView.smoothScrollToPosition(targetPosition)

CustomLinearLayout.kt :

class CustomLayoutManager(private val context: Context, layoutDirection: Int):
  LinearLayoutManager(context, layoutDirection, false) {

    companion object {
      // This determines how smooth the scrolling will be
      private
      const val MILLISECONDS_PER_INCH = 300f
    }

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {

      val smoothScroller: LinearSmoothScroller = object: LinearSmoothScroller(context) {

        fun dp2px(dpValue: Float): Int {
          val scale = context.resources.displayMetrics.density
          return (dpValue * scale + 0.5f).toInt()
        }

        // change this and the return super type to "calculateDyToMakeVisible" if the layout direction is set to VERTICAL
        override fun calculateDxToMakeVisible(view: View ? , snapPreference : Int): Int {
          return super.calculateDxToMakeVisible(view, SNAP_TO_END) - dp2px(50f)
        }

        //This controls the direction in which smoothScroll looks for your view
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF ? {
          return this @CustomLayoutManager.computeScrollVectorForPosition(targetPosition)
        }

        //This returns the milliseconds it takes to scroll one pixel.
        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
          return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
        }
      }
      smoothScroller.targetPosition = position
      startSmoothScroll(smoothScroller)
    }
  }

Note: The above example is set to HORIZONTAL direction, you can pass VERTICAL/HORIZONTAL during initialization.

If you set the direction to VERTICAL you should change the "calculateDxToMakeVisible" to "calculateDyToMakeVisible" (also mind the supertype call return value)

Activity/Fragment.kt :

...
smoothScrollerLayoutManager = CustomLayoutManager(context, LinearLayoutManager.HORIZONTAL)
recyclerView.layoutManager = smoothScrollerLayoutManager
.
.
.
fun onClick() {
  // targetPosition passed from the adapter to activity/fragment
  recyclerView.smoothScrollToPosition(targetPosition)
}

curl -GET and -X GET

By default you use curl without explicitly saying which request method to use. If you just pass in a HTTP URL like curl http://example.com it will use GET. If you use -d or -F curl will use POST, -I will cause a HEAD and -T will make it a PUT.

If for whatever reason you're not happy with these default choices that curl does for you, you can override those request methods by specifying -X [WHATEVER]. This way you can for example send a DELETE by doing curl -X DELETE [URL].

It is thus pointless to do curl -X GET [URL] as GET would be used anyway. In the same vein it is pointless to do curl -X POST -d data [URL]... But you can make a fun and somewhat rare request that sends a request-body in a GET request with something like curl -X GET -d data [URL].

Digging deeper

curl -GET (using a single dash) is just wrong for this purpose. That's the equivalent of specifying the -G, -E and -T options and that will do something completely different.

There's also a curl option called --get to not confuse matters with either. It is the long form of -G, which is used to convert data specified with -d into a GET request instead of a POST.

(I subsequently used my own answer here to populate the curl FAQ to cover this.)

Warnings

Modern versions of curl will inform users about this unnecessary and potentially harmful use of -X when verbose mode is enabled (-v) - to make users aware. Further explained and motivated in this blog post.

-G converts a POST + body to a GET + query

You can ask curl to convert a set of -d options and instead of sending them in the request body with POST, put them at the end of the URL's query string and issue a GET, with the use of `-G. Like this:

curl -d name=daniel -d grumpy=yes -G https://example.com/

How to find the lowest common ancestor of two nodes in any binary tree?

Code for A Breadth First Search to make sure both nodes are in the tree. Only then move forward with the LCA search. Please comment if you have any suggestions to improve. I think we can probably mark them visited and restart the search at a certain point where we left off to improve for the second node (if it isn't found VISITED)

public class searchTree {
    static boolean v1=false,v2=false;
    public static boolean bfs(Treenode root, int value){
         if(root==null){
           return false;
     }
    Queue<Treenode> q1 = new LinkedList<Treenode>();

    q1.add(root);
    while(!q1.isEmpty())
    {
        Treenode temp = q1.peek();

        if(temp!=null) {
            q1.remove();
            if (temp.value == value) return true;
            if (temp.left != null) q1.add(temp.left);
            if (temp.right != null) q1.add(temp.right);
        }
    }
    return false;

}
public static Treenode lcaHelper(Treenode head, int x,int y){

    if(head==null){
        return null;
    }

    if(head.value == x || head.value ==y){
        if (head.value == y){
            v2 = true;
            return head;
        }
        else {
            v1 = true;
            return head;
        }
    }

    Treenode left = lcaHelper(head.left, x, y);
    Treenode right = lcaHelper(head.right,x,y);

    if(left!=null && right!=null){
        return head;
    }
    return (left!=null) ? left:right;
}

public static int lca(Treenode head, int h1, int h2) {
    v1 = bfs(head,h1);
    v2 = bfs(head,h2);
    if(v1 && v2){
        Treenode lca = lcaHelper(head,h1,h2);
        return lca.value;
    }
    return -1;
}
}

How to set the width of a RaisedButton in Flutter?

In my case I used margin to be able to change the size:

Container(


     margin: EdgeInsets.all(10),

    // or margin: EdgeInsets.only(left:10, right:10),



        child: RaisedButton(
          padding: EdgeInsets.all(10),

          shape: RoundedRectangleBorder(borderRadius: 
BorderRadius.circular(20)),
          onPressed: () {},
          child: Text("Button"),
        ),
      ),

How to pick a new color for each plotted line within a figure in matplotlib?

matplotlib 1.5+

You can use axes.set_prop_cycle (example).

matplotlib 1.0-1.4

You can use axes.set_color_cycle (example).

matplotlib 0.x

You can use Axes.set_default_color_cycle.

Insert 2 million rows into SQL Server quickly

You can try with SqlBulkCopy class.

Lets you efficiently bulk load a SQL Server table with data from another source.

There is a cool blog post about how you can use it.

Switch tabs using Selenium WebDriver with Java

This is a simple solution for opening a new tab, changing focus to it, closing the tab and return focus to the old/original tab:

@Test
public void testTabs() {
    driver.get("https://business.twitter.com/start-advertising");
    assertStartAdvertising();

    // considering that there is only one tab opened in that point.
    String oldTab = driver.getWindowHandle();
    driver.findElement(By.linkText("Twitter Advertising Blog")).click();
    ArrayList<String> newTab = new ArrayList<String>(driver.getWindowHandles());
    newTab.remove(oldTab);
    // change focus to new tab
    driver.switchTo().window(newTab.get(0));
    assertAdvertisingBlog();

    // Do what you want here, you are in the new tab

    driver.close();
    // change focus back to old tab
    driver.switchTo().window(oldTab);
    assertStartAdvertising();

    // Do what you want here, you are in the old tab
}

private void assertStartAdvertising() {
    assertEquals("Start Advertising | Twitter for Business", driver.getTitle());
}

private void assertAdvertisingBlog() {
    assertEquals("Twitter Advertising", driver.getTitle());
}

Why does my Spring Boot App always shutdown immediately after starting?

I think the right answer was at Why does Spring Boot web app close immediately after starting? about the starter-tomcat not being set and if set and running through the IDE, the provided scope should be commented off. Scope doesn't create an issue while running through command. I wonder why.

Anyways just added my additional thoughts.

JQuery to load Javascript file dynamically

I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:

$("#addComment").click(function() {
    if(typeof TinyMCE === "undefined") {
        $.ajax({
            url: "tinymce.js",
            dataType: "script",
            cache: true,
            success: function() {
                TinyMCE.init();
            }
        });
    }
});

The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:

http://www.yoursite.com/js/tinymce.js?_=1399055841840

If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.

===

Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:

jQuery.cachedScript = function( url, options ) {

    // Allow user to set any option except for dataType, cache, and url
    options = $.extend( options || {}, {
        dataType: "script",
        cache: true,
        url: url
    });

    // Use $.ajax() since it is more flexible than $.getScript
    // Return the jqXHR object so we can chain callbacks
    return jQuery.ajax( options );
};

// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
    console.log( textStatus );
});

===

Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:

$.ajaxSetup({
    cache: true
});

Can you do greater than comparison on a date in a Rails 3 search?

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

Note
  .where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
  .order(date: :asc, created_at: :asc)

Here is a link to PR where you can find more examples.

How to find the operating system version using JavaScript?

Use detectOS.js:

var Detect = {
    init: function () {
        this.OS = this.searchString(this.dataOS);
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    dataOS : [
        {
            string: navigator.platform,
            subString: 'Win',
            identity: 'Windows'
        },
        {
            string: navigator.platform,
            subString: 'Mac',
            identity: 'macOS'
        },
        {
            string: navigator.userAgent,
            subString: 'iPhone',
            identity: 'iOS'
        },
        {
            string: navigator.userAgent,
            subString: 'iPad',
            identity: 'iOS'
        },
        {
            string: navigator.userAgent,
            subString: 'iPod',
            identity: 'iOS'
        },
        {
            string: navigator.userAgent,
            subString: 'Android',
            identity: 'Android'
        },
        {
            string: navigator.platform,
            subString: 'Linux',
            identity: 'Linux'
        }
    ]
};

Detect.init();

console.log("We know your OS – it's " + Detect.OS + ". We know everything about you.");

Convert from days to milliseconds

24 hours = 86400 seconds = 86400000 milliseconds. Just multiply your number with 86400000.

What is the difference between single-quoted and double-quoted strings in PHP?

Both kinds of enclosed characters are strings. One type of quote is conveniently used to enclose the other type of quote. "'" and '"'. The biggest difference between the types of quotes is that enclosed identifier references are substituted for inside double quotes, but not inside single quotes.

how to update spyder on anaconda

Go to Anaconda Naviagator, find spyder,click settings in the top right corner of the spyder app.click update tab

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

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

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

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

you can also type from within your repo:

git remote -v

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

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

git remote add origin url/to/your/fork

The OP mentions:

Doing git remote -v gives:

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

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

enter image description here

ImportError: No module named 'bottle' - PyCharm

in your PyCharm project:

  • press Ctrl+Alt+s to open the settings
  • on the left column, select Project Interpreter
  • on the top right there is a list of python binaries found on your system, pick the right one
  • eventually click the + button to install additional python modules
  • validate

enter image description here

EOFError: end of file reached issue with Net::HTTP

I ran into this recently and eventually found that this was caused by a network timeout from the endpoint we were hitting. Fortunately for us we were able to increase the timeout duration.

To verify this was our issue (and actually not an issue with net http), I made the same request with curl and confirmed that the request was being terminated.

Running a Python script from PHP

I recommend using passthru and handling the output buffer directly:

ob_start();
passthru('/usr/bin/python2.7 /srv/http/assets/py/switch.py arg1 arg2');
$output = ob_get_clean(); 

if statement in ng-click

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

<input ng-click="check(profileForm.$valid)" name="submit" 
       id="submit" value="Save" class="submit" type="submit">

Controller:

$scope.check = function(value) {
    if (value) {
       updateMyProfile();
    }
}

How to check if a string array contains one string in JavaScript?

There is an indexOf method that all arrays have (except Internet Explorer 8 and below) that will return the index of an element in the array, or -1 if it's not in the array:

if (yourArray.indexOf("someString") > -1) {
    //In the array!
} else {
    //Not in the array
}

If you need to support old IE browsers, you can polyfill this method using the code in the MDN article.

How do I list all files of a directory?

os.listdir() will get you everything that's in a directory - files and directories.

If you want just files, you could either filter this down using os.path:

from os import listdir
from os.path import isfile, join
onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]

or you could use os.walk() which will yield two lists for each directory it visits - splitting into files and dirs for you. If you only want the top directory you can break the first time it yields

from os import walk

f = []
for (dirpath, dirnames, filenames) in walk(mypath):
    f.extend(filenames)
    break

or, shorter:

from os import walk

_, _, filenames = next(walk(mypath))

mkdir -p functionality in Python

This is easier than trapping the exception:

import os
if not os.path.exists(...):
    os.makedirs(...)

Disclaimer This approach requires two system calls which is more susceptible to race conditions under certain environments/conditions. If you're writing something more sophisticated than a simple throwaway script running in a controlled environment, you're better off going with the accepted answer that requires only one system call.

UPDATE 2012-07-27

I'm tempted to delete this answer, but I think there's value in the comment thread below. As such, I'm converting it to a wiki.

Save PL/pgSQL output from PostgreSQL to a CSV file

If you're interested in all the columns of a particular table along with headers, you can use

COPY table TO '/some_destdir/mycsv.csv' WITH CSV HEADER;

This is a tiny bit simpler than

COPY (SELECT * FROM table) TO '/some_destdir/mycsv.csv' WITH CSV HEADER;

which, to the best of my knowledge, are equivalent.

Excel formula to get week number in month (having Monday)

Finding of week number for each date of a month (considering Monday as beginning of the week)

Keep the first date of month contant $B$13

=WEEKNUM(B18,2)-WEEKNUM($B$13,2)+1

WEEKNUM(B18,2) - returns the week number of the date mentioned in cell B18

WEEKNUM($B$13,2) - returns the week number of the 1st date of month in cell B13

How to change an Eclipse default project into a Java project

In newer versions of eclipse (I'm using 4.9.0) there is another, possibly easier, methods. As well as Project Facets, there are now Project Natures. Here the process is simple get the Project Natures property page up, and then click the Add... button. This will come up with possible natures included Java Nature and Eclipse Faceted Project Properties. Just add the Java Nature and ignore the various warning messages and your done.

Project Nature

This method might be better as you don't have to convert to Faceted form first. Furthermore Java was not offered in the add Facet menu.

Batch - If, ElseIf, Else

batchfiles perform simple string substitution with variables. so, a simple

goto :language%language%
echo notfound
...

does this without any need for if.