Programs & Examples On #Scalar

In computing and programming, a scalar variable or value refers to a single value, as opposed to data structures such as arrays or lists.

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

How to multiply all integers inside list

The simplest way to me is:

map((2).__mul__, [1, 2, 3])

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

PHP Constants Containing Arrays?

If you are using PHP 5.6 or above, use Andrea Faulds answer

I am using it like this. I hope, it will help others.

config.php

class app{
    private static $options = array(
        'app_id' => 'hello',
    );
    public static function config($key){
        return self::$options[$key];
    }
}

In file, where I need constants.

require('config.php');
print_r(app::config('app_id'));

python: how to identify if a variable is an array or a scalar

Simply use size instead of len!

>>> from numpy import size
>>> N = [2, 3, 5]
>>> size(N)
3
>>> N = array([2, 3, 5])
>>> size(N)
3
>>> P = 5
>>> size(P)
1

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

PHP - cannot use a scalar as an array warning

Also make sure that you don't declare it an array and then try to assign something else to the array like a string, float, integer. I had that problem. If you do some echos of output I was seeing what I wanted the first time, but not after another pass of the same code.

How to dynamically add a class to manual class names?

If you're using css modules this is what worked for me.

const [condition, setCondition] = useState(false);

\\ toggle condition

return (
  <span className={`${styles.always} ${(condition ? styles.sometimes : '')`}>
  </span>
)

fcntl substitute on Windows

The fcntl module is just used for locking the pinning file, so assuming you don't try multiple access, this can be an acceptable workaround. Place this module in your sys.path, and it should just work as the official fcntl module.

Try using this module for development/testing purposes only in windows.

def fcntl(fd, op, arg=0):
    return 0

def ioctl(fd, op, arg=0, mutable_flag=True):
    if mutable_flag:
        return 0
    else:
        return ""

def flock(fd, op):
    return

def lockf(fd, operation, length=0, start=0, whence=0):
    return

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Running Selenium Webdriver with a proxy in Python

try running tor service, add the following function to your code.

def connect_tor(port):

socks.set_default_proxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', port, True)
socket.socket = socks.socksocket

def main():

connect_tor()
driver = webdriver.Firefox()

Testing Spring's @RequestBody using Spring MockMVC

the following works for me,

  mockMvc.perform(
            MockMvcRequestBuilders.post("/api/test/url")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(asJsonString(createItemForm)))
            .andExpect(status().isCreated());

  public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Is there an ignore command for git like there is for svn?

You could also use Joe Blau's gitignore.io

Either through the web interfase https://www.gitignore.io/

Or by installing the CLI tool, it's very easy an fast, just type the following on your terminal:

Linux:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bashrc && source ~/.bashrc

OSX:
echo "function gi() { curl -L -s https://www.gitignore.io/api/\$@ ;}" >> ~/.bash_profile && source ~/.bash_profile

And then you can just type gi followd by the all the platform/environment elements you need gitignore criteria for.

Example!
Lets say you're working on a node project that includes grunt and you're using webstorm on linux, then you may want to type:
gi linux,webstorm,node,grunt > .gitignore ( to make a brand new file)
or
gi linux,webstorm,node,grunt >> .gitignore ( to append/add the new rules to an existing file)

bam, you're good to go

Using Cygwin to Compile a C program; Execution error

You might be better off editing a file inside of cygwin shell. Normally it has default user directory when you start it up. You can edit a file from the shell doing something like "vi somefile.c" or "emacs somefile.c". That's assuming vi or emacs are installed in cygwin.

If you want to file on your desktop, you'll have to go to a path similar (on XP) to "/cygwindrive/c/Documents\ and\ Settings/Frank/Desktop" (If memory serves correctly). Just cd to that path, and run your command on the file.

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

No module named MySQLdb

I met the same situation under windows, and searched for the solution.

Seeing this post Install mysql-python (Windows).

It points out installing such a pip environment is difficult, needs many other dependencies.

But I finally know that if we use mysqlclient with a version down to 1.3.4, it don't need that requirements any more, so try:

pip install mysqlclient==1.3.4

MySQL Join Where Not Exists

I'd probably use a LEFT JOIN, which will return rows even if there's no match, and then you can select only the rows with no match by checking for NULLs.

So, something like:

SELECT V.*
FROM voter V LEFT JOIN elimination E ON V.id = E.voter_id
WHERE E.voter_id IS NULL

Whether that's more or less efficient than using a subquery depends on optimization, indexes, whether its possible to have more than one elimination per voter, etc.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Today I have the similar problem.

Previous in my project gradle

// Top-level build file where you can add configuration options common to all 
sub-projects/modules.
allprojects {
repositories {
    jcenter()
    google()
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven { url 'https://plugins.gradle.org/m2/'}
}}

Then I just added this below line in allprojects

maven {
        url "https://maven.google.com"
    }

It saved my day.

And now my current allproject {} code looks like this

allprojects {
repositories {
    jcenter()
    google()
    mavenCentral()
    maven { url "https://jitpack.io" }
    maven { url 'https://plugins.gradle.org/m2/'}
    maven {
        url "https://maven.google.com"
    }
}}

How can I time a code segment for testing performance with Pythons timeit?

If you are profiling your code and can use IPython, it has the magic function %timeit.

%%timeit operates on cells.

In [2]: %timeit cos(3.14)
10000000 loops, best of 3: 160 ns per loop

In [3]: %%timeit
   ...: cos(3.14)
   ...: x = 2 + 3
   ...: 
10000000 loops, best of 3: 196 ns per loop

How to drop a PostgreSQL database if there are active connections to it?

PostgreSQL 13 introduced FORCE option.

DROP DATABASE

DROP DATABASE drops a database ... Also, if anyone else is connected to the target database, this command will fail unless you use the FORCE option described below.

FORCE

Attempt to terminate all existing connections to the target database. It doesn't terminate if prepared transactions, active logical replication slots or subscriptions are present in the target database.

DROP DATABASE db_name WITH (FORCE);

INNER JOIN ON vs WHERE clause

If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.

In ASP.NET MVC: All possible ways to call Controller Action Method from a Razor View

Method 1 : Using jQuery Ajax Get call (partial page update).

Suitable for when you need to retrieve jSon data from database.

Controller's Action Method

[HttpGet]
public ActionResult Foo(string id)
{
    var person = Something.GetPersonByID(id);
    return Json(person, JsonRequestBehavior.AllowGet);
}

Jquery GET

function getPerson(id) {
    $.ajax({
        url: '@Url.Action("Foo", "SomeController")',
        type: 'GET',
        dataType: 'json',
        // we set cache: false because GET requests are often cached by browsers
        // IE is particularly aggressive in that respect
        cache: false,
        data: { id: id },
        success: function(person) {
            $('#FirstName').val(person.FirstName);
            $('#LastName').val(person.LastName);
        }
    });
}

Person class

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Method 2 : Using jQuery Ajax Post call (partial page update).

Suitable for when you need to do partial page post data into database.

Post method is also same like above just replace [HttpPost] on Action method and type as post for jquery method.

For more information check Posting JSON Data to MVC Controllers Here

Method 3 : As a Form post scenario (full page update).

Suitable for when you need to save or update data into database.

View

@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{        
    @Html.TextBoxFor(model => m.Text)
    
    <input type="submit" value="Save" />
}

Action Method

[HttpPost]
public ActionResult SaveData(FormCollection form)
    {
        // Get movie to update
        return View();
   }

Method 4 : As a Form Get scenario (full page update).

Suitable for when you need to Get data from database

Get method also same like above just replace [HttpGet] on Action method and FormMethod.Get for View's form method.

I hope this will help to you.

Display array values in PHP

Iterate over the array and do whatever you want with the individual values.

foreach ($array as $key => $value) {
    echo $key . ' contains ' . $value . '<br/>';
}

How can I check MySQL engine type for a specific table?

SHOW TABLE STATUS WHERE Name = 'xxx'

This will give you (among other things) an Engine column, which is what you want.

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

python NameError: name 'file' is not defined

It seems that your project is written in Python < 3. This is because the file() builtin function is removed in Python 3. Try using Python 2to3 tool or edit the erroneous file yourself.

EDIT: BTW, the project page clearly mentions that

Gunicorn requires Python 2.x >= 2.5. Python 3.x support is planned.

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

and if you don't have the option to go on java8 better use 'yyyy-MM-dd'T'HH:mm:ssXXX' as this gets correctly parsed again (while with only one X this may not be the case... depending on your parsing function)

X generates: +01

XXX generates: +01:00

curl_init() function not working

For Windows, if anybody is interested, uncomment the following line (by removing the ;) from php.ini

;extension=php_curl.dll

Restart apache server.

Remove a specific character using awk or sed

tr can be more concise for removing characters than sed or awk, especially when you want to remove different characters from a string.

Removing double quotes:

echo '"Hi"' | tr -d \"
# Produces Hi without quotes

Removing different kinds of brackets:

echo '[{Hi}]' | tr -d {}[]
# Produces Hi without brackets

-d stands for "delete".

Laravel: Validation unique on update

$rules = [
    "email" => "email|unique:users, email, '.$id.', user_id"
];

In Illuminate\Validation\Rules\Unique;

Unique validation will parse string validation to Rule object

Unique validation has pattern: unique:%s,%s,%s,%s,%s'

Corresponding with: table name, column, ignore, id column, format wheres

/**
 * Convert the rule to a validation string.
 *
 * @return string
 */
public function __toString()
{
    return rtrim(sprintf('unique:%s,%s,%s,%s,%s',
        $this->table,
        $this->column,
        $this->ignore ?: 'NULL',
        $this->idColumn,
        $this->formatWheres()
    ), ',');
}

How to set the default value of an attribute on a Laravel model

You can set Default attribute in Model also>

protected $attributes = [
        'status' => self::STATUS_UNCONFIRMED,
        'role_id' => self::ROLE_PUBLISHER,
    ];

You can find the details in these links

1.) How to set a default attribute value for a Laravel / Eloquent model?

2.) https://laracasts.com/index.php/discuss/channels/eloquent/eloquent-help-generating-attribute-values-before-creating-record


You can also Use Accessors & Mutators for this You can find the details in the Laravel documentation 1.) https://laravel.com/docs/4.2/eloquent#accessors-and-mutators

2.) https://scotch.io/tutorials/automatically-format-laravel-database-fields-with-accessors-and-mutators

3.) Universal accessors and mutators in Laravel 4

How to deserialize JS date using Jackson?

This works for me - i am using jackson 2.0.4

ObjectMapper objectMapper = new ObjectMapper();
final DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
objectMapper.setDateFormat(df);

accessing a docker container from another container

Easiest way is to use --link, however the newer versions of docker are moving away from that and in fact that switch will be removed soon.

The link below offers a nice how too, on connecting two containers. You can skip the attach portion, since that is just a useful how to on adding items to images.

https://deis.com/blog/2016/connecting-docker-containers-1/

The part you are interested in is the communication between two containers. The easiest way, is to refer to the DB container by name from the webserver container.

Example:

you named the db container db1 and the webserver container web0. The containers should both be on the bridge network, which means the web container should be able to connect to the DB container by referring to it's name.

So if you have a web config file for your app, then for DB host you will use the name db1.

if you are using an older version of docker, then you should use --link.

Example:

Step 1: docker run --name db1 oracle/database:12.1.0.2-ee

then when you start the web app. use:

Step 2: docker run --name web0 --link db1 webapp/webapp:3.0

and the web app will be linked to the DB. However, as I said the --link switch will be removed soon.

I'd use docker compose instead, which will build a network for you. However; you will need to download docker compose for your system. https://docs.docker.com/compose/install/#prerequisites

an example setup is like this:

file name is base.yml

version: "2"
services:
  webserver:
    image: "moodlehq/moodle-php-apache:7.1
    depends_on:
      - db
    volumes:
      - "/var/www/html:/var/www/html"
      - "/home/some_user/web/apache2_faildumps.conf:/etc/apache2/conf-enabled/apache2_faildumps.conf"
    environment:
      MOODLE_DOCKER_DBTYPE: pgsql
      MOODLE_DOCKER_DBNAME: moodle
      MOODLE_DOCKER_DBUSER: moodle
      MOODLE_DOCKER_DBPASS: "m@0dl3ing"
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"
  db:
    image: postgres:9
    environment:
      POSTGRES_USER: moodle
      POSTGRES_PASSWORD: "m@0dl3ing"
      POSTGRES_DB: moodle
      HTTP_PROXY: "${HTTP_PROXY}"
      HTTPS_PROXY: "${HTTPS_PROXY}"
      NO_PROXY: "${NO_PROXY}"

this will name the network a generic name, I can't remember off the top of my head what that name is, unless you use the --name switch.

IE docker-compose --name setup1 up base.yml

NOTE: if you use the --name switch, you will need to use it when ever calling docker compose, so docker-compose --name setup1 down this is so you can have more then one instance of webserver and db, and in this case, so docker compose knows what instance you want to run commands against; and also so you can have more then one running at once. Great for CI/CD, if you are running test in parallel on the same server.

Docker compose also has the same commands as docker so docker-compose --name setup1 exec webserver do_some_command

best part is, if you want to change db's or something like that for unit test you can include an additional .yml file to the up command and it will overwrite any items with similar names, I think of it as a key=>value replacement.

Example:

db.yml

version: "2"
services:
  webserver:
    environment:
      MOODLE_DOCKER_DBTYPE: oci
      MOODLE_DOCKER_DBNAME: XE
  db:
    image: moodlehq/moodle-db-oracle

Then call docker-compose --name setup1 up base.yml db.yml

This will overwrite the db. with a different setup. When needing to connect to these services from each container, you use the name set under service, in this case, webserver and db.

I think this might actually be a more useful setup in your case. Since you can set all the variables you need in the yml files and just run the command for docker compose when you need them started. So a more start it and forget it setup.

NOTE: I did not use the --port command, since exposing the ports is not needed for container->container communication. It is needed only if you want the host to connect to the container, or application from outside of the host. If you expose the port, then the port is open to all communication that the host allows. So exposing web on port 80 is the same as starting a webserver on the physical host and will allow outside connections, if the host allows it. Also, if you are wanting to run more then one web app at once, for whatever reason, then exposing port 80 will prevent you from running additional webapps if you try exposing on that port as well. So, for CI/CD it is best to not expose ports at all, and if using docker compose with the --name switch, all containers will be on their own network so they wont collide. So you will pretty much have a container of containers.

UPDATE: After using features further and seeing how others have done it for CICD programs like Jenkins. Network is also a viable solution.

Example:

docker network create test_network

The above command will create a "test_network" which you can attach other containers too. Which is made easy with the --network switch operator.

Example:

docker run \
    --detach \
    --name db1 \
    --network test_network \
    -e MYSQL_ROOT_PASSWORD="${DBPASS}" \
    -e MYSQL_DATABASE="${DBNAME}" \
    -e MYSQL_USER="${DBUSER}" \
    -e MYSQL_PASSWORD="${DBPASS}" \
    --tmpfs /var/lib/mysql:rw \
    mysql:5

Of course, if you have proxy network settings you should still pass those into the containers using the "-e" or "--env-file" switch statements. So the container can communicate with the internet. Docker says the proxy settings should be absorbed by the container in the newer versions of docker; however, I still pass them in as an act of habit. This is the replacement for the "--link" switch which is going away. Once the containers are attached to the network you created you can still refer to those containers from other containers using the 'name' of the container. Per the example above that would be db1. You just have to make sure all containers are connected to the same network, and you are good to go.

For a detailed example of using network in a cicd pipeline, you can refer to this link: https://git.in.moodle.com/integration/nightlyscripts/blob/master/runner/master/run.sh

Which is the script that is ran in Jenkins for a huge integration tests for Moodle, but the idea/example can be used anywhere. I hope this helps others.

How can I post an array of string to ASP.NET MVC Controller without a form?

FYI: JQuery changed the way they serialize post data.

http://forum.jquery.com/topic/nested-param-serialization

You have to set the 'Traditional' setting to true, other wise

{ Values : ["1", "2", "3"] }

will come out as

Values[]=1&Values[]=2&Values[]=3

instead of

Values=1&Values=2&Values=3

How to drop all user tables?

To remove all objects in oracle :

1) Dynamic

DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE' 
AND OWNER='SCHEMA_NAME';
 CURSOR IY IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE 
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND  OWNER='SCHEMA_NAME';
 CURSOR IZ IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND  OWNER='SCHEMA_NAME';
BEGIN
 FOR X IN IX LOOP
   EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' SCHEMA_NAME.'||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
 END LOOP;
 FOR Y IN IY LOOP
   EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' SCHEMA_NAME.'||Y.OBJECT_NAME);
 END LOOP;
 FOR Z IN IZ LOOP
   EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' SCHEMA_NAME.'||Z.OBJECT_NAME||' FORCE ');
 END LOOP;
END;
/

2)Static

    SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
        union ALL
        select 'drop '||object_type||' '|| object_name || ';' from user_objects 
        where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
        union ALL
        SELECT 'drop '
        ||object_type
        ||' '
        || object_name
        || ' force;'
        FROM user_objects
        WHERE object_type IN ('TYPE');

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How to reload the datatable(jquery) data?

Simpler solution:

var dt = $('#table_scroll').dataTable();

$.getJSON(url, null, function (json) {
    dt.fnClearTable();
    dt.fnAddData(json.aaData);
    dt.fnDraw();
});

Force IE10 to run in IE10 Compatibility View?

You can try :

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE8" >

Just like you tried before, but caution:

It seems like the X-UA-Compatible tag has to be the first tag in the < head > section

If this conclusion is correct, then I believe it is undocumented in Microsoft’s blogs/msdn (and if it is documented, then it isn’t sticking out well enough from the docs). Ensuring that this was the first meta tag in the forced IE9 to switch to IE8 mode successfully

Using a batch to copy from network drive to C: or D: drive

This might be due to a security check. This thread might help you.

There are two suggestions: one with pushd and one with a registry change. I'd suggest to use the first one...

In Tkinter is there any way to make a widget not visible?

I was not using grid or pack.
I used just place for my widgets as their size and positioning was fixed.
I wanted to implement hide/show functionality on frame.
Here is demo

from tkinter import *
window=Tk()
window.geometry("1366x768+1+1")
def toggle_graph_visibility():
    graph_state_chosen=show_graph_checkbox_value.get()
    if graph_state_chosen==0:
        frame.place_forget()
    else:
        frame.place(x=1025,y=165)
score_pixel = PhotoImage(width=300, height=430)
show_graph_checkbox_value = IntVar(value=1)
frame=Frame(window,width=300,height=430)
graph_canvas = Canvas(frame, width = 300, height = 430,scrollregion=(0,0,300,300))
my_canvas=graph_canvas.create_image(20, 20, anchor=NW, image=score_pixel)
vbar=Scrollbar(frame,orient=VERTICAL)
vbar.config(command=graph_canvas.yview)
vbar.pack(side=RIGHT,fill=Y)
graph_canvas.config(yscrollcommand=vbar.set)
graph_canvas.pack(side=LEFT,expand=True,fill=BOTH)
frame.place(x=1025,y=165)
Checkbutton(window, text="show graph",variable=show_graph_checkbox_value,command=toggle_graph_visibility).place(x=900,y=165)
window.mainloop()

Note that in above example when 'show graph' is ticked then there is vertical scrollbar.
Graph disappears when checkbox is unselected.
I was fitting some bar graph in that area which I have not shown to keep example simple.
Most important thing to learn from above is the use of frame.place_forget() to hide and frame.place(x=x_pos,y=y_pos) to show back the content.

Visual Studio 2012 Web Publish doesn't copy files

Here we had the same problem.

We just change the "Publish method:" from "File System" to for example "Web Deploy", and immediately change it back to "File System".

Select statement to find duplicates on certain fields

You mention "the first one", so I assume that you have some kind of ordering on your data. Let's assume that your data is ordered by some field ID.

This SQL should get you the duplicate entries except for the first one. It basically selects all rows for which another row with (a) the same fields and (b) a lower ID exists. Performance won't be great, but it might solve your problem.

SELECT A.ID, A.field1, A.field2, A.field3
  FROM myTable A
 WHERE EXISTS (SELECT B.ID
                 FROM myTable B
                WHERE B.field1 = A.field1
                  AND B.field2 = A.field2
                  AND B.field3 = A.field3
                  AND B.ID < A.ID)

Removing a Fragment from the back stack

You add to the back state from the FragmentTransaction and remove from the backstack using FragmentManager pop methods:

FragmentManager manager = getActivity().getSupportFragmentManager();
FragmentTransaction trans = manager.beginTransaction();
trans.remove(myFrag);
trans.commit();
manager.popBackStack();

jQuery click anywhere in the page except on 1 div

here is what i did. wanted to make sure i could click any of the children in my datepicker without closing it.

$('html').click(function(e){
    if (e.target.id == 'menu_content' || $(e.target).parents('#menu_content').length > 0) {
        // clicked menu content or children
    } else {
        // didnt click menu content
    }
});

my actual code:

$('html').click(function(e){
    if (e.target.id != 'datepicker'
        && $(e.target).parents('#datepicker').length == 0
        && !$(e.target).hasClass('datepicker')
    ) {
        $('#datepicker').remove();
    }
});

How to use the 'main' parameter in package.json?

One important function of the main key is that it provides the path for your entry point. This is very helpful when working with nodemon. If you work with nodemon and you define the main key in your package.json as let say "main": "./src/server/app.js", then you can simply crank up the server with typing nodemon in the CLI with root as pwd instead of nodemon ./src/server/app.js.

What is the difference between instanceof and Class.isAssignableFrom(...)?

instanceof can only be used with reference types, not primitive types. isAssignableFrom() can be used with any class objects:

a instanceof int  // syntax error
3 instanceof Foo  // syntax error
int.class.isAssignableFrom(int.class)  // true

See http://java.sun.com/javase/6/docs/api/java/lang/Class.html#isAssignableFrom(java.lang.Class).

How do Mockito matchers work?

Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:

If a call to a method matches more than one mock's when trained calls, the order of the when calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:

when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);

is the order that ensures the (probably) desired result:

foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false

If you inverse the when calls then the result would always be true.

Where do I find the Instagram media ID of a image

Instagram deprecated their legacy APIs in support for Basic Display API during the late 2019

In Basic Display API you are supposed to use the following API endpoint to get the media id. You will need to supply a valid access token.

https://graph.instagram.com/me/media?fields=id,caption&access_token={access-token}

You can read here on how to configure test account and generate access token on Facebook developer portal.

Here is another article which also describes about how to get access token.

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

Java for loop multiple variables

Your for loop is wrong. Try :

for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){

Also, System instead of system and == instead of ===.

But I'm not sure what you're trying to do.

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");    
    var arrSelected = [];

    // selected.each(function(){
    //   arrSelected.push($(this).val());
    // });

    // The problem with the above selected.each statement is that  
    // there is no iteration value.
    // $(this).val() is all selected items, not an iterative item value.
    // With each iteration the selected items will be appended to 
    // arrSelected like so    
    //
    // arrSelected [0]['item0','item1','item2']
    // arrSelected [1]['item0','item1','item2'] 

    // You need to get the iteration value. 
    //
    selected.each((idx, val) => {
        arrSelected.push(val.value);
    });
    // arrSelected [0]['item0'] 
    // arrSelected [1]['item1']
    // arrSelected [2]['item2']
});

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

Might as well add a bit of flex to the answers.

_x000D_
_x000D_
.Radio {_x000D_
  display: inline-flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.Radio--large {_x000D_
  font-size: 2rem;_x000D_
}_x000D_
_x000D_
.Radio-Input {_x000D_
  margin: 0 0.5rem 0;_x000D_
}
_x000D_
<div>_x000D_
  <label class="Radio" for="sex-female">_x000D_
    <input class="Radio-Input" type="radio" id="sex-female" name="sex" value="female" />_x000D_
    Female_x000D_
  </label>_x000D_
_x000D_
  <label class="Radio" for="sex-male">_x000D_
    <input class="Radio-Input" type="radio" id="sex-male" name="sex" value="male" />_x000D_
    Male_x000D_
  </label>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div>_x000D_
  <label class="Radio Radio--large" for="sex-female2">_x000D_
    <input class="Radio-Input" type="radio" id="sex-female2" name="sex" value="female" />_x000D_
    Female_x000D_
  </label>_x000D_
_x000D_
  <label class="Radio Radio--large" for="sex-male2">_x000D_
    <input class="Radio-Input" type="radio" id="sex-male2" name="sex" value="male" />_x000D_
    Male_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

"Too many characters in character literal error"

A char can hold a single character only, a character literal is a single character in single quote, i.e. '&' - if you have more characters than one you want to use a string, for that you have to use double quotes:

case "&&": 

How to remove specific substrings from a set of strings in Python?

if you delete something from list , u can use this way : (method sub is case sensitive)

new_list = []
old_list= ["ABCDEFG","HKLMNOP","QRSTUV"]

for data in old_list:
     new_list.append(re.sub("AB|M|TV", " ", data))

print(new_list) // output : [' CDEFG', 'HKL NOP', 'QRSTUV']

Formatting Numbers by padding with leading zeros in SQL Server

The solution works for signed / negative numbers with leading zeros, for all Sql versions:

DECLARE
    @n money = -3,
    @length tinyint = 15,
    @decimals tinyint = 0

SELECT REPLICATE('-', CHARINDEX('-', @n, 1)) + REPLACE(REPLACE(str(@n, @length, @decimals), '-', ''), ' ', '0')

Defined Edges With CSS3 Filter Blur

Insert the image inside a with position: relative; and overflow: hidden;

HTML

<div><img src="#"></div>

CSS

div {
    position: relative;
    overflow: hidden;
}
img {
    filter: blur(5px);
        -webkit-filter: blur(5px);
        -moz-filter: blur(5px);
        -o-filter: blur(5px);
        -ms-filter: blur(5px);
}

This also works on variable sizes elements, like dynamic div's.

Passing a local variable from one function to another

You can very easily use this to re-use the value of the variable in another function.

// Use this in source window.var1= oEvent.getSource().getBindingContext();

// Get value of var1 in destination var var2= window.var1;

How can I select multiple columns from a subquery (in SQL Server) that should have one record (select top 1) for each record in the main query?

You'll have to make a join:

SELECT A.SalesOrderID, B.Foo
FROM A
JOIN B bo ON bo.id = (
     SELECT TOP 1 id
     FROM B bi
     WHERE bi.SalesOrderID = a.SalesOrderID
     ORDER BY bi.whatever
     )
WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'

, assuming that b.id is a PRIMARY KEY on B

In MS SQL 2005 and higher you may use this syntax:

SELECT SalesOrderID, Foo
FROM (
  SELECT A.SalesOrderId, B.Foo,
         ROW_NUMBER() OVER (PARTITION BY B.SalesOrderId ORDER BY B.whatever) AS rn
  FROM A
  JOIN B ON B.SalesOrderID = A.SalesOrderID
  WHERE A.Date BETWEEN '2000-1-4' AND '2010-1-4'
) i
WHERE rn

This will select exactly one record from B for each SalesOrderId.

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

Cross Browser Flash Detection in Javascript

Have created a small .swf which redirects. If the browser is flash enabled it will redirect.

package com.play48.modules.standalone.util;

import flash.net.URLRequest;


class Redirect {


static function main() {

    flash.Lib.getURL(new URLRequest("http://play48.com/flash.html"), "_self");

}

}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Use jackson-bom which will have all the three jackson versions.i.e.jackson-annotations, jackson-core and jackson-databind. This will resolve the dependencies related to those versions

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
   return{
      exampleProperty: exampleValue 
   }
}

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);

CSS transition when class removed

Basically set up your css like:

element {
  border: 1px solid #fff;      
  transition: border .5s linear;
}

element.saved {
  border: 1px solid transparent;
}

Argument Exception "Item with Same Key has already been added"

If you want "insert or replace" semantics, use this syntax:

A[key] = value;     // <-- insert or replace semantics

It's more efficient and readable than calls involving "ContainsKey()" or "Remove()" prior to "Add()".

So in your case:

rct3Features[items[0]] = items[1];

Django - makemigrations - No changes detected

The possible reason could be deletion of the existing db file and migrations folder you can use python manage.py makemigrations <app_name> this should work. I once faced a similar problem.

Git: "please tell me who you are" error

I ran into this error message whilst trying to commit some files.

Simply running git fetch then trying my commit again worked for me.

Can you force Visual Studio to always run as an Administrator in Windows 8?

Also, you can check the compatibility troubleshooting

  • Right-click on Visual Studio > select Troubleshoot compatibility.
  • Select Troubleshoot Program.
  • Check The program requires additional permissions.
  • Click on Test the program.
  • Wait for a moment until the program launch. Click Next.
  • Select Yes, save these settings for this program.
  • Wait for resolving the issue.
  • Make sure the final status is fixed. Click Close.

Check the detail steps, and other ways to always open VS as Admin at Visual Studio requires the application to have elevated permissions.

Struct like objects in Java

By the way, the structure you're giving as an example already exist in the Java base class library as java.awt.Point. It has x and y as public fields, check it out for yourself.

If you know what you're doing, and others in your team know about it, then it is okay to have public fields. But you shouldn't rely on it because they can cause headaches as in bugs related to developers using objects as if they were stack allocated structs (java objects are always sent to methods as references and not as copies).

Maintaining the final state at end of a CSS3 animation

If you are using more animation attributes the shorthand is:

animation: bubble 2s linear 0.5s 1 normal forwards;

This gives:

  • bubble animation name
  • 2s duration
  • linear timing-function
  • 0.5s delay
  • 1 iteration-count (can be 'infinite')
  • normal direction
  • forwards fill-mode (set 'backwards' if you want to have compatibility to use the end position as the final state[this is to support browsers that has animations turned off]{and to answer only the title, and not your specific case})

Java word count program

To count total words Or to count total words without repeat word count

public static void main(String[] args) {
    // TODO Auto-generated method stub
    String test = "I am trying to make make make";
    Pattern p = Pattern.compile("\\w+");
    Matcher m = p.matcher(test);
    HashSet<String> hs =  new HashSet<>();
    int i=0;
    while (m.find()) {
        i++;
        hs.add(m.group());
    }
    System.out.println("Total words Count==" + i);
    System.out.println("Count without Repetation ==" + hs.size());
}

}

Output :

Total words Count==7

Count without Repeatation ==5

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The general approach to write to any stream (not only MemoryStream) is to use BinaryWriter:

static void Write(Stream s, Byte[] bytes)
{
    using (var writer = new BinaryWriter(s))
    {
        writer.Write(bytes);
    }
}

Input text dialog Android

How about this EXAMPLE? It seems straightforward.

final EditText txtUrl = new EditText(this);

// Set the default text to a link of the Queen
txtUrl.setHint("http://www.librarising.com/astrology/celebs/images2/QR/queenelizabethii.jpg");

new AlertDialog.Builder(this)
  .setTitle("Moustachify Link")
  .setMessage("Paste in the link of an image to moustachify!")
  .setView(txtUrl)
  .setPositiveButton("Moustachify", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
      String url = txtUrl.getText().toString();
      moustachify(null, url);
    }
  })
  .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int whichButton) {
    }
  })
  .show(); 

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to use the addr2line command in Linux?

That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.

For example:

$ cat t.c
#include <stdio.h>
int main()
{
    printf("hello\n");
    return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0

0x400534 is the address of main in my case. 0x400408 is also a valid function address in a.out, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init. You can see the layout of your executable with readelf -a your_exe.)

Other times when addr2line will fail is if you're including a library that has no debug information.

How to stop process from .BAT file?

Why don't you use PowerShell?

Stop-Process -Name notepad

And if you are in a batch file:

powershell -Command "Stop-Process -Name notepad"
powershell -Command "Stop-Process -Id 4232"

LDAP Authentication using Java

// this class will authenticate LDAP UserName or Email

// simply call LdapAuth.authenticateUserAndGetInfo (username,password);

//Note: Configure ldapURI ,requiredAttributes ,ADSearchPaths,accountSuffex 

import java.util.*;

import javax.naming.*;

import java.util.regex.*;

import javax.naming.directory.*;

import javax.naming.ldap.InitialLdapContext;

import javax.naming.ldap.LdapContext;

public class LdapAuth {


private final static String ldapURI = "ldap://20.200.200.200:389/DC=corp,DC=local";

private final static String contextFactory = "com.sun.jndi.ldap.LdapCtxFactory";

private  static String[] requiredAttributes = {"cn","givenName","sn","displayName","userPrincipalName","sAMAccountName","objectSid","userAccountControl"};


// see you active directory user OU's hirarchy 

private  static String[] ADSearchPaths = 

{ 

    "OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=In-House,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Torbram Users,OU=Users,OU=O365 Synced Accounts,OU=ALL USERS",

    "OU=Migrated Users,OU=TES-Users"

};


private static String accountSuffex = "@corp.local"; // this will be used if user name is just provided


private static void authenticateUserAndGetInfo (String user, String password) throws Exception {

    try {


        Hashtable<String,String> env = new Hashtable <String,String>();

        env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);

        env.put(Context.PROVIDER_URL, ldapURI);     

        env.put(Context.SECURITY_AUTHENTICATION, "simple");

        env.put(Context.SECURITY_PRINCIPAL, user);

        env.put(Context.SECURITY_CREDENTIALS, password);

        DirContext ctx = new InitialDirContext(env);

        String filter = "(sAMAccountName="+user+")";  // default for search filter username

        if(user.contains("@"))  // if user name is a email then
        {
            //String parts[] = user.split("\\@");
            //use different filter for email
            filter = "(userPrincipalName="+user+")";
        }

        SearchControls ctrl = new SearchControls();
        ctrl.setSearchScope(SearchControls.SUBTREE_SCOPE);
        ctrl.setReturningAttributes(requiredAttributes);

        NamingEnumeration userInfo = null;


        Integer i = 0;
        do
        {
            userInfo = ctx.search(ADSearchPaths[i], filter, ctrl);
            i++;

        } while(!userInfo.hasMore() && i < ADSearchPaths.length );

        if (userInfo.hasMore()) {

            SearchResult UserDetails = (SearchResult) userInfo.next();
            Attributes userAttr = UserDetails.getAttributes();System.out.println("adEmail = "+userAttr.get("userPrincipalName").get(0).toString());

            System.out.println("adFirstName = "+userAttr.get("givenName").get(0).toString());

            System.out.println("adLastName = "+userAttr.get("sn").get(0).toString());

            System.out.println("name = "+userAttr.get("cn").get(0).toString());

            System.out.println("AdFullName = "+userAttr.get("cn").get(0).toString());

        }

        userInfo.close();

    }
    catch (javax.naming.AuthenticationException e) {

    }
}   
}

Handle ModelState Validation in ASP.NET Web API

Add below code in startup.cs file

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2).ConfigureApiBehaviorOptions(options =>
            {
                options.InvalidModelStateResponseFactory = (context) =>
                {
                    var errors = context.ModelState.Values.SelectMany(x => x.Errors.Select(p => new ErrorModel()
                   {
                       ErrorCode = ((int)HttpStatusCode.BadRequest).ToString(CultureInfo.CurrentCulture),
                        ErrorMessage = p.ErrorMessage,
                        ServerErrorMessage = string.Empty
                    })).ToList();
                    var result = new BaseResponse
                    {
                        Error = errors,
                        ResponseCode = (int)HttpStatusCode.BadRequest,
                        ResponseMessage = ResponseMessageConstants.VALIDATIONFAIL,

                    };
                    return new BadRequestObjectResult(result);
                };
           });

Sqlite: CURRENT_TIMESTAMP is in GMT, not the timezone of the machine

I found on the sqlite documentation (https://www.sqlite.org/lang_datefunc.html) this text:

Compute the date and time given a unix timestamp 1092941466, and compensate for your local timezone.

SELECT datetime(1092941466, 'unixepoch', 'localtime');

That didn't look like it fit my needs, so I tried changing the "datetime" function around a bit, and wound up with this:

select datetime(timestamp, 'localtime')

That seems to work - is that the correct way to convert for your timezone, or is there a better way to do this?

Apache Spark: map vs mapPartitions?

Map :

  1. It processes one row at a time , very similar to map() method of MapReduce.
  2. You return from the transformation after every row.

MapPartitions

  1. It processes the complete partition in one go.
  2. You can return from the function only once after processing the whole partition.
  3. All intermediate results needs to be held in memory till you process the whole partition.
  4. Provides you like setup() map() and cleanup() function of MapReduce

Map Vs mapPartitions http://bytepadding.com/big-data/spark/spark-map-vs-mappartitions/

Spark Map http://bytepadding.com/big-data/spark/spark-map/

Spark mapPartitions http://bytepadding.com/big-data/spark/spark-mappartitions/

Wrapping long text without white space inside of a div

I have found something strange here about word-wrap only works with width property of CSS properly.

_x000D_
_x000D_
#ONLYwidth {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
#wordwrapWITHOUTWidth {_x000D_
  word-wrap: break-word;_x000D_
}_x000D_
_x000D_
#wordwrapWITHWidth {_x000D_
  width: 200px;_x000D_
  word-wrap: break-word;_x000D_
}
_x000D_
<b>This is the example of word-wrap only using width property</b>_x000D_
<p id="ONLYwidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap without width property</b>_x000D_
<p id="wordwrapWITHOUTWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>_x000D_
<br/>_x000D_
<b>This is the example of word-wrap with width property</b>_x000D_
<p id="wordwrapWITHWidth">827938828ey823876te37257e5t328er6367r5erd663275e65r532r6s3624e5645376er563rdr753624e544341763r567r4e56r326r5632r65sr32dr32udr56r634r57rd63725</p>
_x000D_
_x000D_
_x000D_

Here is a working demo that I have prepared about it. http://jsfiddle.net/Hss5g/2/

How can I share Jupyter notebooks with non-programmers?

Michael's suggestion of running your own nbviewer instance is a good one I used in the past with an Enterprise Github server.

Another lightweight alternative is to have a cell at the end of your notebook that does a shell call to nbconvert so that it's automatically refreshed after running the whole thing:

!ipython nbconvert <notebook name>.ipynb --to html

EDIT: With Jupyter/IPython's Big Split, you'll probably want to change this to !jupyter nbconvert <notebook name>.ipynb --to html now.

c++ string array initialization

With support for C++11 initializer lists it is very easy:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

using Strings = vector<string>;

void foo( Strings const& strings )
{
    for( string const& s : strings ) { cout << s << endl; }
}

auto main() -> int
{
    foo( Strings{ "hi", "there" } ); 
}

Lacking that (e.g. for Visual C++ 10.0) you can do things like this:

#include <iostream>
#include <vector>
#include <string>
using namespace std;

typedef vector<string> Strings;

void foo( Strings const& strings )
{
    for( auto it = begin( strings );  it != end( strings );  ++it )
    {
        cout << *it << endl;
    }
}

template< class Elem >
vector<Elem>& r( vector<Elem>&& o ) { return o; }

template< class Elem, class Arg >
vector<Elem>& operator<<( vector<Elem>& v, Arg const& a )
{
    v.push_back( a );
    return v;
}

int main()
{
    foo( r( Strings() ) << "hi" << "there" ); 
}

Service Reference Error: Failed to generate code for the service reference

I have encountered this problem when upgrading a VS2010 WCF+Silverlight solution in VS2015 Professional. Besides automatically upgrading from Silverlight 4 to Silverlight 5, the service reference reuse checkbox value was changed and generation failed.

Shell script - remove first and last quote (") from a variable

This is the most discrete way without using sed:

x='"fish"'
printf "   quotes: %s\nno quotes:  %s\n" "$x" "${x//\"/}"

Or

echo $x
echo ${x//\"/}

Output:

   quotes: "fish"
no quotes:  fish

I got this from a source.

How do I align spans or divs horizontally?

What you might like to do is look up CSS grid based layouts. This layout method involves specifying some CSS classes to align the page contents to a grid structure. It's more closely related to print-bsed layout than web-based, but it's a technique used on a lot of websites to layout the content into a structure without having to resort to tables.

Try this for starters from Smashing Magazine.

How to generate service reference with only physical wsdl file

This may be the easiest method

  • Right click on the project and select "Add Service Reference..."
  • In the Address: box, enter the physical path (C:\test\project....) of the downloaded/Modified wsdl.
  • Hit Go

Row count with PDO

fetchColumn()

used if want to get count of record [effisien]

$sql   = "SELECT COUNT(*) FROM fruit WHERE calories > 100";
$res   = $conn->query($sql);
$count = $res->fetchColumn(); // ex = 2

query()

used if want to retrieve data and count of record [options]

$sql = "SELECT * FROM fruit WHERE calories > 100";
$res = $conn->query($sql);

if ( $res->rowCount() > 0) {

    foreach ( $res as $row ) {
        print "Name: {$row['NAME']} <br />";
    }

}
else {
    print "No rows matched the query.";
}

PDOStatement::rowCount

What is the difference between UNION and UNION ALL?

The basic difference between UNION and UNION ALL is union operation eliminates the duplicated rows from the result set but union all returns all rows after joining.

from http://zengin.wordpress.com/2007/07/31/union-vs-union-all/

How do I test a single file using Jest?

import LoggerService from '../LoggerService ';

describe('Method called****', () => {
  it('00000000', () => {
    const logEvent = jest.spyOn(LoggerService, 'logEvent');
    expect(logEvent).toBeDefined();
  });
});

Usage:

npm test -- __tests__/LoggerService.test.ts -t '00000000'

if statements matching multiple values

Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement

switch(value)
{
case 1:
case 2:
   return true;
default:
   return false
}

sql query to return differences between two tables

To get all the differences between two tables, you can use like me this SQL request :

SELECT 'TABLE1-ONLY' AS SRC, T1.*
FROM (
      SELECT * FROM Table1
      EXCEPT
      SELECT * FROM Table2
      ) AS T1
UNION ALL
SELECT 'TABLE2-ONLY' AS SRC, T2.*
FROM (
      SELECT * FROM Table2
      EXCEPT
      SELECT * FROM Table1
      ) AS T2
;

Pyspark: Exception: Java gateway process exited before sending the driver its port number

Had same issue, after installing java using below lines solved the issue !

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java8-installer

How can I install pip on Windows?

-- Outdated -- use distribute, not setuptools as described here. --
-- Outdated #2 -- use setuptools as distribute is deprecated.

As you mentioned pip doesn't include an independent installer, but you can install it with its predecessor easy_install.

So:

  1. Download the last pip version from here: http://pypi.python.org/pypi/pip#downloads
  2. Uncompress it
  3. Download the last easy installer for Windows: (download the .exe at the bottom of http://pypi.python.org/pypi/setuptools ). Install it.
  4. copy the uncompressed pip folder content into C:\Python2x\ folder (don't copy the whole folder into it, just the content), because python command doesn't work outside C:\Python2x folder and then run: python setup.py install
  5. Add your python C:\Python2x\Scripts to the path

You are done.

Now you can use pip install package to easily install packages as in Linux :)

How to create a popup windows in javafx

Have you looked into ControlsFx Popover control.


import org.controlsfx.control.PopOver;
import org.controlsfx.control.PopOver.ArrowLocation;

private PopOver item;

final Scene scene = addItemButton.getScene();

final Point2D windowCoord = new Point2D(scene.getWindow()
        .getX(), scene.getWindow().getY());

final Point2D sceneCoord = new Point2D(scene.getX(), scene.
                getY());

final Point2D nodeCoord = addItemButton.localToScene(0.0,
                        0.0);
final double clickX = Math.round(windowCoord.getX()
    + sceneCoord.getY() + nodeCoord.getX());

final double clickY = Math.round(windowCoord.getY()
        + sceneCoord.getY() + nodeCoord.getY());
item.setContentNode(addItemScreen);
item.setArrowLocation(ArrowLocation.BOTTOM_LEFT);
item.setCornerRadius(4);                            
item.setDetachedTitle("Add New Item");
item.show(addItemButton.getParent(), clickX, clickY);

This is only an example but a PopOver sounds like it could accomplish what you want. Check out the documentation for more info.

Important note: ControlsFX will only work on JavaFX 8.0 b118 or later.

Forward slash in Java Regex

The problem is actually that you need to double-escape backslashes in the replacement string. You see, "\\/" (as I'm sure you know) means the replacement string is \/, and (as you probably don't know) the replacement string \/ actually just inserts /, because Java is weird, and gives \ a special meaning in the replacement string. (It's supposedly so that \$ will be a literal dollar sign, but I think the real reason is that they wanted to mess with people. Other languages don't do it this way.) So you have to write either:

"Hello/You/There".replaceAll("/", "\\\\/");

or:

"Hello/You/There".replaceAll("/", Matcher.quoteReplacement("\\/"));

(Using java.util.regex.Matcher.quoteReplacement(String).)

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

You need to add icon.png through visual.

Resouces... / Dravable/ Add ///

How does one convert a HashMap to a List in Java?

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
    System.out.println(s);
}

Make a nav bar stick

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  _x000D_
  $(window).scroll(function () {_x000D_
      //if you hard code, then use console_x000D_
      //.log to determine when you want the _x000D_
      //nav bar to stick.  _x000D_
      console.log($(window).scrollTop())_x000D_
    if ($(window).scrollTop() > 280) {_x000D_
      $('#nav_bar').addClass('navbar-fixed');_x000D_
    }_x000D_
    if ($(window).scrollTop() < 281) {_x000D_
      $('#nav_bar').removeClass('navbar-fixed');_x000D_
    }_x000D_
  });_x000D_
});
_x000D_
html, body {_x000D_
 height: 4000px;_x000D_
}_x000D_
_x000D_
.navbar-fixed {_x000D_
    top: 0;_x000D_
    z-index: 100;_x000D_
  position: fixed;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
#body_div {_x000D_
 top: 0;_x000D_
 position: relative;_x000D_
    height: 200px;_x000D_
    background-color: green;_x000D_
}_x000D_
_x000D_
#banner {_x000D_
 width: 100%;_x000D_
 height: 273px;_x000D_
    background-color: gray;_x000D_
 overflow: hidden;_x000D_
}_x000D_
_x000D_
#nav_bar {_x000D_
 border: 0;_x000D_
 background-color: #202020;_x000D_
 border-radius: 0px;_x000D_
 margin-bottom: 0;_x000D_
    height: 30px;_x000D_
}_x000D_
_x000D_
.nav_links {_x000D_
    margin: 0;_x000D_
}_x000D_
_x000D_
.nav_links li {_x000D_
 display: inline-block;_x000D_
    margin-top: 4px;_x000D_
}_x000D_
.nav_links li a {_x000D_
 padding: 0 15.5px;_x000D_
 color: #3498db;_x000D_
 text-decoration: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="banner">_x000D_
     <h2>put what you want here</h2>_x000D_
     <p>just adjust javascript size to match this window</p>_x000D_
  </div>_x000D_
_x000D_
  <nav id='nav_bar'>_x000D_
    <ul class='nav_links'>_x000D_
      <li><a href="url">Nav Bar</a></li>_x000D_
      <li><a href="url">Sign In</a></li>_x000D_
      <li><a href="url">Blog</a></li>_x000D_
      <li><a href="url">About</a></li>_x000D_
    </ul>_x000D_
  </nav>_x000D_
<div id='body_div'>_x000D_
    <p style='margin: 0; padding-top: 50px;'>and more stuff to continue scrolling here</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make flexbox items the same size?

Set them so that their flex-basis is 0 (so all elements have the same starting point), and allow them to grow:

flex: 1 1 0px

Your IDE or linter might mention that the unit of measure 'px' is redundant. If you leave it out (like: flex: 1 1 0), IE will not render this correctly. So the px is required to support Internet Explorer, as mentioned in the comments by @fabb;

Querying DynamoDB by date

Updated Answer:

DynamoDB allows for specification of secondary indexes to aid in this sort of query. Secondary indexes can either be global, meaning that the index spans the whole table across hash keys, or local meaning that the index would exist within each hash key partition, thus requiring the hash key to also be specified when making the query.

For the use case in this question, you would want to use a global secondary index on the "CreatedAt" field.

For more on DynamoDB secondary indexes see the secondary index documentation

Original Answer:

DynamoDB does not allow indexed lookups on the range key only. The hash key is required such that the service knows which partition to look in to find the data.

You can of course perform a scan operation to filter by the date value, however this would require a full table scan, so it is not ideal.

If you need to perform an indexed lookup of records by time across multiple primary keys, DynamoDB might not be the ideal service for you to use, or you might need to utilize a separate table (either in DynamoDB or a relational store) to store item metadata that you can perform an indexed lookup against.

Optimal way to Read an Excel file (.xls/.xlsx)

Try to use this free way to this, https://freenetexcel.codeplex.com

 Workbook workbook = new Workbook();

 workbook.LoadFromFile(@"..\..\parts.xls",ExcelVersion.Version97to2003);
 //Initialize worksheet
 Worksheet sheet = workbook.Worksheets[0];

 DataTable dataTable = sheet.ExportDataTable();

How can I print a quotation mark in C?

Try this:

#include <stdio.h>

int main()
{
  printf("Printing quotation mark \" ");
}

Creating a daemon in Linux

man 7 daemon describes how to create daemon in great detail. My answer is just excerpt from this manual.

There are at least two types of daemons:

  1. traditional SysV daemons (old-style),
  2. systemd daemons (new-style).

SysV Daemons

If you are interested in traditional SysV daemon, you should implement the following steps:

  1. Close all open file descriptors except standard input, output, and error (i.e. the first three file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor stays around in the daemon process. On Linux, this is best implemented by iterating through /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by getrlimit() for RLIMIT_NOFILE.
  2. Reset all signal handlers to their default. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL.
  3. Reset the signal mask using sigprocmask().
  4. Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
  5. Call fork(), to create a background process.
  6. In the child, call setsid() to detach from any terminal and create an independent session.
  7. In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again.
  8. Call exit() in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be.
  9. In the daemon process, connect /dev/null to standard input, output, and error.
  10. In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and suchlike directly control the access mode of the created files and directories.
  11. In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted.
  12. In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for example /run/foobar.pid (for a hypothetical daemon "foobar") to ensure that the daemon cannot be started more than once. This must be implemented in race-free fashion so that the PID file is only updated when it is verified at the same time that the PID previously stored in the PID file no longer exists or belongs to a foreign process.
  13. In the daemon process, drop privileges, if possible and applicable.
  14. From the daemon process, notify the original process started that initialization is complete. This can be implemented via an unnamed pipe or similar communication channel that is created before the first fork() and hence available in both the original and the daemon process.
  15. Call exit() in the original process. The process that invoked the daemon must be able to rely on that this exit() happens after initialization is complete and all external communication channels are established and accessible.

Note this warning:

The BSD daemon() function should not be used, as it implements only a subset of these steps.

A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. However, it is recommended to make this behavior optional and configurable via a command line argument to ease debugging as well as to simplify integration into systems using systemd.

Note that daemon() is not POSIX compliant.


New-Style Daemons

For new-style daemons the following steps are recommended:

  1. If SIGTERM is received, shut down the daemon and exit cleanly.
  2. If SIGHUP is received, reload the configuration files, if this applies.
  3. Provide a correct exit code from the main daemon process, as this is used by the init system to detect service errors and problems. It is recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts.
  4. If possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as last step of initialization.
  5. For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See systemd.service(5) for details.
  6. As much as possible, rely on the init system's functionality to limit the access of the daemon to files, services and other resources, i.e. in the case of systemd, rely on systemd's resource limit control instead of implementing your own, rely on systemd's privilege dropping code instead of implementing it in the daemon, and similar. See systemd.exec(5) for the available controls.
  7. If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service activation configuration file. This has multiple advantages: your daemon may be started lazily on-demand; it may be started in parallel to other daemons requiring it — which maximizes parallelization and boot-up speed; your daemon can be restarted on failure without losing any bus requests, as the bus queues requests for activatable services. See below for details.
  8. If your daemon provides services to other local processes or remote clients via a socket, it should be made socket-activatable following the scheme pointed out below. Like D-Bus activation, this enables on-demand starting of services as well as it allows improved parallelization of service start-up. Also, for state-less protocols (such as syslog, DNS), a daemon implementing socket-based activation can be restarted without losing a single request. See below for details.
  9. If applicable, a daemon should notify the init system about startup completion or status updates via the sd_notify(3) interface.
  10. Instead of using the syslog() call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error via fprintf(), which is then forwarded to syslog by the init system. If log levels are necessary, these can be encoded by prefixing individual log lines with strings like "<4>" (for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel's printk() level system. For details, see sd-daemon(3) and systemd.exec(5).

To learn more read whole man 7 daemon.

How to set width of a div in percent in JavaScript?

The question is what do you want the div's height/width to be a percent of?

By default, if you assign a percentage value to a height/width it will be relative to it's direct parent dimensions. If the parent doesn't have a defined height, then it won't work.

So simply, remember to set the height of the parent, then a percentage height will work via the css attribute:

obj.style.width = '50%';

Getting "Skipping JaCoCo execution due to missing execution data file" upon executing JaCoCo

My response is very late but for others users In your case you have to configure failsafe pluging to use the command line agent configuration saved in itCoverageAgent variable. For exemple

<configuration>
    <argLine>${itCoverageAgent}</argLine>
</configuration>

In your maven configuration, jacoco prepare the command line arguments in prepare-agent phase, but failsafe plugin doesn't use it so there is no execution data file.

HTML: how to force links to open in a new tab, not new window

The way the browser handles new windows vs new tab is set in the browser's options and can only be changed by the user.

Regular expression containing one word or another

You can use a single group for seconds/minutes. The following expression may suit your needs:

([0-9]+)\s*(seconds|minutes)

Online demo

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

What is the difference between application server and web server?

An application server is a machine (an executable process running on some machine, actually) that "listens" (on any channel, using any protocol), for requests from clients for whatever service it provides, and then does something based on those requests. (may or may not involve a respose to the client)

A Web server is process running on a machine that "listens" specifically on TCP/IP Channel using one of the "internet" protocols, (http, https, ftp, etc..) and does whatever it does based on those incoming requests... Generally, (as origianly defined), it fetched/generated and returned an html web page to the client, either fetched from a static html file on the server, or constructed dynamically based on parameters in the incoming client request.

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

SLF4J: Class path contains multiple SLF4J bindings

Gradle version;

configurations.all {
    exclude module: 'slf4j-log4j12'
}

How to print binary tree diagram?

See also these answers.

In particular it wasn't too difficult to use abego TreeLayout to produce results shown below with the default settings.

If you try that tool, note this caveat: It prints children in the order they were added. For a BST where left vs right matters I found this library to be inappropriate without modification.

Also, the method to add children simply takes a parent and child node as parameters. (So to process a bunch of nodes, you must take the first one separately to create a root.)

I ended up using this solution above, modifying it to take in the type <Node> so as to have access to Node's left and right (children).

tree created with abego TreeLayout

Error: Unable to run mksdcard SDK tool

if you do this: sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6. You may get this error:

E: Unable to locate package lib32bz2-1.0

E: Couldn't find any package by glob 'lib32bz2-1.0'

E: Couldn't find any package by regex 'lib32bz2-1.0'

So i suggest just doing this:

sudo apt-get install lib32stdc++6

And also, the AOSP should look for how while installing Android-Studio, that is installed too.

How to select specific form element in jQuery?

$("#name", '#form2').val("Hello World")

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

This is happening because this is a dynamic component and you didn't add it to entryComponents under @NgModule.

Simply add it there:

@NgModule({
  /* ----------------- */
  entryComponents: [ DialogResultExampleDialog ] // <---- Add it here

Look at how the Angular team talks about entryComponents:

entryComponents?: Array<Type<any>|any[]>

Specifies a list of components that should be compiled when this module is defined. For each component listed here, Angular will create a ComponentFactory and store it in the ComponentFactoryResolver.

Also, this is the list of the methods on @NgModule including entryComponents...

As you can see, all of them are optional (look at the question marks), including entryComponents which accept an array of components:

@NgModule({ 
  providers?: Provider[]
  declarations?: Array<Type<any>|any[]>
  imports?: Array<Type<any>|ModuleWithProviders|any[]>
  exports?: Array<Type<any>|any[]>
  entryComponents?: Array<Type<any>|any[]>
  bootstrap?: Array<Type<any>|any[]>
  schemas?: Array<SchemaMetadata|any[]>
  id?: string
})

How to set timeout in Retrofit library?

public class ApiClient {
    private static Retrofit retrofit = null;
    private static final Object LOCK = new Object();

    public static void clear() {
        synchronized (LOCK) {
            retrofit = null;
        }
    }

    public static Retrofit getClient() {
        synchronized (LOCK) {
            if (retrofit == null) {

                Gson gson = new GsonBuilder()
                        .setLenient()
                        .create();

                OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
                        .connectTimeout(40, TimeUnit.SECONDS)
                        .readTimeout(60, TimeUnit.SECONDS)
                        .writeTimeout(60, TimeUnit.SECONDS)
                        .build();

                // Log.e("jjj", "=" + (MySharedPreference.getmInstance().isEnglish() ? Constant.WEB_SERVICE : Constant.WEB_SERVICE_ARABIC));
                retrofit = new Retrofit.Builder()
                        .client(okHttpClient)
                        .baseUrl(Constants.WEB_SERVICE)
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .build();
            }
            return retrofit;
        }`enter code here`

    }

    public static RequestBody plain(String content) {
        return getRequestBody("text/plain", content);
    }

    public static RequestBody getRequestBody(String type, String content) {
        return RequestBody.create(MediaType.parse(type), content);
    }
}


-------------------------------------------------------------------------


    implementation 'com.squareup.retrofit2:retrofit:2.4.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.4.0'

Escape regex special characters in a Python string

As it was mentioned above, the answer depends on your case. If you want to escape a string for a regular expression then you should use re.escape(). But if you want to escape a specific set of characters then use this lambda function:

>>> escape = lambda s, escapechar, specialchars: "".join(escapechar + c if c in specialchars or c == escapechar else c for c in s)
>>> s = raw_input()
I'm "stuck" :\
>>> print s
I'm "stuck" :\
>>> print escape(s, "\\", ['"'])
I'm \"stuck\" :\\

How to "fadeOut" & "remove" a div in jQuery?

Use

.fadeOut(360).delay(400).remove();

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

How do I use StringUtils in Java?

StringUtils is part of Apache Commons Lang (http://commons.apache.org/lang/, and as the name suggest it provides some nice utilities for dealing with Strings, going beyond what is offered in java.lang.String. It consists of over 50 static methods.

There are two different versions available, the newer org.apache.commons.lang3.StringUtils and the older org.apache.commons.lang.StringUtils. There are not really any significant differences between the two. lang3.StringUtils requires Java 5.0 and is probably the version you'll want to use.

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Difference between Relative path and absolute path in javascript

I think this example will help you in understanding this more simply.

Path differences in Windows

Windows absolute path C:\Windows\calc.exe

Windows non absolute path (relative path) calc.exe

In the above example, the absolute path contains the full path to the file and not just the file as seen in the non absolute path. In this example, if you were in a directory that did not contain "calc.exe" you would get an error message. However, when using an absolute path you can be in any directory and the computer would know where to open the "calc.exe" file.

Path differences in Linux

Linux absolute path /home/users/c/computerhope/public_html/cgi-bin

Linux non absolute path (relative path) /public_html/cgi-bin

In these example, the absolute path contains the full path to the cgi-bin directory on that computer. How to find the absolute path of a file in Linux Since most users do not want to see the full path as their prompt, by default the prompt is relative to their personal directory as shown above. To find the full absolute path of the current directory use the pwd command.

It is a best practice to use relative file paths (if possible).

When using relative file paths, your web pages will not be bound to your current base URL. All links will work on your own computer (localhost) as well as on your current public domain and your future public domains.

Best Regular Expression for Email Validation in C#

I would like to suggest new EmailAddressAttribute().IsValid(emailTxt) for additional validation before/after validating using RegEx

Remember EmailAddressAttribute is part of System.ComponentModel.DataAnnotations namespace.

How to get Current Directory?

If you are using the Poco library, it's a one liner and it should work on all platforms I think.

Poco::Path::current()

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

Can I call methods in constructor in Java?

You can: this is what constructors are for. Also you make it clear that the object is never constructed in an unknown state (without configuration loaded).

You shouldn't: calling instance method in constructor is dangerous because the object is not yet fully initialized (this applies mainly to methods than can be overridden). Also complex processing in constructor is known to have a negative impact on testability.

jQuery Date Picker - disable past dates

you have to declare current date into variables like this

 $(function() {
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();
    $('#datepicker').datepicker({
    minDate: new Date(currentYear, currentMonth, currentDate)
    });
})

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Split string by single spaces

If you are not averse to boost, boost.tokenizer is flexible enough to solve this

#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>

void split_and_show(const std::string s)
{
    boost::char_separator<char> sep(" ", "", boost::keep_empty_tokens);
    boost::tokenizer<boost::char_separator<char> > tok(s, sep);
    for(auto i = tok.begin(); i!=tok.end(); ++i)
            std::cout << '"' << *i << "\"\n";
}
int main()
{
    split_and_show("This is a string");
    split_and_show("This  is a string");

}

test: https://ideone.com/mN2sR

How to iterate over columns of pandas dataframe to run regression

You can use iteritems():

for name, values in df.iteritems():
    print('{name}: {value}'.format(name=name, value=values[0]))

Replace None with NaN in pandas dataframe

Here's another option:

df.replace(to_replace=[None], value=np.nan, inplace=True)

Could not load NIB in bundle

Visit the properties of the .xib files in the file inspector ,the property "Target Membership" pitch on the select box, then your xib file was linked with your target

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Hide separator line on one UITableViewCell

The width of the iphone is 320 . So put left and right value in Cell attribute for separatorInset more than half of 320 .

Insert line break inside placeholder attribute of a textarea?

UPDATE (Jan 2016): The nice little hack might not work on all browsers anymore so I have a new solution with a tiny bit of javascript below.


A Nice Little Hack

It doesn't feel nice, but you can just put the new lines in the html. Like this:

_x000D_
_x000D_
<textarea rows="6" id="myAddress" type="text" placeholder="My Awesome House,
1 Long St
London
Postcode
UK"></textarea>
_x000D_
_x000D_
_x000D_

Notice each line is on a new line (not being wrapped) and each 'tab' indent is 4 spaces. Granted it is not a very nice method, but it seems to work:

http://jsfiddle.net/01taylop/HDfju/

  • It is likely that the indent level of each line will vary depending on the width of your text area.
  • It is important to have resize: none; in the css so that the size of the textarea is fixed (See jsfiddle).

Alternatively When you want a new line, hit return twice (So there is a empty line between your 'new lines'. This 'empty line' created needs to have enough tabs/spaces that would equate to the width of your textarea. It doesn't seem to matter if you have far too many, you just need enough. This is so dirty though and probably not browser compliant. I wish there was an easier way!


A Better Solution

Check out the JSFiddle.

  • This solution positions a div behind the textarea.
  • Some javascript is used to change the background colour of the textarea, hiding or revealing the placeholder appropriately.
  • The inputs and placeholders must have the same font sizes, hence the two mixins.
  • The box-sizing and display: block properties on the textarea are important or the div behind it will not be the same size.
  • Setting resize: vertical and a min-height on the textarea are also important - notice how the placeholder text will wrap and expanding the textarea will keep the white background. However, commenting out the resize property will cause issues when expanding the textarea horizontally.
  • Just make sure the min-height on the textarea is enough to cover your entire placeholder at its smallest width.**

JSFiddle Screenshot

HTML:

<form>
  <input type='text' placeholder='First Name' />
  <input type='text' placeholder='Last Name' />
  <div class='textarea-placeholder'>
    <textarea></textarea>
    <div>
      First Line
      <br /> Second Line
      <br /> Third Line
    </div>
  </div>
</form>

SCSS:

$input-padding: 4px;

@mixin input-font() {
  font-family: 'HelveticaNeue-Light', 'Helvetica Neue Light', 'Helvetica Neue', Helvetica, Arial, 'Lucida Grande', sans-serif;
  font-size: 12px;
  font-weight: 300;
  line-height: 16px;
}

@mixin placeholder-style() {
  color: #999;
  @include input-font();
}

* {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

form {
  width: 250px;
}

input,textarea {
  display: block;
  width: 100%;
  padding: $input-padding;
  border: 1px solid #ccc;
}

input {
  margin-bottom: 10px;
  background-color: #fff;

  @include input-font();
}

textarea {
  min-height: 80px;
  resize: vertical;
  background-color: transparent;
  &.data-edits {
    background-color: #fff;
  }
}

.textarea-placeholder {
  position: relative;
  > div {
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    padding: $input-padding;
    background-color: #fff;
    @include placeholder-style();
  }
}

::-webkit-input-placeholder {
  @include placeholder-style();
}
:-moz-placeholder {
  @include placeholder-style();
}
::-moz-placeholder {
  @include placeholder-style();
}
:-ms-input-placeholder {
  @include placeholder-style();
}

Javascript:

$("textarea").on('change keyup paste', function() {
  var length = $(this).val().length;
  if (length > 0) {
    $(this).addClass('data-edits');
  } else {
    $(this).removeClass('data-edits');
  }
});

What causes a java.lang.StackOverflowError

What is java.lang.StackOverflowError

The error java.lang.StackOverflowError is thrown to indicate that the application’s stack was exhausted, due to deep recursion i.e your program/script recurses too deeply.

Details

The StackOverflowError extends VirtualMachineError class which indicates that the JVM have been or have run out of resources and cannot operate further. The VirtualMachineError which extends the Error class is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its throw clause because these errors are abnormal conditions that was never expected to occur.

An Example

Minimal, Complete, and Verifiable Example :

package demo;

public class StackOverflowErrorExample {

    public static void main(String[] args) 
    {
        StackOverflowErrorExample.recursivePrint(1);
    }

    public static void recursivePrint(int num) {
        System.out.println("Number: " + num);

        if(num == 0)
            return;
        else
            recursivePrint(++num);
    }

}

Console Output

Number: 1
Number: 2
.
.
.
Number: 8645
Number: 8646
Number: 8647Exception in thread "main" java.lang.StackOverflowError
    at java.io.FileOutputStream.write(Unknown Source)
    at java.io.BufferedOutputStream.flushBuffer(Unknown Source)
    at java.io.BufferedOutputStream.flush(Unknown Source)
    at java.io.PrintStream.write(Unknown Source)
    at sun.nio.cs.StreamEncoder.writeBytes(Unknown Source)
    at sun.nio.cs.StreamEncoder.implFlushBuffer(Unknown Source)
    at sun.nio.cs.StreamEncoder.flushBuffer(Unknown Source)
    at java.io.OutputStreamWriter.flushBuffer(Unknown Source)
    at java.io.PrintStream.newLine(Unknown Source)
    at java.io.PrintStream.println(Unknown Source)
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:11)
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)
    .
    .
    .
    at demo.StackOverflowErrorExample.recursivePrint(StackOverflowErrorExample.java:16)

Explaination

When a function call is invoked by a Java Application, a stack frame is allocated on the call stack. The stack frame contains the parameters of the invoked method, its local parameters, and the return address of the method. The return address denotes the execution point from which, the program execution shall continue after the invoked method returns. If there is no space for a new stack frame then, the StackOverflowError is thrown by the Java Virtual Machine (JVM).

The most common case that can possibly exhaust a Java application’s stack is recursion. In recursion, a method invokes itself during its execution. Recursion one of the most powerful general-purpose programming technique, but must be used with caution, in order for the StackOverflowError to be avoided.

References

Where are shared preferences stored?

Preferences can either be set in code or can be found in res/xml/preferences.xml. You can read more about preferences on the Android SDK website.

How to create file execute mode permissions in Git on Windows?

I have no touch and chmod command in my cmd.exe and git update-index --chmod=+x foo.sh doesn't work for me.

I finally resolve it by setting skip-worktree bit:

git update-index --skip-worktree --chmod=+x foo.sh

NameError: global name 'xrange' is not defined in Python 3

I agree with the last answer.But there is another way to solve this problem.You can download the package named future,such as pip install future.And in your .py file input this "from past.builtins import xrange".This method is for the situation that there are many xranges in your file.

Deleting multiple columns based on column names in Pandas

This is probably a good way to do what you want. It will delete all columns that contain 'Unnamed' in their header.

for col in df.columns:
    if 'Unnamed' in col:
        del df[col]

How to stop and restart memcached server?

Using root, try something like this:

/etc/init.d/memcached restart

import .css file into .less file

I had to use the following with version 1.7.4

@import (less) "foo.css"

I know the accepted answer is @import (css) "foo.css" but it didn't work. If you want to reuse your css class in your new less file, you need to use (less) and not (css).

Check the documentation.

How do I prevent 'git diff' from using a pager?

If you use the oh-my-zsh, in the ~/.oh-my-zsh/lib/misc.zsh file, comment this line:

env_default 'LESS' '-R'

Command to collapse all sections of code?

if you want to collapse and expand particular loop, if else then install following plugins for visual studio.

enter image description here

Oracle JDBC intermittent Connection Issue

I was facing exactly the same problem. With Windows Vista I could not reproduce the problem but on Ubuntu I reproduced the 'connection reset'-Error constantly.

I found http://forums.oracle.com/forums/thread.jspa?threadID=941911&tstart=0&messageID=3793101

According to a user on that forum:

I opened a ticket with Oracle and this is what they told me.

java.security.SecureRandom is a standard API provided by sun. Among various methods offered by this class void nextBytes(byte[]) is one. This method is used for generating random bytes. Oracle 11g JDBC drivers use this API to generate random number during login. Users using Linux have been encountering SQLException("Io exception: Connection reset").

The problem is two fold

  1. The JVM tries to list all the files in the /tmp (or alternate tmp directory set by -Djava.io.tmpdir) when SecureRandom.nextBytes(byte[]) is invoked. If the number of files is large the method takes a long time to respond and hence cause the server to timeout

  2. The method void nextBytes(byte[]) uses /dev/random on Linux and on some machines which lack the random number generating hardware the operation slows down to the extent of bringing the whole login process to a halt. Ultimately the the user encounters SQLException("Io exception: Connection reset")

Users upgrading to 11g can encounter this issue if the underlying OS is Linux which is running on a faulty hardware.

Cause The cause of this has not yet been determined exactly. It could either be a problem in your hardware or the fact that for some reason the software cannot read from dev/random

Solution Change the setup for your application, so you add the next parameter to the java command:

-Djava.security.egd=file:/dev/../dev/urandom

We made this change in our java.security file and it has gotten rid of the error.

which solved my problem.

How can I assign an ID to a view programmatically?

You can just use the View.setId(integer) for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views you add programmatically.

According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.

Credits to this answer.

How to fix HTTP 404 on Github Pages?

I had this exact problem with typedocs. The README.md worked but none of the actual docs generated by my doc strings displayed, I just got a 404 Github Pages screen.

To fix this, just place a empty file in your /docs directory (or wherever you generate your docs) & call it .nojekyll

To confirm, your file structure should now look like:

./docs/.nojekyll  # plus all your generated docs

Push this up to your remote Github repo and your links etc should work now.

Also make sure you have selected in your Github settings:

Settings -> Github Pages -> Source -> master brach /docs folder

Depending on your doc framework, you probably have to recreate this file each time you update your docs, this is an example of using typedocs & creating the .nojekyll file each time in a package.json file:

# package.json

      "scripts": {
        "typedoc": "typedoc --out docs src && touch docs/.nojekyll"
      },

Matplotlib: Specify format of floats for tick labels

If you are directly working with matplotlib's pyplot (plt) and if you are more familiar with the new-style format string, you can try this:

from matplotlib.ticker import StrMethodFormatter
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.0f}')) # No decimal places
plt.gca().yaxis.set_major_formatter(StrMethodFormatter('{x:,.2f}')) # 2 decimal places

From the documentation:

class matplotlib.ticker.StrMethodFormatter(fmt)

Use a new-style format string (as used by str.format()) to format the tick.

The field used for the value must be labeled x and the field used for the position must be labeled pos.

Python name 'os' is not defined

Just add:

import os

in the beginning, before:

from settings import PROJECT_ROOT

This will import the python's module os, which apparently is used later in the code of your module without being imported.

How do I call a function twice or more times consecutively?

You could define a function that repeats the passed function N times.

def repeat_fun(times, f):
    for i in range(times): f()

If you want to make it even more flexible, you can even pass arguments to the function being repeated:

def repeat_fun(times, f, *args):
    for i in range(times): f(*args)

Usage:

>>> def do():
...   print 'Doing'
... 
>>> def say(s):
...   print s
... 
>>> repeat_fun(3, do)
Doing
Doing
Doing
>>> repeat_fun(4, say, 'Hello!')
Hello!
Hello!
Hello!
Hello!

Prevent any form of page refresh using jQuery/Javascript

Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.

However, a better solution is to synchronize the two sessions if possible like in google docs.

No provider for Router?

Babar Bilal's answer likely worked perfectly for earlier Angular 2 alpha/beta releases. However, anyone solving this problem with Angular release v4+ may want to try the following change to his answer instead (wrapping the single route in the required array):

RouterModule.forRoot([{ path: "", component: LoginComponent}])

How to enumerate a range of numbers starting at 1

Ok, I feel a bit stupid here... what's the reason not to just do it with something like
[(a+1,b) for (a,b) in enumerate(r)] ? If you won't function, no problem either:

>>> r = range(2000, 2005)
>>> [(a+1,b) for (a,b) in enumerate(r)]
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

>>> enumerate1 = lambda r:((a+1,b) for (a,b) in enumerate(r)) 

>>> list(enumerate1(range(2000,2005)))   # note - generator just like original enumerate()
[(1, 2000), (2, 2001), (3, 2002), (4, 2003), (5, 2004)]

Comparing arrays in C#

Providing that you have LINQ available and don't care too much about performance, the easiest thing is the following:

var arraysAreEqual = Enumerable.SequenceEqual(a1, a2);

In fact, it's probably worth checking with Reflector or ILSpy what the SequenceEqual methods actually does, since it may well optimise for the special case of array values anyway!

JQuery Number Formatting

Browser development progresses:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

 Number.toLocaleString(locale);

 // E.g.
 parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
 "1,234,567.891"

Reading tab-delimited file with Pandas - works on Windows, but not on Mac

The biggest clue is the rows are all being returned on one line. This indicates line terminators are being ignored or are not present.

You can specify the line terminator for csv_reader. If you are on a mac the lines created will end with \rrather than the linux standard \n or better still the suspenders and belt approach of windows with \r\n.

pandas.read_csv(filename, sep='\t', lineterminator='\r')

You could also open all your data using the codecs package. This may increase robustness at the expense of document loading speed.

import codecs

doc = codecs.open('document','rU','UTF-16') #open for reading with "universal" type set

df = pandas.read_csv(doc, sep='\t')

extract part of a string using bash/cut/split

What about sed? That will work in a single command:

sed 's#.*/\([^:]*\).*#\1#' <<<$string
  • The # are being used for regex dividers instead of / since the string has / in it.
  • .*/ grabs the string up to the last backslash.
  • \( .. \) marks a capture group. This is \([^:]*\).
    • The [^:] says any character _except a colon, and the * means zero or more.
  • .* means the rest of the line.
  • \1 means substitute what was found in the first (and only) capture group. This is the name.

Here's the breakdown matching the string with the regular expression:

        /var/cpanel/users/           joebloggs  :DNS9=domain.com joebloggs
sed 's#.*/                          \([^:]*\)   .*              #\1       #'

Convert UIImage to NSData and convert back to UIImage in Swift?

For safe execution of code, use if-let block with Data to prevent app crash & , as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3+ class. Use Data instead of NSData with Swift 3+

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(self)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

How can I use iptables on centos 7?

Try the following command iptables-save.

Random character generator with a range of (A..Z, 0..9) and punctuation

The easiest is to do the following:

  • Create a String alphabet with the chars that you want.
  • Say N = alphabet.length()
  • Then we can ask a java.util.Random for an int x = nextInt(N)
  • alphabet.charAt(x) is a random char from the alphabet

Here's an example:

    final String alphabet = "0123456789ABCDE";
    final int N = alphabet.length();

    Random r = new Random();

    for (int i = 0; i < 50; i++) {
        System.out.print(alphabet.charAt(r.nextInt(N)));
    }

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

How to change pivot table data source in Excel?

right click on the pivot table in excel choose wizard click 'back' click 'get data...' in the query window File - Table Definition

then you can create a new or choose a different connection

How do I cancel form submission in submit button onclick event?

function btnClick() {
    return validData();
}

IOException: Too many open files

This problem comes when you are writing data in many files simultaneously and your Operating System has a fixed limit of Open files. In Linux, you can increase the limit of open files.

https://www.tecmint.com/increase-set-open-file-limits-in-linux/

How do I change the number of open files limit in Linux?

Spring MVC + JSON = 406 Not Acceptable

I have got the similar issue and resolved by using below code

public class ProductList {

    private List<Product> productList =  new ArrayList<Product>();

    @JsonProperty("data")
    @JsonTypeInfo(use=JsonTypeInfo.Id.NAME, include=JsonTypeInfo.As.WRAPPER_OBJECT)
    public List<Product> getProductList() {
        return productList;
    }
public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

I am setting ProductList object in ResponseEntity object and returning from controller.

Can jQuery read/write cookies to a browser?

The default JavaScript "API" for setting a cookie is as easy as:

document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'

Use the jQuery cookie plugin like:

$.cookie('mycookie', 'valueOfCookie')

Git fails when pushing commit to github

in these cases you can try ssh if https is stuck.

Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000

ImportError: No module named google.protobuf

The reason for this would be mostly due to the evil command pip install google. I was facing a similar issue for google-cloud, but the same steps are true for protobuf as well. Both of our issues deal with a namespace conflict over the 'google' namespace.

If you executed the pip install google command like I did then you are in the correct place. The google package is actually not owned by Google which can be confirmed by the command pip show google which outputs:

 Name: google
 Version: 1.9.3
 Summary: Python bindings to the Google search engine.
 Home-page: http://breakingcode.wordpress.com/
 Author: Mario Vilas
 Author-email: [email protected]
 License: UNKNOWN
 Location: <Path where this package is installed>
 Requires: beautifulsoup4

Because of this package, the google namespace is reserved and coincidentally google-cloud also expects namespace google > cloud and it results in a namespace collision for these two packages.

See in below screenshot namespace of google-protobuf as google > protobuf

google-cloud namespace screenshot google > cloud > datastore

Solution :- Unofficial google package need to be uninstalled which can be done by using pip uninstall google after this you can reinstall google-cloud using pip install google-cloud or protobuf using pip install protobuf

FootNotes :- Assuming you have installed the unofficial google package by mistake and you don't actually need it along with google-cloud package. If you need both unofficial google and google-cloud above solution won't work.

Furthermore, the unofficial 'google' package installs with it 'soupsieve' and 'beautifulsoup4'. You may want to also uninstall those packages.

Let me know if this solves your particular issue.

VueJS conditionally add an attribute for an element

Try:

<input :required="test ? true : false">

what is the use of annotations @Id and @GeneratedValue(strategy = GenerationType.IDENTITY)? Why the generationtype is identity?

Simply, @Id: This annotation specifies the primary key of the entity. 

@GeneratedValue: This annotation is used to specify the primary key generation strategy to use. i.e Instructs database to generate a value for this field automatically. If the strategy is not specified by default AUTO will be used. 

GenerationType enum defines four strategies: 
1. Generation Type . TABLE, 
2. Generation Type. SEQUENCE,
3. Generation Type. IDENTITY   
4. Generation Type. AUTO

GenerationType.SEQUENCE

With this strategy, underlying persistence provider must use a database sequence to get the next unique primary key for the entities. 

GenerationType.TABLE

With this strategy, underlying persistence provider must use a database table to generate/keep the next unique primary key for the entities. 

GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.

GenerationType.AUTO
This GenerationType indicates that the persistence provider should automatically pick an appropriate strategy for the particular database. This is the default GenerationType, i.e. if we just use @GeneratedValue annotation then this value of GenerationType will be used. 

Reference:- https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/jpa-primary-key.html

ajax jquery simple get request

i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.

if you use

$.ajax({
        url: "https://app.asana.com/-/api/0.1/workspaces/",
        type: 'GET',
         error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
  }
    });

there will be your 401 code i think (this link says so)

Android- create JSON Array and JSON Object

 JSONObject obj = new JSONObject();
            try {
                obj.put("id", "3");
                obj.put("name", "NAME OF STUDENT");
                obj.put("year", "3rd");
                obj.put("curriculum", "Arts");
                obj.put("birthday", "5/5/1993");

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
             JSONArray js=new JSONArray(obj.toString());
             JSONObject obj2 = new JSONObject();
             obj2.put("student", js.toString());

How to replace all special character into a string using C#

Yes, you can use regular expressions in C#.

Using regular expressions with C#:

using System.Text.RegularExpressions;

string your_String = "Hello@Hello&Hello(Hello)";
string my_String =  Regex.Replace(your_String, @"[^0-9a-zA-Z]+", ",");

Random string generation with upper case letters and digits

From Python 3.6 on you should use the secrets module if you need it to be cryptographically secure instead of the random module (otherwise this answer is identical to the one of @Ignacio Vazquez-Abrams):

from secrets import choice
import string

''.join([choice(string.ascii_uppercase + string.digits) for _ in range(N)])

One additional note: a list-comprehension is faster in the case of str.join than using a generator expression!

Store images in a MongoDB database

You can use the bin data type if you are using any scripting language to store files/images in MongoDB. Bin data is developed to store small size of files.

Refer to your scripting language driver. For PHP, click here.

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

How to get the index of an item in a list in a single step?

That's all fine and good -- but what if you want to select an existing element as the default? In my issue there is no "--select a value--" option.

Here's my code -- you could make it into a one liner if you didn't want to check for no results I suppose...

private void LoadCombo(ComboBox cb, string itemType, string defVal = "")
{
    cb.DisplayMember = "Name";
    cb.ValueMember = "ItemCode";
    cb.DataSource = db.Items.Where(q => q.ItemTypeId == itemType).ToList();

    if (!string.IsNullOrEmpty(defVal))
    {
        var i = ((List<GCC_Pricing.Models.Item>)cb.DataSource).FindIndex(q => q.ItemCode == defVal);
        if (i>=0) cb.SelectedIndex = i;
    }
}

How to get JSON response from http.Get

You need upper case property names in your structs in order to be used by the json packages.

Upper case property names are exported properties. Lower case property names are not exported.

You also need to pass the your data object by reference (&data).

package main

import "os"
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"

type tracks struct {
    Toptracks []toptracks_info
}

type toptracks_info struct {
    Track []track_info
    Attr  []attr_info
}

type track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []streamable_info
    Artist     []artist_info
    Attr       []track_attr_info
}

type attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type streamable_info struct {
    Text      string
    Fulltrack string
}

type artist_info struct {
    Name string
    Mbid string
    Url  string
}

type track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"

    res, err := http.Get(url)

    if err != nil {
        panic(err.Error())
    }

    body, err := ioutil.ReadAll(res.Body)

    if err != nil {
        panic(err.Error())
    }

    var data tracks
    json.Unmarshal(body, &data)
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

How to echo (or print) to the js console with php

For something simple that work for arrays , strings , and objects I builed this function:

function console_testing($var){

    $var = json_encode($var,JSON_UNESCAPED_UNICODE);

    $output = <<<EOT
    <script>
        console.log($var); 
    </script>
EOT;

    echo $output;

}

How do I restrict a float value to only two places after the decimal point in C?

Also, if you're using C++, you can just create a function like this:

string prd(const double x, const int decDigits) {
    stringstream ss;
    ss << fixed;
    ss.precision(decDigits); // set # places after decimal
    ss << x;
    return ss.str();
}

You can then output any double myDouble with n places after the decimal point with code such as this:

std::cout << prd(myDouble,n);

Change the location of the ~ directory in a Windows install of Git Bash

So, $HOME is what I need to modify. However I have been unable to find where this mythical $HOME variable is set so I assumed it was a Linux system version of PATH or something. Anyway...**

Answer

Adding HOME at the top of the profile file worked.

HOME="c://path/to/custom/root/".

  #THE FIX WAS ADDING THE FOLLOWING LINE TO THE TOP OF THE PROFILE FILE

  HOME="c://path/to/custom/root/"

  # below are the original contents ===========
  # To the extent possible under law, ..blah blah

  # Some resources...
  # Customizing Your Shell: http://www.dsl.org/cookbook/cookbook_5.html#SEC69
  # Consistent BackSpace and Delete Configuration:
  #   http://www.ibb.net/~anne/keyboard.html
  # The Linux Documentation Project: http://www.tldp.org/
  # The Linux Cookbook: http://www.tldp.org/LDP/linuxcookbook/html/
  # Greg's Wiki http://mywiki.wooledge.org/

  # Setup some default paths. Note that this order will allow user installed
  # software to override 'system' software.
  # Modifying these default path settings can be done in different ways.
  # To learn more about startup files, refer to your shell's man page.

  MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
  MANPATH="/usr/local/man:/usr/share/man:/usr/man:/share/man:${MANPATH}"
  INFOPATH="/usr/local/info:/usr/share/info:/usr/info:/share/info:${INFOPATH}"
  MINGW_MOUNT_POINT=
  if [ -n "$MSYSTEM" ]
  then
    case "$MSYSTEM" in
      MINGW32)
        MINGW_MOUNT_POINT=/mingw32
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MINGW64)
        MINGW_MOUNT_POINT=/mingw64
        PATH="${MINGW_MOUNT_POINT}/bin:${MSYS2_PATH}:${PATH}"
        PKG_CONFIG_PATH="${MINGW_MOUNT_POINT}/lib/pkgconfig:${MINGW_MOUNT_POINT}/share/pkgconfig"
        ACLOCAL_PATH="${MINGW_MOUNT_POINT}/share/aclocal:/usr/share/aclocal"
        MANPATH="${MINGW_MOUNT_POINT}/share/man:${MANPATH}"
      ;;
      MSYS)
        PATH="${MSYS2_PATH}:/opt/bin:${PATH}"
        PKG_CONFIG_PATH="/usr/lib/pkgconfig:/usr/share/pkgconfig:/lib/pkgconfig"
      ;;
      *)
        PATH="${MSYS2_PATH}:${PATH}"
      ;;
    esac
  else
    PATH="${MSYS2_PATH}:${PATH}"
  fi

  MAYBE_FIRST_START=false
  SYSCONFDIR="${SYSCONFDIR:=/etc}"

  # TMP and TEMP as defined in the Windows environment must be kept
  # for windows apps, even if started from msys2. However, leaving
  # them set to the default Windows temporary directory or unset
  # can have unexpected consequences for msys2 apps, so we define
  # our own to match GNU/Linux behaviour.
  ORIGINAL_TMP=$TMP
  ORIGINAL_TEMP=$TEMP
  #unset TMP TEMP
  #tmp=$(cygpath -w "$ORIGINAL_TMP" 2> /dev/null)
  #temp=$(cygpath -w "$ORIGINAL_TEMP" 2> /dev/null)
  #TMP="/tmp"
  #TEMP="/tmp"
  case "$TMP" in *\\*) TMP="$(cygpath -m "$TMP")";; esac
  case "$TEMP" in *\\*) TEMP="$(cygpath -m "$TEMP")";; esac
  test -d "$TMPDIR" || test ! -d "$TMP" || {
    TMPDIR="$TMP"
    export TMPDIR
  }


  # Define default printer
  p='/proc/registry/HKEY_CURRENT_USER/Software/Microsoft/Windows NT/CurrentVersion/Windows/Device'
  if [ -e "${p}" ] ; then
    read -r PRINTER < "${p}"
    PRINTER=${PRINTER%%,*}
  fi
  unset p

  print_flags ()
  {
    (( $1 & 0x0002 )) && echo -n "binary" || echo -n "text"
    (( $1 & 0x0010 )) && echo -n ",exec"
    (( $1 & 0x0040 )) && echo -n ",cygexec"
    (( $1 & 0x0100 )) && echo -n ",notexec"
  }

  # Shell dependent settings
  profile_d ()
  {
    local file=
    for file in $(export LC_COLLATE=C; echo /etc/profile.d/*.$1); do
      [ -e "${file}" ] && . "${file}"
    done

    if [ -n ${MINGW_MOUNT_POINT} ]; then
      for file in $(export LC_COLLATE=C; echo ${MINGW_MOUNT_POINT}/etc/profile.d/*.$1); do
        [ -e "${file}" ] && . "${file}"
      done
    fi
  }

  for postinst in $(export LC_COLLATE=C; echo /etc/post-install/*.post); do
    [ -e "${postinst}" ] && . "${postinst}"
  done

  if [ ! "x${BASH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    [ -f "/etc/bash.bashrc" ] && . "/etc/bash.bashrc"
  elif [ ! "x${KSH_VERSION}" = "x" ]; then
    typeset -l HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1=$(print '\033]0;${PWD}\n\033[32m${USER}@${HOSTNAME} \033[33m${PWD/${HOME}/~}\033[0m\n$ ')
  elif [ ! "x${ZSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d zsh
    PS1='(%n@%m)[%h] %~ %% '
  elif [ ! "x${POSH_VERSION}" = "x" ]; then
    HOSTNAME="$(/usr/bin/hostname)"
    PS1="$ "
  else
    HOSTNAME="$(/usr/bin/hostname)"
    profile_d sh
    PS1="$ "
  fi

  if [ -n "$ACLOCAL_PATH" ]
  then
    export ACLOCAL_PATH
  fi

  export PATH MANPATH INFOPATH PKG_CONFIG_PATH USER TMP TEMP PRINTER HOSTNAME PS1 SHELL tmp temp
  test -n "$TERM" || export TERM=xterm-256color

  if [ "$MAYBE_FIRST_START" = "true" ]; then
    sh /usr/bin/regen-info.sh

    if [ -f "/usr/bin/update-ca-trust" ]
    then
      sh /usr/bin/update-ca-trust
    fi

    clear
    echo
    echo
    echo "###################################################################"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "#                   C   A   U   T   I   O   N                     #"
    echo "#                                                                 #"
    echo "#                  This is first start of MSYS2.                  #"
    echo "#       You MUST restart shell to apply necessary actions.        #"
    echo "#                                                                 #"
    echo "#                                                                 #"
    echo "###################################################################"
    echo
    echo
  fi
  unset MAYBE_FIRST_START

Difference between using "chmod a+x" and "chmod 755"

chmod a+x modifies the argument's mode while chmod 755 sets it. Try both variants on something that has full or no permissions and you will notice the difference.

Is it possible to run CUDA on AMD GPUs?

You can't use CUDA for GPU Programming as CUDA is supported by NVIDIA devices only. If you want to learn GPU Computing I would suggest you to start CUDA and OpenCL simultaneously. That would be very much beneficial for you.. Talking about CUDA, you can use mCUDA. It doesn't require NVIDIA's GPU..

How do I resolve a path relative to an ASP.NET MVC 4 application root?

In your controller use:

var path = HttpContext.Server.MapPath("~/Data/data.html");

This allows you to test the controller with Moq like so:

var queryString = new NameValueCollection();
var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(r => r.QueryString).Returns(queryString);
var mockHttpContext = new Mock<HttpContextBase>();
mockHttpContext.Setup(c => c.Request).Returns(mockRequest.Object);
var server = new Mock<HttpServerUtilityBase>();
server.Setup(m => m.MapPath("~/Data/data.html")).Returns("path/to/test/data");
mockHttpContext.Setup(m => m.Server).Returns(server.Object);
var mockControllerContext = new Mock<ControllerContext>();
mockControllerContext.Setup(c => c.HttpContext).Returns(mockHttpContext.Object);
var controller = new MyTestController();
controller.ControllerContext = mockControllerContext.Object;

Using gradle to find dependency tree

For me, it was simply one command

in build.gradle add plugin

apply plugin: 'project-report'

and then go to cmd and run following command

./gradlew htmlDependencyReport

This gives me an HTML report WOW Html report


Or if you want the report in a text file, to make search easy use following command

gradlew dependencyReport

enter image description here

That's all my lord.

could not extract ResultSet in hibernate

The @JoinColumn annotation specifies the name of the column being used as the foreign key on the targeted entity.

On the Product class above, the name of the join column is set to ID_CATALOG.

@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;

However, the foreign key on the Product table is called catalog_id

`catalog_id` int(11) DEFAULT NULL,

You'll need to change either the column name on the table or the name you're using in the @JoinColumn so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

How to perform a fade animation on Activity transition?

You could create your own .xml animation files to fade in a new Activity and fade out the current Activity:

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="0.0" android:toAlpha="1.0"
           android:duration="500" />

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="1.0" android:toAlpha="0.0"
           android:fillAfter="true"
           android:duration="500" />

Use it in code like that: (Inside your Activity)

Intent i = new Intent(this, NewlyStartedActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

The above code will fade out the currently active Activity and fade in the newly started Activity resulting in a smooth transition.

UPDATE: @Dan J pointed out that using the built in Android animations improves performance, which I indeed found to be the case after doing some testing. If you prefer working with the built in animations, use:

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

Notice me referencing android.R instead of R to access the resource id.

UPDATE: It is now common practice to perform transitions using the Transition class introduced in API level 19.

Best way to convert text files between character sets?

Stand-alone utility approach

iconv -f ISO-8859-1 -t UTF-8 in.txt > out.txt
-f ENCODING  the encoding of the input
-t ENCODING  the encoding of the output

You don't have to specify either of these arguments. They will default to your current locale, which is usually UTF-8.

How to free memory from char array in C

char arr[3] = "bo";

The arr takes the memory into the stack segment. which will be automatically free, if arr goes out of scope.

How Best to Compare Two Collections in Java and Act on Them?

I have created an approximation of what I think you are looking for just using the Collections Framework in Java. Frankly, I think it is probably overkill as @Mike Deck points out. For such a small set of items to compare and process I think arrays would be a better choice from a procedural standpoint but here is my pseudo-coded (because I'm lazy) solution. I have an assumption that the Foo class is comparable based on it's unique id and not all of the data in it's contents:

Collection<Foo> oldSet = ...;
Collection<Foo> newSet = ...;

private Collection difference(Collection a, Collection b) {
    Collection result = a.clone();
    result.removeAll(b)
    return result;
}

private Collection intersection(Collection a, Collection b) {
    Collection result = a.clone();
    result.retainAll(b)
    return result;
}

public doWork() {
    // if foo is in(*) oldSet but not newSet, call doRemove(foo)
    Collection removed = difference(oldSet, newSet);
    if (!removed.isEmpty()) {
        loop removed {
            Foo foo = removedIter.next();
            doRemove(foo);
        }
    }
    //else if foo is not in oldSet but in newSet, call doAdd(foo)
    Collection added = difference(newSet, oldSet);
    if (!added.isEmpty()) {
        loop added  {
            Foo foo = addedIter.next();
            doAdd(foo);
        }
    }

    // else if foo is in both collections but modified, call doUpdate(oldFoo, newFoo)
    Collection matched = intersection(oldSet, newSet);
    Comparator comp = new Comparator() {
        int compare(Object o1, Object o2) {
            Foo f1, f2;
            if (o1 instanceof Foo) f1 = (Foo)o1;
            if (o2 instanceof Foo) f2 = (Foo)o2;
            return f1.activated == f2.activated ? f1.startdate.compareTo(f2.startdate) == 0 ? ... : f1.startdate.compareTo(f2.startdate) : f1.activated ? 1 : 0;
        }

        boolean equals(Object o) {
             // equal to this Comparator..not used
        }
    }
    loop matched {
        Foo foo = matchedIter.next();
        Foo oldFoo = oldSet.get(foo);
        Foo newFoo = newSet.get(foo);
        if (comp.compareTo(oldFoo, newFoo ) != 0) {
            doUpdate(oldFoo, newFoo);
        } else {
            //else if !foo.activated && foo.startDate >= now, call doStart(foo)
            if (!foo.activated && foo.startDate >= now) doStart(foo);

            // else if foo.activated && foo.endDate <= now, call doEnd(foo)
            if (foo.activated && foo.endDate <= now) doEnd(foo);
        }
    }
}

As far as your questions: If I convert oldSet and newSet into HashMap (order is not of concern here), with the IDs as keys, would it made the code easier to read and easier to compare? How much of time & memory performance is loss on the conversion? I think that you would probably make the code more readable by using a Map BUT...you would probably use more memory and time during the conversion.

Would iterating the two sets and perform the appropriate operation be more efficient and concise? Yes, this would be the best of both worlds especially if you followed @Mike Sharek 's advice of Rolling your own List with the specialized methods or following something like the Visitor Design pattern to run through your collection and process each item.

Open Jquery modal dialog on click event

May be helpful... :)

$(document).ready(function() {
    $('#buutonId').on('click', function() {
        $('#modalId').modal('open');
    });
});

How to randomly select rows in SQL?

SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()

That said, everybody seems to come to this page for the more general answer to your question:

Selecting a random row in SQL

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX 
FROM table 
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Select a random row with sqlite:

SELECT column FROM table 
ORDER BY RANDOM() LIMIT 1

Original purpose of <input type="hidden">?

In short, the original purpose was to make a field which will be submitted with form's submit. Sometimes, there were need to store some information in hidden field(for example, id of user) and submit it with form's submit.

From HTML September 22, 1995 specification

An INPUT element with `TYPE=HIDDEN' represents a hidden field.The user does not interact with this field; instead, the VALUE attribute specifies the value of the field. The NAME and VALUE attributes are required.

Change the Textbox height?

for me, the best approach is remove border of the textbox, and place it inside a Panel, which can be customized as you like.

What is the easiest way to parse an INI file in Java?

You could try JINIFile. Is a translation of the TIniFile from Delphi, but for java

https://github.com/SubZane/JIniFile

What's an easy way to read random line from a file in Unix command line?

Single bash line:

sed -n $((1+$RANDOM%`wc -l test.txt | cut -f 1 -d ' '`))p test.txt

Slight problem: duplicate filename.

How to keep indent for second line in ordered lists via CSS?

Update

This answer is outdated. You can do this a lot more simply, as pointed out in another answer below:

ul {
  list-style-position: outside;
}

See https://www.w3schools.com/cssref/pr_list-style-position.asp

Original Answer

I'm surprised to see this hasn't been solved yet. You can make use of the browser's table layout algorithm (without using tables) like this:

ol {
    counter-reset: foo;
    display: table;
}

ol > li {
    counter-increment: foo;
    display: table-row;
}

ol > li::before {
    content: counter(foo) ".";
    display: table-cell; /* aha! */
    text-align: right;
}

Demo: http://jsfiddle.net/4rnNK/1/

enter image description here

To make it work in IE8, use the legacy :before notation with one colon.

What does MissingManifestResourceException mean and how to fix it?

In my case it was a typo in the Xaml of a window opened from Winforms Form:

Incorrect: <Image Source="/Resources/WorkGreen.gif"/>

Correct: <Image Source="../Resources/WorkGreen.gif"/> It may help someone

Java Project: Failed to load ApplicationContext

I've faced this issue because during bootstrapping my spring project using the class that implements ApplicationListener<ContextRefreshedEvent> and inside onApplicationEvent function it throws an exception

so make sure that your application bootstrap points do not throw any exception

in my case, I was using maven surefire plugin for testing so to debug the test process use this command

mvn -Dmaven.surefire.debug test

sql how to cast a select query

I interpreted the question as using cast on a subquery. Yes, you can do that:

select cast((<subquery>) as <newtype>)

If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:

select (select cast(<val> as <newtype>) . . .)

Convert array to JSON string in swift

SWIFT 2.0

var tempJson : NSString = ""
do {
    let arrJson = try NSJSONSerialization.dataWithJSONObject(arrInvitationList, options: NSJSONWritingOptions.PrettyPrinted)
    let string = NSString(data: arrJson, encoding: NSUTF8StringEncoding)
    tempJson = string! as NSString
}catch let error as NSError{
    print(error.description)
}

NOTE:- use tempJson variable when you want to use.

Using Custom Domains With IIS Express

When using Visual Studio 2012 with IIS Express, changing an existing binding does not work permanently. (It may work until you close VS, but after that, things get really messed up.)

The key is keeping the existing localhost binding and adding a new binding after it.

Unless you're running as administrator, you'll also need to run netsh add urlacl (to give yourself permissions to run a non-localhost site as a standard user).

If you want to allow any host name, the full process is as follows:

  1. Create your web application, and find out what port it is using (see project properties, Web tab, Project Url).
  2. From an administrator prompt, run the following commands (replacing portnumber with the port number you figured out in #1):

    netsh http add urlacl url="http://*:portnumber/" user=everyone
    netsh http add urlacl url="http://localhost:portnumber/" user=everyone
    

You can also use your user name (DOMAIN\USER) instead of everyone for better security.

  1. Open applicationhost.config (usually under My Documents\IIS Express\config), and find the element with your port number.
  2. Add one more binding with the host name you want (in this case, *). For example:

    <site name="MvcApplication1" id="2">
        <application path="/" applicationPool="Clr4IntegratedAppPool">
            <virtualDirectory path="/" physicalPath="C:\sites\MvcApplication1" />
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:12853:localhost" />
            <binding protocol="http" bindingInformation="*:12853:*" />
        </bindings>
    </site>
    

Note that, if want to open up all host names (*), you'll need two netsh commands (one for * and one for localhost). If you only want to open up a specific host name, you don't strictly need the second netsh command (localhost); just the one with your specific host name is sufficient.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

I was using the $('div').attr('style', ''); technique and it wasn't working in IE8.

I outputted the style attribute using alert() and it was not stripping out inline styles.

.removeAttr ended up doing the trick in IE8.