Programs & Examples On #Sinclair

Sinclair Research was a British electronics company which produced the popular ZX80, ZX81, and ZX Spectrum microcomputers before being acquired by Amstrad in 1986.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

Found this:

The google-services.json file is generally placed in the app/ directory, but as of version 2.0.0-alpha3 of the plugin support was added for build types, which would make the following directory structure valid:

app/src/
    main/google-services.json
    dogfood/google-services.json
    mytype1/google-services.json
    ...

Source

Source 2

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

ROWS UNBOUNDED PRECEDING is no Teradata-specific syntax, it's Standard SQL. Together with the ORDER BY it defines the window on which the result is calculated.

Logically a Windowed Aggregate Function is newly calculated for each row within the PARTITION based on all ROWS between a starting row and an ending row.

Starting and ending rows might be fixed or relative to the current row based on the following keywords:

  • CURRENT ROW, the current row
  • UNBOUNDED PRECEDING, all rows before the current row -> fixed
  • UNBOUNDED FOLLOWING, all rows after the current row -> fixed
  • x PRECEDING, x rows before the current row -> relative
  • y FOLLOWING, y rows after the current row -> relative

Possible kinds of calculation include:

  • Both starting and ending row are fixed, the window consists of all rows of a partition, e.g. a Group Sum, i.e. aggregate plus detail rows
  • One end is fixed, the other relative to current row, the number of rows increases or decreases, e.g. a Running Total, Remaining Sum
  • Starting and ending row are relative to current row, the number of rows within a window is fixed, e.g. a Moving Average over n rows

So SUM(x) OVER (ORDER BY col ROWS UNBOUNDED PRECEDING) results in a Cumulative Sum or Running Total

11 -> 11
 2 -> 11 +  2                = 13
 3 -> 13 +  3 (or 11+2+3)    = 16
44 -> 16 + 44 (or 11+2+3+44) = 60

jQuery not working with IE 11

Thanks @Arnaud & @Conny for highlighting this answer. This really helped me. I would like to add one more thing here is, adding this line <meta http-equiv="x-ua-compatible" content="IE=edge"> just after the title in tag prior to all meta tags is must for to work as it overrides the compatibility mode of IE.

How can I maintain fragment state when added to the back stack?

Public void replaceFragment(Fragment mFragment, int id, String tag, boolean addToStack) {
        FragmentTransaction mTransaction = getSupportFragmentManager().beginTransaction();
        mTransaction.replace(id, mFragment);
        hideKeyboard();
        if (addToStack) {
            mTransaction.addToBackStack(tag);
        }
        mTransaction.commitAllowingStateLoss();
    }
replaceFragment(new Splash_Fragment(), R.id.container, null, false);

Create database from command line

PostgreSQL Create Database - Steps to create database in Postgres.

  1. Login to server using postgres user.
    su - postgres
  2. Connect to postgresql database.
bash-4.1$ psql
psql (12.1)
Type "help" for help.
postgres=#
  1. Execute below command to create database.
CREATE DATABASE database_name;

Check for detailed information below: https://orahow.com/postgresql-create-database/

How to center links in HTML

p is not how you put text in a. That is the problem. The only solution is to put the text between <a> and </a>. For example:

<a href="https://stackoverflow.com/posts/64201994/edit" style="text-align:center;">Stack Overflow</a>

Find specific string in a text file with VBS script

Try to change like this ..

firstStr = "<?xml version" 'my file always starts like this

Do until objInputFile.AtEndOfStream  

    strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/DD/Beginning_of_DD_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_DD_TC" & CStr(index) & "</a></td></tr>"  

   substrToFind = "<tr><td><a href=" & chr(34) & "../Test case " & trim(cstr((index)))

   tmpStr = objInputFile.ReadLine

   If InStr(tmpStr, substrToFind) <= 0 Then
       If Instr(tmpStr, firstStr) > 0 Then
          text = tmpStr 'to avoid the first empty line
       Else
          text = text & vbCrLf & tmpStr
       End If
   Else
      text = text & vbCrLf & strToAdd & vbCrLf & tmpStr

   End If
   index = index + 1
Loop

Sort a list of numerical strings in ascending order

The recommended approach in this case is to sort the data in the database, adding an ORDER BY at the end of the query that fetches the results, something like this:

SELECT temperature FROM temperatures ORDER BY temperature ASC;  -- ascending order
SELECT temperature FROM temperatures ORDER BY temperature DESC; -- descending order

If for some reason that is not an option, you can change the sorting order like this in Python:

templist = [25, 50, 100, 150, 200, 250, 300, 33]
sorted(templist, key=int)               # ascending order
> [25, 33, 50, 100, 150, 200, 250, 300]
sorted(templist, key=int, reverse=True) # descending order
> [300, 250, 200, 150, 100, 50, 33, 25]

As has been pointed in the comments, the int key (or float if values with decimals are being stored) is required for correctly sorting the data if the data received is of type string, but it'd be very strange to store temperature values as strings, if that is the case, go back and fix the problem at the root, and make sure that the temperatures being stored are numbers.

Laravel assets url

Besides put all your assets in the public folder, you can use the HTML::image() Method, and only needs an argument which is the path to the image, relative on the public folder, as well:

{{ HTML::image('imgs/picture.jpg') }}

Which generates the follow HTML code:

<img src="http://localhost:8000/imgs/picture.jpg">

The link to other elements of HTML::image() Method: http://laravel-recipes.com/recipes/185/generating-an-html-image-element

JavaScript open in a new window, not tab

You don't need to use height, just make sure you use _blank, Without it, it opens in a new tab.

For a empty window:

window.open('', '_blank', 'toolbar=0,location=0,menubar=0');

For a specific URL:

window.open('http://www.google.com', '_blank', 'toolbar=0,location=0,menubar=0');

How to replace item in array?

If using a complex object (or even a simple one) and you can use es6, Array.prototype.findIndex is a good one. For the OP's array, they could do,

const index = items.findIndex(x => x === 3452)
items[index] = 1010

For more complex objects, this really shines. For example,

const index = 
    items.findIndex(
       x => x.jerseyNumber === 9 && x.school === 'Ohio State'
    )

items[index].lastName = 'Utah'
items[index].firstName = 'Johnny'

Get user input from textarea

Here is full component example

import { Component } from '@angular/core';

@Component({
  selector: 'app-text-box',
  template: `
        <h1>Text ({{textValue}})</h1>
        <input #textbox type="text" [(ngModel)]="textValue" required>
        <button (click)="logText(textbox.value)">Update Log</button>
        <button (click)="textValue=''">Clear</button>

        <h2>Template Reference Variable</h2>
        Type: '{{textbox.type}}', required: '{{textbox.hasAttribute('required')}}',
        upper: '{{textbox.value.toUpperCase()}}'

        <h2>Log <button (click)="log=''">Clear</button></h2>
        <pre>{{log}}</pre>`
})
export class TextComponent {

  textValue = 'initial value';
  log = '';

  logText(value: string): void {
    this.log += `Text changed to '${value}'\n`;
  }
}

How to store token in Local or Session Storage in Angular 2?

Here is the best practice: https://github.com/PillowPillow/ng2-webstorage

I was use it in AngularJs, now with Angular2. Wery usefull.

Fastest way to update 120 Million records

If the table has an index which you can iterate over I would put update top(10000) statement in a while loop moving over the data. That would keep the transaction log slim and won't have such a huge impact on the disk system. Also, I would recommend to play with maxdop option (setting it closer to 1).

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

There's an ELSE in the DOS batch language? Back in the days when I did more of this kinda thing, there wasn't.

If my theory is correct and your ELSE is being ignored, you may be better off doing

IF NOT EXIST file GOTO label

...which will also save you a line of code (the one right after your IF).

Second, I vaguely remember some kind of bug with testing for the existence of directories. Life would be easier if you could test for the existence of a file in that directory. If there's no file you can be sure of, something to try (this used to work up to Win95, IIRC) would be to append the device file name NUL to your directory name, e.g.

IF NOT EXIST C:\dir\NUL GOTO ...

Standard way to embed version into python package?

For what it's worth, if you're using NumPy distutils, numpy.distutils.misc_util.Configuration has a make_svn_version_py() method that embeds the revision number inside package.__svn_version__ in the variable version .

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

I was struggling with this recently, and found the right way to create a default task that runs sass then sass:watch was:

gulp.task('default', gulp.series('sass', 'sass:watch'));

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

Entity Framework Provider type could not be loaded?

Additional to all useful suggestions here, if you are using EF 6.1.3, get sure your project's .net version is 4.5 or more.

How to programmatically send SMS on the iPhone?

You need to use the MFMessageComposeViewController if you want to show creating and sending the message in your own app.

Otherwise, you can use the sharedApplication method.

Partial Dependency (Databases)

A FD (functional dependency) that holds in a relation is partial when removing one of the determining attributes gives a FD that holds in the relation. A FD that isn't partial is full.

Eg: If {A,B} ? {C} but also {A} ? {C} then {C} is partially functionally dependent on {A,B}.

Eg: Here's a relation value where that example condition holds. (A FD holds in a relation variable when it holds in every value that can arise.)

A  B  C
1  1  1
1  2  1
2  1  1

The non-trivial FDs that hold: {A,B} determines {C}, {B,C}, {A,C} & {A,B,C}; {A}, {B} & {} also determine {C}. Of those: {A,B} ? {C} is partial per {A} ? {C}, {B} ? {C} & {} ? {C}; {A} ? {C} & {B} ? {C} are partial per {} ? {C}; the others are full.

A functional dependency X ? Y is a full functional dependency if removal of any attribute A from X means that the dependency does not hold any more; that is, for any attribute A e X, (X – {A}) does not functionally determine Y. A functional dependency X ? Y is a partial dependency if some attribute A e X can be removed from X and the dependency still holds; that is, for some A e X, (X – {A}) ? Y.

-- FUNDAMENTALS OF Database Systems SIXTH EDITION Ramez Elmasri & Navathe

Notice that whether a FD is full vs partial doesn't depend on CKs (candidate keys), let alone one CK that you might be calling the PK (primary key).

(A definition of 2NF is that every non-CK attribute is fully functionally determined by every CK. Observe that the only CK is {A,B} & the only non-CK attribute C is partially dependent on it so this value is not in 2NF & indeed it is the lossless join of components/projections onto {A,B} & {A,C}, onto {A,B} & {B,C} & onto {A,B} & {C}.)

(Beware that that textbook's definition of "transitive FD" does not define the same sort of thing as the standard definition of "transitive FD".)

git - Your branch is ahead of 'origin/master' by 1 commit

I resolved this by just running a simple:

git pull

Nothing more. Now it's showing:

# On branch master
nothing to commit, working directory clean

How to filter array in subdocument with MongoDB

Above solution works best if multiple matching sub documents are required. $elemMatch also comes in very use if single matching sub document is required as output

db.test.find({list: {$elemMatch: {a: 1}}}, {'list.$': 1})

Result:

{
  "_id": ObjectId("..."),
  "list": [{a: 1}]
}

Skip over a value in the range function in python

for i in range(100):
    if i == 50:
        continue
    dosomething

How to get first object out from List<Object> using Linq

Try:

var firstElement = lstComp.First();

You can also use FirstOrDefault() just in case lstComp does not contain any items.

http://msdn.microsoft.com/en-gb/library/bb340482(v=vs.100).aspx

Edit:

To get the Component Value:

var firstElement = lstComp.First().ComponentValue("Dep");

This would assume there is an element in lstComp. An alternative and safer way would be...

var firstOrDefault = lstComp.FirstOrDefault();
if (firstOrDefault != null) 
{
    var firstComponentValue = firstOrDefault.ComponentValue("Dep");
}

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

How can a query multiply 2 cell for each row MySQL?

You can do it with:

UPDATE mytable SET Total = Pieces * Price;

Timestamp Difference In Hours for PostgreSQL

You can use the "extract" or "date_part" functions on intervals as well as timestamps, but I don't think that does what you want. For example, it gives 3 for an interval of '2 days, 3 hours'. However, you can convert an interval to a number of seconds by specifying 'epoch' as the time element you want: extract(epoch from '2 days, 3 hours'::interval) returns 183600 (which you then divide by 3600 to convert seconds to hours).

So, putting this all together, you get basically Michael's answer: extract(epoch from timestamp1 - timestamp2)/3600. Since you don't seem to care about which timestamp precedes which, you probably want to wrap that in abs:

SELECT abs(extract(epoch from timestamp1 - timestamp2)/3600)

How to set headers in http get request?

Go's net/http package has many functions that deal with headers. Among them are Add, Del, Get and Set methods. The way to use Set is:

func yourHandler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("header_name", "header_value")
}

Can not get a simple bootstrap modal to work

Try skipping the p tag or replace it with a h3 tag or similar. Replace:

<p>One fine body…</p>

with

<h3>One fine body…</h3>

It worked for me, I don't know why, but it seems the p tag is somehow not fully compatible with some versions of Bootstrap.

Windows batch script launch program and exit console

%ComSpec% /c %systemroot%\notepad.exe

jQuery Toggle Text?

Modifying my answer from your other question, I would do this:

$(function() {
 $("#show-background").click(function () {
  var c = $("#content-area");
  var o = (c.css('opacity') == 0) ? 1 : 0;
  var t = (o==1) ? 'Show Background' : 'Show Text';
  c.animate({opacity: o}, 'slow');
  $(this).text(t);
 });
});

How to maintain a Unique List in Java?

You can use a Set implementation:

Some info from the JAVADoc:

A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.

Note: Great care must be exercised if mutable objects are used as set elements. The behavior of a set is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is an element in the set. A special case of this prohibition is that it is not permissible for a set to contain itself as an element.`

These are the implementations:

  • HashSet

    This class offers constant time performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

    When iterating a HashSet the order of the yielded elements is undefined.

  • LinkedHashSet

    Hash table and linked list implementation of the Set interface, with predictable iteration order. This implementation differs from HashSet in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is the order in which elements were inserted into the set (insertion-order). Note that insertion order is not affected if an element is re-inserted into the set. (An element e is reinserted into a set s if s.add(e) is invoked when s.contains(e) would return true immediately prior to the invocation.)

    So, the output of the code above...

     Set<Integer> linkedHashSet = new LinkedHashSet<>();
     linkedHashSet.add(3);
     linkedHashSet.add(1);
     linkedHashSet.add(2);
    
     for (int i : linkedHashSet) {
         System.out.println(i);
     }
    

    ...will necessarily be

    3
    1
    2
    
  • TreeSet

    This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains). By default he elements returned on iteration are sorted by their "natural ordering", so the code above...

     Set<Integer> treeSet = new TreeSet<>();
     treeSet.add(3);
     treeSet.add(1);
     treeSet.add(2);
    
     for (int i : treeSet) {
         System.out.println(i);
     }
    

    ...will output this:

    1
    2
    3
    

    (You can also pass a Comparator instance to a TreeSet constructor, making it sort the elements in a different order.)

    Note that the ordering maintained by a set (whether or not an explicit comparator is provided) must be consistent with equals if it is to correctly implement the Set interface. (See Comparable or Comparator for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a TreeSet instance performs all element comparisons using its compareTo (or compare) method, so two elements that are deemed equal by this method are, from the standpoint of the set, equal. The behavior of a set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

Display string multiple times

The accepted answer is short and sweet, but here is an alternate syntax allowing to provide a separator in Python 3.x.

print(*3*('-',), sep='_')

Is there a 'box-shadow-color' property?

Actually… there is! Sort of. box-shadow defaults to color, just like border does.

According to http://dev.w3.org/.../#the-box-shadow

The color is the color of the shadow. If the color is absent, the used color is taken from the ‘color’ property.

In practice, you have to change the color property and leave box-shadow without a color:

box-shadow: 1px 2px 3px;
color: #a00;

Support

  • Safari 6+
  • Chrome 20+ (at least)
  • Firefox 13+ (at least)
  • IE9+ (IE8 doesn't support box-shadow at all)

Demo

_x000D_
_x000D_
div {_x000D_
    box-shadow: 0 0 50px;_x000D_
    transition: 0.3s color;_x000D_
}_x000D_
.green {_x000D_
    color: green;_x000D_
}_x000D_
.red {_x000D_
    color: red;_x000D_
}_x000D_
div:hover {_x000D_
    color: yellow;_x000D_
}_x000D_
_x000D_
/*demo style*/_x000D_
body {_x000D_
    text-align: center;_x000D_
}_x000D_
div {_x000D_
    display: inline-block;_x000D_
    background: white;_x000D_
    height: 100px;_x000D_
    width: 100px;_x000D_
    margin: 30px;_x000D_
    border-radius: 50%;_x000D_
}
_x000D_
<div class="green"></div>_x000D_
<div class="red"></div>
_x000D_
_x000D_
_x000D_

The bug mentioned in the comment below has since been fixed :)

Get custom product attributes in Woocommerce

woocommerce_get_product_terms() is now deprecated.

Use wc_get_product_terms() instead.

Example:

global $product;
$koostis = array_shift( wc_get_product_terms( $product->id, 'pa_koostis', array( 'fields' => 'names' ) ) );

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I have try with the SCFRench and with the Ru Hasha on octave.

And finally it works: but I have done some modification

function message = makefuns
    assignin('base','fun1', @fun1);   % Ru Hasha
    assignin('base', 'fun2', @fun2);  % Ru Hasha
    message.fun1=@fun1;               % SCFrench
    message.fun2=@fun2;               % SCFrench
end

function y=fun1(x)
    y=x;
end

function z=fun2
    z=1;
end

Can be called in other 'm' file:

printf("%d\n", makefuns.fun1(123));
printf("%d\n", makefuns.fun2());

update:

I added an answer because neither the +72 nor the +20 worked in octave for me. The one I wrote works perfectly (and I tested it last Friday when I later wrote the post).

How to get multiple counts with one SQL query?

Building on other posted answers.

Both of these will produce the right values:

select distributor_id,
    count(*) total,
    sum(case when level = 'exec' then 1 else 0 end) ExecCount,
    sum(case when level = 'personal' then 1 else 0 end) PersonalCount
from yourtable
group by distributor_id

SELECT a.distributor_id,
          (SELECT COUNT(*) FROM myTable WHERE level='personal' and distributor_id = a.distributor_id) as PersonalCount,
          (SELECT COUNT(*) FROM myTable WHERE level='exec' and distributor_id = a.distributor_id) as ExecCount,
          (SELECT COUNT(*) FROM myTable WHERE distributor_id = a.distributor_id) as TotalCount
       FROM myTable a ; 

However, the performance is quite different, which will obviously be more relevant as the quantity of data grows.

I found that, assuming no indexes were defined on the table, the query using the SUMs would do a single table scan, while the query with the COUNTs would do multiple table scans.

As an example, run the following script:

IF OBJECT_ID (N't1', N'U') IS NOT NULL 
drop table t1

create table t1 (f1 int)


    insert into t1 values (1) 
    insert into t1 values (1) 
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (2)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (3)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)
    insert into t1 values (4)


SELECT SUM(CASE WHEN f1 = 1 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 2 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 3 THEN 1 else 0 end),
SUM(CASE WHEN f1 = 4 THEN 1 else 0 end)
from t1

SELECT 
(select COUNT(*) from t1 where f1 = 1),
(select COUNT(*) from t1 where f1 = 2),
(select COUNT(*) from t1 where f1 = 3),
(select COUNT(*) from t1 where f1 = 4)

Highlight the 2 SELECT statements and click on the Display Estimated Execution Plan icon. You will see that the first statement will do one table scan and the second will do 4. Obviously one table scan is better than 4.

Adding a clustered index is also interesting. E.g.

Create clustered index t1f1 on t1(f1);
Update Statistics t1;

The first SELECT above will do a single Clustered Index Scan. The second SELECT will do 4 Clustered Index Seeks, but they are still more expensive than a single Clustered Index Scan. I tried the same thing on a table with 8 million rows and the second SELECT was still a lot more expensive.

Getting the object's property name

Other than "Object.keys( obj )", we have very simple "for...in" loop - which loops over enumerable property names of an object.

_x000D_
_x000D_
const obj = {"fName":"John","lName":"Doe"};_x000D_
_x000D_
for (const key in obj) {_x000D_
    //This will give key_x000D_
      console.log(key);_x000D_
    //This will give value_x000D_
    console.log(obj[key]);_x000D_
    _x000D_
}
_x000D_
_x000D_
_x000D_

List of All Folders and Sub-folders

As well as find listed in other answers, better shells allow both recurvsive globs and filtering of glob matches, so in zsh for example...

ls -lad **/*(/)

...lists all directories while keeping all the "-l" details that you want, which you'd otherwise need to recreate using something like...

find . -type d -exec ls -ld {} \;

(not quite as easy as the other answers suggest)

The benefit of find is that it's more independent of the shell - more portable, even for system() calls from within a C/C++ program etc..

How do I create a ListView with rounded corners in Android?

Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#FF00FF00" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape> 

In Java, what is the best way to determine the size of an object?

I wrote a quick test once to estimate on the fly:

public class Test1 {

    // non-static nested
    class Nested { }

    // static nested
    static class StaticNested { }

    static long getFreeMemory () {
        // waits for free memory measurement to stabilize
        long init = Runtime.getRuntime().freeMemory(), init2;
        int count = 0;
        do {
            System.out.println("waiting..." + init);
            System.gc();
            try { Thread.sleep(250); } catch (Exception x) { }
            init2 = init;
            init = Runtime.getRuntime().freeMemory();
            if (init == init2) ++ count; else count = 0;
        } while (count < 5);
        System.out.println("ok..." + init);
        return init;
    }

    Test1 () throws InterruptedException {

        Object[] s = new Object[10000];
        Object[] n = new Object[10000];
        Object[] t = new Object[10000];

        long init = getFreeMemory();

        //for (int j = 0; j < 10000; ++ j)
        //    s[j] = new Separate();

        long afters = getFreeMemory();

        for (int j = 0; j < 10000; ++ j)
            n[j] = new Nested();

        long aftersn = getFreeMemory();

        for (int j = 0; j < 10000; ++ j)
            t[j] = new StaticNested();

        long aftersnt = getFreeMemory();

        System.out.println("separate:      " + -(afters - init) + " each=" + -(afters - init) / 10000);
        System.out.println("nested:        " + -(aftersn - afters) + " each=" + -(aftersn - afters) / 10000);
        System.out.println("static nested: " + -(aftersnt - aftersn) + " each=" + -(aftersnt - aftersn) / 10000);

    }

    public static void main (String[] args) throws InterruptedException {
        new Test1();
    }

}

General concept is allocate objects and measure change in free heap space. The key being getFreeMemory(), which requests GC runs and waits for the reported free heap size to stabilize. The output of the above is:

nested:        160000 each=16
static nested: 160000 each=16

Which is what we expect, given alignment behavior and possible heap block header overhead.

The instrumentation method detailed in the accepted answer here the most accurate. The method I described is accurate but only under controlled conditions where no other threads are creating/discarding objects.

"SMTP Error: Could not authenticate" in PHPMailer

SMTP Error: could not authenticate I had the same problem. The following troubleshooting steps helped me.

  • I turned off two-factor authentication in my gmail account.
  • I allowed less secure apps to access my gmail account. To get it working, I had to go to myaccount.google.com -> Sign-in & security -> Apps with account access, and turn Allow less secure apps to ON (near the bottom of the page).
  • At this step, when I tried to register a user, I would get the same error. Google would sent me a warning message that someone has my password and the login was blocked.
  • Gmail will then provide you with options. You either click whether the activity was yours or not yours. Click the option that the activity was yours.
  • Try registration again. It should now work.

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In Windows, I only managed to be able to delete the lock file after Ending Task for all Git Windows (32bit) processes in the Task Manager.

Solution (Win 10)

1. End Task for all Git Windows (32bit) processes in the Task Manager

2. Delete the .git/index.lock file

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

How to make the division of 2 ints produce a float instead of another int?

Just cast one of the two operands to a float first.

v = (float)s / t;

The cast has higher precedence than the division, so happens before the division.

The other operand will be effectively automatically cast to a float by the compiler because the rules say that if either operand is of floating point type then the operation will be a floating point operation, even if the other operand is integral. Java Language Specification, §4.2.4 and §15.17

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Getting the array length of a 2D array in Java

With Java 8, allow you doing something more elegant like this:

int[][] foo = new int[][] {
        new int[] { 1, 2, 3 },
        new int[] { 1, 2, 3, 4},
    };

int length = Arrays.stream(array).max(Comparator.comparingInt(ArrayUtils::getLength)).get().length

Fatal error: Call to a member function prepare() on null

It looks like your $pdo variable is not initialized. I can't see in the code you've uploaded where you are initializing it.

Make sure you create a new PDO object in the global scope before calling the class methods. (You should declare it in the global scope because of how you implemented the methods inside the Category class).

$pdo = new PDO('mysql:host=localhost;dbname=test', $user, $pass);

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

env: node: No such file or directory in mac

I re-installed node through this link and it fixed it.

I think the issue was that I somehow got node to be in my /usr/bin instead of /usr/local/bin.

How can I get the IP address from NIC in Python?

It worked for me

 import subprocess
 my_ip = subprocess.Popen(['ifconfig eth0 | awk "/inet /" | cut -d":" -f 2 | cut -d" " -f1'], stdout=subprocess.PIPE, shell=True)
 (IP,errors) = my_ip.communicate()
 my_ip.stdout.close()
 print IP

SQLite UPSERT / UPDATE OR INSERT

The problem with all presented answers it complete lack of taking triggers (and probably other side effects) into account. Solution like

INSERT OR IGNORE ...
UPDATE ...

leads to both triggers executed (for insert and then for update) when row does not exist.

Proper solution is

UPDATE OR IGNORE ...
INSERT OR IGNORE ...

in that case only one statement is executed (when row exists or not).

How can I check the size of a collection within a Django template?

Collection.count no bracket

{% if request.user.is_authenticated %}
{{wishlists.count}}
{% else %}0{% endif %}

Using multiple IF statements in a batch file

You can structurize your batch file by using goto

IF EXIST somefile.txt goto somefileexists
goto exit

:somefileexists
IF EXIST someotherfile.txt SET var=...

:exit

Change onClick attribute with javascript

You want to do this - set a function that will be executed to respond to the onclick event:

document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;

The things you are doing don't work because:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
    
  2. In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:

    document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
    

How do I pass a class as a parameter in Java?

Construct your method to accept it-

public <T> void printClassNameAndCreateList(Class<T> className){
    //example access 1
    System.out.print(className.getName());

    //example access 2
    ArrayList<T> list = new ArrayList<T>();
    //note that if you create a list this way, you will have to cast input
    list.add((T)nameOfObject);
}

Call the method-

printClassNameAndCreateList(SomeClass.class);

You can also restrict the type of class, for example, this is one of the methods from a library I made-

protected Class postExceptionActivityIn;

protected <T extends PostExceptionActivity>  void  setPostExceptionActivityIn(Class <T> postExceptionActivityIn) {
    this.postExceptionActivityIn = postExceptionActivityIn;
}

For more information, search Reflection and Generics.

Use awk to find average of a column

Your specific error is with line 11:

awk 'BEGIN{sum+=$2}'

This is a line where awk is invoked, and its BEGIN block is specified - but you are already within a awk script, so you do not need to specify awk. Also you want to run sum+=$2 on each line of input, so you do not want it within a BEGIN block. Hence the line should simply read:

sum+=$2

You also do not need the lines:

x=sum
read name

the first just creates a synonym to sum named x and I'm not sure what the second does, but neither are needed.

This would make your awk script:

#!/bin/awk

### This script currently prints the total number of rows processed.
### You must edit this script to print the average of the 2nd column
### instead of the number of rows.

# This block of code is executed for each line in the file
{
    sum+=$2
    # The script should NOT print out a value for each line
}
# The END block is processed after the last line is read
END {
    # NR is a variable equal to the number of rows in the file
    print "Average: " sum/ NR
    # Change this to print the Average instead of just the number of rows
}

Jonathan Leffler's answer gives the awk one liner which represents the same fixed code, with the addition of checking that there are at least 1 lines of input (this stops any divide by zero error). If

Add Items to ListView - Android

Try this one it will work

public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_third);
     String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
                "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
                "Linux", "OS/2" };
     liste = new ArrayList<String>();
     Collections.addAll(liste, values);
     adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, liste);
     setListAdapter(adapter);
}
 @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
     liste.add("Nokia");
     adapter.notifyDataSetChanged();
  }
}

How to set cache: false in jQuery.get call

Add the parameter yourself.

$.get(url,{ "_": $.now() }, function(rdata){
  console.log(rdata);
});

As of jQuery 3.0, you can now do this:

$.get({
  url: url, 
  cache: false
}).then(function(rdata){
  console.log(rdata);
});

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

Parsing a comma-delimited std::string

bool GetList (const std::string& src, std::vector<int>& res)
  {
    using boost::lexical_cast;
    using boost::bad_lexical_cast;
    bool success = true;
    typedef boost::tokenizer<boost::char_separator<char> > tokenizer;
    boost::char_separator<char> sepa(",");
    tokenizer tokens(src, sepa);
    for (tokenizer::iterator tok_iter = tokens.begin(); 
         tok_iter != tokens.end(); ++tok_iter) {
      try {
        res.push_back(lexical_cast<int>(*tok_iter));
      }
      catch (bad_lexical_cast &) {
        success = false;
      }
    }
    return success;
  }

How to concatenate columns in a Postgres SELECT?

CONCAT functions sometimes not work with older postgreSQL version

see what I used to solve problem without using CONCAT

 u.first_name || ' ' || u.last_name as user,

Or also you can use

 "first_name" || ' ' || "last_name" as user,

in second case I used double quotes for first_name and last_name

Hope this will be useful, thanks

specifying goal in pom.xml

I've bumped into this question because I actually wanted to define a default goal in pom.xml. You can define a default goal under build:

<build>
    <defaultGoal>install</defaultGoal>
...
</build>

After that change, you can then simply run mvn which will do exactly the same as mvn install.

Note: I don't favor this as a default approach. My use case was to define a profile that downloaded a previous version of that project from Artifactory and wanted to tie that profile to a given phase. For convenience, I can run mvn -Pdownload-jar -Dversion=0.0.9 and don't need to specify a goal/phase there. I think it's reasonable to define a defaultGoal in a profile which has a very specific function for a particular phase.

Python:Efficient way to check if dictionary is empty or not

This will do it:

while d:
    k, v = d.popitem()
    # now use k and v ...

A dictionary in boolean context is False if empty, True otherwise.

There is no "first" item in a dictionary, because dictionaries aren't ordered. But popitem will remove and return some item for you each time.

Why does .NET foreach loop throw NullRefException when collection is null?

There is a big difference between an empty collection and a null reference to a collection.

When you use foreach, internally, this is calling the IEnumerable's GetEnumerator() method. When the reference is null, this will raise this exception.

However, it is perfectly valid to have an empty IEnumerable or IEnumerable<T>. In this case, foreach will not "iterate" over anything (since the collection is empty), but it will also not throw, since this is a perfectly valid scenario.


Edit:

Personally, if you need to work around this, I'd recommend an extension method:

public static IEnumerable<T> AsNotNull<T>(this IEnumerable<T> original)
{
     return original ?? Enumerable.Empty<T>();
}

You can then just call:

foreach (int i in returnArray.AsNotNull())
{
    // do some more stuff
}

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Exceptions bubble up the stack. If a caller calls a method that throws a checked exception, like IOException, it must also either catch the exception, or itself throw it.

In the case of the first block:

filecontent()
{
    setGUI();
    setRegister();
    showfile();
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

You would have to include a try catch block:

filecontent()
{
    setGUI();
    setRegister();
    try {
        showfile();
    }
    catch (IOException e) {
        // Do something here
    }
    setTitle("FileData");
    setVisible(true);
    setSize(300, 300);

    /*
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent we)
            {
                System.exit(0);
            }
        });
    */
}

In the case of the second:

public void actionPerformed(ActionEvent ae)
{
    if (ae.getSource() == submit)
    {
        showfile();
    }
}

You cannot throw IOException from this method as its signature is determined by the interface, so you must catch the exception within:

public void actionPerformed(ActionEvent ae)
{
    if(ae.getSource()==submit)
    {
        try {
            showfile();
        }
        catch (IOException e) {
            // Do something here
        }
    }
}

Remember, the showFile() method is throwing the exception; that's what the "throws" keyword indicates that the method may throw that exception. If the showFile() method is throwing, then whatever code calls that method must catch, or themselves throw the exception explicitly by including the same throws IOException addition to the method signature, if it's permitted.

If the method is overriding a method signature defined in an interface or superclass that does not also declare that the method may throw that exception, you cannot declare it to throw an exception.

Split Strings into words with multiple word boundary delimiters

First, I want to agree with others that the regex or str.translate(...) based solutions are most performant. For my use case the performance of this function wasn't significant, so I wanted to add ideas that I considered with that criteria.

My main goal was to generalize ideas from some of the other answers into one solution that could work for strings containing more than just regex words (i.e., blacklisting the explicit subset of punctuation characters vs whitelisting word characters).

Note that, in any approach, one might also consider using string.punctuation in place of a manually defined list.

Option 1 - re.sub

I was surprised to see no answer so far uses re.sub(...). I find it a simple and natural approach to this problem.

import re

my_str = "Hey, you - what are you doing here!?"

words = re.split(r'\s+', re.sub(r'[,\-!?]', ' ', my_str).strip())

In this solution, I nested the call to re.sub(...) inside re.split(...) — but if performance is critical, compiling the regex outside could be beneficial — for my use case, the difference wasn't significant, so I prefer simplicity and readability.

Option 2 - str.replace

This is a few more lines, but it has the benefit of being expandable without having to check whether you need to escape a certain character in regex.

my_str = "Hey, you - what are you doing here!?"

replacements = (',', '-', '!', '?')
for r in replacements:
    my_str = my_str.replace(r, ' ')

words = my_str.split()

It would have been nice to be able to map the str.replace to the string instead, but I don't think it can be done with immutable strings, and while mapping against a list of characters would work, running every replacement against every character sounds excessive. (Edit: See next option for a functional example.)

Option 3 - functools.reduce

(In Python 2, reduce is available in global namespace without importing it from functools.)

import functools

my_str = "Hey, you - what are you doing here!?"

replacements = (',', '-', '!', '?')
my_str = functools.reduce(lambda s, sep: s.replace(sep, ' '), replacements, my_str)
words = my_str.split()

Truncate (not round off) decimal numbers in javascript

Nice one-line solution:

function truncate (num, places) {
  return Math.trunc(num * Math.pow(10, places)) / Math.pow(10, places);
}

Then call it with:

truncate(3.5636232, 2); // returns 3.56
truncate(5.4332312, 3); // returns 5.433
truncate(25.463214, 4); // returns 25.4632

Getting cursor position in Python

win32gui.GetCursorPos(point)

This retrieves the cursor's position, in screen coordinates - point = (x,y)

flags, hcursor, (x,y) = win32gui.GetCursorInfo()

Retrieves information about the global cursor.

Links:

I am assuming that you would be using python win32 API bindings or pywin32.

How can you remove all documents from a collection with Mongoose?

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

Source: Mongodb.

If you are using mongo sheel, just do:

db.Datetime.remove({})

In your case, you need:

You didn't show me the delete button, so this button is just an example:

<a class="button__delete"></a>

Change the controller to:

exports.destroy = function(req, res, next) {
    Datetime.remove({}, function(err) {
            if (err) {
                console.log(err)
            } else {
                res.end('success');
            }
        }
    );
};

Insert this ajax delete method in your client js file:

        $(document).ready(function(){
            $('.button__delete').click(function() {
                var dataId = $(this).attr('data-id');

                if (confirm("are u sure?")) {
                    $.ajax({
                        type: 'DELETE',
                        url: '/',
                        success: function(response) {
                            if (response == 'error') {
                                console.log('Err!');
                            }
                            else {
                                alert('Success');
                                location.reload();
                            }
                        }
                    });
                } else {
                    alert('Canceled!');
                }
            });
        });

Pass table as parameter into sql server UDF

I've been dealing with a very similar problem and have been able to achieve what I was looking for, even though I'm using SQL Server 2000. I know it is an old question, but think its valid to post here the solution since there should be others like me that use old versions and still need help.

Here's the trick: SQL Server won't accept passing a table to a UDF, nor you can pass a T-SQL query so the function creates a temp table or even calls a stored procedure to do that. So, instead, I've created a reserved table, which I called xtList. This will hold the list of values (1 column, as needed) to work with.

CREATE TABLE [dbo].[xtList](
    [List] [varchar](1000) NULL
) ON [PRIMARY]

Then, a stored procedure to populate the list. This is not strictly necessary, but I think is very usefull and best practice.

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpCreateList]
    @ListQuery varchar(2000)
AS
BEGIN
    SET NOCOUNT ON;

  DELETE FROM xtList

  INSERT INTO xtList
    EXEC(@ListQuery)
END

Now, just deal with the list in any way you want, using the xtList. You can use in a procedure (for executing several T-SQL commands), scalar functions (for retrieving several strings) or multi-statement table-valued functions (retrieves the strings but like it was inside a table, 1 string per row). For any of that, you'll need cursors:

DECLARE @Item varchar(100)
DECLARE cList CURSOR DYNAMIC
  FOR (SELECT * FROM xtList WHERE List is not NULL)
  OPEN cList

FETCH FIRST FROM cList INTO @Item
WHILE @@FETCH_STATUS = 0 BEGIN

  << desired action with values >>

FETCH NEXT FROM cList INTO @Item
END
CLOSE cList
DEALLOCATE cList

The desired action would be as follows, depending on which type of object created:

Stored procedures

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE PROCEDURE [dbo].[xpProcreateExec]
(
    @Cmd varchar(8000),
    @ReplaceWith varchar(1000)
)
AS
BEGIN
  DECLARE @Query varchar(8000)

  << cursor start >>
    SET @Query = REPLACE(@Cmd,@ReplaceWith,@Item)
    EXEC(@Query)
  << cursor end >>
END

/* EXAMPLES

  (List A,B,C)

  Query = 'SELECT x FROM table'
    with EXEC xpProcreateExec(Query,'x') turns into
  SELECT A FROM table
  SELECT B FROM table
  SELECT C FROM table

  Cmd = 'EXEC procedure ''arg''' --whatchout for wrong quotes, since it executes as dynamic SQL
    with EXEC xpProcreateExec(Cmd,'arg') turns into
  EXEC procedure 'A'
  EXEC procedure 'B'
  EXEC procedure 'C'

*/

Scalar functions

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateStr]
(
    @OriginalText varchar(8000),
    @ReplaceWith varchar(1000)
)
RETURNS varchar(8000)
AS
BEGIN
    DECLARE @Result varchar(8000)

  SET @Result = ''
  << cursor start >>
    SET @Result = @Result + REPLACE(@OriginalText,@ReplaceWith,@Item) + char(13) + char(10)
  << cursor end >>

    RETURN @Result
END

/* EXAMPLE

  (List A,B,C)

  Text = 'Access provided for user x'
    with "SELECT dbo.xfProcreateStr(Text,'x')" turns into
  'Access provided for user A
  Access provided for user B
  Access provided for user C'

*/

Multi-statement table-valued functions

-- =============================================
-- Author:      Zark Khullah
-- Create date: 20/06/2014
-- =============================================
CREATE FUNCTION [dbo].[xfProcreateInRows]
(
    @OriginalText varchar(8000),
    @ReplaceWith varchar(1000)
)
RETURNS 
@Texts TABLE 
(
    Text varchar(2000)
)
AS
BEGIN
  << cursor start >>
      INSERT INTO @Texts VALUES(REPLACE(@OriginalText,@ReplaceWith,@Item))
  << cursor end >>
END

/* EXAMPLE

  (List A,B,C)

  Text = 'Access provided for user x'
    with "SELECT * FROM dbo.xfProcreateInRow(Text,'x')" returns rows
  'Access provided for user A'
  'Access provided for user B'
  'Access provided for user C'

*/

jquery find closest previous sibling with class

Using prevUntil() will allow us to get a distant sibling without having to get all. I had a particularly long set that was too CPU intensive using prevAll().

var category = $('li.current_sub').prev('li.par_cat');
if (category.length == 0){
  category = $('li.current_sub').prevUntil('li.par_cat').last().prev();
}
category.show();

This gets the first preceding sibling if it matches, otherwise it gets the sibling preceding the one that matches, so we just back up one more with prev() to get the desired element.

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

Renaming part of a filename

I like to do this with sed. In you case:

for x in DET01-*.dat; do
    echo $x | sed -r 's/DET01-ABC-(.+)\.dat/mv -v "\0" "DET01-XYZ-\1.dat"/'
done | sh -e

It is best to omit the "sh -e" part first to see what will be executed.

How to install pip with Python 3?

This is what I did on OS X Mavericks to get this to work.

Firstly, have brew installed

Install python 3.4

brew install python3

Then I get the latest version of distribute:

wget https://pypi.python.org/packages/source/d/distribute/distribute-0.7.3.zip#md5=c6c59594a7b180af57af8a0cc0cf5b4a

unzip distribute-0.7.3.zip
cd distribute-0.7.3
sudo setup.py install
sudo easy_install-3.4 pip
sudo pip3.4 install virtualenv
sudo pip3.4 install virtualenvwrapper

mkvirtualenv py3 

python --version
Python 3.4.1

I hope this helps.

How do I get the currently-logged username from a Windows service in .NET?

Completing the answer from @xanblax

private static string getUserName()
    {
        SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (System.Management.ManagementObject Process in searcher.Get())
            {
                if (Process["ExecutablePath"] != null &&
                    string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    string[] OwnerInfo = new string[2];
                    Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

                    return OwnerInfo[0];
                }
            }
        }
        return "";
    }

Android : How to read file in bytes?

Following is the working solution to read the entire file in chunks and its efficient solution to read the large files using a scanner class.

   try {
        FileInputStream fiStream = new FileInputStream(inputFile_name);
        Scanner sc = null;
        try {
            sc = new Scanner(fiStream);
            while (sc.hasNextLine()) {
                String line = sc.nextLine();
                byte[] buf = line.getBytes();
            }
        } finally {
            if (fiStream != null) {
                fiStream.close();
            }

            if (sc != null) {
                sc.close();
            }
        }
    }catch (Exception e){
        Log.e(TAG, "Exception: " + e.toString());
    }

Convert date yyyyMMdd to system.datetime format

have at look at the static methods DateTime.Parse() and DateTime.TryParse(). They will allow you to pass in your date string and a format string, and get a DateTime object in return.

http://msdn.microsoft.com/en-us/library/6fw7727c.aspx

How to set root password to null

For MySQL 8.0 just:

SET PASSWORD FOR 'root'@'localhost' = '';

How to display an unordered list in two columns?

With Bootstrap... This answer (https://stackoverflow.com/a/23005046/1128742) got me pointed towards this solution:

<ul class="list-unstyled row">
   <li class="col-xs-6">Item 1</li>
   <li class="col-xs-6">Item 2</li>
   <li class="col-xs-6">Item 3</li>
</ul>

http://jsfiddle.net/patrickbad767/472r0ynf/

angularjs ng-style: background-image isn't working

Correct syntax for background-image is:

background-image: url("path_to_image");

Correct syntax for ng-style is:

ng-style="{'background-image':'url(https://www.google.com/images/srpr/logo4w.png)'}">

How to send a Post body in the HttpClient request in Windows Phone 8?

I implemented it in the following way. I wanted a generic MakeRequest method that could call my API and receive content for the body of the request - and also deserialise the response into the desired type. I create a Dictionary<string, string> object to house the content to be submitted, and then set the HttpRequestMessage Content property with it:

Generic method to call the API:

    private static T MakeRequest<T>(string httpMethod, string route, Dictionary<string, string> postParams = null)
    {
        using (var client = new HttpClient())
        {
            HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), $"{_apiBaseUri}/{route}");

            if (postParams != null)
                requestMessage.Content = new FormUrlEncodedContent(postParams);   // This is where your content gets added to the request body


            HttpResponseMessage response = client.SendAsync(requestMessage).Result;

            string apiResponse = response.Content.ReadAsStringAsync().Result;
            try
            {
                // Attempt to deserialise the reponse to the desired type, otherwise throw an expetion with the response from the api.
                if (apiResponse != "")
                    return JsonConvert.DeserializeObject<T>(apiResponse);
                else
                    throw new Exception();
            }
            catch (Exception ex)
            {
                throw new Exception($"An error ocurred while calling the API. It responded with the following message: {response.StatusCode} {response.ReasonPhrase}");
            }
        }
    }

Call the method:

    public static CardInformation ValidateCard(string cardNumber, string country = "CAN")
    { 
        // Here you create your parameters to be added to the request content
        var postParams = new Dictionary<string, string> { { "cardNumber", cardNumber }, { "country", country } };
        // make a POST request to the "cards" endpoint and pass in the parameters
        return MakeRequest<CardInformation>("POST", "cards", postParams);
    }

Is it possible to insert multiple rows at a time in an SQLite database?

I am able to make the query dynamic. This is my table:

CREATE TABLE "tblPlanner" ("probid" text,"userid" TEXT,"selectedtime" DATETIME,"plannerid" TEXT,"isLocal" BOOL,"applicationid" TEXT, "comment" TEXT, "subject" TEXT)

and I'm getting all data through a JSON, so after getting everything inside an NSArray I followed this:

    NSMutableString *query = [[NSMutableString alloc]init];
    for (int i = 0; i < arr.count; i++)
    {
        NSString *sqlQuery = nil;
        sqlQuery = [NSString stringWithFormat:@" ('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@'),",
                    [[arr objectAtIndex:i] objectForKey:@"plannerid"],
                    [[arr objectAtIndex:i] objectForKey:@"probid"],
                    [[arr objectAtIndex:i] objectForKey:@"userid"],
                    [[arr objectAtIndex:i] objectForKey:@"selectedtime"],
                    [[arr objectAtIndex:i] objectForKey:@"isLocal"],
                    [[arr objectAtIndex:i] objectForKey:@"subject"],
                    [[arr objectAtIndex:i] objectForKey:@"comment"],
                    [[NSUserDefaults standardUserDefaults] objectForKey:@"applicationid"]
                    ];
        [query appendString:sqlQuery];
    }
    // REMOVING LAST COMMA NOW
    [query deleteCharactersInRange:NSMakeRange([query length]-1, 1)];

    query = [NSString stringWithFormat:@"insert into tblPlanner (plannerid, probid, userid, selectedtime, isLocal, applicationid, subject, comment) values%@",query];

And finally the output query is this:

insert into tblPlanner (plannerid, probid, userid, selectedtime, isLocal, applicationid, subject, comment) values 
<append 1>
('pl1176428260', '', 'US32552', '2013-06-08 12:00:44 +0000', '0', 'subj', 'Hiss', 'ap19788'),
<append 2>
('pl2050411638', '', 'US32552', '2013-05-20 10:45:55 +0000', '0', 'TERI', 'Yahoooooooooo', 'ap19788'), 
<append 3>
('pl1828600651', '', 'US32552', '2013-05-21 11:33:33 +0000', '0', 'test', 'Yest', 'ap19788'),
<append 4>
('pl549085534', '', 'US32552', '2013-05-19 11:45:04 +0000', '0', 'subj', 'Comment', 'ap19788'), 
<append 5>
('pl665538927', '', 'US32552', '2013-05-29 11:45:41 +0000', '0', 'subj', '1234567890', 'ap19788'), 
<append 6>
('pl1969438050', '', 'US32552', '2013-06-01 12:00:18 +0000', '0', 'subj', 'Cmt', 'ap19788'),
<append 7>
('pl672204050', '', 'US55240280', '2013-05-23 12:15:58 +0000', '0', 'aassdd', 'Cmt', 'ap19788'), 
<append 8>
('pl1019026150', '', 'US32552', '2013-06-08 12:15:54 +0000', '0', 'exists', 'Cmt', 'ap19788'), 
<append 9>
('pl790670523', '', 'US55240280', '2013-05-26 12:30:21 +0000', '0', 'qwerty', 'Cmt', 'ap19788')

which is running well through code also and I'm able to save everything in SQLite successfully.

Before this i made UNION query stuff dynamic but that started giving some syntax error. Anyways, this is running well for me.

SQL Query to search schema of all tables

You can also try doing this using one of many third party tools that are available for this.

Queries are great for simple searches but if you need to do more manipulation with data, search for references and such this is where you can do a much better job with these.

Also, these come in very handy when some objects are encrypted and you need to search for

I’m using ApexSQL Search which is free but there are also many more (also free) on the market such as Red Gate or SSMS Tool Pack.

Batch files : How to leave the console window open

In the last line of the batch file that you want to keep open put a

pause >nul

How do I make a WinForms app go Full Screen

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Package doesn't exist error in intelliJ

If you are trying the suggested ways and still no chance, be sure about your order:

  1. Delete your .idea/
  2. Invalidate and Restart Cache afterwards
  3. Import maven projects from your maven tool

If you did not invalidate and restart cache just after deleting your .idea/, Intellij keeps generating it and that was keeping error in my case.

How to compare two dates in Objective-C

Here's the Swift variant on Pascal's answer:

extension NSDate {

    func isLaterThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedAscending)
    }

    func isEarlierThanOrEqualTo(date:NSDate) -> Bool {
        return !(self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isLaterThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedDescending)
    }

    func isEarlierThan(date:NSDate) -> Bool {
        return (self.compare(date) == NSComparisonResult.OrderedAscending)
    }
}

Which can be used as:

self.expireDate.isEarlierThanOrEqualTo(NSDate())

How to clear an ImageView in Android?

As kwasi wrote and golu edited, you can use transparent, instead of white:

File drawable/transparent.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@android:color/transparent"/>
</shape>

Inside an activity, view, etc:

view.setImageResource(R.drawable.transparent);

socket.error: [Errno 48] Address already in use

This commonly happened use case for any developer.

It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)

function killport {
   kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
}

Usage:

killport port_number

Example:

killport 8080

uint8_t vs unsigned char

That is really important for example when you are writing a network analyzer. packet headers are defined by the protocol specification, not by the way a particular platform's C compiler works.

SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904)

Anyone who has this error, especially on Azure, try adding "tcp:" to the db-server-name in your connection string in your application. This forces the sql client to communicate with the db using tcp. I'm assuming the connection is UDP by default and there can be intermittent connection issues

How to update value of a key in dictionary in c#?

Just use the indexer and update directly:

dictionary["cat"] = 3

how to get domain name from URL

/^(?:https?:\/\/)?(?:www\.)?([^\/]+)/i

Django - how to create a file and save it to a model's FileField?

It's good practice to use a context manager or call close() in case of exceptions during the file saving process. Could happen if your storage backend is down, etc.

Any overwrite behavior should be configured in your storage backend. For example S3Boto3Storage has a setting AWS_S3_FILE_OVERWRITE. If you're using FileSystemStorage you can write a custom mixin.

You might also want to call the model's save method instead of the FileField's save method if you want any custom side-effects to happen, like last-updated timestamps. If that's the case, you can also set the name attribute of the file to the name of the file - which is relative to MEDIA_ROOT. It defaults to the full path of the file which can cause problems if you don't set it - see File.__init__() and File.name.

Here's an example where self is the model instance where my_file is the FileField / ImageFile, calling save() on the whole model instance instead of just FileField:

import os
from django.core.files import File

with open(filepath, 'rb') as fi:
    self.my_file = File(fi, name=os.path.basename(fi.name))
    self.save()

how do I insert a column at a specific column index in pandas?

see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html

using loc = 0 will insert at the beginning

df.insert(loc, column, value)

df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})

df
Out: 
   B  C
0  1  4
1  2  5
2  3  6

idx = 0
new_col = [7, 8, 9]  # can be a list, a Series, an array or a scalar   
df.insert(loc=idx, column='A', value=new_col)

df
Out: 
   A  B  C
0  7  1  4
1  8  2  5
2  9  3  6

Updating Anaconda fails: Environment Not Writable Error

In my case somehow CONDA_ENVS_PATH was removed, so I was having NotWritableError. So I fixed the error by specifying

CONDA_ENVS_PATH=~/my-envs:/opt/anaconda/envs

in the .bashrc file

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

Converting java.sql.Date to java.util.Date

Since java.sql.Date extends java.util.Date, you should be able to do

java.util.Date newDate = result.getDate("VALUEDATE");

Base64 decode snippet in C++

There are several snippets here. However, this one is compact, efficient, and C++11 friendly:

static std::string base64_encode(const std::string &in) {

    std::string out;

    int val = 0, valb = -6;
    for (uchar c : in) {
        val = (val << 8) + c;
        valb += 8;
        while (valb >= 0) {
            out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[(val>>valb)&0x3F]);
            valb -= 6;
        }
    }
    if (valb>-6) out.push_back("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[((val<<8)>>(valb+8))&0x3F]);
    while (out.size()%4) out.push_back('=');
    return out;
}

static std::string base64_decode(const std::string &in) {

    std::string out;

    std::vector<int> T(256,-1);
    for (int i=0; i<64; i++) T["ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"[i]] = i;

    int val=0, valb=-8;
    for (uchar c : in) {
        if (T[c] == -1) break;
        val = (val << 6) + T[c];
        valb += 6;
        if (valb >= 0) {
            out.push_back(char((val>>valb)&0xFF));
            valb -= 8;
        }
    }
    return out;
}

How can I prevent the backspace key from navigating back?

I've been using this in my code for some time now. I write online tests for students and ran into the problem when students were pressing backspace during their test and it would take them back to the login screen. Frustrating! It works on FF for sure.

document.onkeypress = Backspace;
function Backspace(event) {
    if (event.keyCode == 8) {
        if (document.activeElement.tagName == "INPUT") {
            return true;
        } else {
            return false;
        }
    }
}

Check if input is integer type in C

Try this...

#include <stdio.h>

int main (void)
{
    float a;
    int q;

    printf("\nInsert number\t");
    scanf("%f",&a);

    q=(int)a;
    ++q;

    if((q - a) != 1)
        printf("\nThe number is not an integer\n\n");
    else
        printf("\nThe number is an integer\n\n");

    return 0;
}

Calling JavaScript Function From CodeBehind

You can't call a Javascript function from the CodeBehind, because the CodeBehind file contains the code that executes server side on the web server. Javascript code executes in the web browser on the client side.

How to filter by IP address in Wireshark?

in our use we have to capture with host x.x.x.x. or (vlan and host x.x.x.x)

anything less will not capture? I am not sure why but that is the way it works!

PHPDoc type hinting for array of objects?

Use array[type] in Zend Studio.

In Zend Studio, array[MyClass] or array[int] or even array[array[MyClass]] work great.

CakePHP find method with JOIN

There are two main ways that you can do this. One of them is the standard CakePHP way, and the other is using a custom join.

It's worth pointing out that this advice is for CakePHP 2.x, not 3.x.

The CakePHP Way

You would create a relationship with your User model and Messages Model, and use the containable behavior:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array('Message');
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array('User');
}

You need to change the messages.from column to be messages.user_id so that cake can automagically associate the records for you.

Then you can do this from the messages controller:

$this->Message->find('all', array(
    'contain' => array('User')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

The (other) CakePHP way

I recommend using the first method, because it will save you a lot of time and work. The first method also does the groundwork of setting up a relationship which can be used for any number of other find calls and conditions besides the one you need now. However, cakePHP does support a syntax for defining your own joins. It would be done like this, from the MessagesController:

$this->Message->find('all', array(
    'joins' => array(
        array(
            'table' => 'users',
            'alias' => 'UserJoin',
            'type' => 'INNER',
            'conditions' => array(
                'UserJoin.id = Message.from'
            )
        )
    ),
    'conditions' => array(
        'Message.to' => 4
    ),
    'fields' => array('UserJoin.*', 'Message.*'),
    'order' => 'Message.datetime DESC'
));

Note, I've left the field name messages.from the same as your current table in this example.

Using two relationships to the same model

Here is how you can do the first example using two relationships to the same model:

class User extends AppModel {
    public $actsAs = array('Containable');
    public $hasMany = array(
        'MessagesSent' => array(
            'className'  => 'Message',
            'foreignKey' => 'from'
         )
    );
    public $belongsTo = array(
        'MessagesReceived' => array(
            'className'  => 'Message',
            'foreignKey' => 'to'
         )
    );
}

class Message extends AppModel {
    public $actsAs = array('Containable');
    public $belongsTo = array(
        'UserFrom' => array(
            'className'  => 'User',
            'foreignKey' => 'from'
        )
    );
    public $hasMany = array(
        'UserTo' => array(
            'className'  => 'User',
            'foreignKey' => 'to'
        )
    );
}

Now you can do your find call like this:

$this->Message->find('all', array(
    'contain' => array('UserFrom')
    'conditions' => array(
        'Message.to' => 4
    ),
    'order' => 'Message.datetime DESC'
));

Put search icon near textbox using bootstrap

You can do it in pure CSS using the :after pseudo-element and getting creative with the margins.

Here's an example, using Font Awesome for the search icon:

_x000D_
_x000D_
.search-box-container input {_x000D_
  padding: 5px 20px 5px 5px;_x000D_
}_x000D_
_x000D_
.search-box-container:after {_x000D_
    content: "\f002";_x000D_
    font-family: FontAwesome;_x000D_
    margin-left: -25px;_x000D_
    margin-right: 25px;_x000D_
}
_x000D_
<!-- font awesome -->_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="search-box-container">_x000D_
  <input type="text" placeholder="Search..."  />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do you easily horizontally center a <div> using CSS?

You should use position: relative and text-align: center on the parent element and then display: inline-block on the child element you want to center. This is a simple CSS design pattern that will work across all major browsers. Here is an example below or check out the CodePen Example.

_x000D_
_x000D_
p {_x000D_
  text-align: left;_x000D_
}_x000D_
.container {_x000D_
  position: relative;_x000D_
  display: block;_x000D_
  text-align: center;_x000D_
}_x000D_
/* Style your object */_x000D_
_x000D_
.object {_x000D_
  padding: 10px;_x000D_
  color: #ffffff;_x000D_
  background-color: #556270;_x000D_
}_x000D_
.centerthis {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="container">_x000D_
_x000D_
  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius An Maius Septentrionarius Plas Inproportionabilit Constantinopolis Particularisticus.</p>_x000D_
_x000D_
  <span class="object centerthis">Something Centered</span>_x000D_
_x000D_
  <p>Aeroplanigera Mi Psychopathologia Subdistinctio Chirographum Intuor Sons Superbiloquentia Os Sors Sesquiseptimus Municipatio Archipresbyteratus O Conclusio Compedagogius.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

How to use pip with Python 3.x alongside Python 2.x

Please note that on msys2 I've found these commands to be helpful:

$ pacman -S python3-pip
$ pip3 install --upgrade pip
$ pip3 install --user package_name

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

To make it work you have to replace a run this line of code serviceMetadata httpGetEnabled="true"/> http instead of https and security mode="None" />

pip install mysql-python fails with EnvironmentError: mysql_config not found

You can use the MySQL Connector/Python

Installation via PyPip

pip install mysql-connector-python

Further information can be found on the MySQL Connector/Python 1.0.5 beta announcement blog.

On Launchpad there's a good example of how to add-, edit- or remove data with the library.

Best way to get the max value in a Spark dataframe column

In case some wonders how to do it using Scala (using Spark 2.0.+), here you go:

scala> df.createOrReplaceTempView("TEMP_DF")
scala> val myMax = spark.sql("SELECT MAX(x) as maxval FROM TEMP_DF").
    collect()(0).getInt(0)
scala> print(myMax)
117

Splitting String with delimiter

def (value1, value2) = '1128-2'.split('-') should work.

Can anyone please try this in Groovy Console?

def (v, z) =  '1128-2'.split('-')

assert v == '1128'
assert z == '2'

Failed to resolve: com.android.support:appcompat-v7:26.0.0

1 - in build.gradle change my supportLibVersion to 26.0.0

2 - in app/build.gradle use :

implementation "com.android.support:appcompat v7:${rootProject.ext.supportLibVersion}"

3 - cd android

4 - ./gradlew clean

5 - ./gradlew assembleRelease

How do I handle newlines in JSON?

I used this function to strip newline or other characters in data to parse JSON data:

function normalize_str($str) {

    $invalid = array(
        'Š'=>'S', 'š'=>'s',  'Ð'=>'Dj', 'd'=>'dj', 'Ž'=>'Z', 'ž'=>'z',
        'C'=>'C', 'c'=>'c',  'C'=>'C',  'c'=>'c',  'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A',
        'Ä'=>'A', 'Å'=>'A',  'Æ'=>'A',  'Ç'=>'C',  'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E',
        'Ì'=>'I', 'Í'=>'I',  'Î'=>'I',  'Ï'=>'I',  'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O',
        'Õ'=>'O', 'Ö'=>'O',  'Ø'=>'O',  'Ù'=>'U',  'Ú'=>'U', 'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y',
        'Þ'=>'B', 'ß'=>'Ss', 'à'=>'a',  'á'=>'a',  'â'=>'a', 'ã'=>'a', 'ä'=>'a', 'å'=>'a',
        'æ'=>'a', 'ç'=>'c',  'è'=>'e',  'é'=>'e',  'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i',
        'î'=>'i', 'ï'=>'i',  'ð'=>'o',  'ñ'=>'n',  'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o',
        'ö'=>'o', 'ø'=>'o',  'ù'=>'u',  'ú'=>'u',  'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b',
        'ÿ'=>'y', 'R'=>'R',  'r'=>'r',
        "`" => "'", "´" => "'",  '"' => ',',  '`' => "'",
        '´' => "'", '"' => '\"', '"' => "\"", '´' => "'",
        "&acirc;€™" => "'",
        "{" => "",
        "~" => "",  "–" => "-",  "'" => "'",  "     " => " ");

    $str = str_replace(array_keys($invalid), array_values($invalid), $str);

    $remove = array("\n", "\r\n", "\r");
    $str = str_replace($remove, "\\n", trim($str));

    //$str = htmlentities($str, ENT_QUOTES);

    return htmlspecialchars($str);
}

echo normalize_str($lst['address']);

Increasing (or decreasing) the memory available to R processes

  1. Buy more ram
  2. Switch to a 64-bit OS. Combine with point 1.

Active Directory LDAP Query by sAMAccountName and Domain

If you're using .NET, use the DirectorySearcher class. You can pass in your domain as a string into the constructor.

// if you domain is domain.com...
string username = "user"
string domain = "LDAP://DC=domain,DC=com";
DirectorySearcher search = new DirectorySearcher(domain);
search.Filter = "(SAMAccountName=" + username + ")";

python time + timedelta equivalent

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

Polling the keyboard (detect a keypress) in python

I am using this for checking for key presses, can't get much simpler:

#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import curses, time

def main(stdscr):
    """checking for keypress"""
    stdscr.nodelay(True)  # do not wait for input when calling getch
    return stdscr.getch()

while True:
    print("key:", curses.wrapper(main)) # prints: 'key: 97' for 'a' pressed
                                        # '-1' on no presses
    time.sleep(1)

While curses is not working on windows, there is a 'unicurses' version, supposedly working on Linux, Windows, Mac but I could not get this to work

How to set the image from drawable dynamically in android?

Try this Dynamic code

String fnm = "cat"; //  this is image file name
String PACKAGE_NAME = getApplicationContext().getPackageName();
int imgId = getResources().getIdentifier(PACKAGE_NAME+":drawable/"+fnm , null, null);
System.out.println("IMG ID :: "+imgId);
System.out.println("PACKAGE_NAME :: "+PACKAGE_NAME);
//    Bitmap bitmap = BitmapFactory.decodeResource(getResources(),imgId);
your_image_view.setImageBitmap(BitmapFactory.decodeResource(getResources(),imgId));

In above code you will need Image-file-Name and Image-View object which both you are having.

Unicode character as bullet for list-item in CSS

Images are not recommended since they may appear pixelated on some devices (Apple devices with Retina display) or when zoomed in. With a character, your list looks awesome everytime.

Here is the best solution I've found so far. It works great and it's cross-browser (IE 8+).

ul {
    list-style: none;
    padding-left: 1.2em;
    text-indent: -1.2em;
}

li:before {
    content: "?";
    display: block;
    float: left;
    width: 1.2em;
    color: #ff0000;
}

The important thing is to have the character in a floating block with a fixed width so that the text remains aligned if it's too long to fit on a single line. 1.2em is the width you want for your character, change it for your needs. Don't forget to reset padding and margin for ul and li elements.

EDIT: Be aware that the "1.2em" size may vary if you use a different font in ul and li:before. It's safer to use pixels.

Regex not operator

You could capture the (2001) part and replace the rest with nothing.

public static string extractYearString(string input) {
    return input.replaceAll(".*\(([0-9]{4})\).*", "$1");
}

var subject = "(2001) (asdf) (dasd1123_asd 21.01.2011 zqge)(dzqge) name (20019)";
var result = extractYearString(subject);
System.out.println(result); // <-- "2001"

.*\(([0-9]{4})\).* means

  • .* match anything
  • \( match a ( character
  • ( begin capture
  • [0-9]{4} any single digit four times
  • ) end capture
  • \) match a ) character
  • .* anything (rest of string)

Change One Cell's Data in mysql

UPDATE will change only the columns you specifically list.

UPDATE some_table
SET field1='Value 1'
WHERE primary_key = 7;

The WHERE clause limits which rows are updated. Generally you'd use this to identify your table's primary key (or ID) value, so that you're updating only one row.

The SET clause tells MySQL which columns to update. You can list as many or as few columns as you'd like. Any that you do not list will not get updated.

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

error: ORA-65096: invalid common user or role name in oracle

I just installed oracle11g

ORA-65096: invalid common user or role name in oracle

No, you have installed Oracle 12c. That error could only be on 12c, and cannot be on 11g.

Always check your database version up to 4 decimal places:

SELECT banner FROM v$version WHERE ROWNUM = 1;

Oracle 12c multitenant container database has:

  • a root container(CDB)
  • and/or zero, one or many pluggable databases(PDB).

You must have created the database as a container database. While, you are trying to create user in the container, i.e. CDB$ROOT, however, you should create the user in the PLUGGABLE database.

You are not supposed to create application-related objects in the container, the container holds the metadata for the pluggable databases. You should use the pluggable database for you general database operations. Else, do not create it as container, and not use multi-tenancy. However, 12cR2 onward you cannot create a non-container database anyway.

And most probably, the sample schemas might have been already installed, you just need to unlock them in the pluggable database.

For example, if you created pluggable database as pdborcl:

sqlplus SYS/password@PDBORCL AS SYSDBA

SQL> ALTER USER scott ACCOUNT UNLOCK IDENTIFIED BY tiger;

sqlplus scott/tiger@pdborcl

SQL> show user;
USER is "SCOTT"

To show the PDBs and connect to a pluggable database from root container:

SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCLPDB                        READ WRITE NO

SQL> alter session set container = ORCLPDB;

Session altered.

SQL> show con_name;

CON_NAME
------------------------------
ORCLPDB

I suggest read, Oracle 12c Post Installation Mandatory Steps


Note: Answers suggesting to use the _ORACLE_SCRIPT hidden parameter to set to true is dangerous in a production system and might also invalidate your support contract. Beware, without consulting Oracle support DO NOT use hidden parameters.

Versioning SQL Server database

You could also look at a migrations solution. These allow you to specify your database schema in C# code, and roll your database version up and down using MSBuild.

I'm currently using DbUp, and it's been working well.

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

How to change plot background color?

Something like this? Use the axisbg keyword to subplot:

>>> from matplotlib.figure import Figure
>>> from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
>>> figure = Figure()
>>> canvas = FigureCanvas(figure)
>>> axes = figure.add_subplot(1, 1, 1, axisbg='red')
>>> axes.plot([1,2,3])
[<matplotlib.lines.Line2D object at 0x2827e50>]
>>> canvas.print_figure('red-bg.png')

(Granted, not a scatter plot, and not a black background.)

enter image description here

How can I subset rows in a data frame in R based on a vector of values?

Really human comprehensible example (as this is the first time I am using %in%), how to compare two data frames and keep only rows containing the equal values in specific column:

# Set seed for reproducibility.
set.seed(1)

# Create two sample data frames.
data_A <- data.frame(id=c(1,2,3), value=c(1,2,3))
data_B <- data.frame(id=c(1,2,3,4), value=c(5,6,7,8))

# compare data frames by specific columns and keep only 
# the rows with equal values 
data_A[data_A$id %in% data_B$id,]   # will keep data in data_A
data_B[data_B$id %in% data_A$id,]   # will keep data in data_b

Results:

> data_A[data_A$id %in% data_B$id,]
  id value
1  1     1
2  2     2
3  3     3

> data_B[data_B$id %in% data_A$id,]
  id value
1  1     5
2  2     6
3  3     7

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

ORA-01882: timezone region not found

I ran into this problem with Tomcat. Setting the following in $CATALINA_BASE/bin/setenv.sh solved the issue:

JAVA_OPTS=-Doracle.jdbc.timezoneAsRegion=false

I'm sure that using one of the Java parameter suggestions from the other answers would work in the same way.

Disable mouse scroll wheel zoom on embedded Google Maps

Here is my simple solution.

Put your iframe in a div with a class called "maps" for example.

This will be the CSS for your iframe

.maps iframe { pointer-events: none }

And here is a little javascript that will set the pointer-events property of the iframe to "auto" when you hover the div element for at least 1 second (works best for me - set it to whatever you like) and clears the timeout/set it to "none" again when the mouse leaves the element.

var maptimer;

$(".maps").hover(function(){
    maptimer = setTimeout(function(){
        $(".maps").find("iframe").css("pointer-events", "auto");
    },1000);
},function(){
    clearTimeout(maptimer);
    $(".maps").find("iframe").css("pointer-events", "none");
});

Cheers.

How to import an existing directory into Eclipse?

These days, there's a better solution for importing an existing PHP project. The PDT plugin now has an option on the New PHP Project dialog just for this. So:

From File->New->PHP Project:

New PHP Project Dialog with "Create project at existing location" options badly circled

Google Authenticator available as a public service?

The algorithm is documented in RFC6238. Goes a bit like this:

  • your server gives the user a secret to install into Google Authenticator. Google do this as a QR code documented here.
  • Google Authenticator generates a 6 digit code by from a SHA1-HMAC of the Unix time and the secret (lots more detail on this in the RFC)
  • The server also knows the secret / unix time to verify the 6-digit code.

I've had a play implementing the algorithm in javascript here: http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/

UIView with rounded corners and drop shadow?

Old thread still current...

I've edited Daniel Gindi's method to make it possible to use it with buttons etc. as well. If anyone needs rounded corners or wants to combine round corners and a border it has to be set on the view's layer which is passed to this method. I've also set the rasterization to speed it up a little.

+ (UIView*)putView:(UIView*)view insideShadowWithColor:(CGColorRef)color 
                                 andRadius:(CGFloat)shadowRadius 
                                 andOffset:(CGSize)shadowOffset 
                                 andOpacity:(CGFloat)shadowOpacity
{
    // Must have same position like "view"
    UIView *shadow = [[UIView alloc] initWithFrame:view.frame]; 

    shadow.layer.contentsScale = [UIScreen mainScreen].scale;
    shadow.userInteractionEnabled = YES; // Modify this if needed
    shadow.layer.shadowColor = color;
    shadow.layer.shadowOffset = shadowOffset;
    shadow.layer.shadowRadius = shadowRadius;
    shadow.layer.masksToBounds = NO;
    shadow.clipsToBounds = NO;
    shadow.layer.shadowOpacity = shadowOpacity;
    shadow.layer.rasterizationScale = [UIScreen mainScreen].scale;
    shadow.layer.shouldRasterize = YES;

    [view.superview insertSubview:shadow belowSubview:view];
    [shadow addSubview:view];

    // Move view to the top left corner inside the shadowview 
    // ---> Buttons etc are working again :)
    view.frame = CGRectMake(0, 0, view.frame.size.width, view.frame.size.height);

    return shadow;
}

Passing arguments to C# generic new() of templated type

In order to create an instance of a generic type in a function you must constrain it with the "new" flag.

public static string GetAllItems<T>(...) where T : new()

However that will only work when you want to call the constructor which has no parameters. Not the case here. Instead you'll have to provide another parameter which allows for the creation of object based on parameters. The easiest is a function.

public static string GetAllItems<T>(..., Func<ListItem,T> del) {
  ...
  List<T> tabListItems = new List<T>();
  foreach (ListItem listItem in listCollection) 
  {
    tabListItems.Add(del(listItem));
  }
  ...
}

You can then call it like so

GetAllItems<Foo>(..., l => new Foo(l));

PHP header(Location: ...): Force URL change in address bar

Do not use any white space. I had the same issue. Then I removed white space like:

header("location:index.php"); or header('location:index.php');

Then it worked.

Getting datarow values into a string?

I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:

StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)     
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.

Create an array with same element repeated multiple times

If you need to repeat an array, use the following.

Array(3).fill(['a','b','c']).flat() 

will return

Array(9) [ "a", "b", "c", "a", "b", "c", "a", "b", "c" ]

Insert data using Entity Framework model

It should be:

context.TableName.AddObject(TableEntityInstance);

Where:

  1. TableName: the name of the table in the database.
  2. TableEntityInstance: an instance of the table entity class.

If your table is Orders, then:

Order order = new Order();
context.Orders.AddObject(order);

For example:

 var id = Guid.NewGuid();

 // insert
 using (var db = new EfContext("name=EfSample"))
 {
    var customers = db.Set<Customer>();
    customers.Add( new Customer { CustomerId = id, Name = "John Doe" } );

    db.SaveChanges();
 }

Here is a live example:

public void UpdatePlayerScreen(byte[] imageBytes, string installationKey)
{
  var player = (from p in this.ObjectContext.Players where p.InstallationKey == installationKey select p).FirstOrDefault();

  var current = (from d in this.ObjectContext.Screenshots where d.PlayerID == player.ID select d).FirstOrDefault();

  if (current != null)
  {
    current.Screen = imageBytes;
    current.Refreshed = DateTime.Now;

    this.ObjectContext.SaveChanges();
  }
  else
  {
    Screenshot screenshot = new Screenshot();

    screenshot.ID = Guid.NewGuid();
    screenshot.Interval = 1000;
    screenshot.IsTurnedOn = true;
    screenshot.PlayerID = player.ID;
    screenshot.Refreshed = DateTime.Now;
    screenshot.Screen = imageBytes;

    this.ObjectContext.Screenshots.AddObject(screenshot);
    this.ObjectContext.SaveChanges();
  }
}

How can I detect when the mouse leaves the window?

In order to detect mouseleave without taking in account the scroll bar and the autcomplete field or inspect :

document.addEventListener("mouseleave", function(event){

  if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
  {

     console.log("I'm out");

  }
});

Conditions explanations:

event.clientY <= 0  is when the mouse leave from the top
event.clientX <= 0  is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom

======================== EDIT ===============================

document.addEventListener("mouseleave") seems to be not fired on new firefox version, mouseleave need to be attached to an element like body, or a child element.

I suggest to use instead

document.body.addEventListener("mouseleave")

Or

window.addEventListener("mouseout")

How to select rows with NaN in particular column?

Try the following:

df[df['Col2'].isnull()]

Using an integer as a key in an associative array in JavaScript

Try using an Object, not an Array:

var test = new Object(); test[2300] = 'Some string';

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

Javascript - Open a given URL in a new tab by clicking a button

Open in new tab using javascript

 <button onclick="window.open('https://www.our-url.com')" id="myButton" 
 class="btn request-callback" >Explore More  </button>

get UTC timestamp in python with datetime

I feel like the main answer is still not so clear, and it's worth taking the time to understand time and timezones.

The most important thing to understand when dealing with time is that time is relative!

  • 2017-08-30 13:23:00: (a naive datetime), represents a local time somewhere in the world, but note that 2017-08-30 13:23:00 in London is NOT THE SAME TIME as 2017-08-30 13:23:00 in San Francisco.

Because the same time string can be interpreted as different points-in-time depending on where you are in the world, there is a need for an absolute notion of time.

A UTC timestamp is a number in seconds (or milliseconds) from Epoch (defined as 1 January 1970 00:00:00 at GMT timezone +00:00 offset).

Epoch is anchored on the GMT timezone and therefore is an absolute point in time. A UTC timestamp being an offset from an absolute time therefore defines an absolute point in time.

This makes it possible to order events in time.

Without timezone information, time is relative, and cannot be converted to an absolute notion of time without providing some indication of what timezone the naive datetime should be anchored to.

What are the types of time used in computer system?

  • naive datetime: usually for display, in local time (i.e. in the browser) where the OS can provide timezone information to the program.

  • UTC timestamps: A UTC timestamp is an absolute point in time, as mentioned above, but it is anchored in a given timezone, so a UTC timestamp can be converted to a datetime in any timezone, however it does not contain timezone information. What does that mean? That means that 1504119325 corresponds to 2017-08-30T18:55:24Z, or 2017-08-30T17:55:24-0100 or also 2017-08-30T10:55:24-0800. It doesn't tell you where the datetime recorded is from. It's usually used on the server side to record events (logs, etc...) or used to convert a timezone aware datetime to an absolute point in time and compute time differences.

  • ISO-8601 datetime string: The ISO-8601 is a standardized format to record datetime with timezone. (It's in fact several formats, read on here: https://en.wikipedia.org/wiki/ISO_8601) It is used to communicate timezone aware datetime information in a serializable manner between systems.

When to use which? or rather when do you need to care about timezones?

  • If you need in any way to care about time-of-day, you need timezone information. A calendar or alarm needs time-of-day to set a meeting at the correct time of the day for any user in the world. If this data is saved on a server, the server needs to know what timezone the datetime corresponds to.

  • To compute time differences between events coming from different places in the world, UTC timestamp is enough, but you lose the ability to analyze at what time of day events occured (ie. for web analytics, you may want to know when users come to your site in their local time: do you see more users in the morning or the evening? You can't figure that out without time of day information.

Timezone offset in a date string:

Another point that is important, is that timezone offset in a date string is not fixed. That means that because 2017-08-30T10:55:24-0800 says the offset -0800 or 8 hours back, doesn't mean that it will always be!

In the summer it may well be in daylight saving time, and it would be -0700

What that means is that timezone offset (+0100) is not the same as timezone name (Europe/France) or even timezone designation (CET)

America/Los_Angeles timezone is a place in the world, but it turns into PST (Pacific Standard Time) timezone offset notation in the winter, and PDT (Pacific Daylight Time) in the summer.

So, on top of getting the timezone offset from the datestring, you should also get the timezone name to be accurate.

Most packages will be able to convert numeric offsets from daylight saving time to standard time on their own, but that is not necessarily trivial with just offset. For example WAT timezone designation in West Africa, is UTC+0100 just like CET timezone in France, but France observes daylight saving time, while West Africa does not (because they're close to the equator)

So, in short, it's complicated. VERY complicated, and that's why you should not do this yourself, but trust a package that does it for you, and KEEP IT UP TO DATE!

What causes javac to issue the "uses unchecked or unsafe operations" warning

The "unchecked or unsafe operations" warning was added when java added Generics, if I remember correctly. It's usually asking you to be more explicit about types, in one way or another.

For example. the code ArrayList foo = new ArrayList(); triggers that warning because javac is looking for ArrayList<String> foo = new ArrayList<String>();

AngularJS not detecting Access-Control-Allow-Origin header?

I experienced this exact same issue. For me, the OPTIONS request would go through, but the POST request would say "aborted." This led me to believe that the browser was never making the POST request at all. Chrome said something like "Caution provisional headers are shown" in the request headers but no response headers were shown. In the end I turned to debugging on Firefox which led me to find out my server was responding with an error and no CORS headers were present on the response. Chrome was actually receiving the response, but not allowing the response to be shown in the network view.

How to add hyperlink in JLabel?

Use a JEditorPane with a HyperlinkListener.

How to check if any Checkbox is checked in Angular

Try to think in terms of a model and what happens to that model when a checkbox is checked.

Assuming that each checkbox is bound to a field on the model with ng-model then the property on the model is changed whenever a checkbox is clicked:

<input type='checkbox' ng-model='fooSelected' />
<input type='checkbox' ng-model='baaSelected' />

and in the controller:

$scope.fooSelected = false;
$scope.baaSelected = false;

The next button should only be available under certain circumstances so add the ng-disabled directive to the button:

<button type='button' ng-disabled='nextButtonDisabled'></button>

Now the next button should only be available when either fooSelected is true or baaSelected is true and we need to watch any changes to these fields to make sure that the next button is made available or not:

$scope.$watch('[fooSelected,baaSelected]', function(){
    $scope.nextButtonDisabled = !$scope.fooSelected && !scope.baaSelected;
}, true );

The above assumes that there are only a few checkboxes that affect the availability of the next button but it could be easily changed to work with a larger number of checkboxes and use $watchCollection to check for changes.

How to check if a float value is a whole number

You could use this:

if k == int(k):
    print(str(k) + " is a whole number!")

Create timestamp variable in bash script

In order to get the current timestamp and not the time of when a fixed variable is defined, the trick is to use a function and not a variable:

#!/bin/bash

# Define a timestamp function
timestamp() {
  date +"%T" # current time
}

# do something...
timestamp # print timestamp
# do something else...
timestamp # print another timestamp
# continue...

If you don't like the format given by the %T specifier you can combine the other time conversion specifiers accepted by date. For GNU date, you can find the complete list of these specifiers in the official documentation here: https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers

How to break a while loop from an if condition inside the while loop?

The break keyword does exactly that. Here is a contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}

If you were actually using nested loops, you would be able to use labels.

SQL Server : converting varchar to INT

I would try triming the number to see what you get:

select len(rtrim(ltrim(userid))) from audit

if that return the correct value then just do:

select convert(int, rtrim(ltrim(userid))) from audit

if that doesn't return the correct value then I would do a replace to remove the empty space:

 select convert(int, replace(userid, char(0), '')) from audit

How to add pandas data to an existing csv file?

A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
     file_to=open(path,mode)
     yield file_to
     file_to.close()


##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
      saved_df.to_csv('yourcsv.csv',mode='a',header=False)`

Why is Visual Studio 2010 not able to find/open PDB files?

Referring to the first thread / another possibility VS cant open or find pdb file of the process is when you have your executable running in the background. I was working with mpiexec and ran into this issue. Always check your task manager and kill any exec process that your gonna build in your project. Once I did that, it debugged or built fine.

Also, if you try to continue with the warning , the breakpoints would not be hit and it would not have the current executable

Passing 'this' to an onclick event

You can always call funciton differently: foo.call(this); in this way you will be able to use this context inside the function.

Example:

<button onclick="foo.call(this)" id="bar">Button</button>?

var foo = function()
{
    this.innerHTML = "Not a button";
};

How do I initialize Kotlin's MutableList to empty MutableList?

You can simply write:

val mutableList = mutableListOf<Kolory>()

This is the most idiomatic way.

Alternative ways are

val mutableList : MutableList<Kolory> = arrayListOf()

or

val mutableList : MutableList<Kolory> = ArrayList()

This is exploiting the fact that java types like ArrayList are implicitly implementing the type MutableList via a compiler trick.

How to write some data to excel file(.xlsx)

You can use ClosedXML for this.

Store your table in a DataTable and you can export the table to excel by this simple snippet:

XLWorkbook workbook = new XLWorkbook();
DataTable table = GetYourTable();
workbook.Worksheets.Add(table );

You can read the documentation of ClosedXML to learn more. Hope this helps!

How to escape regular expression special characters using javascript?

Use the \ character to escape a character that has special meaning inside a regular expression.

To automate it, you could use this:

function escapeRegExp(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
}

Update: There is now a proposal to standardize this method, possibly in ES2016: https://github.com/benjamingr/RegExp.escape

Update: The abovementioned proposal was rejected, so keep implementing this yourself if you need it.

How to test android apps in a real device with Android Studio?

I can run on my device at last, just I enabled the "USB debugging" and "Allow mock location" options from the Debug Menu of my device.

Find a class somewhere inside dozens of JAR files?

Filename: searchForFiles.py

import os, zipfile, glob, sys

def main():
    searchFile = sys.argv[1] #class file to search for, sent from batch file below (optional, see second block of code below)
    listOfFilesInJar = []
    for file in glob.glob("*.jar"):
        archive = zipfile.ZipFile(file, 'r')
        for x in archive.namelist():
            if str(searchFile) in str(x):
                listOfFilesInJar.append(file)

    for something in listOfFilesInJar:
        print("location of "+str(searchFile)+": ",something)

if __name__ == "__main__":
    sys.exit(main())

You can easily run this by making a .bat file with the following text (replace "AddWorkflows.class" with the file you are searching for):

(File: CallSearchForFiles.bat)

@echo off
python -B -c "import searchForFiles;x=searchForFiles.main();" AddWorkflows.class
pause

You can double-click CallSearchForFiles.bat to run it, or call it from the command line "CallSearchForFiles.bat SearchFile.class"

Click to See Example Output

ASP.NET Core 1.0 on IIS error 502.5

I had the same problem when I updated my dev machine to Core 1.0.1, but forgot to update the server.

No Spring WebApplicationInitializer types detected on classpath

tomcat-maven-plugin in test

Tomcat usually does not add classes in src/test/java to the classpath. They are missing if you run tomcat in scope test. To order tomcat to respect classes in test, use -Dmaven.tomcat.useTestClasspath=true or add

<properties>
   <maven.tomcat.useTestClasspath>true</maven.tomcat.useTestClasspath>
</properties>

To your pom.xml.

100% Min Height CSS layout

Try this:

body{ height: 100%; }
#content { 
    min-height: 500px;
    height: 100%;
}
#footer {
    height: 100px;
    clear: both !important;
}

The div element below the content div must have clear:both.

What is the difference between `let` and `var` in swift?

let keyword defines a constant

let myNum = 7

so myNum can't be changed afterwards;

But var defines an ordinary variable.

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.

You can use almost any character you like for constant and variable names, including Unicode characters;

e.g.

var x = 7 // here x is instantiated with 7 
x = 99 // now x is 99 it means it has been changed.

But if we take let then...

let x = 7 // here also x is instantiated with 7 
x = 99 // this will a compile time error

Select all 'tr' except the first one

Sorry I know this is old but why not style all tr elements the way you want all except the first and the use the psuedo class :first-child where you revoke what you specified for all tr elements.

Better descriped by this example:

http://jsfiddle.net/DWTr7/1/

tr {
    border-top: 1px solid;
}
tr:first-child {
    border-top: none;   
}

/Patrik

How do you check if a selector matches something in jQuery?

For me .exists doesn't work, so I use the index :

if ($("#elem").index() ! = -1) {}

Illegal pattern character 'T' when parsing a date string to java.util.Date

Update for Java 8 and higher

You can now simply do Instant.parse("2015-04-28T14:23:38.521Z") and get the correct thing now, especially since you should be using Instant instead of the broken java.util.Date with the most recent versions of Java.

You should be using DateTimeFormatter instead of SimpleDateFormatter as well.

Original Answer:

The explanation below is still valid as as what the format represents. But it was written before Java 8 was ubiquitous so it uses the old classes that you should not be using if you are using Java 8 or higher.

This works with the input with the trailing Z as demonstrated:

In the pattern the T is escaped with ' on either side.

The pattern for the Z at the end is actually XXX as documented in the JavaDoc for SimpleDateFormat, it is just not very clear on actually how to use it since Z is the marker for the old TimeZone information as well.

Q2597083.java

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Q2597083
{
    /**
     * All Dates are normalized to UTC, it is up the client code to convert to the appropriate TimeZone.
     */
    public static final TimeZone UTC;

    /**
     * @see <a href="http://en.wikipedia.org/wiki/ISO_8601#Combined_date_and_time_representations">Combined Date and Time Representations</a>
     */
    public static final String ISO_8601_24H_FULL_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    /**
     * 0001-01-01T00:00:00.000Z
     */
    public static final Date BEGINNING_OF_TIME;

    /**
     * 292278994-08-17T07:12:55.807Z
     */
    public static final Date END_OF_TIME;

    static
    {
        UTC = TimeZone.getTimeZone("UTC");
        TimeZone.setDefault(UTC);
        final Calendar c = new GregorianCalendar(UTC);
        c.set(1, 0, 1, 0, 0, 0);
        c.set(Calendar.MILLISECOND, 0);
        BEGINNING_OF_TIME = c.getTime();
        c.setTime(new Date(Long.MAX_VALUE));
        END_OF_TIME = c.getTime();
    }

    public static void main(String[] args) throws Exception
    {

        final SimpleDateFormat sdf = new SimpleDateFormat(ISO_8601_24H_FULL_FORMAT);
        sdf.setTimeZone(UTC);
        System.out.println("sdf.format(BEGINNING_OF_TIME) = " + sdf.format(BEGINNING_OF_TIME));
        System.out.println("sdf.format(END_OF_TIME) = " + sdf.format(END_OF_TIME));
        System.out.println("sdf.format(new Date()) = " + sdf.format(new Date()));
        System.out.println("sdf.parse(\"2015-04-28T14:23:38.521Z\") = " + sdf.parse("2015-04-28T14:23:38.521Z"));
        System.out.println("sdf.parse(\"0001-01-01T00:00:00.000Z\") = " + sdf.parse("0001-01-01T00:00:00.000Z"));
        System.out.println("sdf.parse(\"292278994-08-17T07:12:55.807Z\") = " + sdf.parse("292278994-08-17T07:12:55.807Z"));
    }
}

Produces the following output:

sdf.format(BEGINNING_OF_TIME) = 0001-01-01T00:00:00.000Z
sdf.format(END_OF_TIME) = 292278994-08-17T07:12:55.807Z
sdf.format(new Date()) = 2015-04-28T14:38:25.956Z
sdf.parse("2015-04-28T14:23:38.521Z") = Tue Apr 28 14:23:38 UTC 2015
sdf.parse("0001-01-01T00:00:00.000Z") = Sat Jan 01 00:00:00 UTC 1
sdf.parse("292278994-08-17T07:12:55.807Z") = Sun Aug 17 07:12:55 UTC 292278994

How do I fix this "TypeError: 'str' object is not callable" error?

You are trying to use the string as a function:

"Your new price is: $"(float(price) * 0.1)

Because there is nothing between the string literal and the (..) parenthesis, Python interprets that as an instruction to treat the string as a callable and invoke it with one argument:

>>> "Hello World!"(42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

Seems you forgot to concatenate (and call str()):

easygui.msgbox("Your new price is: $" + str(float(price) * 0.1))

The next line needs fixing as well:

easygui.msgbox("Your new price is: $" + str(float(price) * 0.2))

Alternatively, use string formatting with str.format():

easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.1))
easygui.msgbox("Your new price is: ${:.2f}".format(float(price) * 0.2))

where {:02.2f} will be replaced by your price calculation, formatting the floating point value as a value with 2 decimals.

How do I scroll the UIScrollView when the keyboard appears?

I know it's an old question now but i thought it might help others. I wanted something a little easier to implement for a few apps i had, so i made a class for this. You can download it here if you want: https://github.com/sdernley/iOSTextFieldHandler

It's as simple as setting all of the UITextFields to have a delegate of self

textfieldname.delegate = self;

And then adding this to your view controller with the name of your scrollView and submit button

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [iOSTextFieldHandler TextboxKeyboardMover:containingScrollView tf:textField btn:btnSubmit];
}

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I had a problem with this. I didn't use any clever $MyInvocation stuff to fix it though. If you open the ISE by right clicking a script file and selecting edit then open the second script from within the ISE you can invoke one from the other by just using the normal .\script.ps1 syntax. My guess is that the ISE has the notion of a current folder and opening it like this sets the current folder to the folder containing the scripts. When I invoke one script from another in normal use I just use .\script.ps1, IMO it's wrong to modify the script just to make it work in the ISE properly...

What is size_t in C?

size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.

When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, following program would definitely give the unexpected result:

// C program to demonstrate that size_t or
// any unsigned int type should be used 
// carefully when used in a loop

#include<stdio.h>
int main()
{
const size_t N = 10;
int a[N];

// This is fine
for (size_t n = 0; n < N; ++n)
a[n] = n;

// But reverse cycles are tricky for unsigned 
// types as can lead to infinite loop
for (size_t n = N-1; n >= 0; --n)
printf("%d ", a[n]);
}

Output
Infinite loop and then segmentation fault

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

What is the max size of VARCHAR2 in PL/SQL and SQL?

As per official documentation link shared by Andre Kirpitch, Oracle 10g gives a maximum size of 4000 bytes or characters for varchar2. If you are using a higher version of oracle (for example Oracle 12c), you can get a maximum size upto 32767 bytes or characters for varchar2. To utilize the extended datatype feature of oracle 12, you need to start oracle in upgrade mode. Follow the below steps in command prompt:

1) Login as sysdba (sqlplus / as sysdba)

2) SHUTDOWN IMMEDIATE;

3) STARTUP UPGRADE;

4) ALTER SYSTEM SET max_string_size=extended;

5) Oracle\product\12.1.0.2\rdbms\admin\utl32k.sql

6) SHUTDOWN IMMEDIATE;

7) STARTUP;

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

In the HTTP request case, it is also and alternatively possible to paste the credentials (with password) directly into the url:

http://username:[email protected]/...

This will save the pain to give your credentials every times again. Simple modify your .git/config (the url).

maximum value of int

Here is a macro I use to get the maximum value for signed integers, which is independent of the size of the signed integer type used, and for which gcc -Woverflow won't complain

#define SIGNED_MAX(x) (~(-1 << (sizeof(x) * 8 - 1)))

int a = SIGNED_MAX(a);
long b = SIGNED_MAX(b);
char c = SIGNED_MAX(c); /* if char is signed for this target */
short d = SIGNED_MAX(d);
long long e = SIGNED_MAX(e);

recyclerview No adapter attached; skipping layout

i have this problem , a few time problem is recycleView put in ScrollView object

After checking implementation, the reason appears to be the following. If RecyclerView gets put into a ScrollView, then during measure step its height is unspecified (because ScrollView allows any height) and, as a result, gets equal to minimum height (as per implementation) which is apparently zero.

You have couple of options for fixing this:

  1. Set a certain height to RecyclerView
  2. Set ScrollView.fillViewport to true
  3. Or keep RecyclerView outside of ScrollView. In my opinion, this is the best option by far. If RecyclerView height is not limited - which is the case when it's put into ScrollView - then all Adapter's views have enough place vertically and get created all at once. There is no view recycling anymore which kinda breaks the purpose of RecyclerView .

(Can be followed for android.support.v4.widget.NestedScrollView as well)

Assign a variable inside a Block to a variable outside a Block

To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-

__block Person *aPerson = nil;

Error: The 'brew link' step did not complete successfully

Had been wrecking my head on symlinking node .. and nothing seemed to work...but finally what worked is setting the right permissions . This 'sudo chown -R $(whoami) /usr/local' did the work for me.

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

I had the same problem and I solved it with the following steps

  1. Help > Install New Software...
  2. Select "Eclipse Web Tools Platform Repository (http://download.eclipse.org/webtools/updates)" from the "Work with" drop-down.
  3. Select "Web Tools Platform (WTP)" and "Project Provided Components".

Complete all the installation steps and restart Eclipse. You'll see a bunch of servers when you try to add a server runtime environment.

Get individual query parameters from Uri

You can use:

var queryString = url.Substring(url.IndexOf('?')).Split('#')[0]
System.Web.HttpUtility.ParseQueryString(queryString)

MSDN

SQL query return data from multiple tables

Part 2 - Subqueries

Okay, now the boss has burst in again - I want a list of all of our cars with the brand and a total of how many of that brand we have!

This is a great opportunity to use the next trick in our bag of SQL goodies - the subquery. If you are unfamiliar with the term, a subquery is a query that runs inside another query. There are many different ways to use them.

For our request, lets first put a simple query together that will list each car and the brand:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID

Now, if we wanted to simply get a count of cars sorted by brand, we could of course write this:

select
    b.brand,
    count(a.ID) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID
group by
    b.brand

+--------+-----------+
| brand  | countCars |
+--------+-----------+
| BMW    |         2 |
| Ford   |         2 |
| Nissan |         1 |
| Smart  |         1 |
| Toyota |         5 |
+--------+-----------+

So, we should be able to simply add in the count function to our original query right?

select
    a.ID,
    b.brand,
    count(a.ID) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID
group by
    a.ID,
    b.brand

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  1 | Toyota |         1 |
|  2 | Ford   |         1 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  5 | Toyota |         1 |
|  6 | BMW    |         1 |
|  7 | Ford   |         1 |
|  8 | Toyota |         1 |
|  9 | Toyota |         1 |
| 10 | BMW    |         1 |
| 11 | Toyota |         1 |
+----+--------+-----------+
11 rows in set (0.00 sec)

Sadly, no, we can't do that. The reason is that when we add in the car ID (column a.ID) we have to add it into the group by - so now, when the count function works, there is only one ID matched per ID.

This is where we can however use a subquery - in fact we can do two completely different types of subquery that will return the same results that we need for this. The first is to simply put the subquery in the select clause. This means each time we get a row of data, the subquery will run off, get a column of data and then pop it into our row of data.

select
    a.ID,
    b.brand,
    (
    select
        count(c.ID)
    from
        cars c
    where
        a.brand=c.brand
    ) as countCars
from
    cars a
        join brands b
            on a.brand=b.ID

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  2 | Ford   |         2 |
|  7 | Ford   |         2 |
|  1 | Toyota |         5 |
|  5 | Toyota |         5 |
|  8 | Toyota |         5 |
|  9 | Toyota |         5 |
| 11 | Toyota |         5 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  6 | BMW    |         2 |
| 10 | BMW    |         2 |
+----+--------+-----------+
11 rows in set (0.00 sec)

And Bam!, this would do us. If you noticed though, this sub query will have to run for each and every single row of data we return. Even in this little example, we only have five different Brands of car, but the subquery ran eleven times as we have eleven rows of data that we are returning. So, in this case, it doesn't seem like the most efficient way to write code.

For a different approach, lets run a subquery and pretend it is a table:

select
    a.ID,
    b.brand,
    d.countCars
from
    cars a
        join brands b
            on a.brand=b.ID
        join
            (
            select
                c.brand,
                count(c.ID) as countCars
            from
                cars c
            group by
                c.brand
            ) d
            on a.brand=d.brand

+----+--------+-----------+
| ID | brand  | countCars |
+----+--------+-----------+
|  1 | Toyota |         5 |
|  2 | Ford   |         2 |
|  3 | Nissan |         1 |
|  4 | Smart  |         1 |
|  5 | Toyota |         5 |
|  6 | BMW    |         2 |
|  7 | Ford   |         2 |
|  8 | Toyota |         5 |
|  9 | Toyota |         5 |
| 10 | BMW    |         2 |
| 11 | Toyota |         5 |
+----+--------+-----------+
11 rows in set (0.00 sec)

Okay, so we have the same results (ordered slightly different - it seems the database wanted to return results ordered by the first column we picked this time) - but the same right numbers.

So, what's the difference between the two - and when should we use each type of subquery? First, lets make sure we understand how that second query works. We selected two tables in the from clause of our query, and then wrote a query and told the database that it was in fact a table instead - which the database is perfectly happy with. There can be some benefits to using this method (as well as some limitations). Foremost is that this subquery ran once. If our database contained a large volume of data, there could well be a massive improvement over the first method. However, as we are using this as a table, we have to bring in extra rows of data - so that they can actually be joined back to our rows of data. We also have to be sure that there are enough rows of data if we are going to use a simple join like in the query above. If you recall, the join will only pull back rows that have matching data on both sides of the join. If we aren't careful, this could result in valid data not being returned from our cars table if there wasn't a matching row in this subquery.

Now, looking back at the first subquery, there are some limitations as well. because we are pulling data back into a single row, we can ONLY pull back one row of data. Subqueries used in the select clause of a query very often use only an aggregate function such as sum, count, max or another similar aggregate function. They don't have to, but that is often how they are written.

So, before we move on, lets have a quick look at where else we can use a subquery. We can use it in the where clause - now, this example is a little contrived as in our database, there are better ways of getting the following data, but seeing as it is only for an example, lets have a look:

select
    ID,
    brand
from
    brands
where
    brand like '%o%'

+----+--------+
| ID | brand  |
+----+--------+
|  1 | Ford   |
|  2 | Toyota |
|  6 | Holden |
+----+--------+
3 rows in set (0.00 sec)

This returns us a list of brand IDs and Brand names (the second column is only added to show us the brands) that contain the letter o in the name.

Now, we could use the results of this query in a where clause this:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID
where
    a.brand in
        (
        select
            ID
        from
            brands
        where
            brand like '%o%'
        )

+----+--------+
| ID | brand  |
+----+--------+
|  2 | Ford   |
|  7 | Ford   |
|  1 | Toyota |
|  5 | Toyota |
|  8 | Toyota |
|  9 | Toyota |
| 11 | Toyota |
+----+--------+
7 rows in set (0.00 sec)

As you can see, even though the subquery was returning the three brand IDs, our cars table only had entries for two of them.

In this case, for further detail, the subquery is working as if we wrote the following code:

select
    a.ID,
    b.brand
from
    cars a
        join brands b
            on a.brand=b.ID
where
    a.brand in (1,2,6)

+----+--------+
| ID | brand  |
+----+--------+
|  1 | Toyota |
|  2 | Ford   |
|  5 | Toyota |
|  7 | Ford   |
|  8 | Toyota |
|  9 | Toyota |
| 11 | Toyota |
+----+--------+
7 rows in set (0.00 sec)

Again, you can see how a subquery vs manual inputs has changed the order of the rows when returning from the database.

While we are discussing subqueries, lets see what else we can do with a subquery:

  • You can place a subquery within another subquery, and so on and so on. There is a limit which depends on your database, but short of recursive functions of some insane and maniacal programmer, most folks will never hit that limit.
  • You can place a number of subqueries into a single query, a few in the select clause, some in the from clause and a couple more in the where clause - just remember that each one you put in is making your query more complex and likely to take longer to execute.

If you need to write some efficient code, it can be beneficial to write the query a number of ways and see (either by timing it or by using an explain plan) which is the optimal query to get your results. The first way that works may not always be the best way of doing it.

How to set IE11 Document mode to edge as default?

I've come across this problem myself. In my case, resetting IE was the quickest solution to the problem:

http://support.microsoft.com/kb/923737

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

Any logic having to do with what is displayed in the view should be delegated to a helper method, as methods in the model are strictly for handling data.

Here is what you could do:

# In the helper...

def link_to_thing(text, thing)
  (thing.url?) ? link_to(text, thing_path(thing)) : link_to(text, thing.url)
end

# In the view...

<%= link_to_thing("text", @thing) %>

Can't create project on Netbeans 8.2

As the other people said, NetBeans is always going to use the latest version of JDK installed (currently JDK9) which is not working with NetBeans 8.2 and is causing problems as you guys mentioned.

You can solve this problem by forcing NetBeans to use JDK8 instead of deleting JDK9!
You just have to edit netbeans.conf file:
MacOS /Applications/NetBeans/NetBeans8.2.app/Contents/Resources/NetBeans/etc
Windows C:\Program Files\NetBeans 8.2\etc\

Open netbeans.conf with your favourite editor and find this line: netbeans_jdkhome="/path/to/jdk" Remove # sign in front of it and modify it by typing your desired JDK version (JDK8) home location.

Im not sure why is JDK9 not working with NetBeans8.2, but if I found out I will write it here...


Default JDK locations:

Mac OS ?

/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

Windows ?

C:\Program Files\Java\jdk1.8.0_152

I've used jdk1.8.0_152 as example

When to use reinterpret_cast?

The C++ standard guarantees the following:

static_casting a pointer to and from void* preserves the address. That is, in the following, a, b and c all point to the same address:

int* a = new int();
void* b = static_cast<void*>(a);
int* c = static_cast<int*>(b);

reinterpret_cast only guarantees that if you cast a pointer to a different type, and then reinterpret_cast it back to the original type, you get the original value. So in the following:

int* a = new int();
void* b = reinterpret_cast<void*>(a);
int* c = reinterpret_cast<int*>(b);

a and c contain the same value, but the value of b is unspecified. (in practice it will typically contain the same address as a and c, but that's not specified in the standard, and it may not be true on machines with more complex memory systems.)

For casting to and from void*, static_cast should be preferred.

Getting Git to work with a proxy server - fails with "Request timed out"

I have tried all the above answers and nothing worked for me, as there was a proxy password encoding issues.

This command worked:

git config --global http.proxy http://[email protected]:PortNumber 

Do not enter the password in your command. It will dynamically ask for when you try to connect to any git repo.

How to replace all occurrences of a string in Javascript?

//loop it until number occurrences comes to 0. OR simply copy/paste

    function replaceAll(find, replace, str) 
    {
      while( str.indexOf(find) > -1)
      {
        str = str.replace(find, replace);
      }
      return str;
    }

Boolean.parseBoolean("1") = false...?

If you're trying to get C's behavior (0 == false and everything else is true), you could do this:

boolean uses_votes = Integer.parseInt(o.get("uses_votes")) != 0;

Shorten string without cutting words in JavaScript

we can do this easily by using truncate function of lodash

_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
 });
// => 'hi-diddly-ho there,...'

go on Lodash Documentation for more clearence.