Programs & Examples On #Generative art

CSV parsing in Java - working example..?

My approach would not be to start by writing your own API. Life's too short, and there are more pressing problems to solve. In this situation, I typically:

  • Find a library that appears to do what I want. If one doesn't exist, then implement it.
  • If a library does exist, but I'm not sure it'll be suitable for my needs, write a thin adapter API around it, so I can control how it's called. The adapter API expresses the API I need, and it maps those calls to the underlying API.
  • If the library doesn't turn out to be suitable, I can swap another one in underneath the adapter API (whether it's another open source one or something I write myself) with a minimum of effort, without affecting the callers.

Start with something someone has already written. Odds are, it'll do what you want. You can always write your own later, if necessary. OpenCSV is as good a starting point as any.

How to lock specific cells but allow filtering and sorting

Here is an article that explains the problem and solution with alot more detail:

Sorting Locked Cells in Protected Worksheets

The thing to understand is that the purpose of locking cells is to prevent them from being changed, and sorting permanently changes cell values. You can write a macro, but a much better solution is to use the "Allow Users to Edit Ranges" feature. This makes the cells editable so sorting can work, but because the cells are still technically locked you can prevent users from selecting them.

Android failed to load JS bundle

Running npm start from react-native directory worked out for me.

Wait one second in running program

Is it pausing, but you don't see your red color appear in the cell? Try this:

dataGridView1.Rows[x1].Cells[y1].Style.BackColor = System.Drawing.Color.Red;
dataGridView1.Refresh();
System.Threading.Thread.Sleep(1000);

Django set default form values

If you are creating modelform from POST values initial can be assigned this way:

form = SomeModelForm(request.POST, initial={"option": "10"})

https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/#providing-initial-values

No newline after div?

This works the best, in my case, I tried it all

.div_class {
    clear: left;
}

How can I limit ngFor repeat to some number of items in Angular?

For example, lets say we want to display only the first 10 items of an array, we could do this using the SlicePipe like so:

<ul>
     <li *ngFor="let item of items | slice:0:10">
      {{ item }}
     </li>
</ul>

Installing jQuery?

If you want to use a package manager,

You can use bower:

bower install jquery-ui

PHP - auto refreshing page

Maybe use this code,

<meta http-equiv="refresh" content = "30" />

take it be easy

Razor If/Else conditional operator syntax

You need to put the entire ternary expression in parenthesis. Unfortunately that means you can't use "@:", but you could do something like this:

@(deletedView ? "Deleted" : "Created by")

Razor currently supports a subset of C# expressions without using @() and unfortunately, ternary operators are not part of that set.

How to mount a host directory in a Docker container

Jul 2015 update - boot2docker now supports direct mounting. You can use -v /var/logs/on/host:/var/logs/in/container directly from your Mac prompt, without double mounting

How to compare 2 files fast using .NET?

A checksum comparison will most likely be slower than a byte-by-byte comparison.

In order to generate a checksum, you'll need to load each byte of the file, and perform processing on it. You'll then have to do this on the second file. The processing will almost definitely be slower than the comparison check.

As for generating a checksum: You can do this easily with the cryptography classes. Here's a short example of generating an MD5 checksum with C#.

However, a checksum may be faster and make more sense if you can pre-compute the checksum of the "test" or "base" case. If you have an existing file, and you're checking to see if a new file is the same as the existing one, pre-computing the checksum on your "existing" file would mean only needing to do the DiskIO one time, on the new file. This would likely be faster than a byte-by-byte comparison.

Uncaught ReferenceError: $ is not defined

In my case I was putting my .js file before the jQuery script link, putting the .js file after jQuery script link solved my issue.

<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="exponential.js"></script>

How do I URl encode something in Node.js?

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

After setting up SSRS 2016, I RDP'd into the server (Windows Server 2012 R2), navigated to the reports URL (https://reports.fakeserver.net/Reports/browse/) and created a folder title FakeFolder; everything appeared to be working fine. I then disconnected from the server, browsed to the same URL, logged in as the same user, and encountered the error below.

The permissions granted to user 'fakeserver\mitchs' are insufficient for performing this operation.

Confused, I tried pretty much every solution suggested on this page and still could not create the same behavior both locally and externally when navigating to the URL and authenticating. I then clicked the ellipsis of FakeFolder, clicked Manage, clicked Security (on the left hand side of the screen), and added myself as a user with full permissions. After disconnecting from the server, I browsed to https://reports.fakeserver.net/Reports/browse/FakeFolder, and was able to view the folder's contents without encountering the permissions error. However, when I clicked home I received the permissions error.

For my purposes, this was good enough as no on else will ever need to browse to the root URL, so I just made a mental note whenever I need to make changes in SSRS to first connect to the server and then browse to the Reports URL.

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

Set CSS property in Javascript?

That's actually quite simple with vanilla JavaScript:

menu.style.width = "100px";

Proper use of the IDisposable interface

If MyCollection is going to be garbage collected anyway, then you shouldn't need to dispose it. Doing so will just churn the CPU more than necessary, and may even invalidate some pre-calculated analysis that the garbage collector has already performed.

I use IDisposable to do things like ensure threads are disposed correctly, along with unmanaged resources.

EDIT In response to Scott's comment:

The only time the GC performance metrics are affected is when a call the [sic] GC.Collect() is made"

Conceptually, the GC maintains a view of the object reference graph, and all references to it from the stack frames of threads. This heap can be quite large and span many pages of memory. As an optimisation, the GC caches its analysis of pages that are unlikely to change very often to avoid rescanning the page unnecessarily. The GC receives notification from the kernel when data in a page changes, so it knows that the page is dirty and requires a rescan. If the collection is in Gen0 then it's likely that other things in the page are changing too, but this is less likely in Gen1 and Gen2. Anecdotally, these hooks were not available in Mac OS X for the team who ported the GC to Mac in order to get the Silverlight plug-in working on that platform.

Another point against unnecessary disposal of resources: imagine a situation where a process is unloading. Imagine also that the process has been running for some time. Chances are that many of that process's memory pages have been swapped to disk. At the very least they're no longer in L1 or L2 cache. In such a situation there is no point for an application that's unloading to swap all those data and code pages back into memory to 'release' resources that are going to be released by the operating system anyway when the process terminates. This applies to managed and even certain unmanaged resources. Only resources that keep non-background threads alive must be disposed, otherwise the process will remain alive.

Now, during normal execution there are ephemeral resources that must be cleaned up correctly (as @fezmonkey points out database connections, sockets, window handles) to avoid unmanaged memory leaks. These are the kinds of things that have to be disposed. If you create some class that owns a thread (and by owns I mean that it created it and therefore is responsible for ensuring it stops, at least by my coding style), then that class most likely must implement IDisposable and tear down the thread during Dispose.

The .NET framework uses the IDisposable interface as a signal, even warning, to developers that the this class must be disposed. I can't think of any types in the framework that implement IDisposable (excluding explicit interface implementations) where disposal is optional.

In PHP, how can I add an object element to an array?

Do you really need an object? What about:

$myArray[] = array("name" => "my name");

Just use a two-dimensional array.

Output (var_dump):

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(7) "my name"
  }
}

You could access your last entry like this:

echo $myArray[count($myArray) - 1]["name"];

How to check for empty array in vba macro

Personally, I think one of the answers above can be modified to check if the array has contents:

if UBound(ar) > LBound(ar) Then

This handles negative number references and takes less time than some of the other options.

Plot inline or a separate window using Matplotlib in Spyder IDE

Magic commands such as

%matplotlib qt  

work in the iPython console and Notebook, but do not work within a script.

In that case, after importing:

from IPython import get_ipython

use:

get_ipython().run_line_magic('matplotlib', 'inline')

for inline plotting of the following code, and

get_ipython().run_line_magic('matplotlib', 'qt')

for plotting in an external window.

Edit: solution above does not always work, depending on your OS/Spyder version Anaconda issue on GitHub. Setting the Graphics Backend to Automatic (as indicated in another answer: Tools >> Preferences >> IPython console >> Graphics --> Automatic) solves the problem for me.

Then, after a Console restart, one can switch between Inline and External plot windows using the get_ipython() command, without having to restart the console.

Compiling a java program into an executable

I use launch4j

ANT Command:

<target name="jar" depends="compile, buildDLLs, copy">
    <jar basedir="${java.bin.dir}" destfile="${build.dir}/Project.jar" manifest="META-INF/MANIFEST.MF" />
</target>

<target name="exe" depends="jar">
    <exec executable="cmd" dir="${launch4j.home}">
        <arg line="/c launch4jc.exe ${basedir}/${launch4j.dir}/L4J_ProjectConfig.xml" />
    </exec>
</target>

Android Studio cannot resolve R in imported project?

The solution posted by https://stackoverflow.com/users/1373278/hoss above worked for me. I am reproducing it here because I cannot yet comment on hoss' post:

Remove import android.R; from your activity file in question.

My setup:

Android Studio 1.2.2

Exported project from one Mac to Git (everything was working). I then imported the project on another Mac from Git. Thats when it stopped resolving the resource files.

I tried everything on this thread:

  1. invalidating cache and restart
  2. Delete .iml files and .idea folder and reimport project
  3. Clean and Rebuild project

Nothing worked except removing import android.R; from my activity java file.

To avoid this issue in the future add .idea folder to your .gitignore file. There is a nice plugin from git for gitignore in Android Studio. Install this plugin and right click in .idea > Add to .gitignore

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

Mkcert from @FiloSottile makes this process infinitely simpler:

  1. Install mkcert, there are instructions for macOS/Windows/Linux
  2. mkcert -install to create a local CA
  3. mkcert localhost 127.0.0.1 ::1 to create a trusted cert for localhost in the current directory
  4. You're using node (which doesn't use the system root store), so you need to specify the CA explicitly in an environment variable, e.g: export NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem"
  5. Finally run your express server using the setup described in various other answers (e.g. below)
  6. boom. localhost's swimming in green.

Basic node setup:

const https = require('https');
const fs = require('fs');
const express = require('express');

const app = express();    
const server = https.createServer({
    key: fs.readFileSync('/XXX/localhost+2-key.pem'), // where's me key?
    cert: fs.readFileSync('/XXX/localhost+2.pem'), // where's me cert?
    requestCert: false,
    rejectUnauthorized: false,
}, app).listen(10443); // get creative

is there a post render callback for Angular JS directive?

None of the solutions worked for me accept from using a timeout. This is because I was using a template that was dynamically being created during the postLink.

Note however, there can be a timeout of '0' as the timeout adds the function being called to the browser's queue which will occur after the angular rendering engine as this is already in the queue.

Refer to this: http://blog.brunoscopelliti.com/run-a-directive-after-the-dom-has-finished-rendering

How to spyOn a value property (rather than a method) with Jasmine

In February 2017, they merged a PR adding this feature, they released in April 2017.

so to spy on getters/setters you use: const spy = spyOnProperty(myObj, 'myGetterName', 'get'); where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {} and the third param is the type get or set.

You can use the same assertions that you already use with the spies created with spyOn.

So you can for example:

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.

Here's the line in the github source code where this method is available if you are interested.

https://github.com/jasmine/jasmine/blob/7f8f2b5e7a7af70d7f6b629331eb6fe0a7cb9279/src/core/requireInterface.js#L199

Answering the original question, with jasmine 2.6.1, you would:

const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

You could add in your code a call system with the new definition:

sprintf(newdef,"export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s:%s",ld1,ld2);
system(newdef);

But, I don't know it that is the rigth solution but it works.

Regards

multiple conditions for filter in spark data frames

This question has been answered but for future reference, I would like to mention that, in the context of this question, the where and filter methods in Dataset/Dataframe supports two syntaxes: The SQL string parameters:

df2 = df1.filter(("Status = 2 or Status = 3"))

and Col based parameters (mentioned by @David ):

df2 = df1.filter($"Status" === 2 || $"Status" === 3)

It seems the OP'd combined these two syntaxes. Personally, I prefer the first syntax because it's cleaner and more generic.

write newline into a file

Solution:

in WINDOWS you should write "\r\n" for a new line.

Cannot find name 'require' after upgrading to Angular4

As for me, using VSCode and Angular 5, only had to add "node" to types in tsconfig.app.json. Save, and restart the server.

_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
    .._x000D_
    "types": [_x000D_
      "node"_x000D_
    ]_x000D_
  }_x000D_
  .._x000D_
}
_x000D_
_x000D_
_x000D_

One curious thing, is that this problem "cannot find require (", does not happen when excuting with ts-node

Get Category name from Post ID

doesn't

<?php get_the_category( $id ) ?>

do just that, inside the loop?

For outside:

<?php
global $post;
$categories = get_the_category($post->ID);
var_dump($categories);
?>

Chart creating dynamically. in .net, c#

Add a reference to System.Windows.Form.DataVisualization, then add the appropriate using statement:

using System.Windows.Forms.DataVisualization.Charting;

private void CreateChart()
{
    var series = new Series("Finance");

    // Frist parameter is X-Axis and Second is Collection of Y- Axis
    series.Points.DataBindXY(new[] { 2001, 2002, 2003, 2004 }, new[] { 100, 200, 90, 150 });
    chart1.Series.Add(series);

}

Update just one gem with bundler

If you want to update a single gem to a specific version:

  1. change the version of the gem in the Gemfile
  2. bundle update
> ruby -v
ruby 2.6.5p114 (2019-10-01 revision 67812) [x86_64-darwin19]
> gem -v
3.0.3
> bundle -v
Bundler version 2.1.4

How to remove docker completely from ubuntu 14.04

sudo apt-get remove docker docker-engine docker.io containerd runc
sudo rm -rf /var/lib/docker
sudo apt-get autoclean
sudo apt-get update

ElasticSearch - Return Unique Values

To had to distinct by two fields (derivative_id & vehicle_type) and to sort by cheapest car. Had to nest aggs.

GET /cars/_search
{
  "size": 0,
  "aggs": {
    "distinct_by_derivative_id": {
      "terms": { 
        "field": "derivative_id"
      },
      "aggs": {
        "vehicle_type": {
          "terms": {
            "field": "vehicle_type"
          },
          "aggs": {
            "cheapest_vehicle": {
              "top_hits": {
                "sort": [
                  { "rental": { "order": "asc" } }
                ],
                "_source": { "includes": [ "manufacturer_name",
                  "rental",
                  "vehicle_type" 
                  ]
                },
                "size": 1
              }
            }
          }
        }
      }
    }
  }
}

Result:

{
  "took" : 3,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 8,
      "relation" : "eq"
    },
    "max_score" : null,
    "hits" : [ ]
  },
  "aggregations" : {
    "distinct_by_derivative_id" : {
      "doc_count_error_upper_bound" : 0,
      "sum_other_doc_count" : 0,
      "buckets" : [
        {
          "key" : "04",
          "doc_count" : 3,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "8",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Renault",
                          "rental" : 89.99
                        },
                        "sort" : [
                          89.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "7",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 99.99
                        },
                        "sort" : [
                          99.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "01",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "1",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              },
              {
                "key" : "LCV",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "2",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "LCV",
                          "manufacturer_name" : "Ford",
                          "rental" : 599.99
                        },
                        "sort" : [
                          599.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "02",
          "doc_count" : 2,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 2,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 2,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "4",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 499.99
                        },
                        "sort" : [
                          499.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        },
        {
          "key" : "03",
          "doc_count" : 1,
          "vehicle_type" : {
            "doc_count_error_upper_bound" : 0,
            "sum_other_doc_count" : 0,
            "buckets" : [
              {
                "key" : "CAR",
                "doc_count" : 1,
                "cheapest_vehicle" : {
                  "hits" : {
                    "total" : {
                      "value" : 1,
                      "relation" : "eq"
                    },
                    "max_score" : null,
                    "hits" : [
                      {
                        "_index" : "cars",
                        "_type" : "_doc",
                        "_id" : "5",
                        "_score" : null,
                        "_source" : {
                          "vehicle_type" : "CAR",
                          "manufacturer_name" : "Audi",
                          "rental" : 399.99
                        },
                        "sort" : [
                          399.99
                        ]
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      ]
    }
  }
}

Check if an element contains a class in JavaScript?

I would Poly fill the classList functionality and use the new syntax. This way newer browser will use the new implementation (which is much faster) and only old browsers will take the performance hit from the code.

https://github.com/remy/polyfills/blob/master/classList.js

Splitting String and put it on int array

You are doing Integer division, so you will lose the correct length if the user happens to put in an odd number of inputs - that is one problem I noticed. Because of this, when I run the code with an input of '1,2,3,4,5,6,7' my last value is ignored...

no pg_hba.conf entry for host

To resolved this problem, you can try this.

first you have find out your pg_hba.conf and write :

local all all md5

after that restart pg server:

postgresql restart

or

sudo /etc/init.d/postgresql restart

C# error: "An object reference is required for the non-static field, method, or property"

It looks like you want:

public static string GetRandomBits()

Without static, you would need an object before you can call the GetRandomBits() method. However, since the implementation of GetRandomBits() does not depend on the state of any Program object, it's best to declare it static.

How do I check if there are duplicates in a flat list?

A more simple solution is as follows. Just check True/False with pandas .duplicated() method and then take sum. Please also see pandas.Series.duplicated — pandas 0.24.1 documentation

import pandas as pd

def has_duplicated(l):
    return pd.Series(l).duplicated().sum() > 0

print(has_duplicated(['one', 'two', 'one']))
# True
print(has_duplicated(['one', 'two', 'three']))
# False

Remove all padding and margin table HTML and CSS

Remove padding between cells inside the table. Just use cellpadding=0 and cellspacing=0 attributes in table tag.

How to add a response header on nginx when using proxy_pass?

There is a module called HttpHeadersMoreModule that gives you more control over headers. It does not come with Nginx and requires additional installation. With it, you can do something like this:

location ... {
  more_set_headers "Server: my_server";
}

That will "set the Server output header to the custom value for any status code and any content type". It will replace headers that are already set or add them if unset.

Is it possible to install iOS 6 SDK on Xcode 5?

Just for me the easiest solution:

  1. Locate an older SDK like for example "iPhoneOS6.1 sdk" in an older version of xcode for example. If you haven't, you can downlad it from Apple Developer server at this address: https://developer.apple.com/downloads/index.action?name=Xcode When you open the xcode.dmg you can find it by opening the Xcode.app (right click and "show contents") and go to Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS6.1 sdk enter image description here
  2. Simple Copy the folder iPhoneOS6.X sdk and paste it in your xcode.app
    • right click on your xcode.app in Applications folder.
    • Go to Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/
    • Just paste here.

enter image description here

  1. Close your xcode app and re-open it again.

To test an app in iOS 6 on your simulator: - Just choose iOS 6.0 in your active sheme. enter image description here

To build your app in iOS 6, so the design of your app will be the older design on an iPhone with iOS 7 also: - Choose iOS6.1 in Targets - Base SDK

enter image description here

Just note : When you change the base SDK in your Targets, iOS 7.0 won't be available anymore for building on the simulator !

How to detect online/offline event cross-browser?

In HTML5 you can use the navigator.onLine property. Look here:

http://www.w3.org/TR/offline-webapps/#related

Probably your current behavior is random as the javascript only ready the "browser" variable and then knows if you're offline and online, but it doesn't actually check the Network Connection.

Let us know if this is what you're looking for.

Kind Regards,

How to get device make and model on iOS?

EITHER try this library: http://github.com/erica/uidevice-extension/ (by Erica Sadun). (The library is 7-8 years old, and hence is obsolete)

(Sample Code):

    [[UIDevice currentDevice] platformType]   // ex: UIDevice4GiPhone
    [[UIDevice currentDevice] platformString] // ex: @"iPhone 4G"

OR You can use this method:

You can get the device model number using uname from sys/utsname.h. For example:

Objective-C

    #import <sys/utsname.h> // import it in your header or implementation file.

    NSString* deviceName()
    {
        struct utsname systemInfo;
        uname(&systemInfo);
    
        return [NSString stringWithCString:systemInfo.machine
                                  encoding:NSUTF8StringEncoding];
    }

Swift 3

    extension UIDevice {
        var modelName: String {
            var systemInfo = utsname()
            uname(&systemInfo)
            let machineMirror = Mirror(reflecting: systemInfo.machine)
            let identifier = machineMirror.children.reduce("") { identifier, element in
                guard let value = element.value as? Int8, value != 0 else { return identifier }
                return identifier + String(UnicodeScalar(UInt8(value)))
            }
            return identifier
        }
    }

    print(UIDevice.current.modelName)

The result should be:

// Output on a simulator
@"i386"      on 32-bit Simulator
@"x86_64"    on 64-bit Simulator

// Output on an iPhone
@"iPhone1,1" on iPhone
@"iPhone1,2" on iPhone 3G
@"iPhone2,1" on iPhone 3GS
@"iPhone3,1" on iPhone 4 (GSM)
@"iPhone3,2" on iPhone 4 (GSM Rev A)
@"iPhone3,3" on iPhone 4 (CDMA/Verizon/Sprint)
@"iPhone4,1" on iPhone 4S
@"iPhone5,1" on iPhone 5 (model A1428, AT&T/Canada)
@"iPhone5,2" on iPhone 5 (model A1429, everything else)
@"iPhone5,3" on iPhone 5c (model A1456, A1532 | GSM)
@"iPhone5,4" on iPhone 5c (model A1507, A1516, A1526 (China), A1529 | Global)
@"iPhone6,1" on iPhone 5s (model A1433, A1533 | GSM)
@"iPhone6,2" on iPhone 5s (model A1457, A1518, A1528 (China), A1530 | Global)
@"iPhone7,1" on iPhone 6 Plus
@"iPhone7,2" on iPhone 6
@"iPhone8,1" on iPhone 6S
@"iPhone8,2" on iPhone 6S Plus
@"iPhone8,4" on iPhone SE
@"iPhone9,1" on iPhone 7 (CDMA)
@"iPhone9,3" on iPhone 7 (GSM)
@"iPhone9,2" on iPhone 7 Plus (CDMA)
@"iPhone9,4" on iPhone 7 Plus (GSM)
@"iPhone10,1" on iPhone 8 (CDMA)
@"iPhone10,4" on iPhone 8 (GSM)
@"iPhone10,2" on iPhone 8 Plus (CDMA)
@"iPhone10,5" on iPhone 8 Plus (GSM)
@"iPhone10,3" on iPhone X (CDMA)
@"iPhone10,6" on iPhone X (GSM)
@"iPhone11,2" on iPhone XS
@"iPhone11,4" on iPhone XS Max
@"iPhone11,6" on iPhone XS Max China
@"iPhone11,8" on iPhone XR
@"iPhone12,1" on iPhone 11
@"iPhone12,3" on iPhone 11 Pro
@"iPhone12,5" on iPhone 11 Pro Max
@"iPhone12,8" on iPhone SE (2nd Gen)
@"iPhone13,1" on iPhone 12 Mini
@"iPhone13,2" on iPhone 12
@"iPhone13,3" on iPhone 12 Pro
@"iPhone13,4" on iPhone 12 Pro Max

//iPad 1
@"iPad1,1" on iPad - Wifi (model A1219)
@"iPad1,2" on iPad - Wifi + Cellular (model A1337)

//iPad 2
@"iPad2,1" - Wifi (model A1395)
@"iPad2,2" - GSM (model A1396)
@"iPad2,3" - 3G (model A1397)
@"iPad2,4" - Wifi (model A1395)

// iPad Mini
@"iPad2,5" - Wifi (model A1432)
@"iPad2,6" - Wifi + Cellular (model  A1454)
@"iPad2,7" - Wifi + Cellular (model  A1455)

//iPad 3
@"iPad3,1" - Wifi (model A1416)
@"iPad3,2" - Wifi + Cellular (model  A1403)
@"iPad3,3" - Wifi + Cellular (model  A1430)

//iPad 4
@"iPad3,4" - Wifi (model A1458)
@"iPad3,5" - Wifi + Cellular (model  A1459)
@"iPad3,6" - Wifi + Cellular (model  A1460)

//iPad AIR
@"iPad4,1" - Wifi (model A1474)
@"iPad4,2" - Wifi + Cellular (model A1475)
@"iPad4,3" - Wifi + Cellular (model A1476)

// iPad Mini 2
@"iPad4,4" - Wifi (model A1489)
@"iPad4,5" - Wifi + Cellular (model A1490)
@"iPad4,6" - Wifi + Cellular (model A1491)

// iPad Mini 3
@"iPad4,7" - Wifi (model A1599)
@"iPad4,8" - Wifi + Cellular (model A1600)
@"iPad4,9" - Wifi + Cellular (model A1601)

// iPad Mini 4
@"iPad5,1" - Wifi (model A1538)
@"iPad5,2" - Wifi + Cellular (model A1550)

//iPad AIR 2
@"iPad5,3" - Wifi (model A1566)
@"iPad5,4" - Wifi + Cellular (model A1567)

// iPad PRO 9.7"
@"iPad6,3" - Wifi (model A1673)
@"iPad6,4" - Wifi + Cellular (model A1674)
@"iPad6,4" - Wifi + Cellular (model A1675)

//iPad PRO 12.9"
@"iPad6,7" - Wifi (model A1584)
@"iPad6,8" - Wifi + Cellular (model A1652)

//iPad (5th generation)
@"iPad6,11" - Wifi (model A1822)
@"iPad6,12" - Wifi + Cellular (model A1823)
         
//iPad PRO 12.9" (2nd Gen)
@"iPad7,1" - Wifi (model A1670)
@"iPad7,2" - Wifi + Cellular (model A1671)
@"iPad7,2" - Wifi + Cellular (model A1821)
         
//iPad PRO 10.5"
@"iPad7,3" - Wifi (model A1701)
@"iPad7,4" - Wifi + Cellular (model A1709)

// iPad (6th Gen)
@"iPad7,5" - WiFi
@"iPad7,6" - WiFi + Cellular

// iPad (7th Gen)
@"iPad7,11" - WiFi
@"iPad7,12" - WiFi + Cellular

//iPad PRO 11"
@"iPad8,1" - WiFi
@"iPad8,2" - 1TB, WiFi
@"iPad8,3" - WiFi + Cellular
@"iPad8,4" - 1TB, WiFi + Cellular

//iPad PRO 12.9" (3rd Gen)
@"iPad8,5" - WiFi
@"iPad8,6" - 1TB, WiFi
@"iPad8,7" - WiFi + Cellular
@"iPad8,8" - 1TB, WiFi + Cellular

//iPad PRO 11" (2nd Gen)
@"iPad8,9" - WiFi
@"iPad8,10" - 1TB, WiFi

//iPad PRO 12.9" (4th Gen)
@"iPad8,11" - (WiFi)
@"iPad8,12" - (WiFi+Cellular)

// iPad mini 5th Gen
@"iPad11,1" - WiFi
@"iPad11,2" - Wifi  + Cellular

// iPad Air 3rd Gen
@"iPad11,3" - Wifi 
@"iPad11,4" - Wifi  + Cellular

// iPad (8th Gen)
@"iPad11,6" - iPad 8th Gen (WiFi)
@"iPad11,7" - iPad 8th Gen (WiFi+Cellular)

// iPad Air 4th Gen
@"iPad13,1" - iPad air 4th Gen (WiFi)
@"iPad13,2" - iPad air 4th Gen (WiFi+Cellular)

//iPod Touch
@"iPod1,1"   on iPod Touch
@"iPod2,1"   on iPod Touch Second Generation
@"iPod3,1"   on iPod Touch Third Generation
@"iPod4,1"   on iPod Touch Fourth Generation
@"iPod5,1"   on iPod Touch 5th Generation
@"iPod7,1"   on iPod Touch 6th Generation
@"iPod9,1"   on iPod Touch 7th Generation

// Apple Watch
@"Watch1,1" on Apple Watch 38mm case
@"Watch1,2" on Apple Watch 38mm case
@"Watch2,6" on Apple Watch Series 1 38mm case
@"Watch2,7" on Apple Watch Series 1 42mm case
@"Watch2,3" on Apple Watch Series 2 38mm case
@"Watch2,4" on Apple Watch Series 2 42mm case
@"Watch3,1" on Apple Watch Series 3 38mm case (GPS+Cellular)
@"Watch3,2" on Apple Watch Series 3 42mm case (GPS+Cellular)
@"Watch3,3" on Apple Watch Series 3 38mm case (GPS)
@"Watch3,4" on Apple Watch Series 3 42mm case (GPS)
@"Watch4,1" on Apple Watch Series 4 40mm case (GPS)
@"Watch4,2" on Apple Watch Series 4 44mm case (GPS)
@"Watch4,3" on Apple Watch Series 4 40mm case (GPS+Cellular)
@"Watch4,4" on Apple Watch Series 4 44mm case (GPS+Cellular)
@"Watch5,1" on Apple Watch Series 5 40mm case (GPS)
@"Watch5,2" on Apple Watch Series 5 44mm case (GPS)
@"Watch5,3" on Apple Watch Series 5 40mm case (GPS+Cellular)
@"Watch5,4" on Apple Watch Series 5 44mm case (GPS+Cellular)
@"Watch5,9" on Apple Watch SE 40mm case (GPS)
@"Watch5,10" on Apple Watch SE 44mm case (GPS)
@"Watch5,11" on Apple Watch SE 40mm case (GPS+Cellular)
@"Watch5,12" on Apple Watch SE 44mm case (GPS+Cellular)
@"Watch6,1" on Apple Watch Series 6 40mm case (GPS)
@"Watch6,2" on Apple Watch Series 6 44mm case (GPS)
@"Watch6,3" on Apple Watch Series 6 40mm case (GPS+Cellular)
@"Watch6,4" on Apple Watch Series 6 44mm case (GPS+Cellular)

JavaScript click event listener on class

Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:

    document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
        "click",
        e => {
            alert(e.currentTarget.dataset.myDataContent);
        }));

How to record phone calls in android?

The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:

private void startRecord(String seed) {
        String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
        File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        String file_name = "Record" + seed;
        try {
            audiofile = File.createTempFile(file_name, ".amr", sampleDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        recorder = new MediaRecorder();

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
        recordstarted = true;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_IN)) {
            if ((bundle = intent.getExtras()) != null) {
                state = bundle.getString(TelephonyManager.EXTRA_STATE);
                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    wasRinging = true;
                    Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    if (wasRinging == true) {

                        Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                        startRecord("incoming");
                    }
                } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                    wasRinging = false;
                    Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                    if (recordstarted) {
                        recorder.stop();
                        recordstarted = false;
                    }
                }
            }
        } else if (intent.getAction().equals(ACTION_OUT)) {
            if ((bundle = intent.getExtras()) != null) {
                outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                startRecord("outgoing");
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state != null) {
                        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                            wasRinging = false;
                            Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                            if (recordstarted) {
                                recorder.stop();
                                recordstarted = false;
                            }
                        }
                    }


                }
            }
        }
    }

Android translate animation - permanently move View to new position using AnimationListener

I usually prefer to work with deltas in translate animation, since it avoids a lot of confusion.

Try this out, see if it works for you:

TranslateAnimation anim = new TranslateAnimation(0, amountToMoveRight, 0, amountToMoveDown);
anim.setDuration(1000);

anim.setAnimationListener(new TranslateAnimation.AnimationListener() {

    @Override
    public void onAnimationStart(Animation animation) { }

    @Override
    public void onAnimationRepeat(Animation animation) { }

    @Override
    public void onAnimationEnd(Animation animation) 
    {
        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams)view.getLayoutParams();
        params.topMargin += amountToMoveDown;
        params.leftMargin += amountToMoveRight;
        view.setLayoutParams(params);
    }
});

view.startAnimation(anim);

Make sure to make amountToMoveRight / amountToMoveDown final

Hope this helps :)

How to create an alert message in jsp page after submit process is complete

You can also create a new jsp file sayng that form is submited and in your main action file just write its file name

Eg. Your form is submited is in a file succes.jsp Then your action file will have

Request.sendRedirect("success.jsp")

What is the difference between 'E', 'T', and '?' for Java generics?

Well there's no difference between the first two - they're just using different names for the type parameter (E or T).

The third isn't a valid declaration - ? is used as a wildcard which is used when providing a type argument, e.g. List<?> foo = ... means that foo refers to a list of some type, but we don't know what.

All of this is generics, which is a pretty huge topic. You may wish to learn about it through the following resources, although there are more available of course:

Android, How to limit width of TextView (and add three dots at the end of text)?

You can limit your textview's number of characters and add (...) after the text. Suppose You need to show 5 letters only and thereafter you need to show (...), Just do the following :

String YourString = "abcdefghijk";

if(YourString.length()>5){

YourString  =  YourString.substring(0,4)+"...";

your_text_view.setText(YourString);
}else{

 your_text_view.setText(YourString); //Dont do any change

}

a little hack ^_^. Though its not a good solution. But a work around which worked for me :D

EDIT: I have added check for less character as per your limited no. of characters.

Setting Different Bar color in matplotlib Python

I assume you are using Series.plot() to plot your data. If you look at the docs for Series.plot() here:

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Series.plot.html

there is no color parameter listed where you might be able to set the colors for your bar graph.

However, the Series.plot() docs state the following at the end of the parameter list:

kwds : keywords
Options to pass to matplotlib plotting method

What that means is that when you specify the kind argument for Series.plot() as bar, Series.plot() will actually call matplotlib.pyplot.bar(), and matplotlib.pyplot.bar() will be sent all the extra keyword arguments that you specify at the end of the argument list for Series.plot().

If you examine the docs for the matplotlib.pyplot.bar() method here:

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.bar

..it also accepts keyword arguments at the end of it's parameter list, and if you peruse the list of recognized parameter names, one of them is color, which can be a sequence specifying the different colors for your bar graph.

Putting it all together, if you specify the color keyword argument at the end of your Series.plot() argument list, the keyword argument will be relayed to the matplotlib.pyplot.bar() method. Here is the proof:

import pandas as pd
import matplotlib.pyplot as plt

s = pd.Series(
    [5, 4, 4, 1, 12],
    index = ["AK", "AX", "GA", "SQ", "WN"]
)

#Set descriptions:
plt.title("Total Delay Incident Caused by Carrier")
plt.ylabel('Delay Incident')
plt.xlabel('Carrier')

#Set tick colors:
ax = plt.gca()
ax.tick_params(axis='x', colors='blue')
ax.tick_params(axis='y', colors='red')

#Plot the data:
my_colors = 'rgbkymc'  #red, green, blue, black, etc.

pd.Series.plot(
    s, 
    kind='bar', 
    color=my_colors,
)

plt.show()

enter image description here

Note that if there are more bars than colors in your sequence, the colors will repeat.

starting file download with JavaScript

I suggest to make an invisible iframe on the page and set it's src to url that you've received from the server - download will start without page reloading.

Or you can just set the current document.location.href to received url address. But that's can cause for user to see an error if the requested document actually does not exists.

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

Does JavaScript pass by reference?

Primitives are passed by value. But in case you only need to read the value of a primitve (and value is not known at the time when function is called) you can pass function which retrieves the value at the moment you need it.

function test(value) {
  console.log('retrieve value');
  console.log(value());
}

// call the function like this
var value = 1;
test(() => value);

Android: ListView elements with multiple clickable buttons

The solution to this is actually easier than I thought. You can simply add in your custom adapter's getView() method a setOnClickListener() for the buttons you're using.

Any data associated with the button has to be added with myButton.setTag() in the getView() and can be accessed in the onClickListener via view.getTag()

I posted a detailed solution on my blog as a tutorial.

Generate ER Diagram from existing MySQL database, created for CakePHP

Try MySQL Workbench. It packs in very nice data modeling tools. Check out their screenshots for EER diagrams (Enhanced Entity Relationships, which are a notch up ER diagrams).

This isn't CakePHP specific, but you can modify the options so that the foreign keys and join tables follow the conventions that CakePHP uses. This would simplify your data modeling process once you've put the rules in place.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

Unit testing void methods?

What ever instance you are using to call the void method , You can just use ,Verfiy

For Example:

In My case its _Log is the instance and LogMessage is the method to be tested:

try
{
    this._log.Verify(x => x.LogMessage(Logger.WillisLogLevel.Info, Logger.WillisLogger.Usage, "Created the Student with name as"), "Failure");
}
Catch 
{
    Assert.IsFalse(ex is Moq.MockException);
}

Is the Verify throws an exception due to failure of the method the test would Fail ?

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

How to install mod_ssl for Apache httpd?

Are any other LoadModule commands referencing modules in the /usr/lib/httpd/modules folder? If so, you should be fine just adding LoadModule ssl_module /usr/lib/httpd/modules/mod_ssl.so to your conf file.

Otherwise, you'll want to copy the mod_ssl.so file to whatever directory the other modules are being loaded from and reference it there.

What is the simplest and most robust way to get the user's current location on Android?

Actualy we can use the two providers(GPS & NETWORK). And they just share a public listener:

locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 90 * 1000, (float) 10.0, listener);

This is necessary because the OnLocationChanged() method always need to be called in time.

JQuery - Call the jquery button click event based on name property

You have to use the jquery attribute selector. You can read more here:

http://api.jquery.com/attribute-equals-selector/

In your case it should be:

$('input[name="btnName"]')

Warning about `$HTTP_RAW_POST_DATA` being deprecated

Been awhile until I came across this error. Put up my answer for anyone who may stumble upon this issue.

The error only means that you are sending an empty POST request. This error is commonly found on HTTPRequests with no parameters passed. To avoid this error, you can always add a parameter to the POST without changing the php.ini.

Like:

$.post(URL_HERE
    ,{addedvar : 'anycontent'}
    ,function(d){
       doAnyHere(d);
    }
    ,'json' //or 'html','text'
);

ViewDidAppear is not called when opening app from background

Using Objective-C

You should register a UIApplicationWillEnterForegroundNotification in your ViewController's viewDidLoad method and whenever app comes back from background you can do whatever you want to do in the method registered for notification. ViewController's viewWillAppear or viewDidAppear won't be called when app comes back from background to foreground.

-(void)viewDidLoad{

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff)

  name:UIApplicationWillEnterForegroundNotification object:nil];
}

-(void)doYourStuff{

   // do whatever you want to do when app comes back from background.
}

Don't forget to unregister the notification you are registered for.

-(void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

Note if you register your viewController for UIApplicationDidBecomeActiveNotification then your method would be called every time your app becomes active, It is not recommended to register viewController for this notification .

Using Swift

For adding observer you can use the following code

 override func viewDidLoad() {
    super.viewDidLoad()

     NotificationCenter.default.addObserver(self, selector: "doYourStuff", name: UIApplication.willEnterForegroundNotification, object: nil)
 }

 func doYourStuff(){
     // your code
 }

To remove observer you can use deinit function of swift.

deinit {
    NotificationCenter.default.removeObserver(self)
}

How to run a shell script at startup

Working with Python 3 microservices or shell; using Ubuntu Server 18.04 (Bionic Beaver) or Ubuntu 19.10 (Eoan Ermine) or Ubuntu 18.10 (Cosmic Cuttlefish) I always do like these steps, and it worked always too:

  1. Creating a microservice called p example "brain_microservice1.service" in my case:

    $ nano /lib/systemd/system/brain_microservice1.service
    
  2. Inside this new service that you are in:

    [Unit]
    Description=brain_microservice_1
    After=multi-user.target
    
    [Service]
    Type=simple
    ExecStart=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices    /microservice_1.py -k start -DFOREGROUND
    ExecStop=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k graceful-stop
    ExecReload=/usr/bin/python3.7 /root/scriptsPython/RUN_SERVICES/microservices/microservice_1.py -k graceful
    PrivateTmp=true
    LimitNOFILE=infinity
    KillMode=mixed
    Restart=on-failure
    RestartSec=5s
    
    [Install]
    WantedBy=multi-user.target
    
  3. Give the permissions:

    $ chmod -X /lib/systemd/system/brain_microservice*
    $ chmod -R 775 /lib/systemd/system/brain_microservice*
    
  4. Give the execution permission then:

    $ systemctl daemon-reload
    
  5. Enable then, this will make then always start on startup

    $ systemctl enable brain_microservice1.service
    
  6. Then you can test it;

    $ sudo reboot now

  7. Finish = SUCCESS!!

This can be done with the same body script to run shell, react ... database startup script ... any kind os code ... hope this help u...

...

how do I set height of container DIV to 100% of window height?

Add this to your css:

html, body {
    height:100%;
}

If you say height:100%, you mean '100% of the parent element'. If the parent element has no specified height, nothing will happen. You only set 100% on body, but you also need to add it to html.

Unable to install pyodbc on Linux

Struggled with the same issue

After running: sudo apt-get install unixodbc-dev

I was able to pip install pyodbc

What are some ways of accessing Microsoft SQL Server from Linux?

I was not confortable with the freetds solution, it's why i coded a class (command history, autocompletion on tables and fields, etc.)

http://www.phpclasses.org/package/8168-PHP-Use-ncurses-to-get-key-inputs-and-write-shell-text.html

Paste in insert mode?

Paste in Insert Mode

A custom map seems appropriate in this case. This is what I use to paste yanked items in insert mode:

inoremap <Leader>p <ESC>pa

My Leader key here is \; this means hitting \p in insert mode would paste the previously yanked items/lines.

What is the best way to iterate over a dictionary?

Using C# 7, add this extension method to any project of your solution:

public static class IDictionaryExtensions
{
    public static IEnumerable<(TKey, TValue)> Tuples<TKey, TValue>(
        this IDictionary<TKey, TValue> dict)
    {
        foreach (KeyValuePair<TKey, TValue> kvp in dict)
            yield return (kvp.Key, kvp.Value);
    }
}


And use this simple syntax

foreach (var(id, value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


Or this one, if you prefer

foreach ((string id, object value) in dict.Tuples())
{
    // your code using 'id' and 'value'
}


In place of the traditional

foreach (KeyValuePair<string, object> kvp in dict)
{
    string id = kvp.Key;
    object value = kvp.Value;

    // your code using 'id' and 'value'
}


The extension method transforms the KeyValuePair of your IDictionary<TKey, TValue> into a strongly typed tuple, allowing you to use this new comfortable syntax.

It converts -just- the required dictionary entries to tuples, so it does NOT converts the whole dictionary to tuples, so there are no performance concerns related to that.

There is a only minor cost calling the extension method for creating a tuple in comparison with using the KeyValuePair directly, which should NOT be an issue if you are assigning the KeyValuePair's properties Key and Value to new loop variables anyway.

In practice, this new syntax suits very well for most cases, except for low-level ultra-high performance scenarios, where you still have the option to simply not use it on that specific spot.

Check this out: MSDN Blog - New features in C# 7

How to get all Errors from ASP.Net MVC modelState?

Using LINQ:

IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);

React JS - Uncaught TypeError: this.props.data.map is not a function

If you're using react hooks you have to make sure that data was initialized as an array. Here's is how it must look like:

const[data, setData] = useState([])

JQuery get all elements by class name

Maybe not as clean or efficient as the already posted solutions, but how about the .each() function? E.g:

var mvar = "";
$(".mbox").each(function() {
    console.log($(this).html());
    mvar += $(this).html();
});
console.log(mvar);

How to check if running as root in a bash script

try the following code:

if [ "$(id -u)" != "0" ]; then
    echo "Sorry, you are not root."
    exit 1
fi

OR

if [ `id -u` != "0" ]; then
    echo "Sorry, you are not root."
    exit 1
fi

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Entity Framework The underlying provider failed on Open

I was facing the same error today, what I was doing wrong was that I was not adding Password tag in the connection string. As soon as I added the Password tag with correct password the error went away. Hope it helps someone.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

bash string compare to multiple correct values

Maybe you should better use a case for such lists:

case "$cms" in
  wordpress|meganto|typo3)
    do_your_else_case
    ;;
  *)
    do_your_then_case
    ;;
esac

I think for long such lists this is better readable.

If you still prefer the if you can do it with single brackets in two ways:

if [ "$cms" != wordpress -a "$cms" != meganto -a "$cms" != typo3 ]; then

or

if [ "$cms" != wordpress ] && [ "$cms" != meganto ] && [ "$cms" != typo3 ]; then

urllib2.HTTPError: HTTP Error 403: Forbidden

By adding a few more headers I was able to get the data:

import urllib2,cookielib

site= "http://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/getHistoricalData.jsp?symbol=JPASSOCIAT&fromDate=1-JAN-2012&toDate=1-AUG-2012&datePeriod=unselected&hiddDwnld=true"
hdr = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11',
       'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
       'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
       'Accept-Encoding': 'none',
       'Accept-Language': 'en-US,en;q=0.8',
       'Connection': 'keep-alive'}

req = urllib2.Request(site, headers=hdr)

try:
    page = urllib2.urlopen(req)
except urllib2.HTTPError, e:
    print e.fp.read()

content = page.read()
print content

Actually, it works with just this one additional header:

'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',

Can't find SDK folder inside Android studio path, and SDK manager not opening

Make sure all the folders are visible. click start>control panel>Appearance and Personalization>Show hidden files and folders then click "Show hidden files, folders and drives" The file should be in C:\Users\Username\AppData\Local\Android as mentioned above. otherwise you can check by opening Android SDK Manager - top left under SDK path.

php Replacing multiple spaces with a single space

preg_replace("/[[:blank:]]+/"," ",$input)

How to redirect the output of an application in background to /dev/null

You use:

yourcommand  > /dev/null 2>&1

If it should run in the Background add an &

yourcommand > /dev/null 2>&1 &

>/dev/null 2>&1 means redirect stdout to /dev/null AND stderr to the place where stdout points at that time

If you want stderr to occur on console and only stdout going to /dev/null you can use:

yourcommand 2>&1 > /dev/null

In this case stderr is redirected to stdout (e.g. your console) and afterwards the original stdout is redirected to /dev/null

If the program should not terminate you can use:

nohup yourcommand &

Without any parameter all output lands in nohup.out

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

using Newtonsoft.Json.Linq;
using System.Linq;
using System.IO;
using System.Collections.Generic;

public List<string> GetJsonValues(string filePath, string propertyName)
{
  List<string> values = new List<string>();
  string read = string.Empty;
  using (StreamReader r = new StreamReader(filePath))
  {
    var json = r.ReadToEnd();
    var jObj = JObject.Parse(json);
    foreach (var j in jObj.Properties())
    {
      if (j.Name.Equals(propertyName))
      {
        var value = jObj[j.Name] as JArray;
        return values = value.ToObject<List<string>>();
      }
    }
    return values;
  }
}

Can I run HTML files directly from GitHub, instead of just viewing their source?

Here is a little Greasemonkey script that will add a CDN button to html pages on github

Target page will be of the form: https://cdn.rawgit.com/user/repo/master/filename.js


// ==UserScript==
// @name        cdn.rawgit.com
// @namespace   github.com
// @include     https://github.com/*/blob/*.html
// @version     1
// @grant       none
// ==/UserScript==

var buttonGroup = $(".meta .actions .button-group");
var raw = buttonGroup.find("#raw-url");
var cdn = raw.clone();
cdn.attr("id", "cdn-url");
cdn.attr("href", "https://cdn.rawgit.com" + cdn.attr("href").replace("/raw/","/") );
cdn.text("CDN");
cdn.insertBefore(raw);

Wildcards in jQuery selectors

When you have a more complex id string the double quotes are mandatory.

For example if you have an id like this: id="2.2", the correct way to access it is: $('input[id="2.2"]')

As much as possible use the double quotes, for safety reasons.

Laravel 5 - How to access image uploaded in storage within View?

If you are on windows you can run this command on cmd:

mklink /j /path/to/laravel/public/avatars /path/to/laravel/storage/avatars 

from: http://www.sevenforums.com/tutorials/278262-mklink-create-use-links-windows.html

How to add action listener that listens to multiple buttons

Using my approach, you can write the button click event handler in the 'classical way', just like how you did it in VB or MFC ;)

Suppose we have a class for a frame window which contains 2 buttons:

class MainWindow {
    Jbutton searchButton;
    Jbutton filterButton;
}

You can use my 'router' class to route the event back to your MainWindow class:

class MainWindow {
    JButton searchButton;
    Jbutton filterButton;
    ButtonClickRouter buttonRouter = new ButtonClickRouter(this);
    
    void initWindowContent() {
        // create your components here...
        
        // setup button listeners
        searchButton.addActionListener(buttonRouter);
        filterButton.addActionListener(buttonRouter);
    }

    void on_searchButton() {
        // TODO your handler goes here...
    }
    
    void on_filterButton() {
        // TODO your handler goes here...
    }
}

Do you like it? :)

If you like this way and hate the Java's anonymous subclass way, then you are as old as I am. The problem of 'addActionListener(new ActionListener {...})' is that it squeezes all button handlers into one outer method which makes the programme look wired. (in case you have a number of buttons in one window)

Finally, the router class is at below. You can copy it into your programme without the need for any update.

Just one thing to mention: the button fields and the event handler methods must be accessible to this router class! To simply put, if you copy this router class in the same package of your programme, your button fields and methods must be package-accessible. Otherwise, they must be public.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ButtonClickRouter implements ActionListener {
    private Object target;

    ButtonClickRouter(Object target) {
        this.target = target;
    }

    @Override
    public void actionPerformed(ActionEvent actionEvent) {
        // get source button
        Object sourceButton = actionEvent.getSource();

        // find the corresponding field of the button in the host class
        Field fieldOfSourceButton = null;
        for (Field field : target.getClass().getDeclaredFields()) {
            try {
                if (field.get(target).equals(sourceButton)) {
                    fieldOfSourceButton = field;
                    break;
                }
            } catch (IllegalAccessException e) {
            }
        }

        if (fieldOfSourceButton == null)
            return;

        // make the expected method name for the source button
        // rule: suppose the button field is 'searchButton', then the method
        // is expected to be 'void on_searchButton()'
        String methodName = "on_" + fieldOfSourceButton.getName();

        // find such a method
        Method expectedHanderMethod = null;
        for (Method method : target.getClass().getDeclaredMethods()) {
            if (method.getName().equals(methodName)) {
                expectedHanderMethod = method;
                break;
            }
        }

        if (expectedHanderMethod == null)
            return;

        // fire
        try {
            expectedHanderMethod.invoke(target);
        } catch (IllegalAccessException | InvocationTargetException e) { }
    }
}

I'm a beginner in Java (not in programming), so maybe there are anything inappropriate in the above code. Review it before using it, please.

Live video streaming using Java?

Hi not an expert in streaming but my understanding is that it is included in th Java Media Framework JMF http://java.sun.com/javase/technologies/desktop/media/jmf/2.1.1/support-rtsp.html

Do you need to dispose of objects and set them to null?

I have to answer, too. The JIT generates tables together with the code from it's static analysis of variable usage. Those table entries are the "GC-Roots" in the current stack frame. As the instruction pointer advances, those table entries become invalid and so ready for garbage collection. Therefore: If it is a scoped variable, you don't need to set it to null - the GC will collect the object. If it is a member or a static variable, you have to set it to null

Multiple select statements in Single query

SELECT t1.credit, 
       t2.debit 
FROM   (SELECT Sum(c.total_amount) AS credit 
        FROM   credit c 
        WHERE  c.status = "a") AS t1, 
       (SELECT Sum(d.total_amount) AS debit 
        FROM   debit d 
        WHERE  d.status = "a") AS t2 

How to concatenate strings in a Windows batch file?

Based on Rubens' solution, you need to enable Delayed Expansion of env variables (type "help setlocal" or "help cmd") so that the var is correctly evaluated in the loop:

@echo off
setlocal enabledelayedexpansion
set myvar=the list: 
for /r %%i In (*.sql) DO set myvar=!myvar! %%i,
echo %myvar%

Also consider the following restriction (MSDN):

The maximum individual environment variable size is 8192bytes.

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

Make a DIV fill an entire table cell

Because I do not have enough reputation to post a comment, I want to add a complete cross-browser solution that combined @Madeorsk and @Saadat's approaches with some slight modification! (Tested on Chrome, Firefox, Safari, IE, and Edge as of 2/10/2020)

table { height: 1px; }
tr { height: 100%; }
td { height: 100%; }
td > div { 
   height: -webkit-calc(100vh);
   height: -moz-calc(100vh);
   height: calc(100%);
   width: 100%;
    background: pink;  // This will show that it works!
} 

However, if you're like me, than you want to control vertical alignment as well, and in those cases, I like to use flexbox:

td > div {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: flex-end;
}

Java reverse an int value without using array

public static void main(String args[]) {
    int n = 0, res = 0, n1 = 0, rev = 0;
    int sum = 0;
    Scanner scan = new Scanner(System.in);
    System.out.println("Please Enter No.: ");
    n1 = scan.nextInt(); // String s1=String.valueOf(n1);
    int len = (n1 == 0) ? 1 : (int) Math.log10(n1) + 1;
    while (n1 > 0) {
        rev = res * ((int) Math.pow(10, len));
        res = n1 % 10;
        n1 = n1 / 10;
        // sum+=res; //sum=sum+res;
        sum += rev;
        len--;
    }
    // System.out.println("sum No: " + sum);
    System.out.println("sum No: " + (sum + res));
}

This will return reverse of integer

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

If you're working with an x64 server, keep in mind that there are different ODBC settings for x86 and x64 applications. The "Data Sources (ODBC)" tool in the Administrative Tools list takes you to the x64 version. To view/edit the x86 ODBC settings, you'll need to run that version of the tool manually:

%windir%\SysWOW64\odbcad32.exe (%windir% is usually C:\Windows)

When your app runs as x64, it will use the x64 data sources, and when it runs as x86, it will use those data sources instead.

Convert PDF to PNG using ImageMagick

Reducing the image size before output results in something that looks sharper, in my case:

convert -density 300 a.pdf -resize 25% a.png

What's the difference between Cache-Control: max-age=0 and no-cache?

By the way, it's worth noting that some mobile devices, particularly Apple products like iPhone/iPad completely ignore headers like no-cache, no-store, Expires: 0, or whatever else you may try to force them to not re-use expired form pages.

This has caused us no end of headaches as we try to get the issue of a user's iPad say, being left asleep on a page they have reached through a form process, say step 2 of 3, and then the device totally ignores the store/cache directives, and as far as I can tell, simply takes what is a virtual snapshot of the page from its last state, that is, ignoring what it was told explicitly, and, not only that, taking a page that should not be stored, and storing it without actually checking it again, which leads to all kinds of strange Session issues, among other things.

I'm just adding this in case someone comes along and can't figure out why they are getting session errors with particularly iphones and ipads, which seem by far to be the worst offenders in this area.

I've done fairly extensive debugger testing with this issue, and this is my conclusion, the devices ignore these directives completely.

Even in regular use, I've found that some mobiles also totally fail to check for new versions via say, Expires: 0 then checking last modified dates to determine if it should get a new one.

It simply doesn't happen, so what I was forced to do was add query strings to the css/js files I needed to force updates on, which tricks the stupid mobile devices into thinking it's a file it does not have, like: my.css?v=1, then v=2 for a css/js update. This largely works.

User browsers also, by the way, if left to their defaults, as of 2016, as I continuously discover (we do a LOT of changes and updates to our site) also fail to check for last modified dates on such files, but the query string method fixes that issue. This is something I've noticed with clients and office people who tend to use basic normal user defaults on their browsers, and have no awareness of caching issues with css/js etc, almost invariably fail to get the new css/js on change, which means the defaults for their browsers, mostly MSIE / Firefox, are not doing what they are told to do, they ignore changes and ignore last modified dates and do not validate, even with Expires: 0 set explicitly.

This was a good thread with a lot of good technical information, but it's also important to note how bad the support for this stuff is in particularly mobile devices. Every few months I have to add more layers of protection against their failure to follow the header commands they receive, or to properly interpet those commands.

IndexOf function in T-SQL

I believe you want to use CHARINDEX. You can read about it here.

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

HTTP Content-Type Header and JSON

Content-Type: application/json is just the content header. The content header is just information about the type of returned data, ex::JSON,image(png,jpg,etc..),html.

Keep in mind, that JSON in JavaScript is an array or object. If you want to see all the data, use console.log instead of alert:

alert(response.text); // Will alert "[object Object]" string
console.log(response.text); // Will log all data objects

If you want to alert the original JSON content as a string, then add single quotation marks ('):

echo "'" . json_encode(array('text' => 'omrele')) . "'";
// alert(response.text) will alert {"text":"omrele"}

Do not use double quotes. It will confuse JavaScript, because JSON uses double quotes on each value and key:

echo '<script>var returndata=';
echo '"' . json_encode(array('text' => 'omrele')) . '"';
echo ';</script>';

// It will return the wrong JavaScript code:
<script>var returndata="{"text":"omrele"}";</script>

Remove pandas rows with duplicate indices

This adds the index as a dataframe column, drops duplicates on that, then removes the new column:

df = df.reset_index().drop_duplicates(subset='index', keep='last').set_index('index').sort_index()

Note that the use of .sort_index() above at the end is as needed and is optional.

Basic HTML - how to set relative path to current folder?

The top answer is not clear enough. here is what worked for me: The correct format should look like this if you want to point to the actual file:

 <a href="./page.html">

This will have you point to that file within the same folder if you are on the page http://example.com/folder/index.html

How do I animate constraint changes?

I was trying to animate Constraints and was not really easy to found a good explanation.

What other answers are saying is totally true: you need to call [self.view layoutIfNeeded]; inside animateWithDuration: animations:. However, the other important point is to have pointers for every NSLayoutConstraint you want to animate.

I created an example in GitHub.

Jquery sortable 'change' event element position

This works for me:

start: function(event, ui) {
        var start_pos = ui.item.index();
        ui.item.data('start_pos', start_pos);
    },
update: function (event, ui) {
        var start_pos = ui.item.data('start_pos');
        var end_pos = ui.item.index();
        //$('#sortable li').removeClass('highlights');
    }

How to make HTML code inactive with comments

Behold HTML comments:

<!-- comment -->

http://www.w3.org/TR/html401/intro/sgmltut.html#idx-HTML

The proper way to delete code without deleting it, of course, is to use version control, which enables you to resurrect old code from the past. Don't get into the habit of accumulating commented-out code in your pages, it's no fun. :)

Android load from URL to Bitmap

Its Working in Pie OS Use this

    @Override
    protected void onCreate() {
        super.onCreate();
        //setNotificationBadge();

        if (android.os.Build.VERSION.SDK_INT >= 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

    }

        BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
        Menu menu = bottomNavigationView.getMenu();
        MenuItem userImage = menu.findItem(R.id.navigation_download);
        userImage.setTitle("Login");

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    URL url = new URL("https://rukminim1.flixcart.com/image/832/832/jmux18w0/mobile/b/g/n/mi-redmi-6-mzb6387in-original-imaf9z8eheryfbsu.jpeg?q=70");
                    Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

                    Log.e("keshav", "Bitmap " + myBitmap);
                    userImage.setIcon(new BitmapDrawable(getResources(), myBitmap));

                } catch (IOException e) {
                    Log.e("keshav", "Exception " + e.getMessage());
                }
            }
        });

Calculate number of hours between 2 dates in PHP

$day1 = "2006-04-12 12:30:00"
$day1 = strtotime($day1);
$day2 = "2006-04-14 11:30:00"
$day2 = strtotime($day2);

$diffHours = round(($day2 - $day1) / 3600);

I guess strtotime() function accept this date format.

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

Android getActivity() is undefined

If you want to call your activity, just use this . You use the getActivity method when you are inside a fragment.

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

Declare a variable in DB2 SQL

I'm coming from a SQL Server background also and spent the past 2 weeks figuring out how to run scripts like this in IBM Data Studio. Hope it helps.

CREATE VARIABLE v_lookupid INTEGER DEFAULT (4815162342); --where 4815162342 is your variable data 
  SELECT * FROM DB1.PERSON WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_DATA WHERE PERSON_ID = v_lookupid;
  SELECT * FROM DB1.PERSON_HIST WHERE PERSON_ID = v_lookupid;
DROP VARIABLE v_lookupid; 

How does Facebook disable the browser's integrated Developer Tools?

Besides redefining console._commandLineAPI, there are some other ways to break into InjectedScriptHost on WebKit browsers, to prevent or alter the evaluation of expressions entered into the developer's console.

Edit:

Chrome has fixed this in a past release. - which must have been before February 2015, as I created the gist at that time

So here's another possibility. This time we hook in, a level above, directly into InjectedScript rather than InjectedScriptHost as opposed to the prior version.

Which is kind of nice, as you can directly monkey patch InjectedScript._evaluateAndWrap instead of having to rely on InjectedScriptHost.evaluate as that gives you more fine-grained control over what should happen.

Another pretty interesting thing is, that we can intercept the internal result when an expression is evaluated and return that to the user instead of the normal behavior.

Here is the code, that does exactly that, return the internal result when a user evaluates something in the console.

var is;
Object.defineProperty(Object.prototype,"_lastResult",{
   get:function(){
       return this._lR;
   },
   set:function(v){
       if (typeof this._commandLineAPIImpl=="object") is=this;
       this._lR=v;
   }
});
setTimeout(function(){
   var ev=is._evaluateAndWrap;
   is._evaluateAndWrap=function(){
       var res=ev.apply(is,arguments);
       console.log();
       if (arguments[2]==="completion") {
           //This is the path you end up when a user types in the console and autocompletion get's evaluated

           //Chrome expects a wrapped result to be returned from evaluateAndWrap.
           //You can use `ev` to generate an object yourself.
           //In case of the autocompletion chrome exptects an wrapped object with the properties that can be autocompleted. e.g.;
           //{iGetAutoCompleted: true}
           //You would then go and return that object wrapped, like
           //return ev.call (is, '', '({test:true})', 'completion', true, false, true);
           //Would make `test` pop up for every autocompletion.
           //Note that syntax as well as every Object.prototype property get's added to that list later,
           //so you won't be able to exclude things like `while` from the autocompletion list,
           //unless you wou'd find a way to rewrite the getCompletions function.
           //
           return res; //Return the autocompletion result. If you want to break that, return nothing or an empty object
       } else {
           //This is the path where you end up when a user actually presses enter to evaluate an expression.
           //In order to return anything as normal evaluation output, you have to return a wrapped object.

           //In this case, we want to return the generated remote object. 
           //Since this is already a wrapped object it would be converted if we directly return it. Hence,
           //`return result` would actually replicate the very normal behaviour as the result is converted.
           //to output what's actually in the remote object, we have to stringify it and `evaluateAndWrap` that object again.`
           //This is quite interesting;
           return ev.call (is, null, '(' + JSON.stringify (res) + ')', "console", true, false, true)
       }
   };
},0);

It's a bit verbose, but I thought I put some comments into it

So normally, if a user, for example, evaluates [1,2,3,4] you'd expect the following output:

enter image description here

After monkeypatching InjectedScript._evaluateAndWrap evaluating the very same expression, gives the following output:

enter image description here

As you see the little-left arrow, indicating output, is still there, but this time we get an object. Where the result of the expression, the array [1,2,3,4] is represented as an object with all its properties described.

I recommend trying to evaluate this and that expression, including those that generate errors. It's quite interesting.

Additionally, take a look at the is - InjectedScriptHost - object. It provides some methods to play with and get a bit of insight into the internals of the inspector.

Of course, you could intercept all that information and still return the original result to the user.

Just replace the return statement in the else path by a console.log (res) following a return res. Then you'd end up with the following.

enter image description here

End of Edit


This is the prior version which was fixed by Google. Hence not a possible way anymore.

One of it is hooking into Function.prototype.call

Chrome evaluates the entered expression by calling its eval function with InjectedScriptHost as thisArg

var result = evalFunction.call(object, expression);

Given this, you can listen for the thisArg of call being evaluate and get a reference to the first argument (InjectedScriptHost)

if (window.URL) {
    var ish, _call = Function.prototype.call;
    Function.prototype.call = function () { //Could be wrapped in a setter for _commandLineAPI, to redefine only when the user started typing.
        if (arguments.length > 0 && this.name === "evaluate" && arguments [0].constructor.name === "InjectedScriptHost") { //If thisArg is the evaluate function and the arg0 is the ISH
            ish = arguments[0];
            ish.evaluate = function (e) { //Redefine the evaluation behaviour
                throw new Error ('Rejected evaluation of: \n\'' + e.split ('\n').slice(1,-1).join ("\n") + '\'');
            };
            Function.prototype.call = _call; //Reset the Function.prototype.call
            return _call.apply(this, arguments);  
        }
    };
}

You could e.g. throw an error, that the evaluation was rejected.

enter image description here

Here is an example where the entered expression gets passed to a CoffeeScript compiler before passing it to the evaluate function.

C# Dictionary get item by index

you can easily access elements by index , by use System.Linq

Here is the sample

First add using in your class file

using System.Linq;

Then

yourDictionaryData.ElementAt(i).Key
yourDictionaryData.ElementAt(i).Value

Hope this helps.

What is the size of a boolean variable in Java?

It's undefined; doing things like Jon Skeet suggested will get you an approximation on a given platform, but the way to know precisely for a specific platform is to use a profiler.

How do I setup the InternetExplorerDriver so it works

public class NavigateUsingAllBrowsers {


public static void main(String[] args) {

WebDriver driverFF= new FirefoxDriver();
driverFF.navigate().to("http://www.firefox.com");


File file =new File("C:/Users/mkv/workspace/ServerDrivers/IEDriverServer.exe");
System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
WebDriver driverIE=new InternetExplorerDriver();
driverIE.navigate().to("http://www.msn.com");

// Download Chrome Driver from http://code.google.com/p/chromedriver/downloads/list

file =new File("C:/Users/mkv/workspace/ServerDrivers/ChromeDriver.exe");
System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
WebDriver driverChrome=new ChromeDriver();
driverChrome.navigate().to("http://www.chrome.com");

}

}

Sublime Text 2 multiple line edit

I'm not sure it's possible "out of the box". And, unfortunately, I don't know an appropriate plugin either. To solve the problem you suggested you could use regular expressions.

  1. Cmd + F (Find)
  2. Regexp: [^ ]+ (or \d+, or whatever you prefer)
  3. Option + F (Find All)
  4. Edit it

Hotkeys may vary depending on you OS and personal preferences (mine are for OS X).

What is the difference between URL parameters and query strings?

The query component is indicated by the first ? in a URI. "Query string" might be a synonym (this term is not used in the URI standard).

Some examples for HTTP URIs with query components:

http://example.com/foo?bar
http://example.com/foo/foo/foo?bar/bar/bar
http://example.com/?bar
http://example.com/?@bar._=???/1:
http://example.com/?bar1=a&bar2=b

(list of allowed characters in the query component)

The "format" of the query component is up to the URI authors. A common convention (but nothing more than a convention, as far as the URI standard is concerned¹) is to use the query component for key-value pairs, aka. parameters, like in the last example above: bar1=a&bar2=b.

Such parameters could also appear in the other URI components, i.e., the path² and the fragment. As far as the URI standard is concerned, it’s up to you which component and which format to use.

Example URI with parameters in the path, the query, and the fragment:

http://example.com/foo;key1=value1?key2=value2#key3=value3

¹ The URI standard says about the query component:

[…] query components are often used to carry identifying information in the form of "key=value" pairs […]

² The URI standard says about the path component:

[…] the semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes.

Finding duplicate values in a SQL table

How we can count the duplicated values?? either it is repeated 2 times or greater than 2. just count them, not group wise.

as simple as

select COUNT(distinct col_01) from Table_01

How to solve java.lang.OutOfMemoryError trouble in Android

android:largeHeap="true" didn't fix the error

In my case, I got this error after I added an icon/image to Drawable folder by converting SVG to vector. Simply, go to the icon xml file and set small numbers for the width and height

android:width="24dp"
android:height="24dp"
android:viewportWidth="3033"
android:viewportHeight="3033"

Get response from PHP file using AJAX

var data="your data";//ex data="id="+id;
      $.ajax({
       method : "POST",
       url : "file name",  //url: "demo.php"
       data : "data",
       success : function(result){
               //set result to div or target 
              //ex $("#divid).html(result)
        }
   });

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

I can not use the "int length" constructor for StringBuilder since the length of my CLOB is longer than a int and needs a long value.

If the CLOB length is greater than fits in an int, the CLOB data won't fit in a String either. You'll have to use a streaming approach to deal with this much XML data.

If the actual length of the CLOB is smaller than Integer.MAX_VALUE, just force the long to int by putting (int) in front of it.

What is the difference between encrypting and signing in asymmetric encryption?

Signing is producing a "hash" with your private key that can be verified with your public key. The text is sent in the clear.

Encrypting uses the receiver's public key to encrypt the data; decoding is done with their private key.

So, the use of keys is not reversed (otherwise your private key wouldn't be private anymore!).

How to allow only integers in a textbox?

Another solution is to use a RangeValidator where you set Type="Integer" like this:

<asp:RangeValidator runat="server"
    id="valrNumberOfPreviousOwners"
    ControlToValidate="txtNumberOfPreviousOwners"
    Type="Integer"
    MinimumValue="0"
    MaximumValue="999"
    CssClass="input-error"
    ErrorMessage="Please enter a positive integer."
    Display="Dynamic">
</asp:RangeValidator>

You can set reasonable values for the MinimumValue and MaximumValue attributes too.

How can I concatenate strings in VBA?

The main (very interesting) difference for me is that:
"string" & Null -> "string"
while
"string" + Null -> Null

But that's probably more useful in database apps like Access.

How to convert a Collection to List?

Something like this should work, calling the ArrayList constructor that takes a Collection:

List theList = new ArrayList(coll);

%i or %d to print integer in C using printf()?

They are completely equivalent when used with printf(). Personally, I prefer %d, it's used more often (should I say "it's the idiomatic conversion specifier for int"?).

(One difference between %i and %d is that when used with scanf(), then %d always expects a decimal integer, whereas %i recognizes the 0 and 0x prefixes as octal and hexadecimal, but no sane programmer uses scanf() anyway so this should not be a concern.)

How to add icon to mat-icon-button

The Material icons use the Material icon font, and the font needs to be included with the page.

Here's the CDN from Google Web Fonts:

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">

Conda activate not working?

????

source activate

????

source deactivate

Cannot find module cv2 when using OpenCV

I solved my issue using the following command :

pip install opencv-python

How can I convert a string to a number in Perl?

You don't need to convert it at all:

% perl -e 'print "5.45" + 0.1;'
5.55

Detailed 500 error message, ASP + IIS 7.5

try setting the value of the "existingResponse" httpErrors attribute to "PassThrough". Mine was set at "Replace" which was causing the YSOD not to display.

<httpErrors errorMode="Detailed" existingResponse="PassThrough">

How to hide iOS status bar

Add the following to your Info.plist:

<key>UIStatusBarHidden</key>
<true/>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Image

Run as java application option disabled in eclipse

I had this same problem. For me, the reason turned out to be that I had a mismatch in the name of the class and the name of the file. I declared class "GenSig" in a file called "SignatureTester.java".

I changed the name of the class to "SignatureTester", and the "Run as Java Application" option showed up immediately.

Using "&times" word in html changes to ×

I suspect you did not know that there are different & escapes in HTML. The W3C you can see the codes. &times means × in HTML code. Use &amp;times instead.

Error on line 2 at column 1: Extra content at the end of the document

I think you are creating a document that looks like this:

<mycatch>
    ....
</mycatch>
<mycatch>
    ....
</mycatch>

This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in

<mydocument>      
  <mycatch>
      ....
  </mycatch>
  <mycatch>
      ....
  </mycatch>
  ....
</mydocument>

How to select count with Laravel's fluent query builder?

$count = DB::table('category_issue')->count();

will give you the number of items.

For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

Static Classes In Java

You cannot use the static keyword with a class unless it is an inner class. A static inner class is a nested class which is a static member of the outer class. It can be accessed without instantiating the outer class, using other static members. Just like static members, a static nested class does not have access to the instance variables and methods of the outer class.

public class Outer {
   static class Nested_Demo {
      public void my_method() {
          System.out.println("This is my nested class");
      }
   }
public static void main(String args[]) {
      Outer.Nested_Demo nested = new Outer.Nested_Demo();
      nested.my_method();
   }
}

How do I read a resource file from a Java jar file?

You don't say if this is a desktop or web app. I would use the getResourceAsStream() method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.

Convert array of JSON object strings to array of JS objects

If you have a JS array of JSON objects:

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);

// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);

// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');

See the speed tests for browser comparisons.


If you have a single JSON string representing an array of objects:

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

and you want an array of objects:

// JavaScript array of JavaScript objects
var objs = JSON.parse(s);

If you have an array of objects:

// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];

…and you want JSON representation for it, then:

// JSON string representing an array of objects
var json = JSON.stringify(s);

…or if you want a JavaScript array of JSON strings, then:

// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);

// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);

Check for null variable in Windows batch

rem set defaults:
set filename1="c:\file1.txt"
set filename2="c:\file2.txt"
set filename3="c:\file3.txt"
rem set parameters:
IF NOT "a%1"=="a" (set filename1="%1")
IF NOT "a%2"=="a" (set filename2="%2")
IF NOT "a%3"=="a" (set filename1="%3")
echo %filename1%, %filename2%, %filename3%

Be careful with quotation characters though, you may or may not need them in your variables.

Give column name when read csv file pandas

I'd do it like this:

colnames=['TIME', 'X', 'Y', 'Z'] 
user1 = pd.read_csv('dataset/1.csv', names=colnames, header=None)

Convert a PHP object to an associative array

All other answers posted here are only working with public attributes. Here is one solution that works with JavaBeans-like objects using reflection and getters:

function entity2array($entity, $recursionDepth = 2) {
    $result = array();
    $class = new ReflectionClass(get_class($entity));
    foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
        $methodName = $method->name;
        if (strpos($methodName, "get") === 0 && strlen($methodName) > 3) {
            $propertyName = lcfirst(substr($methodName, 3));
            $value = $method->invoke($entity);

            if (is_object($value)) {
                if ($recursionDepth > 0) {
                    $result[$propertyName] = $this->entity2array($value, $recursionDepth - 1);
                }
                else {
                    $result[$propertyName] = "***";  // Stop recursion
                }
            }
            else {
                $result[$propertyName] = $value;
            }
        }
    }
    return $result;
}

How to add new column to MYSQL table?

You should look into normalizing your database to avoid creating columns at runtime.

Make 3 tables:

  1. assessment
  2. question
  3. assessment_question (columns assessmentId, questionId)

Put questions and assessments in their respective tables and link them together through assessment_question using foreign keys.

Is there a git-merge --dry-run option?

Make a temporary copy of your working copy, then merge into that, and diff the two.

Exception.Message vs Exception.ToString()

In terms of the XML format for log4net, you need not worry about ex.ToString() for the logs. Simply pass the exception object itself and log4net does the rest do give you all of the details in its pre-configured XML format. The only thing I run into on occasion is new line formatting, but that's when I'm reading the files raw. Otherwise parsing the XML works great.

How can I change the value of the elements in a vector?

Well, you could always run a transform over the vector:

std::transform(v.begin(), v.end(), v.begin(), [mean](int i) -> int { return i - mean; });

You could always also devise an iterator adapter that returns the result of an operation applied to the dereference of its component iterator when it's dereferenced. Then you could just copy the vector to the output stream:

std::copy(adapter(v.begin(), [mean](int i) -> { return i - mean; }), v.end(), std::ostream_iterator<int>(cout, "\n"));

Or, you could use a for loop...but that's kind of boring.

Why is using a wild card with a Java import statement bad?

Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

@nmr also check the ownership and groups on the sqlite file itself... I'd copied my database in from /sdcard as root so had to change the permissions..

-rw-rw---- root     root       180224 2014-05-05 11:06 test.sqlite

should be..

-rw-rw---- u0_a80   u0_a80     180224 2014-05-05 11:06 test.sqlite

Used the following commands to set the correct ownership and group. The u0_a80 I got from ls -al on other files in the directory

chown u0_a80 test.sqlite
chgrp u0_a80 test.sqlite

How to make android listview scrollable?

Never put ListView in ScrollView. ListView itself is scrollable.

How to pass arguments within docker-compose?

This can now be done as of docker-compose v2+ as part of the build object;

docker-compose.yml

version: '2'
services:
    my_image_name:
        build:
            context: . #current dir as build context
            args:
                var1: 1
                var2: c

See the docker compose docs.

In the above example "var1" and "var2" will be sent to the build environment.

Note: any env variables (specified by using the environment block) which have the same name as args variable(s) will override that variable.

Where can I set environment variables that crontab will use?

Instead of

0  *  *  *  *  sh /my/script.sh

Use bash -l -c

0  *  *  *  *  bash -l -c 'sh /my/script.sh'

ASP.NET MVC 3 Razor - Adding class to EditorFor

You can't set class for the generic EditorFor. If you know the editor that you want, you can use it straight away, there you can set the class. You don't need to build any custom templates.

@Html.TextBoxFor(x => x.Created, new { @class = "date" }) 

Unable to import a module that is definitely installed

I had this exact problem, but none of the answers above worked. It drove me crazy until I noticed that sys.path was different after I had imported from the parent project. It turned out that I had used importlib to write a little function in order to import a file not in the project hierarchy. Bad idea: I forgot that I had done this. Even worse, the import process mucked with the sys.path--and left it that way. Very bad idea.

The solution was to stop that, and simply put the file I needed to import into the project. Another approach would have been to put the file into its own project, as it needs to be rebuilt from time to time, and the rebuild may or may not coincide with the rebuild of the main project.

Get the name of a pandas DataFrame

Here is a sample function: 'df.name = file` : Sixth line in the code below

def df_list(): filename_list = current_stage_files(PATH) df_list = [] for file in filename_list: df = pd.read_csv(PATH+file) df.name = file df_list.append(df) return df_list

How a thread should close itself in Java?

Thread is a class, not an instance; currentThread() is a static method that returns the Thread instance corresponding to the calling thread.

Use (2). interrupt() is a bit brutal for normal use.

How do I check CPU and Memory Usage in Java?

Since Java 1.5 the JDK comes with a new tool: JConsole wich can show you the CPU and memory usage of any 1.5 or later JVM. It can do charts of these parameters, export to CSV, show the number of classes loaded, the number of instances, deadlocks, threads etc...

How do I detect IE 8 with jQuery?

Note:

1) $.browser appears to be dropped in jQuery 1.9+ (as noted by Mandeep Jain). It is recommended to use .support instead.

2) $.browser.version can return "7" in IE >7 when the browser is in "compatibility" mode.

3) As of IE 10, conditional comments will no longer work.

4) jQuery 2.0+ will drop support for IE 6/7/8

5) document.documentMode appears to be defined only in Internet Explorer 8+ browsers. The value returned will tell you in what "compatibility" mode Internet Explorer is running. Still not a good solution though.

I tried numerous .support() options, but it appears that when an IE browser (9+) is in compatibility mode, it will simply behave like IE 7 ... :(

So far I only found this to work (kind-a):

(if documentMode is not defined and htmlSerialize and opacity are not supported, then you're very likely looking at IE <8 ...)

if(!document.documentMode && !$.support.htmlSerialize && !$.support.opacity) 
{
    // IE 6/7 code
}

Class constructor type in typescript?

Like that:

class Zoo {
    AnimalClass: typeof Animal;

    constructor(AnimalClass: typeof Animal ) {
        this.AnimalClass = AnimalClass
        let Hector = new AnimalClass();
    }
}

Or just:

class Zoo {
    constructor(public AnimalClass: typeof Animal ) {
        let Hector = new AnimalClass();
    }
}

typeof Class is the type of the class constructor. It's preferable to the custom constructor type declaration because it processes static class members properly.

Here's the relevant part of TypeScript docs. Search for the typeof. As a part of a TypeScript type annotation, it means "give me the type of the symbol called Animal" which is the type of the class constructor function in our case.

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

Can an abstract class have a constructor?

Yes, an abstract class can have a constructor. Consider this:

abstract class Product { 
    int multiplyBy;
    public Product( int multiplyBy ) {
        this.multiplyBy = multiplyBy;
    }

    public int mutiply(int val) {
       return multiplyBy * val;
    }
}

class TimesTwo extends Product {
    public TimesTwo() {
        super(2);
    }
}

class TimesWhat extends Product {
    public TimesWhat(int what) {
        super(what);
    }
}

The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.

Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.

NOTE: As there is no default (or no-arg) constructor in the parent abstract class, the constructor used in subclass must explicitly call the parent constructor.

CSS performance relative to translateZ(0)

It forces the browser to use hardware acceleration to access the device’s graphical processing unit (GPU) to make pixels fly. Web applications, on the other hand, run in the context of the browser, which lets the software do most (if not all) of the rendering, resulting in less horsepower for transitions. But the Web has been catching up, and most browser vendors now provide graphical hardware acceleration by means of particular CSS rules.

Using -webkit-transform: translate3d(0,0,0); will kick the GPU into action for the CSS transitions, making them smoother (higher FPS).

Note: translate3d(0,0,0) does nothing in terms of what you see. It moves the object by 0px in x,y and z axis. It's only a technique to force the hardware acceleration.

Good read here: http://www.smashingmagazine.com/2012/06/21/play-with-hardware-accelerated-css/

Show animated GIF

I wanted to put the .gif file in a GUI but displayed with other elements. And the .gif file would be taken from the java project and not from an URL.

1 - Top of the interface would be a list of elements where we can choose one

2 - Center would be the animated GIF

3 - Bottom would display the element chosen from the list

Here is my code (I need 2 java files, the first (Interf.java) calls the second (Display.java)):

1 - Interf.java

public class Interface_for {

    public static void main(String[] args) {

        Display Fr = new Display();

    }
}

2 - Display.java

INFOS: Be shure to create a new source folder (NEW > source folder) in your java project and put the .gif inside for it to be seen as a file.

I get the gif file with the code below, so I can it export it in a jar project(it's then animated).

URL url = getClass().getClassLoader().getResource("fire.gif");

  public class Display extends JFrame {
  private JPanel container = new JPanel();
  private JComboBox combo = new JComboBox();
  private JLabel label = new JLabel("A list");
  private JLabel label_2 = new JLabel ("Selection");

  public Display(){
    this.setTitle("Animation");
    this.setSize(400, 350);
    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setLocationRelativeTo(null);
    container.setLayout(new BorderLayout());
    combo.setPreferredSize(new Dimension(190, 20));
    //We create te list of elements for the top of the GUI
    String[] tab = {"Option 1","Option 2","Option 3","Option 4","Option 5"};
    combo = new JComboBox(tab);

    //Listener for the selected option
    combo.addActionListener(new ItemAction());

    //We add elements from the top of the interface
    JPanel top = new JPanel();
    top.add(label);
    top.add(combo);
    container.add(top, BorderLayout.NORTH);

    //We add elements from the center of the interface
    URL url = getClass().getClassLoader().getResource("fire.gif");
    Icon icon = new ImageIcon(url);
    JLabel center = new JLabel(icon);
    container.add(center, BorderLayout.CENTER);

    //We add elements from the bottom of the interface
    JPanel down = new JPanel();
    down.add(label_2);
    container.add(down,BorderLayout.SOUTH);

    this.setContentPane(container);
    this.setVisible(true);
    this.setResizable(false);
  }
  class ItemAction implements ActionListener{
      public void actionPerformed(ActionEvent e){
          label_2.setText("Chosen option: "+combo.getSelectedItem().toString());
      }
  }
}

Jenkins Host key verification failed

  • Make sure we are not editing any of the default sshd_config properties to skip the error

  • Host Verification Failed - Definitely a missing entry of hostname in known_hosts file

  • Login to the server where the process is failing and do the following:

    1. Sudo to the user running the process

    2. ssh-copy-id destinationuser@destinationhostname

    3. It will prompt like this for the first time, say yes and it will also ask password for the first time:

      The authenticity of host 'sample.org (205.214.640.91)' can't be established.
      RSA key fingerprint is 97:8c:1b:f2:6f:14:6b:5c:3b:ec:aa:46:46:74:7c:40.
      Are you sure you want to continue connecting (yes/no)? *yes*
      

      Password prompt ? give password

    4. Now from the server where process is running, do ssh destinationuser@destinationhostname. It should login without a password.

      Note: Do not change the default permissions of files in the user's .ssh directory, you will end up with different issues

Javascript, Change google map marker color

To expand upon the accepted answer, you can create custom MarkerImages of any color using the API at http://chart.googleapis.com

In addition to changing color, this also changes marker shape, which may be unwanted.

const marker = new window.google.maps.Marker(
        position: markerPosition,
        title: markerTitle,
        map: map)
marker.addListener('click', () => marker.setIcon(changeIcon('00ff00'));)

const changeIcon = (newIconColor) => {
    const newIcon = new window.google.maps.MarkerImage(
        `http://chart.googleapis.com/chart?                                      
        chst=d_map_spin&chld=1.0|0|${newIconColor}|60|_|%E2%80%A2`,
        new window.google.maps.Size(21, 34),
        new window.google.maps.Point(0, 0),
        new window.google.maps.Point(10, 34),
        new window.google.maps.Size(21,34)
    );
    return newIcon
}

Source: free udacity course on google maps apis

What is the runtime performance cost of a Docker container?

An excellent 2014 IBM research paper “An Updated Performance Comparison of Virtual Machines and Linux Containers” by Felter et al. provides a comparison between bare metal, KVM, and Docker containers. The general result is: Docker is nearly identical to native performance and faster than KVM in every category.

The exception to this is Docker’s NAT — if you use port mapping (e.g., docker run -p 8080:8080), then you can expect a minor hit in latency, as shown below. However, you can now use the host network stack (e.g., docker run --net=host) when launching a Docker container, which will perform identically to the Native column (as shown in the Redis latency results lower down).

Docker NAT overhead

They also ran latency tests on a few specific services, such as Redis. You can see that above 20 client threads, highest latency overhead goes Docker NAT, then KVM, then a rough tie between Docker host/native.

Docker Redis Latency Overhead

Just because it’s a really useful paper, here are some other figures. Please download it for full access.

Taking a look at Disk I/O:

Docker vs. KVM vs. Native I/O Performance

Now looking at CPU overhead:

Docker CPU Overhead

Now some examples of memory (read the paper for details, memory can be extra tricky):

Docker Memory Comparison

Making a Bootstrap table column fit to content

Make a class that will fit table cell width to content

.table td.fit, 
.table th.fit {
    white-space: nowrap;
    width: 1%;
}

make script execution to unlimited

Your script could be stopping, not because of the PHP timeout but because of the timeout in the browser you're using to access the script (ie. Firefox, Chrome, etc). Unfortunately there's seldom an easy way to extend this timeout, and in most browsers you simply can't. An option you have here is to access the script over a terminal. For example, on Windows you would make sure the PHP executable is in your path variable and then I think you execute:

C:\path\to\script> php script.php

Or, if you're using the PHP CGI, I think it's:

C:\path\to\script> php-cgi script.php

Plus, you would also set ini_set('max_execution_time', 0); in your script as others have mentioned. When running a PHP script this way, I'm pretty sure you can use buffer flushing to echo out the script's progress to the terminal periodically if you wish. The biggest issue I think with this method is there's really no way of stopping the script once it's started, other than stopping the entire PHP process or service.

Change the size of a JTextField inside a JBorderLayout

Any component added to the GridLayout will be resized to the same size as the largest component added. If you want a component to remain at its preferred size, then wrap that component in a JPanel and then the panel will be resized:

JPanel displayPanel = new JPanel(new GridLayout(4, 2)); 
JTextField titleText = new JTextField("title"); 
JPanel wrapper = new JPanel( new FlowLayout(0, 0, FlowLayout.LEADING) );
wrapper.add( titleText );
displayPanel.add(wrapper); 
//displayPanel.add(titleText); 

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

This draws an arc with the center in the specified rectangle. You can draw, half-circles, quarter-circles, etc.

g.drawArc(x - r, y - r, r * 2, r * 2, 0, 360)

SQL grouping by month and year

You can try multiplication to adjust the year and month so they will be one number. This, from my tests, runs much faster than format(date,'yyyy.MM'). I prefer having the year before month for sorting purpose. Code created from MS SQL Server Express Version 12.0.

SELECT (YEAR(Date) * 100) + MONTH(Date) AS yyyyMM
FROM [Order]
...
GROUP BY (YEAR(Date) * 100) + MONTH(Date)
ORDER BY yyyyMM

How to forward declare a template class in namespace std?

there is a limited alternative you can use

header:

class std_int_vector;

class A{
    std_int_vector* vector;
public:
    A();
    virtual ~A();
};

cpp:

#include "header.h"
#include <vector>
class std_int_vector: public std::vectror<int> {}

A::A() : vector(new std_int_vector()) {}
[...]

not tested in real programs, so expect it to be non-perfect.

How to run .NET Core console app from the command line

You can also run your app like any other console applications but only after the publish.

Let's suppose you have the simple console app named MyTestConsoleApp. Open the package manager console and run the following command:

dotnet publish -c Debug -r win10-x64 

-c flag mean that you want to use the debug configuration (in other case you should use Release value) - r flag mean that your application will be runned on Windows platform with x64 architecture.

When the publish procedure will be finished your will see the *.exe file located in your bin/Debug/publish directory.

Now you can call it via command line tools. So open the CMD window (or terminal) move to the directory where your *.exe file is located and write the next command:

>> MyTestConsoleApp.exe argument-list

For example:

>> MyTestConsoleApp.exe --input some_text -r true

JavaScript file not updating no matter what I do

Don't forget to check any errors in webpack compilation. Sometimes the application.js in app/javascript/packs/ doesn't reload due to webpack compilation error.

Is it safe to delete a NULL pointer?

From the C++0x draft Standard.

$5.3.5/2 - "[...]In either alternative, the value of the operand of delete may be a null pointer value.[...'"

Of course, no one would ever do 'delete' of a pointer with NULL value, but it is safe to do. Ideally one should not have code that does deletion of a NULL pointer. But it is sometimes useful when deletion of pointers (e.g. in a container) happens in a loop. Since delete of a NULL pointer value is safe, one can really write the deletion logic without explicit checks for NULL operand to delete.

As an aside, C Standard $7.20.3.2 also says that 'free' on a NULL pointer does no action.

The free function causes the space pointed to by ptr to be deallocated, that is, made available for further allocation. If ptr is a null pointer, no action occurs.

Decimal or numeric values in regular expression validation

Try this code, hope it will help you

String regex = "(\\d+)(\\.)?(\\d+)?";  for integer and decimal like 232 232.12 

Why does Python code use len() function instead of a length method?

Python is a pragmatic programming language, and the reasons for len() being a function and not a method of str, list, dict etc. are pragmatic.

The len() built-in function deals directly with built-in types: the CPython implementation of len() actually returns the value of the ob_size field in the PyVarObject C struct that represents any variable-sized built-in object in memory. This is much faster than calling a method -- no attribute lookup needs to happen. Getting the number of items in a collection is a common operation and must work efficiently for such basic and diverse types as str, list, array.array etc.

However, to promote consistency, when applying len(o) to a user-defined type, Python calls o.__len__() as a fallback. __len__, __abs__ and all the other special methods documented in the Python Data Model make it easy to create objects that behave like the built-ins, enabling the expressive and highly consistent APIs we call "Pythonic".

By implementing special methods your objects can support iteration, overload infix operators, manage contexts in with blocks etc. You can think of the Data Model as a way of using the Python language itself as a framework where the objects you create can be integrated seamlessly.

A second reason, supported by quotes from Guido van Rossum like this one, is that it is easier to read and write len(s) than s.len().

The notation len(s) is consistent with unary operators with prefix notation, like abs(n). len() is used way more often than abs(), and it deserves to be as easy to write.

There may also be a historical reason: in the ABC language which preceded Python (and was very influential in its design), there was a unary operator written as #s which meant len(s).

What's the difference between Apache's Mesos and Google's Kubernetes

Mesos and Kubernetes both are container orchestration tools.

When you say "Google Kubernetes"?

Google Kubernetes Engine provides a managed environment for deploying, managing, and scaling your containerized applications using Google infrastructure.

Kubernetes is an open-source system for automating deployment, scaling, and management of containerized applications.” Kubernetes was built by Google based on their experience running containers in production over the last decade.

The major components in a Kubernetes cluster are:

pods — a way to group containers together replication controllers — a way to handle the lifecycle of containers labels — a way to find and query containers, and services — a set of containers performing a common function

Mesos is an open-source cluster management project by Apache, designed to scale to very large clusters, from hundreds to thousands of hosts. Mesos supports diverse kinds of workloads such as Hadoop tasks, cloud native applications etc. It gives you the ability to run both containerized, and non-containerized workloads in a distributed manner.

It was initially written as a research project at Berkeley and was later adopted by Twitter as an answer to Google’s Borg (Kubernetes’ predecessor). To combat its high degree of complexity (Mesos is super complicated and hard to manage!), Mesosphere came into the picture to try and make Mesos into something regular human beings can use.

Mesosphere supplied the superb Marathon “plugin” to Mesos, which provides users with an easy way to manage container orchestration over Mesos.

In mid-2016, DC/OS (Data Center Operating System) — an open source project backed by Mesosphere — was introduced, which simplifies Mesos even further and allows you to deploy your own Mesos cluster, with Marathon, in a matter of minutes.

Now, if we compare kubernetes and Mesos(DC/OS)

kubernetes is a cluster manager for containers while mesos is a distributed system kernel that will make your cluster look like one giant computer system to all supported frameworks and apps that are built to be run on mesos.

Mesos was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application runs very well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps.

Mesos cluster also runs alongside the Marathon cluster. Marathon, created by Mesosphere, is designed to start, monitor and scale long-running applications, including cloud native apps. Clients interact with Marathon through a REST API.

Also, a point to be noted is that you can actually run Kubernetes on top of DC/OS and schedule containers with it instead of using Marathon. This implies the biggest difference of all — DC/OS, as it name suggests, is more similar to an operating system rather than an orchestration framework. You can run non-containerized, stateful workloads on it. Container scheduling is handled by the Marathon.

What exactly does numpy.exp() do?

It calculates ex for each x in your list where e is Euler's number (approximately 2.718). In other words, np.exp(range(5)) is similar to [math.e**x for x in range(5)].

Writing outputs to log file and console

I have found a way to get the desired output. Though it may be somewhat unorthodox way. Anyways here it goes. In the redir.env file I have following code:

#####redir.env#####    
export LOG_FILE=log.txt

      exec 2>>${LOG_FILE}

    function log {
     echo "$1">>${LOG_FILE}
    }

    function message {
     echo "$1"
     echo "$1">>${LOG_FILE}
    }

Then in the actual script I have the following codes:

#!/bin/sh 
. redir.env
echo "Echoed to console only"
log "Written to log file only"
message "To console and log"
echo "This is stderr. Written to log file only" 1>&2

Here echo outputs only to console, log outputs to only log file and message outputs to both the log file and console.

After executing the above script file I have following outputs:

In console

In console
Echoed to console only
To console and log

For the Log file

In Log File Written to log file only
This is stderr. Written to log file only
To console and log

Hope this help.

How to check if two words are anagrams

Many complicated answers here. Base on the accepted answer and the comment mentioning the 'ac'-'bb' issue assuming A=65 B=66 C=67, we could simply use the square of each integer that represent a char and solve the problem:

public boolean anagram(String s, String t) {
    if(s.length() != t.length())
        return false;

    int value = 0;
    for(int i = 0; i < s.length(); i++){
        value += ((int)s.charAt(i))^2;
        value -= ((int)t.charAt(i))^2;
    }
    return value == 0;
}

How to join a slice of strings into a single string?

The title of your question is:

How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

reg := []string {"a","b","c"}

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

fmt.Println(strings.Join(reg[:], ","))

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

Prevent typing non-numeric in input type number

Update on the accepted answer:

Because of many properties becoming deprecated

(property) KeyboardEvent.which: number @deprecated

you should just rely on the key property and create the rest of the logic by yourself:

The code allows Enter, Backspace and all numbers [0-9], every other character is disallowed.

document.querySelector("input").addEventListener("keypress", (e) => {
  if (isNaN(parseInt(e.key, 10)) && e.key !== "Backspace" && e.key !== "Enter") {
      e.preventDefault();
    }
});

NOTE This will disable paste action

How to pass json POST data to Web API method as an object?

Make sure that your WebAPI service is expecting a strongly typed object with a structure that matches the JSON that you are passing. And make sure that you stringify the JSON that you are POSTing.

Here is my JavaScript (using AngluarJS):

$scope.updateUserActivity = function (_objuserActivity) {
        $http
        ({
            method: 'post',
            url: 'your url here',
            headers: { 'Content-Type': 'application/json'},
            data: JSON.stringify(_objuserActivity)
        })
        .then(function (response)
        {
            alert("success");
        })
        .catch(function (response)
        {
            alert("failure");
        })
        .finally(function ()
        {
        });

And here is my WebAPI Controller:

[HttpPost]
[AcceptVerbs("POST")]
public string POSTMe([FromBody]Models.UserActivity _activity)
{
    return "hello";
}

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Export HTML table to pdf using jspdf

We can separate out section of which we need to convert in PDF

For example, if table is in class "pdf-table-wrap"

After this, we need to call html2canvas function combined with jsPDF

following is sample code

var pdf = new jsPDF('p', 'pt', [580, 630]);
html2canvas($(".pdf-table-wrap")[0], {
    onrendered: function(canvas) {
        document.body.appendChild(canvas);
        var ctx = canvas.getContext('2d');
        var imgData = canvas.toDataURL("image/png", 1.0);
        var width = canvas.width;
        var height = canvas.clientHeight;
        pdf.addImage(imgData, 'PNG', 20, 20, (width - 10), (height));

    }
});
setTimeout(function() {
    //jsPDF code to save file
    pdf.save('sample.pdf');
}, 0);

Complete tutorial is given here http://freakyjolly.com/create-multipage-html-pdf-jspdf-html2canvas/

mongodb/mongoose findMany - find all documents with IDs listed in array

The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same.

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});

This method will work well even for arrays containing tens of thousands of ids. (See Efficiently determine the owner of a record)

I would recommend that anybody working with mongoDB read through the Advanced Queries section of the excellent Official mongoDB Docs

How can I exclude all "permission denied" messages from "find"?

If you want to start search from root "/" , you will probably see output somethings like:

find: /./proc/1731/fdinfo: Permission denied
find: /./proc/2032/task/2032/fd: Permission denied

It's because of permission. To solve this:

  1. You can use sudo command:

    sudo find /. -name 'toBeSearched.file'
    

It asks super user's password, when enter the password you will see result what you really want. If you don't have permission to use sudo command which means you don't have super user's password, first ask system admin to add you to the sudoers file.

  1. You can use redirect the Standard Error Output from (Generally Display/Screen) to some file and avoid seeing the error messages on the screen! redirect to a special file /dev/null :

    find /. -name 'toBeSearched.file' 2>/dev/null
    
  2. You can use redirect the Standard Error Output from (Generally Display/Screen) to Standard output (Generally Display/Screen), then pipe with grep command with -v "invert" parameter to not to see the output lines which has 'Permission denied' word pairs:

    find /. -name 'toBeSearched.file' 2>&1 | grep -v 'Permission denied'
    

How to parse freeform street/postal address out of text, and into components

For US Address Parsing,

I prefer using usaddress package that is available in pip for usaddress only

python3 -m pip install usaddress

Documentation
PyPi

This worked well for me for US address.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# address_parser.py
import sys
from usaddress import tag
from json import dumps, loads

if __name__ == '__main__':
    tag_mapping = {
        'Recipient': 'recipient',
        'AddressNumber': 'addressStreet',
        'AddressNumberPrefix': 'addressStreet',
        'AddressNumberSuffix': 'addressStreet',
        'StreetName': 'addressStreet',
        'StreetNamePreDirectional': 'addressStreet',
        'StreetNamePreModifier': 'addressStreet',
        'StreetNamePreType': 'addressStreet',
        'StreetNamePostDirectional': 'addressStreet',
        'StreetNamePostModifier': 'addressStreet',
        'StreetNamePostType': 'addressStreet',
        'CornerOf': 'addressStreet',
        'IntersectionSeparator': 'addressStreet',
        'LandmarkName': 'addressStreet',
        'USPSBoxGroupID': 'addressStreet',
        'USPSBoxGroupType': 'addressStreet',
        'USPSBoxID': 'addressStreet',
        'USPSBoxType': 'addressStreet',
        'BuildingName': 'addressStreet',
        'OccupancyType': 'addressStreet',
        'OccupancyIdentifier': 'addressStreet',
        'SubaddressIdentifier': 'addressStreet',
        'SubaddressType': 'addressStreet',
        'PlaceName': 'addressCity',
        'StateName': 'addressState',
        'ZipCode': 'addressPostalCode',
    }
    try:
        address, _ = tag(' '.join(sys.argv[1:]), tag_mapping=tag_mapping)
    except:
        with open('failed_address.txt', 'a') as fp:
            fp.write(sys.argv[1] + '\n')
        print(dumps({}))
    else:
        print(dumps(dict(address)))

Running the address_parser.py

 python3 address_parser.py 9757 East Arcadia Ave. Saugus MA 01906
 {"addressStreet": "9757 East Arcadia Ave.", "addressCity": "Saugus", "addressState": "MA", "addressPostalCode": "01906"}

Twitter Bootstrap inline input with dropdown

This is the code for Bootstrap with input search dropdown. I search a lot then i try its in javascript and html with bootstrap,

HTML Code :

<div class="form-group">
    <label class="col-xs-3 control-label">Language</label>
    <div class="col-xs-7">
        <div class="dropdown">
          <button id="mydef" class="btn dropdown-toggle" type="button" data-toggle="dropdown" onclick="doOn(this);">
            <div class="col-xs-10">
                <input type="text" id="search" placeholder="search" onkeyup="doOn(this);"></input>
            </div>
            <span class="glyphicon glyphicon-search"></span>
         </button>
      <ul id="def" class="dropdown-menu" style="display:none;" >
            <li><a id="HTML" onclick="mydef(this);" >HTML</a></li>
            <li><a id="CSS" onclick="mydef(this);" >CSS</a></li>
            <li><a id="JavaScript" onclick="mydef(this);" >JavaScript</a></li>
      </ul>
      <ul id="def1" class="dropdown-menu" style="display:none"></ul>
    </div>
</div>

Javascript Code :

function doOn(obj)
     {

        if(obj.id=="mydef")
        {
            document.getElementById("def1").style.display="none";
            document.getElementById("def").style.display="block";
        }
        if(obj.id=="search")
        {
            document.getElementById("def").style.display="none";

            document.getElementById("def1").innerHTML='<li><a id="Java" onclick="mydef(this);" >java</a></li><li><a id="oracle" onclick="mydef(this);" >Oracle</a></li>';

            document.getElementById("def1").style.display="block";
        }

    }
    function mydef(obj)
    {
        document.getElementById("search").value=obj.innerHTML;
        document.getElementById("def1").style.display="none";
        document.getElementById("def").style.display="none";
    }

You can use jquery and json code also as per your requirement.

Output like: enter image description here

enter image description here

enter image description here

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

null check in jsf expression language

Use empty (it checks both nullness and emptiness) and group the nested ternary expression by parentheses (EL is in certain implementations/versions namely somewhat problematic with nested ternary expressions). Thus, so:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap.contains('key') ? 'highlight_field' : 'highlight_row')}"

If still in vain (I would then check JBoss EL configs), use the "normal" EL approach:

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (obj.validationErrorMap['key'] ne null ? 'highlight_field' : 'highlight_row')}"

Update: as per the comments, the Map turns out to actually be a List (please work on your naming conventions). To check if a List contains an item the "normal" EL way, use JSTL fn:contains (although not explicitly documented, it works for List as well).

styleClass="#{empty obj.validationErrorMap ? ' ' :  
 (fn:contains(obj.validationErrorMap, 'key') ? 'highlight_field' : 'highlight_row')}"

How the int.TryParse actually works

Regex is compiled so for speed create it once and reuse it.
The new takes longer than the IsMatch.
This only checks for all digits.
It does not check for range.
If you need to test range then TryParse is the way to go.

private static Regex regexInt = new Regex("^\\d+$");
static bool CheckReg(string value)
{
    return regexInt.IsMatch(value);
}

jQuery If DIV Doesn't Have Class "x"

You can also use the addClass and removeClass methods to toggle between items such as tabs.

e.g.

if($(element).hasClass("selected"))
   $(element).removeClass("selected");

Does Index of Array Exist

You can rather use a List, so you can check the existence.

List<int> l = new List<int>();
l.Add(45);
...
...

if (l.Count == 25) {
  doStuff();
}
int num = 45;
if (l.Contains(num)) {
  doMoreStuff();
}