Programs & Examples On #Android framework

Get key by value in dictionary

This is how you access the dictionary to do what you want:

list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for age in list:
    if list[age] == search_age:
        print age

of course, your names are so off it looks like it would be printing an age, but it DOES print the name. Since you are accessing by name, it becomes more understandable if you write:

list = {'george': 16, 'amber': 19}
search_age = raw_input("Provide age")
for name in list:
    if list[name] == search_age:
        print name

Better yet:

people = {'george': {'age': 16}, 'amber': {'age': 19}}
search_age = raw_input("Provide age")
for name in people:
    if people[name]['age'] == search_age:
        print name

Replace CRLF using powershell

Below is my script for converting all files recursively. You can specify folders or files to exclude.

$excludeFolders = "node_modules|dist|.vs";
$excludeFiles = ".*\.map.*|.*\.zip|.*\.png|.*\.ps1"

Function Dos2Unix {
    [CmdletBinding()]
    Param([Parameter(ValueFromPipeline)] $fileName)

    Write-Host -Nonewline "."

    $fileContents = Get-Content -raw $fileName
    $containsCrLf = $fileContents | %{$_ -match "\r\n"}
    If($containsCrLf -contains $true)
    {
        Write-Host "`r`nCleaing file: $fileName"
        set-content -Nonewline -Encoding utf8 $fileName ($fileContents -replace "`r`n","`n")
    }
}

Get-Childitem -File "." -Recurse |
Where-Object {$_.PSParentPath -notmatch $excludeFolders} |
Where-Object {$_.PSPath -notmatch $excludeFiles} |
foreach { $_.PSPath | Dos2Unix }

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

What is the format specifier for unsigned short int?

For scanf, you need to use %hu since you're passing a pointer to an unsigned short. For printf, it's impossible to pass an unsigned short due to default promotions (it will be promoted to int or unsigned int depending on whether int has at least as many value bits as unsigned short or not) so %d or %u is fine. You're free to use %hu if you prefer, though.

"could not find stored procedure"

One more possibility to check. Listing here because it just happened to me and wasn't mentioned;-)

I had accidentally added a space character on the end of the name. Many hours of trying things before I finally noticed it. It's always something simple after you figure it out.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

As others have said, bad file references in the build path is often the culprit.

Usually a .jar file that has been moved/deleted. Eclipse expects to find everything referenced on the build path at the location specified, and will complain if not.

Select multiple columns by labels in pandas

How do I select multiple columns by labels in pandas?

Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:

loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]

          A         B         C         E         G         H         I
0 -1.666330  0.321260 -1.768185 -0.034774  0.023294  0.533451 -0.241990
1  0.911498  3.408758  0.419618 -0.462590  0.739092  1.103940  0.116119
2  1.243001 -0.867370  1.058194  0.314196  0.887469  0.471137 -1.361059
3 -0.525165  0.676371  0.325831 -1.152202  0.606079  1.002880  2.032663
4  0.706609 -0.424726  0.308808  1.994626  0.626522 -0.033057  1.725315
5  0.879802 -1.961398  0.131694 -0.931951 -0.242822 -1.056038  0.550346
6  0.199072  0.969283  0.347008 -2.611489  0.282920 -0.334618  0.243583
7  1.234059  1.000687  0.863572  0.412544  0.569687 -0.684413 -0.357968
8 -0.299185  0.566009 -0.859453 -0.564557 -0.562524  0.233489 -0.039145
9  0.937637 -2.171174 -1.940916 -1.553634  0.619965 -0.664284 -0.151388

Note that the +1 is added because when using iloc the rightmost index is exclusive.


Comments on Other Solutions

  • filter is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.

  • The "location-based" solution with loc is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.

  • Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.

Task vs Thread differences

Source

Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

How to find out if a file exists in C# / .NET?

I use WinForms and my way to use File.Exists(string path) is the next one:

public bool FileExists(string fileName)
{
    var workingDirectory = Environment.CurrentDirectory;
    var file = $"{workingDirectory}\{fileName}";
    return File.Exists(file);
}

fileName must include the extension like myfile.txt

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

cin and getline skipping input

If you're using getline after cin >> something, you need to flush the newline out of the buffer in between.

My personal favourite for this if no characters past the newline are needed is cin.sync(). However, it is implementation defined, so it might not work the same way as it does for me. For something solid, use cin.ignore(). Or make use of std::ws to remove leading whitespace if desirable:

int a;

cin >> a;
cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
//discard characters until newline is found

//my method: cin.sync(); //discard unread characters

string s;
getline (cin, s); //newline is gone, so this executes

//other method: getline(cin >> ws, s); //remove all leading whitespace

std::enable_if to conditionally compile a member function

I made this short example which also works.

#include <iostream>
#include <type_traits>

class foo;
class bar;

template<class T>
struct is_bar
{
    template<class Q = T>
    typename std::enable_if<std::is_same<Q, bar>::value, bool>::type check()
    {
        return true;
    }

    template<class Q = T>
    typename std::enable_if<!std::is_same<Q, bar>::value, bool>::type check()
    {
        return false;
    }
};

int main()
{
    is_bar<foo> foo_is_bar;
    is_bar<bar> bar_is_bar;
    if (!foo_is_bar.check() && bar_is_bar.check())
        std::cout << "It works!" << std::endl;

    return 0;
}

Comment if you want me to elaborate. I think the code is more or less self-explanatory, but then again I made it so I might be wrong :)

You can see it in action here.

LaTeX: Prevent line break in a span of text

\mbox is the simplest answer. Regarding the update:

TeX prefers overlong lines to adding too much space between words on a line; I think the idea is that you will notice the lines that extend into the margin (and the black boxes it inserts after such lines), and will have a chance to revise the contents, whereas if there was too much space, you might not notice it.

Use \sloppy or \begin{sloppypar}...\end{sloppypar} to adjust this behavior, at least a little. Another possibility is \raggedright (or \begin{raggedright}...\end{raggedright}).

Is there a simple way to delete a list element by value?

Say for example, we want to remove all 1's from x. This is how I would go about it:

x = [1, 2, 3, 1, 2, 3]

Now, this is a practical use of my method:

def Function(List, Unwanted):
    [List.remove(Unwanted) for Item in range(List.count(Unwanted))]
    return List
x = Function(x, 1)
print(x)

And this is my method in a single line:

[x.remove(1) for Item in range(x.count(1))]
print(x)

Both yield this as an output:

[2, 3, 2, 3, 2, 3]

Hope this helps. PS, pleas note that this was written in version 3.6.2, so you might need to adjust it for older versions.

Best data type to store money values in MySQL

Storing money as BIGINT multiplied by 100 or more with the reason to use less storage space makes no sense in all "normal" situations.

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

This might be the late response, but recently i got the same error. After lot of surfing this solution helped me.

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
def myconverter(obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

Call myconverter in json.dumps() like below. json.dumps(alerts, default=myconverter).

android.content.Context.getPackageName()' on a null object reference

android API level 23.

Use

getContext()

instead of

getActivity()

getActivity() gives the parent Activity, a Context object

Here You can use

MyActivity.this

instead of

getActivity() / getApplicationContext()

ReactJS - Does render get called any time "setState" is called?

No, React doesn't render everything when the state changes.

  • Whenever a component is dirty (its state changed), that component and its children are re-rendered. This, to some extent, is to re-render as little as possible. The only time when render isn't called is when some branch is moved to another root, where theoretically we don't need to re-render anything. In your example, TimeInChild is a child component of Main, so it also gets re-rendered when the state of Main changes.

  • React doesn't compare state data. When setState is called, it marks the component as dirty (which means it needs to be re-rendered). The important thing to note is that although render method of the component is called, the real DOM is only updated if the output is different from the current DOM tree (a.k.a diffing between the Virtual DOM tree and document's DOM tree). In your example, even though the state data hasn't changed, the time of last change did, making Virtual DOM different from the document's DOM, hence why the HTML is updated.

What are the differences between virtual memory and physical memory?

Virtual memory is, among other things, an abstraction to give the programmer the illusion of having infinite memory available on their system.

Virtual memory mappings are made to correspond to actual physical addresses. The operating system creates and deals with these mappings - utilizing the page table, among other data structures to maintain the mappings. Virtual memory mappings are always found in the page table or some similar data structure (in case of other implementations of virtual memory, we maybe shouldn't call it the "page table"). The page table is in physical memory as well - often in kernel-reserved spaces that user programs cannot write over.

Virtual memory is typically larger than physical memory - there wouldn't be much reason for virtual memory mappings if virtual memory and physical memory were the same size.

Only the needed part of a program is resident in memory, typically - this is a topic called "paging". Virtual memory and paging are tightly related, but not the same topic. There are other implementations of virtual memory, such as segmentation.

I could be assuming wrong here, but I'd bet the things you are finding hard to wrap your head around have to do with specific implementations of virtual memory, most likely paging. There is no one way to do paging - there are many implementations and the one your textbook describes is likely not the same as the one that appears in real OSes like Linux/Windows - there are probably subtle differences.

I could blab a thousand paragraphs about paging... but I think that is better left to a different question targeting specifically that topic.

How to set child process' environment variable in Makefile

Make variables are not exported into the environment of processes make invokes... by default. However you can use make's export to force them to do so. Change:

test: NODE_ENV = test

to this:

test: export NODE_ENV = test

(assuming you have a sufficiently modern version of GNU make >= 3.77 ).

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

How do I open a new window using jQuery?

Those are by no means the same. The first will simply send you to whatever URL you have assigned to window.location.href (in the same window you're currently in). The second makes a GET AJAX request.

Try this page: http://www.codebelt.com/jquery/open-new-browser-window-with-jquery-custom-size/

It gives a great example on how to open a new window*.

If you wish to use raw javascript then this is what you're looking for:

window.open(URL,name,specs,replace)

As seen in http://www.w3schools.com/jsref/met_win_open.asp

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

JavaScript replace \n with <br />

Handles either type of line break

str.replace(new RegExp('\r?\n','g'), '<br />');

How to change the hosts file on android

adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:

adb shell
su
mount -o remount,rw /system

Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.

how to use Spring Boot profiles

Since Spring Boot v2+

I have verified with Spring Boot v2.3.5.RELEASE

With Spring Boot Maven Plugin

You can provide commandline argument like this:

mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=dev"

You can provide JVM argument like this:

mvn spring-boot:run -Dspring-boot.run.jvmArguments="-Dspring.profiles.active=dev"

java -jar

java -Dspring.profiles.active=dev -jar app.jar (Note order)

or

java -jar app.jar --spring.profiles.active=dev (Note order)

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

Using Axios GET with Authorization Header in React-Native App

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

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

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



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



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

System.Drawing.Image to stream C#

Try the following:

public static Stream ToStream(this Image image, ImageFormat format) {
  var stream = new System.IO.MemoryStream();
  image.Save(stream, format);
  stream.Position = 0;
  return stream;
}

Then you can use the following:

var stream = myImage.ToStream(ImageFormat.Gif);

Replace GIF with whatever format is appropriate for your scenario.

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.

<system.webServer>
    <defaultDocument>
        <files>
            <add value="myDefault.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>

Count the number of commits on a Git branch

It might require a relatively recent version of Git, but this works well for me:

git rev-list --count develop..HEAD

This gives me an exact count of commits in the current branch having its base on master.

The command in Peter's answer, git rev-list --count HEAD ^develop includes many more commits, 678 vs 97 on my current project.

My commit history is linear on this branch, so YMMV, but it gives me the exact answer I wanted, which is "How many commits have I added so far on this feature branch?".

Link to add to Google calendar

There is a comprehensive doc for google calendar and other calendar services: https://github.com/InteractionDesignFoundation/add-event-to-calendar-docs/blob/master/services/google.md

An example of working link: https://calendar.google.com/calendar/render?action=TEMPLATE&text=Bithday&dates=20201231T193000Z/20201231T223000Z&details=With%20clowns%20and%20stuff&location=North%20Pole

PUT and POST getting 405 Method Not Allowed Error for Restful Web Services

Notice Allowed methods in the response

Connection: close
Date: Tue, 11 Feb 2014 15:17:24 GMT 
Content-Length: 34 
Content-Type: text/html 
Allow: GET, DELETE 
X-Powered-By: Servlet/2.5 JSP/2.1

It accepts only GET and DELETE. Hence, you need to tweak the server to enable PUT and POST as well.

Allow: GET, DELETE

Chrome extension id - how to find it

Use the chrome.runtime.id property from the chrome.runtime API.

Perl read line by line

With these types of complex programs, it's better to let Perl generate the Perl code for you:

$ perl -MO=Deparse -pe'exit if $.>2'

Which will gladly tell you the answer,

LINE: while (defined($_ = <ARGV>)) {
    exit if $. > 2;
}
continue {
    die "-p destination: $!\n" unless print $_;
}

Alternatively, you can simply run it as such from the command line,

$ perl -pe'exit if$.>2' file.txt

Developing C# on Linux

This is an old question but it has a high view count, so I think some new information should be added: In the mean time a lot has changed, and you can now also use Microsoft's own .NET Core on linux. It's also available in ARM builds, 32 and 64 bit.

How to stop process from .BAT file?

Here is how to kill one or more process from a .bat file.

Step 1. Open a preferred text editor and create a new file.

step 2. To kill one process use the 'taskkill' command, with the '/im' parameter that specifies the image name of the process to be terminated. Example:

taskkill /im examplename.exe

To 'force' kill a process use the '/f' parameter which specifies that processes be forcefully terminated. Example:

taskkill /f /im somecorporateprocess.exe

To kill more than one process you rinse and repeat the first part of step 2. Example:

taskkill /im examplename.exe
taskkill /im examplename1.exe
taskkill /im examplename2.exe

or

taskkill /f /im examplename.exe
taskkill /f /im examplename1.exe
taskkill /f /im examplename2.exe

step 3. Save your file to desired location with the .bat extension.

step 4. click newly created bat file to run it.

pip install - locale.Error: unsupported locale setting

[This answer is target on linux platform only]

The first thing you should know is most of the locale config file located path can be get from localedef --help :

$ localedef --help | tail -n 5
System's directory for character maps : /usr/share/i18n/charmaps
                       repertoire maps: /usr/share/i18n/repertoiremaps
                       locale path    : /usr/lib/locale:/usr/share/i18n
For bug reporting instructions, please see:
<https://bugs.launchpad.net/ubuntu/+source/glibc/+bugs>

See the last /usr/share/i18n ? This is where your xx_XX.UTF-8 config file located:

$ ls /usr/share/i18n/locales/zh_*
/usr/share/i18n/locales/zh_CN  /usr/share/i18n/locales/zh_HK  /usr/share/i18n/locales/zh_SG  /usr/share/i18n/locales/zh_TW

Now what ? We need to compile them into archive binary. One of the way, e.g. assume I have /usr/share/i18n/locales/en_LOVE, I can add it into compile list, i.e. /etc/locale-gen file:

$ tail -1 /etc/locale.gen 
en_LOVE.UTF-8 UTF-8

And compile it to binary with sudo locale-gen:

$ sudo locale-gen 
Generating locales (this might take a while)...
  en_AG.UTF-8... done
  en_AU.UTF-8... done
  en_BW.UTF-8... done
  ...
  en_LOVE.UTF-8... done
Generation complete.

And now update the system default locale with desired LANG, LC_ALL ...etc with this update-locale:

sudo update-locale LANG=en_LOVE.UTF-8

update-locale actually also means to update this /etc/default/locale file which will source by system on login to setup environment variables:

$ head /etc/default/locale 
#  File generated by update-locale
LANG=en_LOVE.UTF-8
LC_NUMERIC="en_US.UTF-8"
...

But we may not want to reboot to take effect, so we can just source it to environment variable in current shell session:

$ . /etc/default/locale

How about sudo dpkg-reconfigure locales ? If you play around it you will know this command basically act as GUI to simplify the above steps, i.e. Edit /etc/locale.gen -> sudo locale-gen -> sudo update-locale LANG=en_LOVE.UTF-8

For python, as long as /etc/locale.gen contains that locale candidate and locale.gen get compiled, setlocale(category, locale) should work without throws locale.Error: unsupoorted locale setting. You can check the correct string en_US.UTF-8/en_US/....etc to be set in setlocale(), by observing /etc/locale.gen file, and then uncomment and compile it as desired. zh_CN GB2312 without dot in that file means the correct string is zh_CN and zh_CN.GB2312.

How to stop mongo DB in one command

mongod --dbpath /path/to/your/db --shutdown

More info at official: http://docs.mongodb.org/manual/tutorial/manage-mongodb-processes/

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

If you already have MinGW installed in Windows 7, just simply do the following:

  1. Make another copy of C:\MinGW\bin\mingw32-make.exe file in the same folder.
  2. Rename the file name from mingw32-make.exe to make.exe.
  3. Run make command again.

Tested working in my laptop for above steps.

Please add a @Pipe/@Directive/@Component annotation. Error

You get this error when you wrongly add shared service to "declaration" in your appmodules instead of adding it to "provider".

How can I make my website's background transparent without making the content (images & text) transparent too?

I would agree with @evillinux, It would be best to make your background image semi transparent so it supports < ie8

The other suggestions of using another div are also a great option, and it's the way to go if you want to do this in css. For example if the site had such features as selecting your own background color. I would suggest using a filter for older IE. eg:

filter:Alpha(opacity=50)

Scale iFrame css width 100% like an image

I like this solution best. Simple, scalable, responsive. The idea here is to create a zero-height outer div with bottom padding set to the aspect ratio of the video. The iframe is scaled to 100% in both width and height, completely filling the outer container. The outer container automatically adjusts its height according to its width, and the iframe inside adjusts itself accordingly.

<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
    <iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
        src="http://www.youtube.com/embed/RksyMaJiD8Y">
    </iframe>
</div>

The only variable here is the padding-bottom value in the outer div. It's 75% for 4:3 aspect ratio videos, and 56.25% for widescreen 16:9 aspect ratio videos.

PHP: Update multiple MySQL fields in single query

If you are using pdo, it will look like

$sql = "UPDATE users SET firstname = :firstname, lastname = :lastname WHERE id= :id";
$query = $this->pdo->prepare($sql);
$result = $query->execute(array(':firstname' => $firstname, ':lastname' => $lastname, ':id' => $id));

CSS text-align: center; is not centering things

You can use flex-grow: 1. The default value is 0 and it will cause the text-align: center looks like left.

https://css-tricks.com/almanac/properties/f/flex-grow/

how to use math.pi in java

Here is usage of Math.PI to find circumference of circle and Area First we take Radius as a string in Message Box and convert it into integer

public class circle {

    public static void main(String[] args) {
        // TODO code application logic here

        String rad;

        float radius,area,circum;

       rad = JOptionPane.showInputDialog("Enter the Radius of circle:");

        radius = Integer.parseInt(rad);
        area = (float) (Math.PI*radius*radius);
        circum = (float) (2*Math.PI*radius);

        JOptionPane.showMessageDialog(null, "Area: " + area,"AREA",JOptionPane.INFORMATION_MESSAGE);
        JOptionPane.showMessageDialog(null, "circumference: " + circum, "Circumfernce",JOptionPane.INFORMATION_MESSAGE);
    }

}

How to give the background-image path in CSS?

There are two basic ways:

url(../../images/image.png)

or

url(/Web/images/image.png)

I prefer the latter, as it's easier to work with and works from all locations in the site (so useful for inline image paths too).

Mind you, I wouldn't do so much deep nesting of folders. It seems unnecessary and makes life a bit difficult, as you've found.

if block inside echo statement?

In sake of readability it should be something like

<?php 
  $countries = $myaddress->get_countries();
  foreach($countries as $value) {
    $selected ='';
    if($value=='United States') $selected ='selected="selected"'; 
    echo '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
  }
?>

desire to stuff EVERYTHING in a single line is a decease, man. Write distinctly.

But there is another way, a better one. There is no need to use echo at all. Learn to use templates. Prepare your data first, and display it only then ready.

Business logic part:

$countries = $myaddress->get_countries();
$selected_country = 1;    

Template part:

<? foreach($countries as $row): ?>
<option value="<?=$row['id']?>"<? if ($row['id']==$current_country):> "selected"><? endif ?>
  <?=$row['name']?>
</option>
<? endforeach ?>

Where are environment variables stored in the Windows Registry?

There is a more efficient way of doing this in Windows 7. SETX is installed by default and supports connecting to other systems.

To modify a remote system's global environment variables, you would use

setx /m /s HOSTNAME-GOES-HERE VariableNameGoesHere VariableValueGoesHere

This does not require restarting Windows Explorer.

psql: FATAL: Peer authentication failed for user "dev"

In my case I was using different port. Default is 5432. I was using 5433. This worked for me:

$ psql -f update_table.sql -d db_name -U db_user_name -h 127.0.0.1 -p 5433

SQL Server JOIN missing NULL values

Dirty and quick hack:

SELECT Table1.Col1, Table1.Col2, Table1.Col3, Table2.Col4
FROM Table1 INNER JOIN Table2 ON Table1.Col1 = Table2.Col1
 AND ((Table1.Col2 = Table2.Col2) OR (Table1.Col2 IS NULL AND Table2.Col2 IS NULL))

How correctly produce JSON by RESTful web service?

You can annotate your bean with jaxb annotations.

  @XmlRootElement
  public class MyJaxbBean {
    public String name;
    public int age;

    public MyJaxbBean() {} // JAXB needs this

    public MyJaxbBean(String name, int age) {
      this.name = name;
      this.age = age;
    }
  }

and then your method would look like this:

   @GET @Produces("application/json")
   public MyJaxbBean getMyBean() {
      return new MyJaxbBean("Agamemnon", 32);
   }

There is a chapter in the latest documentation that deals with this:

https://jersey.java.net/documentation/latest/user-guide.html#json

Re-enabling window.alert in Chrome

In Chrome Browser go to setting , clear browsing history and then reload the page

C# Encoding a text string with line breaks

Try this :

string myStr = ...
myStr = myStr.Replace("\n", Environment.NewLine)

Android Pop-up message

You can use Dialog to create this easily

create a Dialog instance using the context

Dialog dialog = new Dialog(contex);

You can design your layout as you like.

You can add this layout to your dialog by dialog.setContentView(R.layout.popupview);//popup view is the layout you created

then you can access its content (textviews, etc.) by using findViewById method

TextView txt = (TextView)dialog.findViewById(R.id.textbox);

you can add any text here. the text can be stored in the String.xml file in res\values.

txt.setText(getString(R.string.message));

then finally show the pop up menu

dialog.show();

more information http://developer.android.com/guide/topics/ui/dialogs.html

http://developer.android.com/reference/android/app/Dialog.html

Jenkins - Configure Jenkins to poll changes in SCM

I believe best practice these days is H/5 * * * *, which means every 5 minutes with a hashing factor to avoid all jobs starting at EXACTLY the same time.

Determine whether an array contains a value

Since ECMAScript6, one can use Set:

var myArray = ['A', 'B', 'C'];
var mySet = new Set(myArray);
var hasB = mySet.has('B'); // true
var hasZ = mySet.has('Z'); // false

Why is 22 the default port number for SFTP?

Not authoritative, but interesting: 21 is FTP, 23 is telnet. 22 is SSH...something in between (that can take the place of both).

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

Use string in switch case in java

Not very pretty but here is another way:

String runFct = 
        queryType.equals("eq") ? "method1":
        queryType.equals("L_L")? "method2":
        queryType.equals("L_R")? "method3":
        queryType.equals("L_LR")? "method4":
            "method5";
Method m = this.getClass().getMethod(runFct);
m.invoke(this);

How to vertically align a html radio button to it's label?

Try this:

input[type="radio"] {
  margin-top: -1px;
  vertical-align: middle;
}

How to convert JSON to CSV format and store in a variable

A more elegant way to convert json to csv is to use the map function without any framework:

var json = json3.items
var fields = Object.keys(json[0])
var replacer = function(key, value) { return value === null ? '' : value } 
var csv = json.map(function(row){
  return fields.map(function(fieldName){
    return JSON.stringify(row[fieldName], replacer)
  }).join(',')
})
csv.unshift(fields.join(',')) // add header column
 csv = csv.join('\r\n');
console.log(csv)

Output:

title,description,link,timestamp,image,embed,language,user,user_image,user_link,user_id,geo,source,favicon,type,domain,id
"Apple iPhone 4S Sale Cancelled in Beijing Amid Chaos (Design You Trust)","Advertise here with BSA Apple cancelled its scheduled sale of iPhone 4S in one of its stores in China’s capital Beijing on January 13. Crowds outside the store in the Sanlitun district were waiting on queues overnight. There were incidents of scuffle between shoppers and the store’s security staff when shoppers, hundreds of them, were told that the sales [...]Source : Design You TrustExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309201303","1326439500","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","2388575404943858468"
"Apple to halt sales of iPhone 4S in China (Fame Dubai Blog)","SHANGHAI – Apple Inc said on Friday it will stop selling its latest iPhone in its retail stores in Beijing and Shanghai to ensure the safety of its customers and employees. Go to SourceSource : Fame Dubai BlogExplore : iPhone, iPhone 4, Phone","http://wik.io/info/US/309198933","1326439320","","","","","","","","","wikio","http://wikio.com/favicon.ico","blogs","wik.io","16209851193593872066"

Update ES6 (2016)

Use this less dense syntax and also JSON.stringify to add quotes to strings while keeping numbers unquoted:

const items = json3.items
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
const header = Object.keys(items[0])
const csv = [
  header.join(','), // header row first
  ...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')

console.log(csv)

How to format current time using a yyyyMMddHHmmss format?

import("time")

layout := "2006-01-02T15:04:05.000Z"
str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(layout, str)
if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

gives:

>> 2014-11-12 11:45:26.371 +0000 UTC

How can you get the Manifest Version number from the App's (Layout) XML variables?

Easiest solution is to use BuildConfig.

I use BuildConfig.VERSION_NAME in my application.

You can also use BuildConfig.VERSION_CODE to get version code.

CSS Select box arrow style

Please follow the way like below:

_x000D_
_x000D_
.selectParent {_x000D_
 width:120px;_x000D_
 overflow:hidden;   _x000D_
}_x000D_
.selectParent select { _x000D_
 display: block;_x000D_
 width: 100%;_x000D_
 padding: 2px 25px 2px 2px; _x000D_
 border: none; _x000D_
 background: url("http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png") right center no-repeat; _x000D_
 appearance: none; _x000D_
 -webkit-appearance: none;_x000D_
 -moz-appearance: none; _x000D_
}_x000D_
.selectParent.left select {_x000D_
 direction: rtl;_x000D_
 padding: 2px 2px 2px 25px;_x000D_
 background-position: left center;_x000D_
}_x000D_
/* for IE and Edge */ _x000D_
select::-ms-expand { _x000D_
 display: none; _x000D_
}
_x000D_
<div class="selectParent">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>_x000D_
<br />_x000D_
<div class="selectParent left">_x000D_
  <select>_x000D_
    <option value="1">Option 1</option>_x000D_
    <option value="2">Option 2</option>           _x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to restrict user to type 10 digit numbers in input element?

$(document).on('keypress','#typeyourid',function(e){
if($(e.target).prop('value').length>=10){
if(e.keyCode!=32)
{return false} 
}})

Advantage is this works with type="number"

Uncaught (in promise) TypeError: Failed to fetch and Cors error

Adding mode:'no-cors' to the request header guarantees that no response will be available in the response

Adding a "non standard" header, line 'access-control-allow-origin' will trigger a OPTIONS preflight request, which your server must handle correctly in order for the POST request to even be sent

You're also doing fetch wrong ... fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type...

In short, if your server side handles CORS correctly (which from your comment suggests it does) the following should work

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.json();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = JSON.stringify(muutuja);
    });
}

however, since your code isn't really interested in JSON (it stringifies the object after all) - it's simpler to do

function send(){
    var myVar = {"id" : 1};
    console.log("tuleb siia", document.getElementById('saada').value);
    fetch("http://localhost:3000", {
        method: "POST",
        headers: {
            "Content-Type": "text/plain"
        },
        body: JSON.stringify(myVar)
    }).then(function(response) {
        return response.text();
    }).then(function(muutuja){
        document.getElementById('väljund').innerHTML = muutuja;
    });
}

Android and Facebook share intent

Facebook does not allow to share plain text data with Intent.EXTRA_TEXT but You can share text+link with facebook messanger using this, this works fine for me

            Intent sendIntent = new Intent();
            sendIntent.setAction(Intent.ACTION_SEND);
            sendIntent.putExtra(Intent.EXTRA_TEXT, text+url link);
            sendIntent.setType("text/plain");
            sendIntent.setPackage("com.facebook.orca");
            startActivity(sendIntent);

Call php function from JavaScript

I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php

Simple example usage:

// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25

// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]

Show Curl POST Request Headers? Is there a way to do this?

You can make you request headers by yourself using:

// open a socket connection on port 80
$fp = fsockopen($host, 80);

// send the request headers:
fputs($fp, "POST $path HTTP/1.1\r\n");
fputs($fp, "Host: $host\r\n");
fputs($fp, "Referer: $referer\r\n");
fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

$result = ''; 
while(!feof($fp)) {
    // receive the results of the request
    $result .= fgets($fp, 128);
}

// close the socket connection:
fclose($fp);

Like writen on how make request

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

"<pre>" is an HTML tag. If you insert this line of code in your program

echo "<pre>";

then you will enable the viewing of multiple spaces and line endings. Without this, all \n, \r and other end line characters wouldn't have any effect in the browser and wherever you had more than 1 space in the code, the output would be shortened to only 1 space. That's the default HTML. In that case only with <br> you would be able to break the line and go to the next one.

For example,

the code below would be displayed on multiple lines, due to \n line ending specifier.

<?php
    echo "<pre>";
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>

However the following code, would be displayed in one line only (line endings are disregarded).

<?php
    printf("<span style='color:#%X%X%X'>Hello</span>\n", 65, 127, 245);
    printf("Goodbye");
?>

Appending values to dictionary in Python

If you want to append to the lists of each key inside a dictionary, you can append new values to them using + operator (tested in Python 3.7):

mydict = {'a':[], 'b':[]}
print(mydict)
mydict['a'] += [1,3]
mydict['b'] += [4,6]
print(mydict)
mydict['a'] += [2,8]
print(mydict)

and the output:

{'a': [], 'b': []}
{'a': [1, 3], 'b': [4, 6]}
{'a': [1, 3, 2, 8], 'b': [4, 6]}

mydict['a'].extend([1,3]) will do the job same as + without creating a new list (efficient way).

Removing underline with href attribute

Add a style with the attribute text-decoration:none;:

There are a number of different ways of doing this.

Inline style:

<a href="xxx.html" style="text-decoration:none;">goto this link</a>

Inline stylesheet:

<html>
<head>
<style type="text/css">
   a {
      text-decoration:none;
   }
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

External stylesheet:

<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>

stylesheet.css:

a {
      text-decoration:none;
   }

Python find elements in one list that are not in the other

Not sure why the above explanations are so complicated when you have native methods available:

main_list = list(set(list_2)-set(list_1))

Excel VBA, How to select rows based on data in a column?

The easiest way to do it is to use the End method, which is gives you the cell that you reach by pressing the end key and then a direction when you're on a cell (in this case B6). This won't give you what you expect if B6 or B7 is empty, though.

Dim start_cell As Range
Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Range(start_cell, start_cell.End(xlDown)).Copy Range("[Workbook2.xlsx]Sheet1!A2")

If you can't use End, then you would have to use a loop.

Dim start_cell As Range, end_cell As Range

Set start_cell = Range("[Workbook1.xlsx]Sheet1!B6")
Set end_cell = start_cell

Do Until IsEmpty(end_cell.Offset(1, 0))
    Set end_cell = end_cell.Offset(1, 0)
Loop

Range(start_cell, end_cell).Copy Range("[Workbook2.xlsx]Sheet1!A2")

How to get label text value form a html page?

For cases where the data element is inside the label like in this example:

<label for="subscription">Subscription period
    <select id='subscription' name='subscription'>
        <option></option>
        <option>1 year</option>
        <option>2 years</option>
        <option>3 years</option>
    </select>
</label>

all the previous answers will give an unexpected result:

"Subscription period


                    1 year
                    2 years
                    3 years

            "

While the expected result would be:

"Subscription period"

So, the correct solution will be like this:

const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
    .call(label.childNodes, x => x.nodeName === "#text")
    .map(x => x.textContent)
    .join(" ")
    .trim();

Repeat command automatically in Linux

If you want to avoid "drifting", meaning you want the command to execute every N seconds regardless of how long the command takes (assuming it takes less than N seconds), here's some bash that will repeat a command every 5 seconds with one-second accuracy (and will print out a warning if it can't keep up):

PERIOD=5

while [ 1 ]
do
    let lastup=`date +%s`
    # do command
    let diff=`date +%s`-$lastup
    if [ "$diff" -lt "$PERIOD" ]
    then
        sleep $(($PERIOD-$diff))
    elif [ "$diff" -gt "$PERIOD" ]
    then
        echo "Command took longer than iteration period of $PERIOD seconds!"
    fi
done

It may still drift a little since the sleep is only accurate to one second. You could improve this accuracy by creative use of the date command.

How can I get the full/absolute URL (with domain) in Django?

I came across this thread because I was looking to build an absolute URI for a success page. request.build_absolute_uri() gave me a URI for my current view but to get the URI for my success view I used the following....

request.build_absolute_uri(reverse('success_view_name'))

How to get the return value from a thread in python?

I'm using this wrapper, which comfortably turns any function for running in a Thread - taking care of its return value or exception. It doesn't add Queue overhead.

def threading_func(f):
    """Decorator for running a function in a thread and handling its return
    value or exception"""
    def start(*args, **kw):
        def run():
            try:
                th.ret = f(*args, **kw)
            except:
                th.exc = sys.exc_info()
        def get(timeout=None):
            th.join(timeout)
            if th.exc:
                raise th.exc[0], th.exc[1], th.exc[2] # py2
                ##raise th.exc[1] #py3                
            return th.ret
        th = threading.Thread(None, run)
        th.exc = None
        th.get = get
        th.start()
        return th
    return start

Usage Examples

def f(x):
    return 2.5 * x
th = threading_func(f)(4)
print("still running?:", th.is_alive())
print("result:", th.get(timeout=1.0))

@threading_func
def th_mul(a, b):
    return a * b
th = th_mul("text", 2.5)

try:
    print(th.get())
except TypeError:
    print("exception thrown ok.")

Notes on threading module

Comfortable return value & exception handling of a threaded function is a frequent "Pythonic" need and should indeed already be offered by the threading module - possibly directly in the standard Thread class. ThreadPool has way too much overhead for simple tasks - 3 managing threads, lots of bureaucracy. Unfortunately Thread's layout was copied from Java originally - which you see e.g. from the still useless 1st (!) constructor parameter group.

How do I work with dynamic multi-dimensional arrays in C?

Since C99, C has 2D arrays with dynamical bounds. If you want to avoid that such beast are allocated on the stack (which you should), you can allocate them easily in one go as the following

double (*A)[n] = malloc(sizeof(double[n][n]));

and that's it. You can then easily use it as you are used for 2D arrays with something like A[i][j]. And don't forget that one at the end

free(A);

Randy Meyers wrote series of articles explaining variable length arrays (VLAs).

Append data to a POST NSURLRequest

The previous posts about forming POST requests are largely correct (add the parameters to the body, not the URL). But if there is any chance of the input data containing any reserved characters (e.g. spaces, ampersand, plus sign), then you will want to handle these reserved characters. Namely, you should percent-escape the input.

//create body of the request

NSString *userid = ...
NSString *encodedUserid = [self percentEscapeString:userid];
NSString *postString    = [NSString stringWithFormat:@"userid=%@", encodedUserid];
NSData   *postBody      = [postString dataUsingEncoding:NSUTF8StringEncoding];

//initialize a request from url

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPBody:postBody];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

//initialize a connection from request, any way you want to, e.g.

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

Where the precentEscapeString method is defined as follows:

- (NSString *)percentEscapeString:(NSString *)string
{
    NSString *result = CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                                                 (CFStringRef)string,
                                                                                 (CFStringRef)@" ",
                                                                                 (CFStringRef)@":/?@!$&'()*+,;=",
                                                                                 kCFStringEncodingUTF8));
    return [result stringByReplacingOccurrencesOfString:@" " withString:@"+"];
}

Note, there was a promising NSString method, stringByAddingPercentEscapesUsingEncoding (now deprecated), that does something very similar, but resist the temptation to use that. It handles some characters (e.g. the space character), but not some of the others (e.g. the + or & characters).

The contemporary equivalent is stringByAddingPercentEncodingWithAllowedCharacters, but, again, don't be tempted to use URLQueryAllowedCharacterSet, as that also allows + and & pass unescaped. Those two characters are permitted within the broader "query", but if those characters appear within a value within a query, they must escaped. Technically, you can either use URLQueryAllowedCharacterSet to build a mutable character set and remove a few of the characters that they've included in there, or build your own character set from scratch.

For example, if you look at Alamofire's parameter encoding, they take URLQueryAllowedCharacterSet and then remove generalDelimitersToEncode (which includes the characters #, [, ], and @, but because of a historical bug in some old web servers, neither ? nor /) and subDelimitersToEncode (i.e. !, $, &, ', (, ), *, +, ,, ;, and =). This is correct implementation (though you could debate the removal of ? and /), though pretty convoluted. Perhaps CFURLCreateStringByAddingPercentEscapes is more direct/efficient.

How do I change a single value in a data.frame?

To change a cell value using a column name, one can use

iris$Sepal.Length[3]=999

jQuery .each() with input elements

$.each($('input[type=number]'),function(){
  alert($(this).val());
});

This will alert the value of input type number fields

Demo is present at http://jsfiddle.net/2dJAN/33/

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

Can I create view with parameter in MySQL?

I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.

EDIT (Copied up from comments)

create a table that contains a column called connection_id (make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id. replace into the parameter table and use CONNECTION_ID() to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID(). This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id.

What is "Signal 15 received"

This indicates the linux has delivered a SIGTERM to your process. This is usually at the request of some other process (via kill()) but could also be sent by your process to itself (using raise()). This signal requests an orderly shutdown of your process.

If you need a quick cheatsheet of signal numbers, open a bash shell and:

$ kill -l
 1) SIGHUP   2) SIGINT   3) SIGQUIT  4) SIGILL
 5) SIGTRAP  6) SIGABRT  7) SIGBUS   8) SIGFPE
 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG  24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM   27) SIGPROF 28) SIGWINCH
29) SIGIO   30) SIGPWR  31) SIGSYS  34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX    

You can determine the sender by using an appropriate signal handler like:

#include <signal.h>
#include <stdio.h>
#include <stdlib.h>

void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
  fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
      info->si_pid);
  exit(0);
}

int main (void)
{
  struct sigaction action = {
    .sa_handler = NULL,
    .sa_sigaction = sigterm_handler,
    .sa_mask = 0,
    .sa_flags = SA_SIGINFO,
    .sa_restorer = NULL
  };

  sigaction(SIGTERM, &action, NULL);
  sleep(60);

  return 0;
}

Notice that the signal handler also includes a call to exit(). It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).

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

Scrolling with animation:

Your DIV:

<div class='messageScrollArea' style='height: 100px;overflow: auto;'>
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
      Hello World! Hello World! Hello World! Hello World! Hello World! Hello
</div>

jQuery part:

jQuery(document).ready(function(){       
    var $t = $('.messageScrollArea');
    $t.animate({"scrollTop": $('.messageScrollArea')[0].scrollHeight}, "slow");
});

?http://jsfiddle.net/3Wx3U/

Android: install .apk programmatically

I solved the problem. I made mistake in setData(Uri) and setType(String).

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory() + "/download/" + "app.apk")), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

That is correct now, my auto-update is working. Thanks for help. =)

Edit 20.7.2016:

After a long time, I had to use this way of updating again in another project. I encountered a number of problems with old solution. A lot of things have changed in that time, so I had to do this with a different approach. Here is the code:

    //get destination to update file and set Uri
    //TODO: First I wanted to store my update .apk file on internal storage for my app but apparently android does not allow you to open and install
    //aplication with existing package from there. So for me, alternative solution is Download directory in external storage. If there is better
    //solution, please inform us in comment
    String destination = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/";
    String fileName = "AppName.apk";
    destination += fileName;
    final Uri uri = Uri.parse("file://" + destination);

    //Delete update file if exists
    File file = new File(destination);
    if (file.exists())
    //file.delete() - test this, I think sometimes it doesnt work
        file.delete();

    //get url of app on server
    String url = Main.this.getString(R.string.update_app_url);

    //set downloadmanager
    DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
    request.setDescription(Main.this.getString(R.string.notification_description));
    request.setTitle(Main.this.getString(R.string.app_name));

    //set destination
    request.setDestinationUri(uri);

    // get download service and enqueue file
    final DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
    final long downloadId = manager.enqueue(request);

    //set BroadcastReceiver to install app when .apk is downloaded
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        public void onReceive(Context ctxt, Intent intent) {
            Intent install = new Intent(Intent.ACTION_VIEW);
            install.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            install.setDataAndType(uri,
                    manager.getMimeTypeForDownloadedFile(downloadId));
            startActivity(install);

            unregisterReceiver(this);
            finish();
        }
    };
    //register receiver for when .apk download is compete
    registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

How to compare pointers?

To sum up. If we want to see if two pointers point to the same memory location we can do that. Also if we want to compare the contents of the memory pointed to by two pointers we can do that too, just remeber to dereference them first.

If we have

int *a = something; 
int *b = something;

which are two pointers of the same type we can:

Compare memory address:

a==b

and compare contents:

*a==*b

How do I save JSON to local text file

Node.js:

var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
    if (err) {
        console.log(err);
    }
});

Browser (webapi):

function download(content, fileName, contentType) {
    var a = document.createElement("a");
    var file = new Blob([content], {type: contentType});
    a.href = URL.createObjectURL(file);
    a.download = fileName;
    a.click();
}
download(jsonData, 'json.txt', 'text/plain');

GlobalConfiguration.Configure() not present after Web API 2 and .NET 4.5.1 migration

None of these ideas helped my project using MVC 5.2.2.

  • System.web.Http 5.2.2 was already installed
  • Deleting the Packages folder and completely re-downloading all NuGet libraries did nothing
  • Web.config already had a dependentAssembly entry for System.Web.Http

Forcing a reinstall corrected the problem. From the NuGet package manager console:

update-Package -reinstall Microsoft.AspNet.WebApi.WebHost

View a file in a different Git branch without changing branches

This should work:

git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use

git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

UPDATE 2015-01-19:

Nowadays you can use relative paths with git show a1b35:./file.txt.

How to determine the current language of a wordpress page when using polylang?

I use something like this:

<?php 

$lang = get_bloginfo("language"); 

if ($lang == 'fr-FR') : ?>

   <p>Bienvenue!</p>

<?php endif; ?>

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

remove {{}} braces around foo.bar because angular expressions cannot be used in angular directives.

For More: https://docs.angularjs.org/api/ng/directive/ngShow

example

  <body ng-app="changeExample">
    <div ng-controller="ExampleController">
    <p ng-show="foo.bar">I could be shown, or I could be hidden</p>
    <p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
    </div>
    </body>

<script>
     angular.module('changeExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.foo ={};
          $scope.foo.bar = true;
        }]);
</script>

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

What is the significance of load factor in HashMap?

If the buckets get too full, then we have to look through

a very long linked list.

And that's kind of defeating the point.

So here's an example where I have four buckets.

I have elephant and badger in my HashSet so far.

This is a pretty good situation, right?

Each element has zero or one elements.

Now we put two more elements into our HashSet.

     buckets      elements
      -------      -------
        0          elephant
        1          otter
         2          badger
         3           cat

This isn't too bad either.

Every bucket only has one element . So if I wanna know, does this contain panda?

I can very quickly look at bucket number 1 and it's not

there and

I known it's not in our collection.

If I wanna know if it contains cat, I look at bucket

number 3,

I find cat, I very quickly know if it's in our

collection.

What if I add koala, well that's not so bad.

             buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala 
         2          badger
         3           cat

Maybe now instead of in bucket number 1 only looking at

one element,

I need to look at two.

But at least I don't have to look at elephant, badger and

cat.

If I'm again looking for panda, it can only be in bucket

number 1 and

I don't have to look at anything other then otter and

koala.

But now I put alligator in bucket number 1 and you can

see maybe where this is going.

That if bucket number 1 keeps getting bigger and bigger and

bigger, then I'm basically having to look through all of

those elements to find

something that should be in bucket number 1.

            buckets      elements
      -------      -------
        0          elephant
        1          otter -> koala ->alligator
         2          badger
         3           cat

If I start adding strings to other buckets,

right, the problem just gets bigger and bigger in every

single bucket.

How do we stop our buckets from getting too full?

The solution here is that

          "the HashSet can automatically

        resize the number of buckets."

There's the HashSet realizes that the buckets are getting

too full.

It's losing this advantage of this all of one lookup for

elements.

And it'll just create more buckets(generally twice as before) and

then place the elements into the correct bucket.

So here's our basic HashSet implementation with separate

chaining. Now I'm going to create a "self-resizing HashSet".

This HashSet is going to realize that the buckets are

getting too full and

it needs more buckets.

loadFactor is another field in our HashSet class.

loadFactor represents the average number of elements per

bucket,

above which we want to resize.

loadFactor is a balance between space and time.

If the buckets get too full then we'll resize.

That takes time, of course, but

it may save us time down the road if the buckets are a

little more empty.

Let's see an example.

Here's a HashSet, we've added four elements so far.

Elephant, dog, cat and fish.

          buckets      elements
      -------      -------
        0          
        1          elephant
         2          cat ->dog
         3           fish
          4         
           5

At this point, I've decided that the loadFactor, the

threshold,

the average number of elements per bucket that I'm okay

with, is 0.75.

The number of buckets is buckets.length, which is 6, and

at this point our HashSet has four elements, so the

current size is 4.

We'll resize our HashSet, that is we'll add more buckets,

when the average number of elements per bucket exceeds

the loadFactor.

That is when current size divided by buckets.length is

greater than loadFactor.

At this point, the average number of elements per bucket

is 4 divided by 6.

4 elements, 6 buckets, that's 0.67.

That's less than the threshold I set of 0.75 so we're

okay.

We don't need to resize.

But now let's say we add woodchuck.

                  buckets      elements
      -------      -------
        0          
        1          elephant
         2        woodchuck-> cat ->dog
         3           fish
          4         
           5

Woodchuck would end up in bucket number 3.

At this point, the currentSize is 5.

And now the average number of elements per bucket

is the currentSize divided by buckets.length.

That's 5 elements divided by 6 buckets is 0.83.

And this exceeds the loadFactor which was 0.75.

In order to address this problem, in order to make the

buckets perhaps a little

more empty so that operations like determining whether a

bucket contains

an element will be a little less complex, I wanna resize

my HashSet.

Resizing the HashSet takes two steps.

First I'll double the number of buckets, I had 6 buckets,

now I'm going to have 12 buckets.

Note here that the loadFactor which I set to 0.75 stays the same.

But the number of buckets changed is 12,

the number of elements stayed the same, is 5.

5 divided by 12 is around 0.42, that's well under our

loadFactor,

so we're okay now.

But we're not done because some of these elements are in

the wrong bucket now.

For instance, elephant.

Elephant was in bucket number 2 because the number of

characters in elephant

was 8.

We have 6 buckets, 8 minus 6 is 2.

That's why it ended up in number 2.

But now that we have 12 buckets, 8 mod 12 is 8, so

elephant does not belong in bucket number 2 anymore.

Elephant belongs in bucket number 8.

What about woodchuck?

Woodchuck was the one that started this whole problem.

Woodchuck ended up in bucket number 3.

Because 9 mod 6 is 3.

But now we do 9 mod 12.

9 mod 12 is 9, woodchuck goes to bucket number 9.

And you see the advantage of all this.

Now bucket number 3 only has two elements whereas before it had 3.

So here's our code,

where we had our HashSet with separate chaining that

didn't do any resizing.

Now, here's a new implementation where we use resizing.

Most of this code is the same,

we're still going to determine whether it contains the

value already.

If it doesn't, then we'll figure it out which bucket it

should go into and

then add it to that bucket, add it to that LinkedList.

But now we increment the currentSize field.

currentSize was the field that kept track of the number

of elements in our HashSet.

We're going to increment it and then we're going to look

at the average load,

the average number of elements per bucket.

We'll do that division down here.

We have to do a little bit of casting here to make sure

that we get a double.

And then, we'll compare that average load to the field

that I've set as

0.75 when I created this HashSet, for instance, which was

the loadFactor.

If the average load is greater than the loadFactor,

that means there's too many elements per bucket on

average, and I need to reinsert.

So here's our implementation of the method to reinsert

all the elements.

First, I'll create a local variable called oldBuckets.

Which is referring to the buckets as they currently stand

before I start resizing everything.

Note I'm not creating a new array of linked lists just yet.

I'm just renaming buckets as oldBuckets.

Now remember buckets was a field in our class, I'm going

to now create a new array

of linked lists but this will have twice as many elements

as it did the first time.

Now I need to actually do the reinserting,

I'm going to iterate through all of the old buckets.

Each element in oldBuckets is a LinkedList of strings

that is a bucket.

I'll go through that bucket and get each element in that

bucket.

And now I'm gonna reinsert it into the newBuckets.

I will get its hashCode.

I will figure out which index it is.

And now I get the new bucket, the new LinkedList of

strings and

I'll add it to that new bucket.

So to recap, HashSets as we've seen are arrays of Linked

Lists, or buckets.

A self resizing HashSet can realize using some ratio or

Confirm deletion using Bootstrap 3 modal box

You need the modal in your HTML. When the delete button is clicked it popup the modal. It's also important to prevent the click of that button from submitting the form. When the confirmation is clicked the form will submit.

_x000D_
_x000D_
   _x000D_
_x000D_
 $('button[name="remove_levels"]').on('click', function(e) {_x000D_
      var $form = $(this).closest('form');_x000D_
      e.preventDefault();_x000D_
      $('#confirm').modal({_x000D_
          backdrop: 'static',_x000D_
          keyboard: false_x000D_
      })_x000D_
      .on('click', '#delete', function(e) {_x000D_
          $form.trigger('submit');_x000D_
        });_x000D_
      $("#cancel").on('click',function(e){_x000D_
       e.preventDefault();_x000D_
       $('#confirm').modal.model('hide');_x000D_
      });_x000D_
    });
_x000D_
<link href="http://getbootstrap.com/2.3.2/assets/css/bootstrap.css" rel="stylesheet" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://getbootstrap.com/2.3.2/assets/js/bootstrap.js"></script>_x000D_
<form action="#" method="POST">_x000D_
  <button class='btn btn-danger btn-xs' type="submit" name="remove_levels" value="delete"><span class="fa fa-times"></span> delete</button>_x000D_
</form>_x000D_
_x000D_
<div id="confirm" class="modal">_x000D_
  <div class="modal-body">_x000D_
    Are you sure?_x000D_
  </div>_x000D_
  <div class="modal-footer">_x000D_
    <button type="button" data-dismiss="modal" class="btn btn-primary" id="delete">Delete</button>_x000D_
    <button type="button" data-dismiss="modal" class="btn">Cancel</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a performance difference between a for loop and a for-each loop?

All these loops do the exact same, I just want to show these before throwing in my two cents.

First, the classic way of looping through List:

for (int i=0; i < strings.size(); i++) { /* do something using strings.get(i) */ }

Second, the preferred way since it's less error prone (how many times have YOU done the "oops, mixed the variables i and j in these loops within loops" thing?).

for (String s : strings) { /* do something using s */ }

Third, the micro-optimized for loop:

int size = strings.size();
for (int i = -1; ++i < size;) { /* do something using strings.get(i) */ }

Now the actual two cents: At least when I was testing these, the third one was the fastest when counting milliseconds on how long it took for each type of loop with a simple operation in it repeated a few million times - this was using Java 5 with jre1.6u10 on Windows in case anyone is interested.

While it at least seems to be so that the third one is the fastest, you really should ask yourself if you want to take the risk of implementing this peephole optimization everywhere in your looping code since from what I've seen, actual looping isn't usually the most time consuming part of any real program (or maybe I'm just working on the wrong field, who knows). And also like I mentioned in the pretext for the Java for-each loop (some refer to it as Iterator loop and others as for-in loop) you are less likely to hit that one particular stupid bug when using it. And before debating how this even can even be faster than the other ones, remember that javac doesn't optimize bytecode at all (well, nearly at all anyway), it just compiles it.

If you're into micro-optimization though and/or your software uses lots of recursive loops and such then you may be interested in the third loop type. Just remember to benchmark your software well both before and after changing the for loops you have to this odd, micro-optimized one.

Set Response Status Code

I had the same issue with CakePHP 2.0.1

I tried using

header( 'HTTP/1.1 400 BAD REQUEST' );

and

$this->header( 'HTTP/1.1 400 BAD REQUEST' );

However, neither of these solved my issue.

I did eventually resolve it by using

$this->header( 'HTTP/1.1 400: BAD REQUEST' );

After that, no errors or warning from php / CakePHP.

*edit: In the last $this->header function call, I put a colon (:) between the 400 and the description text of the error.

When should you use 'friend' in C++?

Friend comes handy when you are building a container and you want to implement an iterator for that class.

Looking for a short & simple example of getters/setters in C#

This is a basic example of an object "Article" with getters and setters:

  public class Article
    {

        public String title;
        public String link;
        public String description;

        public string getTitle()
        {
            return title;
        }

        public void setTitle(string value)
        {
            title = value;
        }

        public string getLink()
        {
            return link;
        }

        public void setLink(string value)
        {
            link = value;
        }
        public string getDescription()
        {
            return description;
        }

        public void setDescription(string value)
        {
            description = value;
        }
    }

How to display a list of images in a ListView in Android?

Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.

In main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >

  <TextView
      android:id="@+id/textview"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />

 <ListView
     android:id="@+id/listview"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content" />

create listview_layout.xml and paste this code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

   <ImageView
      android:id="@+id/flag"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:contentDescription="@string/hello"
      android:paddingTop="10dp"
      android:paddingRight="10dp"
      android:paddingBottom="10dp" />

   <LinearLayout
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:orientation="vertical" >

     <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="15dp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/cur"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="10dp"
        android:text="TextView2" />
   </LinearLayout>

In your Activity

package com.test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class SimpleListImageActivity extends Activity {

    // Array of strings storing country names
    String[] countries = new String[] {
        "India",
        "Pakistan",
        "Sri Lanka",
        "China",
        "Bangladesh",
        "Nepal",
        "Afghanistan",
        "North Korea",
        "South Korea",
        "Japan"
    };

    // Array of integers points to images stored in /res/drawable-hdpi/

   //here you have to give image name which you already pasted it in /res/drawable-hdpi/

     int[] flags = new int[]{
        R.drawable.image1,
        R.drawable.image2,   
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    };

    // Array of strings to store currencies
    String[] currency = new String[]{
        "Indian Rupee",
        "Pakistani Rupee",
        "Sri Lankan Rupee",
        "Renminbi",
        "Bangladeshi Taka",
        "Nepalese Rupee",
        "Afghani",
        "North Korean Won",
        "South Korean Won",
        "Japanese Yen"
    };

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // Each row in the list stores country name, currency and flag
        List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();

        for(int i=0;i<10;i++){
            HashMap<String, String> hm = new HashMap<String,String>();
            hm.put("txt", "Country : " + countries[i]);
            hm.put("cur","Currency : " + currency[i]);
            hm.put("flag", Integer.toString(flags[i]) );
            aList.add(hm);
        }

        // Keys used in Hashmap
        String[] from = { "flag","txt","cur" };

        // Ids of views in listview_layout
        int[] to = { R.id.flag,R.id.txt,R.id.cur};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);

        // Getting a reference to listview of main.xml layout file
        ListView listView = ( ListView ) findViewById(R.id.listview);

        // Setting the adapter to the listView
        listView.setAdapter(adapter);
    }
}

This is the full code.you can make changes to your need... Comments are welcome

How to set python variables to true or false?

First to answer your question, you set a variable to true or false by assigning True or False to it:

myFirstVar = True
myOtherVar = False

If you have a condition that is basically like this though:

if <condition>:
    var = True
else:
    var = False

then it is much easier to simply assign the result of the condition directly:

var = <condition>

In your case:

match_var = a == b

Finding an element in an array in Java

There is a contains method for lists, so you should be able to do:

Arrays.asList(yourArray).contains(yourObject);

Warning: this might not do what you (or I) expect, see Tom's comment below.

Convert from ASCII string encoded in Hex to plain ASCII?

A slightly simpler solution:

>>> "7061756c".decode("hex")
'paul'

How to use Python requests to fake a browser visit a.k.a and generate User Agent?

Provide a User-Agent header:

import requests

url = 'http://www.ichangtou.com/#company:data_000008.html'
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}

response = requests.get(url, headers=headers)
print(response.content)

FYI, here is a list of User-Agent strings for different browsers:


As a side note, there is a pretty useful third-party package called fake-useragent that provides a nice abstraction layer over user agents:

fake-useragent

Up to date simple useragent faker with real world database

Demo:

>>> from fake_useragent import UserAgent
>>> ua = UserAgent()
>>> ua.chrome
u'Mozilla/5.0 (Windows NT 6.2; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1667.0 Safari/537.36'
>>> ua.random
u'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.67 Safari/537.36'

Get started with Latex on Linux

First you'll need to Install it:

  • If you're using a distro which packages LaTeX (almost all will do) then look for texlive or tetex. TeX Live is the newer of the two, and is replacing tetex on most distributions now.

If you're using Debian or Ubuntu, something like:

<code>apt-get install texlive</code>

..will get it installed.

RedHat or CentOS need:

<code>yum install tetex</code>

Note : This needs root permissions, so either use su to switch user to root, or prefix the commands with sudo, if you aren't already logged in as the root user.

Next you'll need to get a text editor. Any editor will do, so whatever you are comfortable with. You'll find that advanced editors like Emacs (and vim) add a lot of functionality and so will help with ensuring that your syntax is correct before you try and build your document output.

Create a file called test.tex and put some content in it, say the example from the LaTeX primer:

\documentclass[a4paper,12pt]{article}
\begin{document}

The foundations of the rigorous study of \emph{analysis}
were laid in the nineteenth century, notably by the
mathematicians Cauchy and Weierstrass. Central to the
study of this subject are the formal definitions of
\emph{limits} and \emph{continuity}.

Let $D$ be a subset of $\bf R$ and let
$f \colon D \to \mathbf{R}$ be a real-valued function on
$D$. The function $f$ is said to be \emph{continuous} on
$D$ if, for all $\epsilon > 0$ and for all $x \in D$,
there exists some $\delta > 0$ (which may depend on $x$)
such that if $y \in D$ satisfies
\[ |y - x| < \delta \]
then
\[ |f(y) - f(x)| < \epsilon. \]

One may readily verify that if $f$ and $g$ are continuous
functions on $D$ then the functions $f+g$, $f-g$ and
$f.g$ are continuous. If in addition $g$ is everywhere
non-zero then $f/g$ is continuous.

\end{document}

Once you've got this file you'll need to run latex on it to produce some output (as a .dvi file to start with, which is possible to convert to many other formats):

latex test.tex

This will print a bunch of output, something like this:

=> latex test.tex

This is pdfeTeX, Version 3.141592-1.21a-2.2 (Web2C 7.5.4)
entering extended mode
(./test.tex
LaTeX2e &lt;2003/12/01&gt;
Babel &lt;v3.8d&gt; and hyphenation patterns for american, french, german, ngerman, b
ahasa, basque, bulgarian, catalan, croatian, czech, danish, dutch, esperanto, e
stonian, finnish, greek, icelandic, irish, italian, latin, magyar, norsk, polis
h, portuges, romanian, russian, serbian, slovak, slovene, spanish, swedish, tur
kish, ukrainian, nohyphenation, loaded.
(/usr/share/texmf/tex/latex/base/article.cls
Document Class: article 2004/02/16 v1.4f Standard LaTeX document class
(/usr/share/texmf/tex/latex/base/size12.clo))
No file test.aux.
[1] (./test.aux) )
Output written on test.dvi (1 page, 1508 bytes).
Transcript written on test.log.

..don't worry about most of this output -- the important part is the Output written on test.dvi line, which says that it was successful.

Now you need to view the output file with xdvi:

xdvi test.dvi &

This will pop up a window with the beautifully formatted output in it. Hit `q' to quit this, or you can leave it open and it will automatically update when the test.dvi file is modified (so whenever you run latex to update the output).

To produce a PDF of this you simply run pdflatex instead of latex:

pdflatex test.tex

..and you'll have a test.pdf file created instead of the test.dvi file.

After this is all working fine, I would suggest going to the LaTeX primer page and running through the items on there as you need features for documents you want to write.

Future things to consider include:

  • Use tools such as xfig or dia to create diagrams. These can be easily inserted into your documents in a variety of formats. Note that if you are creating PDFs then you shouldn't use EPS (encapsulated postscript) for images -- use pdf exported from your diagram editor if possible, or you can use the epstopdf package to automatically convert from (e)ps to pdf for figures included with \includegraphics.

  • Start using version control on your documents. This seems excessive at first, but being able to go back and look at earlier versions when you are writing something large can be extremely useful.

  • Use make to run latex for you. When you start on having bibliographies, images and other more complex uses of latex you'll find that you need to run it over multiple files or multiple times (the first time updates the references, and the second puts references into the document, so they can be out-of-date unless you run latex twice...). Abstracting this into a makefile can save a lot of time and effort.

  • Use a better editor. Something like Emacs + AUCTeX is highly competent. This is of course a highly subjective subject, so I'll leave it at that (that and that Emacs is clearly the best option :)

How do you declare an object array in Java?

vehicle[] car = new vehicle[N];

Why use double indirection? or Why use pointers to pointers?

Adding to Asha's response, if you use single pointer to the example bellow (e.g. alloc1() ) you will lose the reference to the memory allocated inside the function.

#include <stdio.h>
#include <stdlib.h>

void alloc2(int** p) {
    *p = (int*)malloc(sizeof(int));
    **p = 10;
}

void alloc1(int* p) {
    p = (int*)malloc(sizeof(int));
    *p = 10;
}

int main(){
    int *p = NULL;
    alloc1(p);
    //printf("%d ",*p);//undefined
    alloc2(&p);
    printf("%d ",*p);//will print 10
    free(p);
    return 0;
}

The reason it occurs like this is that in alloc1 the pointer is passed in by value. So, when it is reassigned to the result of the malloc call inside of alloc1, the change does not pertain to code in a different scope.

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

How to find the location of the Scheduled Tasks folder

I want to extend @Jan answer:

It's seems, that Task Scheduler 1.0 API uses C:\Windows\Tasks folder for create and enumerate tasks (this example), while Task Scheduler 2.0 API uses C:\Windows\System32\Tasks to create and enumerate tasks (this example).

It's also seems, that windows console utility schtasks and GUI utility taskschd.msc uses Task Scheduler 2.0 API.

P.S. I found, that if task placed in C:\Windows\Tasks and have not set AccountInformation, then task won't be displayed in windows console and GUI schedulers. If you set AccountInformation (even "" for SYSTEM account) and set flag TASK_FLAG_RUN_ONLY_IF_LOGGED_ON - task will be displayed in all standard applications.

Solution found here

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

Peak signal detection in realtime timeseries data

Found another algorithm by G. H. Palshikar in Simple Algorithms for Peak Detection in Time-Series.

The algorithm goes like this:

algorithm peak1 // one peak detection algorithms that uses peak function S1 

input T = x1, x2, …, xN, N // input time-series of N points 
input k // window size around the peak 
input h // typically 1 <= h <= 3 
output O // set of peaks detected in T 

begin 
O = empty set // initially empty 

    for (i = 1; i < n; i++) do
        // compute peak function value for each of the N points in T 
        a[i] = S1(k,i,xi,T); 
    end for 

    Compute the mean m' and standard deviation s' of all positive values in array a; 

    for (i = 1; i < n; i++) do // remove local peaks which are “small” in global context 
        if (a[i] > 0 && (a[i] – m') >( h * s')) then O = O + {xi}; 
        end if 
    end for 

    Order peaks in O in terms of increasing index in T 

    // retain only one peak out of any set of peaks within distance k of each other 

    for every adjacent pair of peaks xi and xj in O do 
        if |j – i| <= k then remove the smaller value of {xi, xj} from O 
        end if 
    end for 
end

Advantages

  • The paper provides 5 different algorithms for peak detection
  • The algorithms work on the raw time-series data (no smoothing needed)

Disadvantages

  • Difficult to determine k and h beforehand
  • Peaks cannot be flat (like the third peak in my test data)

Example:

enter image description here

How to Set Opacity (Alpha) for View in Android

Although btnMybutton.getBackground().setAlpha(45); is nice idea, it just apply alpha to background and not the whole view.

If you want apply alpha to view use btnMybutton.setAlpha(0.30f); instead. This apply opacity to View. It accepts a value between 0 and 1.

Doc says:

Sets the opacity of the view. This is a value from 0 to 1, where 0 means the view is completely transparent and 1 means the view is completely opaque. If this view overrides onSetAlpha(int) to return true, then this view is responsible for applying the opacity itself. Otherwise, calling this method is equivalent to calling setLayerType(int, android.graphics.Paint) and setting a hardware layer. Note that setting alpha to a translucent value (0 < alpha < 1) may have performance implications. It is generally best to use the alpha property sparingly and transiently, as in the case of fading animations.

Java socket API: How to tell if a connection has been closed?

There is no TCP API that will tell you the current state of the connection. isConnected() and isClosed() tell you the current state of your socket. Not the same thing.

  1. isConnected() tells you whether you have connected this socket. You have, so it returns true.

  2. isClosed() tells you whether you have closed this socket. Until you have, it returns false.

  3. If the peer has closed the connection in an orderly way

    • read() returns -1
    • readLine() returns null
    • readXXX() throws EOFException for any other XXX.

    • A write will throw an IOException: 'connection reset by peer', eventually, subject to buffering delays.

  4. If the connection has dropped for any other reason, a write will throw an IOException, eventually, as above, and a read may do the same thing.

  5. If the peer is still connected but not using the connection, a read timeout can be used.

  6. Contrary to what you may read elsewhere, ClosedChannelException doesn't tell you this. [Neither does SocketException: socket closed.] It only tells you that you closed the channel, and then continued to use it. In other words, a programming error on your part. It does not indicate a closed connection.

  7. As a result of some experiments with Java 7 on Windows XP it also appears that if:

    • you're selecting on OP_READ
    • select() returns a value of greater than zero
    • the associated SelectionKey is already invalid (key.isValid() == false)

    it means the peer has reset the connection. However this may be peculiar to either the JRE version or platform.

How to add a linked source folder in Android Studio?

in your build.gradle add the following to the end of the android node

android {
    ....
    ....

    sourceSets {
        main.java.srcDirs += 'src/main/<YOUR DIRECTORY>'
    }

}

Convert string to date in Swift

Please use an ISO8601 parsing library for doing this. There are too many ways how the string could be encoded. Don't rely on a specific format and don't rely on the server sending always the same. The problems start with the 'Z' at the end and it will extend through all varieties of the standard. A parsing library will handle all cases and will always provide a safe conversion - whereas a fixed formatting string is likely to fail in the future.

You could use one of these libraries. They are also available on CococaPods:

https://github.com/boredzo/iso-8601-date-formatter/

https://github.com/malcommac/SwiftDate

Take a look at the implementations. They are both several hundred lines long - for good reason.

With regards to the question: You can pull out the date components from the date using NSDateComponents. The example on the website covers exactly your case.

https://developer.apple.com/documentation/foundation/nscalendar/1414841-components?language=objc

Please be aware, that converting your date will take into account the time zone. You might want to set the 'locale' of the NSCalendar explicitly.

What does "int 0x80" mean in assembly code?

It passes control to interrupt vector 0x80

See http://en.wikipedia.org/wiki/Interrupt_vector

On Linux, have a look at this: it was used to handle system_call. Of course on another OS this could mean something totally different.

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

One more idea for anyone else getting this...

I had some gzipped svg, but it had a php error in the output, which caused this error message. (Because there was text in the middle of gzip binary.) Fixing the php error solved it.

Maven not found in Mac OSX mavericks

I am not allowed to comment to pkyeck's response which did not work for a few people including me, so I am adding a separate comment in continuation to his response:

Basically try to add the variable which he has mentioned in the .profile file if the .bash_profile did not work. It is located in your home directory and then restart the terminal. that got it working for me.

The obvious blocker would be that you do not have an access to edit the .profile file, for which use the "touch" to check the access and the "sudo" command to get the access

  1. touch .profile

  2. vi .profile

Here are the variable pkyeck suggests that we added as a solution which worked with editing .profile for me:

  1. export M2_HOME=/apache-maven-3.3.3

  2. export PATH=$PATH:$M2_HOME/bin

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

In C#, how to check whether a string contains an integer?

        string text = Console.ReadLine();
        bool isNumber = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (char.IsDigit(text[i]))
            {
                isNumber = true;
                break;
            }
        }

        if (isNumber)
        {
            Console.WriteLine("Text contains number.");
        }
        else
        {
            Console.WriteLine("Text doesn't contain number.");
        }

        Console.ReadKey();

Or Linq:

        string text = Console.ReadLine();

        bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
        Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
        Console.ReadKey();

Variable length (Dynamic) Arrays in Java

Arrays in Java are of fixed size. What you'd need is an ArrayList, one of a number of extremely valuable Collections available in Java.

Instead of

Integer[] ints = new Integer[x]

you use

List<Integer> ints = new ArrayList<Integer>();

Then to change the list you use ints.add(y) and ints.remove(z) amongst many other handy methods you can find in the appropriate Javadocs.

I strongly recommend studying the Collections classes available in Java as they are very powerful and give you a lot of builtin functionality that Java-newbies tend to try to rewrite themselves unnecessarily.

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Be sure to stringify before sending. I leaned on the libraries too much and thought they would encode properly based on the contentType I was posting, but they do not seem to.

Works:

$.ajax({
    url: _saveAllDevicesUrl
,   type: 'POST'
,   contentType: 'application/json'
,   data: JSON.stringify(postData) //stringify is important
,   success: _madeSave.bind(this)
});

I prefer this method to using a plugin like $.toJSON, although that does accomplish the same thing.

Parameter "stratify" from method "train_test_split" (scikit Learn)

This stratify parameter makes a split so that the proportion of values in the sample produced will be the same as the proportion of values provided to parameter stratify.

For example, if variable y is a binary categorical variable with values 0 and 1 and there are 25% of zeros and 75% of ones, stratify=y will make sure that your random split has 25% of 0's and 75% of 1's.

MySQL Error: #1142 - SELECT command denied to user

This is th privileges issue in your database users. first check and grant permission to user 'marco' in localhost

Is the Scala 2.8 collections library a case of "the longest suicide note in history"?

I do not have a PhD, nor any other kind of degree neither in CS nor math nor indeed any other field. I have no prior experience with Scala nor any other similar language. I have no experience with even remotely comparable type systems. In fact, the only language that I have more than just a superficial knowledge of which even has a type system is Pascal, not exactly known for its sophisticated type system. (Although it does have range types, which AFAIK pretty much no other language has, but that isn't really relevant here.) The other three languages I know are BASIC, Smalltalk and Ruby, none of which even have a type system.

And yet, I have no trouble at all understanding the signature of the map function you posted. It looks to me like pretty much the same signature that map has in every other language I have ever seen. The difference is that this version is more generic. It looks more like a C++ STL thing than, say, Haskell. In particular, it abstracts away from the concrete collection type by only requiring that the argument is IterableLike, and also abstracts away from the concrete return type by only requiring that an implicit conversion function exists which can build something out of that collection of result values. Yes, that is quite complex, but it really is only an expression of the general paradigm of generic programming: do not assume anything that you don't actually have to.

In this case, map does not actually need the collection to be a list, or being ordered or being sortable or anything like that. The only thing that map cares about is that it can get access to all elements of the collection, one after the other, but in no particular order. And it does not need to know what the resulting collection is, it only needs to know how to build it. So, that is what its type signature requires.

So, instead of

map :: (a ? b) ? [a] ? [b]

which is the traditional type signature for map, it is generalized to not require a concrete List but rather just an IterableLike data structure

map :: (IterableLike i, IterableLike j) ? (a ? b) ? i ? j

which is then further generalized by only requiring that a function exists that can convert the result to whatever data structure the user wants:

map :: IterableLike i ? (a ? b) ? i ? ([b] ? c) ? c

I admit that the syntax is a bit clunkier, but the semantics are the same. Basically, it starts from

def map[B](f: (A) ? B): List[B]

which is the traditional signature for map. (Note how due to the object-oriented nature of Scala, the input list parameter vanishes, because it is now the implicit receiver parameter that every method in a single-dispatch OO system has.) Then it generalized from a concrete List to a more general IterableLike

def map[B](f: (A) ? B): IterableLike[B]

Now, it replaces the IterableLike result collection with a function that produces, well, really just about anything.

def map[B, That](f: A ? B)(implicit bf: CanBuildFrom[Repr, B, That]): That

Which I really believe is not that hard to understand. There's really only a couple of intellectual tools you need:

  1. You need to know (roughly) what map is. If you gave only the type signature without the name of the method, I admit, it would be a lot harder to figure out what is going on. But since you already know what map is supposed to do, and you know what its type signature is supposed to be, you can quickly scan the signature and focus on the anomalies, like "why does this map take two functions as arguments, not one?"
  2. You need to be able to actually read the type signature. But even if you have never seen Scala before, this should be quite easy, since it really is just a mixture of type syntaxes you already know from other languages: VB.NET uses square brackets for parametric polymorphism, and using an arrow to denote the return type and a colon to separate name and type, is actually the norm.
  3. You need to know roughly what generic programming is about. (Which isn't that hard to figure out, since it's basically all spelled out in the name: it's literally just programming in a generic fashion).

None of these three should give any professional or even hobbyist programmer a serious headache. map has been a standard function in pretty much every language designed in the last 50 years, the fact that different languages have different syntax should be obvious to anyone who has designed a website with HTML and CSS and you can't subscribe to an even remotely programming related mailinglist without some annoying C++ fanboy from the church of St. Stepanov explaining the virtues of generic programming.

Yes, Scala is complex. Yes, Scala has one of the most sophisticated type systems known to man, rivaling and even surpassing languages like Haskell, Miranda, Clean or Cyclone. But if complexity were an argument against success of a programming language, C++ would have died long ago and we would all be writing Scheme. There are lots of reasons why Scala will very likely not be successful, but the fact that programmers can't be bothered to turn on their brains before sitting down in front of the keyboard is probably not going to be the main one.

Editor does not contain a main type

This could be the issue with the Java Build path. Try below steps :

  1. Go to project properties
  2. Go to java Build Path
  3. Go to Source tab and add project's src folder

This should resolve the issue.

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

@bogatron has it right, you can use where, it's worth noting that you can do this natively in pandas:

df1 = df.where(pd.notnull(df), None)

Note: this changes the dtype of all columns to object.

Example:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

Note: what you cannot do recast the DataFrames dtype to allow all datatypes types, using astype, and then the DataFrame fillna method:

df1 = df.astype(object).replace(np.nan, 'None')

Unfortunately neither this, nor using replace, works with None see this (closed) issue.


As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.

However, in this specific case it seems you do (at least at the time of this answer).

String's Maximum length in Java - calling length() method

The Return type of the length() method of the String class is int.

public int length()

Refer http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#length()

So the maximum value of int is 2147483647.

String is considered as char array internally,So indexing is done within the maximum range. This means we cannot index the 2147483648th member.So the maximum length of String in java is 2147483647.

Primitive data type int is 4 bytes(32 bits) in java.As 1 bit (MSB) is used as a sign bit,The range is constrained within -2^31 to 2^31-1 (-2147483648 to 2147483647). We cannot use negative values for indexing.So obviously the range we can use is from 0 to 2147483647.

Generating a SHA-256 hash from the Linux command line

echo -n works and is unlikely to ever disappear due to massive historical usage, however per recent versions of the POSIX standard, new conforming applications are "encouraged to use printf".

SQLException: No suitable driver found for jdbc:derby://localhost:1527

You may be missing to start the Derby server. Once a derby server starts, it starts listening to default port 1527.

Start script is located as below:

Windows:

    <DERBY_INSTALLATION_DIRECTORY>/bin/startNetworkServer.bat

Linux:

    <DERBY_INSTALLATION_DIRECTORY>/bin/startNetworkServer

How do you change the width and height of Twitter Bootstrap's tooltips?

BS3:

.tooltip-inner { width:400px; max-width: 400px; }

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

For the second request, pause/wait, where you stop processing in Lua and continue to run your application, you need coroutines. You end up with some C code like this following:

Lthread=lua_newthread(L);
luaL_loadfile(Lthread, file);
while ((status=lua_resume(Lthread, 0) == LUA_YIELD) {
  /* do some C code here */
}

and in Lua, you have the following:

function try_pause (func, param)
  local rc=func(param)
  while rc == false do
    coroutine.yield()
    rc=func(param)
  end
end

function is_data_ready (data)
  local rc=true
  -- check if data is ready, update rc to false if not ready
  return rc
end

try_pause(is_data_ready, data)

How should I cast in VB.NET?

MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)

When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.

One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.

Overflow:hidden dots at the end

<!DOCTYPE html>
<html>
<head>
<style>
.cardDetaileclips{
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3; /* after 3 line show ... */
    -webkit-box-orient: vertical;
}
</style>
</head>
<body>
<div style="width:100px;">
  <div class="cardDetaileclips">
    My Name is Manoj and pleasure to help you.
  </div>
</div> 
</body>
</html>

C# password TextBox in a ASP.net website

@JohnHartsock: You can also write type="password". It's acceptable in aspx.

<asp:TextBox ID="txtBox" type="password" runat="server"/>

How to use the TextWatcher class in Android?

Supplemental answer

Here is a visual supplement to the other answers. My fuller answer with the code and explanations is here.

  • Red: text about to be deleted (replaced)
  • Green: text that was just added (replacing the old red text)

enter image description here

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

Use the Post/Redirect/Get pattern. http://en.wikipedia.org/wiki/Post/Redirect/Get

With my website, I will store a message in a cookie or session, redirect after the post, read the cookie/session, and then clear the value of that session or cookie variable.

OnClick in Excel VBA

In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection.

The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
  'put your code here to process the selection, then..
  ActiveWindow.VisibleRange.Cells(1, 1).Select
End Sub

Get an image extension from an uploaded file in Laravel

 //working code from laravel 5.2

 public function store(Request $request)
 {
          $file = $request->file('file');
            if($file)
            {
                    $extension =  $file->clientExtension();
            }
            echo $extension;
 }

How can I parse a String to BigDecimal?

BigDecimal offers a string constructor. You'll need to strip all commas from the number, via via an regex or String filteredString=inString.replaceAll(",","").

You then simply call BigDecimal myBigD=new BigDecimal(filteredString);

You can also create a NumberFormat and call setParseBigDecimal(true). Then parse( will give you a BigDecimal without worrying about manually formatting.

How can I change an element's class with JavaScript?

Working JavaScript code:

<div id="div_add" class="div_add">Add class from Javascript</div>
<div id="div_replace" class="div_replace">Replace class from Javascript</div>
<div id="div_remove" class="div_remove">Remove class from Javascript</div>
<button onClick="div_add_class();">Add class from Javascript</button>
<button onClick="div_replace_class();">Replace class from Javascript</button>
<button onClick="div_remove_class();">Remove class from Javascript</button>
<script type="text/javascript">
    function div_add_class()
    {
        document.getElementById("div_add").className += " div_added";
    }
    function div_replace_class()
    {
        document.getElementById("div_replace").className = "div_replaced";
    }
    function div_remove_class()
    {
        document.getElementById("div_remove").className = "";
    }
</script>

You can download a working code from this link.

BigDecimal setScale and round

One important point that is alluded to but not directly addressed is the difference between "precision" and "scale" and how they are used in the two statements. "precision" is the total number of significant digits in a number. "scale" is the number of digits to the right of the decimal point.

The MathContext constructor only accepts precision and RoundingMode as arguments, and therefore scale is never specified in the first statement.

setScale() obviously accepts scale as an argument, as well as RoundingMode, however precision is never specified in the second statement.

If you move the decimal point one place to the right, the difference will become clear:

// 1.
new BigDecimal("35.3456").round(new MathContext(4, RoundingMode.HALF_UP));
//result = 35.35
// 2.
new BigDecimal("35.3456").setScale(4, RoundingMode.HALF_UP);
// result = 35.3456

Objective-C : BOOL vs bool

Yup, BOOL is a typedef for a signed char according to objc.h.

I don't know about bool, though. That's a C++ thing, right? If it's defined as a signed char where 1 is YES/true and 0 is NO/false, then I imagine it doesn't matter which one you use.

Since BOOL is part of Objective-C, though, it probably makes more sense to use a BOOL for clarity (other Objective-C developers might be puzzled if they see a bool in use).

Return single column from a multi-dimensional array

very simple go for this

$str;
foreach ($arrays as $arr) {
$str .= $arr["tag_name"] . ",";
}
$str = trim($str, ',');//removes the final comma 

Best practice for instantiating a new Android Fragment

Some kotlin code:

companion object {
    fun newInstance(first: String, second: String) : SampleFragment {
        return SampleFragment().apply {
            arguments = Bundle().apply {
                putString("firstString", first)
                putString("secondString", second)
            }
        }
    }
}

And you can get arguments with this:

val first: String by lazy { arguments?.getString("firstString") ?: "default"}
val second: String by lazy { arguments?.getString("secondString") ?: "default"}

How can I reload .emacs after changing it?

I suggest that you don't do this, initially. Instead, start a new emacs session and test whatever changes you made to see if they work correctly. The reason to do it this way is to avoid leaving you in a state where you have an inoperable .emacs file, which fails to load or fails to load cleanly. If you do all of your editing in the original session, and all of your testing in a new session, you'll always have something reliable to comment out offending code.

When you are finally happy with your changes, then go ahead and use one of the other answers to re-load. My personal preference is to eval just the section you've added/changed, and to do that just highlight the region of added/changed code and call M-x eval-region. Doing that minimizes the code that's evaluated, minimizing any unintentional side-effects, as luapyad points out.

Replace only text inside a div using jquery

Text shouldn't be on its own. Put it into a span element.

Change it to this:

<div id="one">
       <div class="first"></div>
       <span>"Hi I am text"</span>
       <div class="second"></div>
       <div class="third"></div>
</div>
$('#one span').text('Hi I am replace');

Read all files in a folder and apply a function to each data frame

Here is a tidyverse option that might not the most elegant, but offers some flexibility in terms of what is included in the summary:

library(tidyverse)
dir_path <- '~/path/to/data/directory/'
file_pattern <- 'Df\\.[0-9]\\.csv' # regex pattern to match the file name format

read_dir <- function(dir_path, file_name){
  read_csv(paste0(dir_path, file_name)) %>% 
    mutate(file_name = file_name) %>%                # add the file name as a column              
    gather(variable, value, A:B) %>%                 # convert the data from wide to long
    group_by(file_name, variable) %>% 
    summarize(sum = sum(value, na.rm = TRUE),
              min = min(value, na.rm = TRUE),
              mean = mean(value, na.rm = TRUE),
              median = median(value, na.rm = TRUE),
              max = max(value, na.rm = TRUE))
  }

df_summary <- 
  list.files(dir_path, pattern = file_pattern) %>% 
  map_df(~ read_dir(dir_path, .))

df_summary
# A tibble: 8 x 7
# Groups:   file_name [?]
  file_name variable   sum   min  mean median   max
  <chr>     <chr>    <int> <dbl> <dbl>  <dbl> <dbl>
1 Df.1.csv  A           34     4  5.67    5.5     8
2 Df.1.csv  B           22     1  3.67    3       9
3 Df.2.csv  A           21     1  3.5     3.5     6
4 Df.2.csv  B           16     1  2.67    2.5     5
5 Df.3.csv  A           30     0  5       5      11
6 Df.3.csv  B           43     1  7.17    6.5    15
7 Df.4.csv  A           21     0  3.5     3       8
8 Df.4.csv  B           42     1  7       6      16

Font is not available to the JVM with Jasper Reports

Hey Having trouble viewing documents produced on Windows?

You can try a fine solution easy:

yum install curl cabextract xorg-x11-font-utils fontconfig

rpm -i https://downloads.sourceforge.net/project/mscorefonts2/rpms/msttcore-fonts-installer-2.6-1.noarch.rpm

After this I need reboot my system CentOS6.

Source: http://mscorefonts2.sourceforge.net/

How do MySQL indexes work?

The first thing you must know is that indexes are a way to avoid scanning the full table to obtain the result that you're looking for.

There are different kinds of indexes and they're implemented in the storage layer, so there's no standard between them and they also depend on the storage engine that you're using.

InnoDB and the B+Tree index

For InnoDB, the most common index type is the B+Tree based index, that stores the elements in a sorted order. Also, you don't have to access the real table to get the indexed values, which makes your query return way faster.

The "problem" about this index type is that you have to query for the leftmost value to use the index. So, if your index has two columns, say last_name and first_name, the order that you query these fields matters a lot.

So, given the following table:

CREATE TABLE person (
    last_name VARCHAR(50) NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    INDEX (last_name, first_name)
);

This query would take advantage of the index:

SELECT last_name, first_name FROM person
WHERE last_name = "John" AND first_name LIKE "J%"

But the following one would not

SELECT last_name, first_name FROM person WHERE first_name = "Constantine"

Because you're querying the first_name column first and it's not the leftmost column in the index.

This last example is even worse:

SELECT last_name, first_name FROM person WHERE first_name LIKE "%Constantine"

Because now, you're comparing the rightmost part of the rightmost field in the index.

The hash index

This is a different index type that unfortunately, only the memory backend supports. It's lightning fast but only useful for full lookups, which means that you can't use it for operations like >, < or LIKE.

Since it only works for the memory backend, you probably won't use it very often. The main case I can think of right now is the one that you create a temporary table in the memory with a set of results from another select and perform a lot of other selects in this temporary table using hash indexes.

If you have a big VARCHAR field, you can "emulate" the use of a hash index when using a B-Tree, by creating another column and saving a hash of the big value on it. Let's say you're storing a url in a field and the values are quite big. You could also create an integer field called url_hash and use a hash function like CRC32 or any other hash function to hash the url when inserting it. And then, when you need to query for this value, you can do something like this:

SELECT url FROM url_table WHERE url_hash=CRC32("http://gnu.org");

The problem with the above example is that since the CRC32 function generates a quite small hash, you'll end up with a lot of collisions in the hashed values. If you need exact values, you can fix this problem by doing the following:

SELECT url FROM url_table 
WHERE url_hash=CRC32("http://gnu.org") AND url="http://gnu.org";

It's still worth to hash things even if the collision number is high cause you'll only perform the second comparison (the string one) against the repeated hashes.

Unfortunately, using this technique, you still need to hit the table to compare the url field.

Wrap up

Some facts that you may consider every time you want to talk about optimization:

  1. Integer comparison is way faster than string comparison. It can be illustrated with the example about the emulation of the hash index in InnoDB.

  2. Maybe, adding additional steps in a process makes it faster, not slower. It can be illustrated by the fact that you can optimize a SELECT by splitting it into two steps, making the first one store values in a newly created in-memory table, and then execute the heavier queries on this second table.

MySQL has other indexes too, but I think the B+Tree one is the most used ever and the hash one is a good thing to know, but you can find the other ones in the MySQL documentation.

I highly recommend you to read the "High Performance MySQL" book, the answer above was definitely based on its chapter about indexes.

Android - get children inside a View?

for(int index = 0; index < ((ViewGroup) viewGroup).getChildCount(); index++) {
    View nextChild = ((ViewGroup) viewGroup).getChildAt(index);
}

Will that do?

.substring error: "is not a function"

document.location is an object, not a string. It returns (by default) the full path, but it actually holds more info than that.

Shortcut for solution: document.location.toString().substring(2,3);

Or use document.location.href or window.location.href

Simplest SOAP example

Some great examples (and a ready-made JavaScript SOAP client!) here: http://plugins.jquery.com/soap/

Check the readme, and beware the same-origin browser restriction.

Scroll Element into View with Selenium

JAVA

Try scroll to element utilize x y position, and use JavascriptExecutor with this is argument: "window.scrollBy(x, y)".

Following import:

import org.openqa.selenium.WebElement;
import org.openqa.selenium.JavascriptExecutor;

First you need get x y location the element.

//initialize element
WebElement element = driver.findElement(By.id("..."));

//get position
int x = element.getLocation().getX();
int y = element.getLocation().getY();

//scroll to x y 
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("window.scrollBy(" +x +", " +y +")");

How to monitor network calls made from iOS Simulator

A good solution if you are used to the chrome inspector tools is Pony debugger: https://github.com/square/PonyDebugger

It is a bit of a pain to setup, but once you do it work well. Be sure to use Safari instead of Chrome to use it though.

How to open spss data files in excel?

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

pspp-convert <input.sav> <output.csv>

[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar

css - position div to bottom of containing div

Assign position:relative to .outside, and then position:absolute; bottom:0; to your .inside.

Like so:

.outside {
    position:relative;
}
.inside {
    position: absolute;
    bottom: 0;
}

How to resolve "Waiting for Debugger" message?

The Dialog Waiting for Debugger is shown if you are building a debug application or somewhere in your source code, you called Debug.waitingForDebugger();

Inside Android Studio 2.0 and above, there is an option of Attach Debugger to Android Process. It is the last menu item in the Run menu.

Screen shot of Run menu options in Android Studio

http://localhost:50070 does not work HADOOP

  • step 1 : bin/stop-all.sh
  • step 2 : bin/hadoop namenode -format
  • step 3 : bin/start-all.sh

Why doesn't C++ have a garbage collector?

The idea behind C++ was that you would not pay any performance impact for features that you don't use. So adding garbage collection would have meant having some programs run straight on the hardware the way C does and some within some sort of runtime virtual machine.

Nothing prevents you from using some form of smart pointers that are bound to some third-party garbage collection mechanism. I seem to recall Microsoft doing something like that with COM and it didn't go to well.

psql: could not connect to server: No such file or directory (Mac OS X)

The causes of this error are many so first locate your log file and check it for clues. It might be at /usr/local/var/log/postgres.log or /usr/local/var/postgres/server.log or possibly elsewhere. If you installed with Homebrew you can find the location in ~/Library/LaunchAgents/homebrew.mxcl.postgresql.plist.

Primary key or Unique index?

There is no such thing as a primary key in relational data theory, so your question has to be answered on the practical level.

Unique indexes are not part of the SQL standard. The particular implementation of a DBMS will determine what are the consequences of declaring a unique index.

In Oracle, declaring a primary key will result in a unique index being created on your behalf, so the question is almost moot. I can't tell you about other DBMS products.

I favor declaring a primary key. This has the effect of forbidding NULLs in the key column(s) as well as forbidding duplicates. I also favor declaring REFERENCES constraints to enforce entity integrity. In many cases, declaring an index on the coulmn(s) of a foreign key will speed up joins. This kind of index should in general not be unique.

COPY with docker but with exclusion

For those using gcloud build:

gcloud build ignores .dockerignore and looks instead for .gcloudignore

Use:

cp .dockerignore .gcloudignore

Source

Generate random string/characters in JavaScript

Here's an improvement on doubletap's excellent answer. The original has two drawbacks which are addressed here:

First, as others have mentioned, it has a small probability of producing short strings or even an empty string (if the random number is 0), which may break your application. Here is a solution:

(Math.random().toString(36)+'00000000000000000').slice(2, N+2)

Second, both the original and the solution above limit the string size N to 16 characters. The following will return a string of size N for any N (but note that using N > 16 will not increase the randomness or decrease the probability of collisions):

Array(N+1).join((Math.random().toString(36)+'00000000000000000').slice(2, 18)).slice(0, N)

Explanation:

  1. Pick a random number in the range [0,1), i.e. between 0 (inclusive) and 1 (exclusive).
  2. Convert the number to a base-36 string, i.e. using characters 0-9 and a-z.
  3. Pad with zeros (solves the first issue).
  4. Slice off the leading '0.' prefix and extra padding zeros.
  5. Repeat the string enough times to have at least N characters in it (by Joining empty strings with the shorter random string used as the delimiter).
  6. Slice exactly N characters from the string.

Further thoughts:

  • This solution does not use uppercase letters, but in almost all cases (no pun intended) it does not matter.
  • The maximum string length at N = 16 in the original answer is measured in Chrome. In Firefox it's N = 11. But as explained, the second solution is about supporting any requested string length, not about adding randomness, so it doesn't make much of a difference.
  • All returned strings have an equal probability of being returned, at least as far as the results returned by Math.random() are evenly distributed (this is not cryptographic-strength randomness, in any case).
  • Not all possible strings of size N may be returned. In the second solution this is obvious (since the smaller string is simply being duplicated), but also in the original answer this is true since in the conversion to base-36 the last few bits may not be part of the original random bits. Specifically, if you look at the result of Math.random().toString(36), you'll notice the last character is not evenly distributed. Again, in almost all cases it does not matter, but we slice the final string from the beginning rather than the end of the random string so that short strings (e.g. N=1) aren't affected.

Update:

Here are a couple other functional-style one-liners I came up with. They differ from the solution above in that:

  • They use an explicit arbitrary alphabet (more generic, and suitable to the original question which asked for both uppercase and lowercase letters).
  • All strings of length N have an equal probability of being returned (i.e. strings contain no repetitions).
  • They are based on a map function, rather than the toString(36) trick, which makes them more straightforward and easy to understand.

So, say your alphabet of choice is

var s = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

Then these two are equivalent to each other, so you can pick whichever is more intuitive to you:

Array(N).join().split(',').map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');

and

Array.apply(null, Array(N)).map(function() { return s.charAt(Math.floor(Math.random() * s.length)); }).join('');

Edit:

I seems like qubyte and Martijn de Milliano came up with solutions similar to the latter (kudos!), which I somehow missed. Since they don't look as short at a glance, I'll leave it here anyway in case someone really wants a one-liner :-)

Also, replaced 'new Array' with 'Array' in all solutions to shave off a few more bytes.

how to properly display an iFrame in mobile safari

<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" src="url" />
</div>

I'm building my first site and this helped me get this working for all sites that I use iframe embededding for.

Thanks!

How to create a connection string in asp.net c#

Add this connection string tag in web.config file:

<connectionStrings>
  <add name="itmall" 
    connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>

And use it like you mentioned. :)

Set value to currency in <input type="number" />

It seems that you'll need two fields, a choice list for the currency and a number field for the value.

A common technique in such case is to use a div or span for the display (form fields offscreen), and on click switch to the form elements for editing.

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

How to fire a button click event from JavaScript in ASP.NET

You can fill a hidden field from your JavaScript code and do an explicit postback from JavaScript. Then from the server side, check that hiddenfield and do whatever necessary.

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

Android Studio: /dev/kvm device permission denied

  1. I tried sudo setfacl -m u:UserName:rwx /dev/kvm . and it works .

  2. In the android studio you need to change : tools> avd manager >(chose the pen to edit your device and change 'graphics' from automatic to software ) to avoid emulator drawable error

Vertical Menu in Bootstrap

The question is old now.

But if somebody looks here the trick in the current version is to use the nav-stack class, like so:

<nav>
  <ul class="nav nav-pills nav-stacked span2">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Contact</a></li>
  </ul>
</nav>

How to edit default dark theme for Visual Studio Code?

Any color theme can be changed in this settings section on VS Code version 1.12 or higher:

 // Overrides colors from the currently selected color theme.
  "workbench.colorCustomizations": {}

See https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme

Available values to edit: https://code.visualstudio.com/docs/getstarted/theme-color-reference

EDIT: To change syntax colors, see here: https://code.visualstudio.com/docs/extensions/themes-snippets-colorizers#_syntax-highlighting-colors and here: https://www.sublimetext.com/docs/3/scope_naming.html

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

Bad File Descriptor with Linux Socket write() Bad File Descriptor C

I had this error too, my problem was in some part of code I didn't close file descriptor and in other part, I tried to open that file!! use close(fd) system call after you finished working on a file.

Global Events in Angular

DO Not Use EventEmitter for your service communication.

You should use one of the Observable types. I personally like BehaviorSubject.

Simple example:

You can pass initial state, here I passing null

let subject = new BehaviorSubject(null);

When you want to update the subject

subject.next(myObject)

Observe from any service or component and act when it gets new updates.

subject.subscribe(this.YOURMETHOD);

Here is more information..

How to disable Django's CSRF validation?

For Django 2:

from django.utils.deprecation import MiddlewareMixin


class DisableCSRF(MiddlewareMixin):
    def process_request(self, request):
        setattr(request, '_dont_enforce_csrf_checks', True)

That middleware must be added to settings.MIDDLEWARE when appropriate (in your test settings for example).

Note: the setting isn't not called MIDDLEWARE_CLASSES anymore.

What is the best (idiomatic) way to check the type of a Python variable?

built-in types in Python have built in names:

>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True

btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You had selected the time format wrong

<?php 
date_default_timezone_set('GMT');

echo date("Y-m-d,h:m:s");
?>

How to create a Java cron job

First I would recommend you always refer docs before you start a new thing.

We have SchedulerFactory which schedules Job based on the Cron Expression given to it.

    //Create instance of factory
    SchedulerFactory schedulerFactory=new StdSchedulerFactory();

    //Get schedular
    Scheduler scheduler= schedulerFactory.getScheduler();

    //Create JobDetail object specifying which Job you want to execute
    JobDetail jobDetail=new JobDetail("myJobClass","myJob1",MyJob.class);

    //Associate Trigger to the Job
    CronTrigger trigger=new CronTrigger("cronTrigger","myJob1","0 0/1 * * * ?");

    //Pass JobDetail and trigger dependencies to schedular
    scheduler.scheduleJob(jobDetail,trigger);

    //Start schedular
    scheduler.start();

MyJob.class

public class MyJob implements Job{

      @Override
      public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
                 System.out.println("My Logic");
        }

    }

Angularjs $http.get().then and binding to a list

Actually you get promise on $http.get.

Try to use followed flow:

<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

Where documents is your array.

$scope.documents = [];

$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    result.data.forEach(function(val, i) { 
        $scope.documents.push(/* put data here*/);
    });
}, function(error) {
    alert(error.message);
});                       

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

Get a specific bit from byte

another way of doing it :)

return ((b >> bitNumber) & 1) != 0;

where to place CASE WHEN column IS NULL in this query

Try this:

CASE WHEN table3.col3 IS NULL THEN table2.col3 ELSE table3.col3 END as col4

The as col4 should go at the end of the CASE the statement. Also note that you're missing the END too.

Another probably more simple option would be:

IIf([table3.col3] Is Null,[table2.col3],[table3.col3])

Just to clarify, MS Access does not support COALESCE. If it would that would be the best way to go.

Edit after radical question change:

To turn the query into SQL Server then you can use COALESCE (so it was technically answered before too):

SELECT dbo.AdminID.CountryID, dbo.AdminID.CountryName, dbo.AdminID.RegionID, 
dbo.AdminID.[Region name], dbo.AdminID.DistrictID, dbo.AdminID.DistrictName,
dbo.AdminID.ADMIN3_ID, dbo.AdminID.ADMIN3,
COALESCE(dbo.EU_Admin3.EUID, dbo.EU_Admin2.EUID)
FROM dbo.AdminID

BTW, your CASE statement was missing a , before the field. That's why it didn't work.

Detecting real time window size changes in Angular 4

The answer is very simple. write the below code

import { Component, OnInit, OnDestroy, Input } from "@angular/core";
// Import this, and write at the top of your .ts file
import { HostListener } from "@angular/core";

@Component({
 selector: "app-login",
 templateUrl: './login.component.html',
 styleUrls: ['./login.component.css']
})

export class LoginComponent implements OnInit, OnDestroy {
// Declare height and width variables
scrHeight:any;
scrWidth:any;

@HostListener('window:resize', ['$event'])
getScreenSize(event?) {
      this.scrHeight = window.innerHeight;
      this.scrWidth = window.innerWidth;
      console.log(this.scrHeight, this.scrWidth);
}

// Constructor
constructor() {
    this.getScreenSize();
}
}

using jquery $.ajax to call a PHP function

You can't call a PHP function with Javascript, in the same way you can't call arbitrary PHP functions when you load a page (just think of the security implications).

If you need to wrap your code in a function for whatever reason, why don't you either put a function call under the function definition, eg:

function test() {
    // function code
}

test();

Or, use a PHP include:

include 'functions.php'; // functions.php has the test function
test();

Node.js global proxy setting

You can try my package node-global-proxy which work with all node versions and most of http-client (axios, got, superagent, request etc.)

after install by

npm install node-global-proxy --save

a global proxy can start by

const proxy = require("node-global-proxy").default;

proxy.setConfig({
  http: "http://localhost:1080",
  https: "https://localhost:1080",
});
proxy.start();

/** Proxy working now! */

More information available here: https://github.com/wwwzbwcom/node-global-proxy

How to check if the string is empty?

The only really solid way of doing this is the following:

if "".__eq__(myString):

All other solutions have possible problems and edge cases where the check can fail.

len(myString)==0 can fail if myString is an object of a class that inherits from str and overrides the __len__() method.

Similarly myString == "" and myString.__eq__("") can fail if myString overrides __eq__() and __ne__().

For some reason "" == myString also gets fooled if myString overrides __eq__().

myString is "" and "" is myString are equivalent. They will both fail if myString is not actually a string but a subclass of string (both will return False). Also, since they are identity checks, the only reason why they work is because Python uses String Pooling (also called String Internment) which uses the same instance of a string if it is interned (see here: Why does comparing strings using either '==' or 'is' sometimes produce a different result?). And "" is interned from the start in CPython

The big problem with the identity check is that String Internment is (as far as I could find) that it is not standardised which strings are interned. That means, theoretically "" is not necessary interned and that is implementation dependant.

The only way of doing this that really cannot be fooled is the one mentioned in the beginning: "".__eq__(myString). Since this explicitly calls the __eq__() method of the empty string it cannot be fooled by overriding any methods in myString and solidly works with subclasses of str.

Also relying on the falsyness of a string might not work if the object overrides it's __bool__() method.

This is not only theoretical work but might actually be relevant in real usage since I have seen frameworks and libraries subclassing str before and using myString is "" might return a wrong output there.

Also, comparing strings using is in general is a pretty evil trap since it will work correctly sometimes, but not at other times, since string pooling follows pretty strange rules.

That said, in most cases all of the mentioned solutions will work correctly. This is post is mostly academic work.

How do I grab an INI value within a shell script?

The answer of "Karen Gabrielyan" among another answers was the best but in some environments we dont have awk, like typical busybox, i changed the answer by below code.

trim()
{
    local trimmed="$1"

    # Strip leading space.
    trimmed="${trimmed## }"
    # Strip trailing space.
    trimmed="${trimmed%% }"

    echo "$trimmed"
}


  function parseIniFile() { #accepts the name of the file to parse as argument ($1)
        #declare syntax below (-gA) only works with bash 4.2 and higher
        unset g_iniProperties
        declare -gA g_iniProperties
        currentSection=""
        while read -r line
        do
            if [[ $line = [*  ]] ; then
                if [[ $line = [* ]] ; then 
                    currentSection=$(echo $line | sed -e 's/\r//g' | tr -d "[]")  
                fi
            else
                if [[ $line = *=*  ]] ; then
                    cleanLine=$(echo $line | sed -e 's/\r//g')
                    key=$(trim $currentSection.$(echo $cleanLine | cut -d'=' -f1'))
                    value=$(trim $(echo $cleanLine | cut -d'=' -f2))
                    g_iniProperties[$key]=$value
                fi
            fi;
        done < $1
    }

Javascript negative number

In ES6 you can use Math.sign function to determine if,

1. its +ve no
2. its -ve no
3. its zero (0)
4. its NaN


console.log(Math.sign(1))        // prints 1 
console.log(Math.sign(-1))       // prints -1
console.log(Math.sign(0))        // prints 0
console.log(Math.sign("abcd"))   // prints NaN

Get file version in PowerShell

Here an alternative method. It uses Get-WmiObject CIM_DATAFILE to select the version.

(Get-WmiObject -Class CIM_DataFile -Filter "Name='C:\\Windows\\explorer.exe'" | Select-Object Version).Version