Programs & Examples On #Uncrustify

Source Code Beautifier for C, C++, C#, ObjectiveC, D, Java, Pawn and VALA

Git blame -- prior commits?

Build on stangls's answer, I put this script in my PATH (even on Windows) as git-bh:

That allows me to look for all commits where a word was involved:

git bh path/to/myfile myWord

Script:

#!/bin/bash
f=$1
shift
csha=""
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    res=$(git blame -L"/$1/",+1 $hash -- "$f" 2>/dev/null | sed 's/^/  /')
    sha=${res%% (*}
    if [[ "${res}" != "" && "${csha}" != "${sha}" ]]; then
      echo "--- ${hash}"
      echo "${res}"
      csha="${sha}"
    fi
  done
}

socket connect() vs bind()

To make understanding better , lets find out where exactly bind and connect comes into picture,

Further to positioning of two calls , as clarified by Sourav,

bind() associates the socket with its local address [that's why server side binds, so that clients can use that address to connect to server.] connect() is used to connect to a remote [server] address, that's why is client side, connect [read as: connect to server] is used.

We cannot use them interchangeably (even when we have client/server on same machine) because of specific roles and corresponding implementation.

I will further recommend to correlate these calls TCP/IP handshake .

enter image description here

So , who will send SYN here , it will be connect() . While bind() is used for defining the communication end point.

Hope this helps!!

Make view 80% width of parent in React Native

You can also try react-native-extended-stylesheet that supports percentage for single-orientation apps:

import EStyleSheet from 'react-native-extended-stylesheet';

const styles = EStyleSheet.create({
  column: {
    width: '80%',
    height: '50%',
    marginLeft: '10%'
  }
});

Update date + one year in mysql

You could use DATE_ADD : (or ADDDATE with INTERVAL)

UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR) 

How can I get the last 7 characters of a PHP string?

Safer results for working with multibyte character codes, allways use mb_substr instead substr. Example for utf-8:

$str = 'Ne zaman seni düsünsem';
echo substr( $str, -7 ) . ' <strong>is not equal to</strong> ' .
  mb_substr( $str, -7, null, 'UTF-8') ;

Using :focus to style outer div?

DIV elements can get focus if set the tabindex attribute. Here is the working example.

_x000D_
_x000D_
#focus-example > .extra {_x000D_
  display: none;_x000D_
}_x000D_
#focus-example:focus > .extra {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="focus-example" tabindex="0">_x000D_
  <div>Focus me!</div>_x000D_
  <div class="extra">Hooray!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

For more information about focus and blur, you can check out this article.

Update: And here is another example using focus to create a menu.

_x000D_
_x000D_
#toggleMenu:focus {_x000D_
  outline: none;_x000D_
}_x000D_
button:focus + .menu {_x000D_
  display: block;_x000D_
}_x000D_
.menu {_x000D_
  display: none;_x000D_
}_x000D_
.menu:focus {_x000D_
  display: none;_x000D_
}
_x000D_
<div id="toggleMenu" tabindex="0">_x000D_
  <button type="button">Menu</button>_x000D_
  <ul class="menu" tabindex="1">_x000D_
    <li>Home</li>_x000D_
    <li>About Me</li>_x000D_
    <li>Contacts</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I have linebreaks in my long LaTeX equations?

Use eqnarray and \nonumber

example:

\begin{eqnarray}
    sample = R(s,\pi(s),s') + \gamma V^{\pi} (s') \nonumber \\
    \label{eq:temporal-difference}
     V^{\pi}_{k+1}(s) = (1-\alpha)V^{\pi}(s) - \alpha[sample]
\end{eqnarray}

Excel VBA - Sum up a column

I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.

Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))

How to check if matching text is found in a string in Lua?

There are 2 options to find matching text; string.match or string.find.

Both of these perform a regex search on the string to find matches.


string.find()

string.find(subject string, pattern string, optional start position, optional plain flag)

Returns the startIndex & endIndex of the substring found.

The plain flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger) being interpreted as a regex capture group matching for tiger, it instead looks for (tiger) within a string.

Going the other way, if you want to regex match but still want literal special characters (such as .()[]+- etc.), you can escape them with a percentage; %(tiger%).

You will likely use this in combination with string.sub

Example

str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

string.match()

string.match(s, pattern, optional index)

Returns the capture groups found.

Example

str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
  print ("The word tiger was found.")
else
  print ("The word tiger was not found.")
end

Use of *args and **kwargs

One case where *args and **kwargs are useful is when writing wrapper functions (such as decorators) that need to be able accept arbitrary arguments to pass through to the function being wrapped. For example, a simple decorator that prints the arguments and return value of the function being wrapped:

def mydecorator( f ):
   @functools.wraps( f )
   def wrapper( *args, **kwargs ):
      print "Calling f", args, kwargs
      v = f( *args, **kwargs )
      print "f returned", v
      return v
   return wrapper

Can I change the viewport meta tag in mobile safari on the fly?

I realize this is a little old, but, yes it can be done. Some javascript to get you started:

viewport = document.querySelector("meta[name=viewport]");
viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0');

Just change the parts you need and Mobile Safari will respect the new settings.

Update:

If you don't already have the meta viewport tag in the source, you can append it directly with something like this:

var metaTag=document.createElement('meta');
metaTag.name = "viewport"
metaTag.content = "width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"
document.getElementsByTagName('head')[0].appendChild(metaTag);

Or if you're using jQuery:

$('head').append('<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">');

RecyclerView vs. ListView

  1. You can use an interface to provide a click listener. I use this technique with ListViews, too.
  2. No divider: Simply add in your row a View with a width of match_parent and a height of 1dp and give it a background color.
  3. Simply use a StateList selector for the row background.
  4. addHeaderView can be avoided in ListViews, too: simply put the Header outside the View.

So, if efficiency is your concern, then yes, it's a good idea to replace a ListView with a RecyclerView.

Laravel whereIn OR whereIn

$query = DB::table('dms_stakeholder_permissions');
$query->select(DB::raw('group_concat(dms_stakeholder_permissions.fid) as fid'),'dms_stakeholder_permissions.rights');
$query->where('dms_stakeholder_permissions.stakeholder_id','4');
$query->orWhere(function($subquery)  use ($stakeholderId){
            $subquery->where('dms_stakeholder_permissions.stakeholder_id',$stakeholderId);
            $subquery->whereIn('dms_stakeholder_permissions.rights',array('1','2','3'));
    });

 $result = $query->get();

return $result;

// OUTPUT @input $stakeholderId = 1

//select group_concat(dms_stakeholder_permissions.fid) as fid, dms_stakeholder_permissionss.rights from dms_stakeholder_permissions where dms_stakeholder_permissions.stakeholder_id = 4 or (dms_stakeholder_permissions.stakeholder_id = 1 and dms_stakeholder_permissions.rights in (1, 2, 3))

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

For Swift 3

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

For Swift 4

let imageDataDict:[String: UIImage] = ["image": image]

  // post a notification
  NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
  // `default` is now a property, not a method call

 // Register to receive notification in your class
 NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

 // handle notification
 @objc func showSpinningWheel(_ notification: NSNotification) {
        print(notification.userInfo ?? "")
        if let dict = notification.userInfo as NSDictionary? {
            if let id = dict["image"] as? UIImage{
                // do something with your image
            }
        }
 }

Change CSS properties on click

    <script>
        function change_css(){
            document.getElementById('result').style.cssText = 'padding:20px; background-color:#b2b2ff; color:#0c0800; border:1px solid #0c0800; font-size:22px;';
        }
    </script>

</head>

<body>
    <center>
        <div id="error"></div>
        <center>
            <div id="result"><h2> Javascript Example On click Change Css style</h2></div>
            <button onclick="change_css();">Check</button><br />
        </center>
    </center>
</body>

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

This worked for me...

  1. I deleted the Entitlements file from the target.
  2. Deleted the app off all my devices
  3. Cleaned the build in Xcode
  4. *optional delete the provisioning profile and re-add it

Hope it works for you guys too :)

JUnit: how to avoid "no runnable methods" in test utils classes

What about adding an empty test method to these classes?

public void avoidAnnoyingErrorMessageWhenRunningTestsInAnt() {
    assertTrue(true); // do nothing;
}

How do you close/hide the Android soft keyboard using Java?

If you want to hide keyboard using Java code, then use this:

  InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);

Or if you want to hide the keyboard always, then use this in your AndroidManifest:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />

What is the difference between canonical name, simple name and class name in Java Class?

I've been confused by the wide range of different naming schemes as well, and was just about to ask and answer my own question on this when I found this question here. I think my findings fit it well enough, and complement what's already here. My focus is looking for documentation on the various terms, and adding some more related terms that might crop up in other places.

Consider the following example:

package a.b;
class C {
  static class D extends C {
  }
  D d;
  D[] ds;
}
  • The simple name of D is D. That's just the part you wrote when declaring the class. Anonymous classes have no simple name. Class.getSimpleName() returns this name or the empty string. It is possible for the simple name to contain a $ if you write it like this, since $ is a valid part of an identifier as per JLS section 3.8 (even if it is somewhat discouraged).

  • According to the JLS section 6.7, both a.b.C.D and a.b.C.D.D.D would be fully qualified names, but only a.b.C.D would be the canonical name of D. So every canonical name is a fully qualified name, but the converse is not always true. Class.getCanonicalName() will return the canonical name or null.

  • Class.getName() is documented to return the binary name, as specified in JLS section 13.1. In this case it returns a.b.C$D for D and [La.b.C$D; for D[].

  • This answer demonstrates that it is possible for two classes loaded by the same class loader to have the same canonical name but distinct binary names. Neither name is sufficient to reliably deduce the other: if you have the canonical name, you don't know which parts of the name are packages and which are containing classes. If you have the binary name, you don't know which $ were introduced as separators and which were part of some simple name. (The class file stores the binary name of the class itself and its enclosing class, which allows the runtime to make this distinction.)

  • Anonymous classes and local classes have no fully qualified names but still have a binary name. The same holds for classes nested inside such classes. Every class has a binary name.

  • Running javap -v -private on a/b/C.class shows that the bytecode refers to the type of d as La/b/C$D; and that of the array ds as [La/b/C$D;. These are called descriptors, and they are specified in JVMS section 4.3.

  • The class name a/b/C$D used in both of these descriptors is what you get by replacing . by / in the binary name. The JVM spec apparently calls this the internal form of the binary name. JVMS section 4.2.1 describes it, and states that the difference from the binary name were for historical reasons.

  • The file name of a class in one of the typical filename-based class loaders is what you get if you interpret the / in the internal form of the binary name as a directory separator, and append the file name extension .class to it. It's resolved relative to the class path used by the class loader in question.

It says that TypeError: document.getElementById(...) is null

Found similar problem within student's work, script element was put after closing body tag, so, obviously, JavaScript could not find any HTML element.

But, there was one more serious error: there was a reference to an external javascript file with some code, which removed all contents of a certain HTML element before inserting new content. After commenting out this reference, everything worked properly.

So, sometimes the error might be that some previously called Javascript changed content or even DOM, so calling for instance getElementById later doesn't make sense, since that element was removed.

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

How to rename a file using svn?

The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:

Target file does not exist:

In this case svn mv should work as follows:

$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding     new_file_name
Deleting   old_file_name
Committing transaction...

Target file already exists in repository:

In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name 
D         new_file_name
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
R  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Replacing      new_file_name
Deleting       old_file_name
Committing transaction...

In the output of svn stat, the R indicates that the file has been replaced, and that the file has a history.

Target file already exists locally (unversioned):

In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name 
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding         new_file_name
Deleting       old_file_name
Committing transaction...

Loaded nib but the 'view' outlet was not set

Just had the same error in my project, but different reason. In my case I had an IBOutlet setup with the name "View" in my custom UITableViewController class. I knew "view" was special because that is a member of the base class, but I didn't think View (different case) would also be a problem. I guess some areas of Cocoa are not case-sensitive, and probably loading a xib is one of those areas. So I just renamed it to DefaultView and all is good now.

Select row with most recent date per user

Already solved, but just for the record, another approach would be to create two views...

CREATE TABLE lms_attendance
(id int, user int, time int, io varchar(3));

CREATE VIEW latest_all AS
SELECT la.user, max(la.time) time
FROM lms_attendance la 
GROUP BY la.user;

CREATE VIEW latest_io AS
SELECT la.* 
FROM lms_attendance la
JOIN latest_all lall 
    ON lall.user = la.user
    AND lall.time = la.time;

INSERT INTO lms_attendance 
VALUES
(1, 9, 1370931202, 'out'),
(2, 9, 1370931664, 'out'),
(3, 6, 1370932128, 'out'),
(4, 12, 1370932128, 'out'),
(5, 12, 1370933037, 'in');

SELECT * FROM latest_io;

Click here to see it in action at SQL Fiddle

Responsive web design is working on desktop but not on mobile device

I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

Creating an IFRAME using JavaScript

You can use:

<script type="text/javascript">
    function prepareFrame() {
        var ifrm = document.createElement("iframe");
        ifrm.setAttribute("src", "http://google.com/");
        ifrm.style.width = "640px";
        ifrm.style.height = "480px";
        document.body.appendChild(ifrm);
    }
</script> 

also check basics of the iFrame element

Tuning nginx worker_process to obtain 100k hits per min

Config file:

worker_processes  4;  # 2 * Number of CPUs

events {
    worker_connections  19000;  # It's the key to high performance - have a lot of connections available
}

worker_rlimit_nofile    20000;  # Each connection needs a filehandle (or 2 if you are proxying)


# Total amount of users you can serve = worker_processes * worker_connections

more info: Optimizing nginx for high traffic loads

Lost httpd.conf file located apache

See http://wiki.apache.org/httpd/DistrosDefaultLayout for discussion of where you might find Apache httpd configuration files on various platforms, since this can vary from release to release and platform to platform. The most common answer, however, is either /etc/apache/conf or /etc/httpd/conf

Generically, you can determine the answer by running the command:

httpd -V

(That's a capital V). Or, on systems where httpd is renamed, perhaps apache2ctl -V

This will return various details about how httpd is built and configured, including the default location of the main configuration file.

One of the lines of output should look like:

-D SERVER_CONFIG_FILE="conf/httpd.conf"

which, combined with the line:

-D HTTPD_ROOT="/etc/httpd"

will give you a full path to the default location of the configuration file

Constraint Layout Vertical Align Center

You can easily center multiple things by creating a chain. It works both vertically and horizontally

Link to official documentation about chains

Edit to answer comment :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <TextView
        android:id="@+id/first_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="10"
        app:layout_constraintEnd_toStartOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/second_score"
        app:layout_constraintBottom_toTopOf="@+id/subtitle"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintVertical_chainStyle="packed"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subtitle"
        app:layout_constraintTop_toBottomOf="@+id/first_score"
        app:layout_constraintBottom_toBottomOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="@id/first_score"
        app:layout_constraintEnd_toEndOf="@id/first_score"
        />
    <TextView
        android:id="@+id/second_score"
        android:layout_width="60dp"
        android:layout_height="120sp"
        android:text="243"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/thrid_score"
        app:layout_constraintStart_toEndOf="@id/first_score"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/thrid_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="3200"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/second_score"
        app:layout_constraintTop_toTopOf="@id/second_score"
        app:layout_constraintBottom_toBottomOf="@id/second_score"
        android:gravity="center"
        />
</android.support.constraint.ConstraintLayout>

This code gives this result

You have the horizontal chain : first_score <=> second_score <=> third_score. second_score is centered vertically. The other scores are centered vertically according to it.

You can definitely create a vertical chain first_score <=> subtitle and center it according to second_score

Java: Array with loop

If your array of numbers always is starting with 1 and ending with X then you could use the following formula: sum = x * (x+1) / 2

from 1 till 100 the sum would be 100 * 101 / 2 = 5050

Text on image mouseover?

And if you come from even further in the future you can use the title property on div tags now to provide tooltips:

<div title="Tooltip text">Hover over me</div>

Let's just hope you're not using a browser from the past.

_x000D_
_x000D_
<div title="Tooltip text">Hover over me</div>
_x000D_
_x000D_
_x000D_

matplotlib: how to change data points color based on some variable

If you want to plot lines instead of points, see this example, modified here to plot good/bad points representing a function as a black/red as appropriate:

def plot(xx, yy, good):
    """Plot data

    Good parts are plotted as black, bad parts as red.

    Parameters
    ----------
    xx, yy : 1D arrays
        Data to plot.
    good : `numpy.ndarray`, boolean
        Boolean array indicating if point is good.
    """
    import numpy as np
    import matplotlib.pyplot as plt
    fig, ax = plt.subplots()
    from matplotlib.colors import from_levels_and_colors
    from matplotlib.collections import LineCollection
    cmap, norm = from_levels_and_colors([0.0, 0.5, 1.5], ['red', 'black'])
    points = np.array([xx, yy]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)
    lines = LineCollection(segments, cmap=cmap, norm=norm)
    lines.set_array(good.astype(int))
    ax.add_collection(lines)
    plt.show()

"Are you missing an assembly reference?" compile error - Visual Studio

Are you strong-naming your assemblies? In that case it is not a good idea to auto-increment your build number because with every new build number you will also have to update all your references.

Bootstrap 3: pull-right for col-lg only

This is what i am using . change @screen-md-max for other sizes

/* Pull left in lg resolutions */
@media (min-width: @screen-md-max) {
    .pull-xs-right {
        float: right !important;
    }
    .pull-xs-left {
        float: left !important;
    }

    .radio-inline.pull-xs-left  + .radio-inline.pull-xs-left ,
    .checkbox-inline.pull-xs-left  + .checkbox-inline.pull-xs-left  {
        margin-left: 0;
    }
    .radio-inline.pull-xs-left, .checkbox-inline.pull-xs-left{
        margin-right: 10px;
    }
}

CORS with spring-boot and angularjs not working

If you want to enable CORS without using filters or without config file just add

@CrossOrigin

to the top of your controller and it work.

What is the difference between Session.Abandon() and Session.Clear()

When you Abandon() a Session, you (or rather the user) will get a new SessionId (on the next request). When you Clear() a Session, all stored values are removed, but the SessionId stays intact.

How to make button look like a link?

try using the css pseudoclass :focus

input[type="button"], input[type="button"]:focus {
  /* your style goes here */
}

edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):

<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>

with this.href you can even access the target of the link in your function. return false will just prevent browsers from following the link when clicked.

if javascript is disabled the link will work as a normal link and just load some/page.php—if you want your link to be dead when js is disabled use href="#"

Repair all tables in one go

Use following query to print REPAIR SQL statments for all tables inside a database:

select concat('REPAIR TABLE ', table_name, ';') from information_schema.tables 
where table_schema='mydatabase'; 

After that copy all the queries and execute it on mydatabase.

Note: replace mydatabase with desired DB name

What is the "right" JSON date format?

I believe that the best format for universal interoperability is not the ISO-8601 string, but rather the format used by EJSON:

{ "myDateField": { "$date" : <ms-since-epoch> } }

As described here: https://docs.meteor.com/api/ejson.html

Benefits

  1. Parsing performance: If you store dates as ISO-8601 strings, this is great if you are expecting a date value under that particular field, but if you have a system which must determine value types without context, you're parsing every string for a date format.
  2. No Need for Date Validation: You need not worry about validation and verification of the date. Even if a string matches ISO-8601 format, it may not be a real date; this can never happen with an EJSON date.
  3. Unambiguous Type Declaration: as far as generic data systems go, if you wanted to store an ISO string as a string in one case, and a real system date in another, generic systems adopting the ISO-8601 string format will not allow this, mechanically (without escape tricks or similar awful solutions).

Conclusion

I understand that a human-readable format (ISO-8601 string) is helpful and more convenient for 80% of use cases, and indeed no-one should ever be told not to store their dates as ISO-8601 strings if that's what their applications understand, but for a universally accepted transport format which should guarantee certain values to for sure be dates, how can we allow for ambiguity and need for so much validation?

How do I concatenate strings in Swift?

You can now use stringByAppendingString in Swift.

var string = "Swift"
var resultString = string.stringByAppendingString(" is new Programming Language")

How to get javax.comm API?

Oracle Java Communications API Reference - http://www.oracle.com/technetwork/java/index-jsp-141752.html

Official 3.0 Download (Solarix, Linux) - http://www.oracle.com/technetwork/java/javasebusiness/downloads/java-archive-downloads-misc-419423.html

Unofficial 2.0 Download (All): http://www.java2s.com/Code/Jar/c/Downloadcomm20jar.htm

Unofficial 2.0 Download (Windows installer) - http://kishor15389.blogspot.hk/2011/05/how-to-install-java-communications.html

In order to ensure there is no compilation error, place the file on your classpath when compiling (-cp command-line option, or check your IDE documentation).

Expected block end YAML error

The line starting ALREADYEXISTS uses as the closing quote, it should be using '. The open quote on the next line (where the error is reported) is seen as the closing quote, and this mix up is causing the error.

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance(boolean) is useful when you want to have some component which is not tied to Activity lifecycle. This technique is used for example by rxloader to "handle Android's activity lifecyle for rxjava's Observable" (which I've found here).

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I got this error when running Visual Studio. By running Visual Studio as Administrator the application was able to access the Security logs as it then had sufficient permissions (thus preventing the error).

Connect different Windows User in SQL Server Management Studio (2005 or later)

None of these answers did what I needed: Login to a remote server using a different domain account than I was logged into on my local machine, and it's a client's domain across a vpn. I don't want to be on their domain!

Instead, on the connect to server dialog, select "Windows Authentication", click the Options button, and then on the Additional Connection Parameters tab, enter

user id=domain\user;password=password

SSMS won't remember, but it will connect with that account.

How can I create an array with key value pairs?

You can create the single value array key-value as

$new_row = array($row["datasource_id"]=>$row["title"]);

inside while loop, and then use array_merge function in loop to combine the each new $new_row array.

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

What do these operators mean (** , ^ , %, //)?

  • **: exponentiation
  • ^: exclusive-or (bitwise)
  • %: modulus
  • //: divide with integral result (discard remainder)

Renaming Columns in an SQL SELECT Statement

select column1 as xyz,
      column2 as pqr,
.....

from TableName;

How should I print types like off_t and size_t?

use "%zo" for off_t. (octal) or "%zu" for decimal.

How to generate a unique hash code for string input in android...?

You can use this code for generating has code for a given string.

int hash = 7;
for (int i = 0; i < strlen; i++) {
    hash = hash*31 + charAt(i);
}

How to check if a scope variable is undefined in AngularJS template?

Using undefined to make a decision is usually a sign of bad design in Javascript. You might consider doing something else.

However, to answer your question: I think the best way of doing so would be adding a helper function.

$scope.isUndefined = function (thing) {
    return (typeof thing === "undefined");
}

and in the template

<div ng-show="isUndefined(foo)"></div>

Can't access object property, even though it shows up in a console log

I had the same issue and no solution above worked for me and it sort of felt like guess work thereafter. However, wrapping my code which creates the object in a setTimeout function did the trick for me.

setTimeout(function() {
   var myObj = xyz; //some code for creation of complex object like above
   console.log(myObj); // this works
   console.log(myObj.propertyName); // this works too
});

Add padding to HTML text input field

padding-right should work. Example linked.

http://jsfiddle.net/8Ged8/

How to create new div dynamically, change it, move it, modify it in every way possible, in JavaScript?

This covers the basics of DOM manipulation. Remember, element addition to the body or a body-contained node is required for the newly created node to be visible within the document.

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

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

If you can restrict it to just (Open Office XML format) *.xlsx files, then probably the most popular library would be EPPLus.

Bonus is, there are no other dependencies. Just install using nuget:

Install-Package EPPlus

Collapse all methods in Visual Studio Code

Mac Users

Fold Commands

enter image description here

Unfold commands enter image description here

How to make a stable two column layout in HTML/CSS

I could care less about IE6, as long as it works in IE8, Firefox 4, and Safari 5

This makes me happy.

Try this: Live Demo

display: table is surprisingly good. Once you don't care about IE7, you're free to use it. It doesn't really have any of the usual downsides of <table>.

CSS:

#container {
    background: #ccc;
    display: table
}
#left, #right {
    display: table-cell
}
#left {
    width: 150px;
    background: #f0f;
    border: 5px dotted blue;
}
#right {
    background: #aaa;
    border: 3px solid #000
}

How to grant all privileges to root user in MySQL 8.0

For those who've been confused by CREATE USER 'root'@'localhost' when you already have a root account on the server machine, keep in mind that your 'root'@'localhost' and 'root'@'your_remote_ip' are two different users (same user name, yet different scope) in mysql server. Hence, creating a new user with your_remote_ip postfix will actually create a new valid root user that you can use to access the mysql server from a remote machine.

For example, if you're using root to connect to your mysql server from a remote machine whose IP is 10.154.10.241 and you want to set a password for the remote root account which is 'Abcdef123!@#', here are steps you would want to follow:

  1. On your mysql server machine, do mysql -u root -p, then enter your password for root to login.

  2. Once in mysql> session, do this to create root user for the remote scope:

    mysql> CREATE USER 'root'@'10.154.10.241' IDENTIFIED BY 'Abcdef123!@#';
    
  3. After the Query OK message, do this to grant the newly created root user all privileges:

    mysql> GRANT ALL ON *.* TO 'root'@'10.154.10.241';
    
  4. And then:

    FLUSH PRIVILEGES;
    
  5. Restart the mysqld service:

    sudo service mysqld restart
    
  6. Confirm that the server has successfully restarted:

    sudo service mysqld status
    

If the steps above were executed without any error, you can now access to the mysql server from a remote machine using root.

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How to change facet labels?

Simple solution (from here):

p <- ggplot(mtcars, aes(disp, drat)) + geom_point()
# Example (old labels)
p + facet_wrap(~am)


to_string <- as_labeller(c(`0` = "Zero", `1` = "One"))
# Example (New labels)
p + facet_wrap(~am, labeller = to_string)

I would like to see a hash_map example in C++

The name accepted into TR1 (and the draft for the next standard) is std::unordered_map, so if you have that available, it's probably the one you want to use.

Other than that, using it is a lot like using std::map, with the proviso that when/if you traverse the items in an std::map, they come out in the order specified by operator<, but for an unordered_map, the order is generally meaningless.

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

nil detection in Go

In addition to Oleiade, see the spec on zero values:

When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.

As you can see, nil is not the zero value for every type but only for pointers, functions, interfaces, slices, channels and maps. This is the reason why config == nil is an error and &config == nil is not.

To check whether your struct is uninitialized you'd have to check every member for its respective zero value (e.g. host == "", port == 0, etc.) or have a private field which is set by an internal initialization method. Example:

type Config struct {
    Host string  
    Port float64
    setup bool
}

func NewConfig(host string, port float64) *Config {
    return &Config{host, port, true}
}

func (c *Config) Initialized() bool { return c != nil && c.setup }

JavaScript equivalent of PHP’s die

This should kind of work like die();

function die(msg = ''){
    if(msg){
        document.getElementsByTagName('html')[0].innerHTML = msg;
    }else{
        document.open();
        document.write(msg);
        document.close();
    }
    throw msg;
}

Using Chrome's Element Inspector in Print Preview Mode?

With shortcuts available, the quickest way is to

  1. Open the Developer Tools

    • Windows: F12 or Ctrl+Shift+I
    • Mac: Cmd+Opt+I
  2. Open the Command Menu

    • Windows: Ctrl+Shift+P
    • Mac: Cmd+Shift+P
  3. Type print and select Emulate CSS print media type from the context menu

    Change Media Type Emulation Via Command Menu

Looking at the excellent and currently most-upvoted answer by lmeurs, I think this solution might also remain stable over time.

How to call a method with a separate thread in Java?

In Java 8 you can do this with one line of code.

If your method doesn't take any parameters, you can use a method reference:

new Thread(MyClass::doWork).start();

Otherwise, you can call the method in a lambda expression:

new Thread(() -> doWork(someParam)).start();

How to center a subview of UIView

1. If you have autolayout enabled:

  • Hint: For centering a view on another view with autolayout you can use same code for any two views sharing at least one parent view.

First of all disable child views autoresizing

UIView *view1, *view2;
[childview setTranslatesAutoresizingMaskIntoConstraints:NO];
  1. If you are UIView+Autolayout or Purelayout:

    [view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
    [view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
    
  2. If you are using only UIKit level autolayout methods:

    [view1 addConstraints:({
        @[ [NSLayoutConstraint
           constraintWithItem:view1
           attribute:NSLayoutAttributeCenterX
           relatedBy:NSLayoutRelationEqual
           toItem:view2
           attribute:NSLayoutAttributeCenterX
           multiplier:1.f constant:0.f],
    
           [NSLayoutConstraint
            constraintWithItem:view1
            attribute:NSLayoutAttributeCenterY
            relatedBy:NSLayoutRelationEqual
            toItem:view2
            attribute:NSLayoutAttributeCenterY
            multiplier:1.f constant:0.f] ];
    })];
    

2. Without autolayout:

I prefer:

UIView *parentView, *childView;
[childView setFrame:({
    CGRect frame = childView.frame;

    frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
    frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;

    CGRectIntegral(frame);
})];

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

Yahoo Finance All Currencies quote API Documentation

I'm developing an application that needs currency conversion, and been using Open Exchange Rates because I wouldn't be paying since the app is in testing. But as of September 2012 Open Exchange Rates is gonna be paid for non-personal, so I checked out that they were using the Yahoo Finance Webservice (the one that "doesn't exist") and looking for documentation on it got here, and opted to use YQL.

Using YQL with the Yahoo Finance table (yahoo.finance.quotes) linked by NT3RP, currencies appear with symbol="ISOCODE=X", for example: "ARS=X" for Argentine Peso, "AUD=X" for Australian Dollar. "USD=X" doesn't exist, but it would be 1, since the rest are rates against USD.

The "price" value on the OP API is in the field "LastTradePriceOnly" of the table. For my application I used the "Ask" field.

How to import multiple .csv files at once?

A speedy and succinct tidyverse solution: (more than twice as fast as Base R's read.csv)

tbl <-
    list.files(pattern = "*.csv") %>% 
    map_df(~read_csv(.))

and data.table's fread() can even cut those load times by half again. (for 1/4 the Base R times)

library(data.table)

tbl_fread <- 
    list.files(pattern = "*.csv") %>% 
    map_df(~fread(.))

The stringsAsFactors = FALSE argument keeps the dataframe factor free, (and as marbel points out, is the default setting for fread)

If the typecasting is being cheeky, you can force all the columns to be as characters with the col_types argument.

tbl <-
    list.files(pattern = "*.csv") %>% 
    map_df(~read_csv(., col_types = cols(.default = "c")))

If you are wanting to dip into subdirectories to construct your list of files to eventually bind, then be sure to include the path name, as well as register the files with their full names in your list. This will allow the binding work to go on outside of the current directory. (Thinking of the full pathnames as operating like passports to allow movement back across directory 'borders'.)

tbl <-
    list.files(path = "./subdirectory/",
               pattern = "*.csv", 
               full.names = T) %>% 
    map_df(~read_csv(., col_types = cols(.default = "c"))) 

As Hadley describes here (about halfway down):

map_df(x, f) is effectively the same as do.call("rbind", lapply(x, f))....

Bonus Feature - adding filenames to the records per Niks feature request in comments below:
* Add original filename to each record.

Code explained: make a function to append the filename to each record during the initial reading of the tables. Then use that function instead of the simple read_csv() function.

read_plus <- function(flnm) {
    read_csv(flnm) %>% 
        mutate(filename = flnm)
}

tbl_with_sources <-
    list.files(pattern = "*.csv", 
               full.names = T) %>% 
    map_df(~read_plus(.))

(The typecasting and subdirectory handling approaches can also be handled inside the read_plus() function in the same manner as illustrated in the second and third variants suggested above.)

### Benchmark Code & Results 
library(tidyverse)
library(data.table)
library(microbenchmark)

### Base R Approaches
#### Instead of a dataframe, this approach creates a list of lists
#### removed from analysis as this alone doubled analysis time reqd
# lapply_read.delim <- function(path, pattern = "*.csv") {
#     temp = list.files(path, pattern, full.names = TRUE)
#     myfiles = lapply(temp, read.delim)
# }

#### `read.csv()`
do.call_rbind_read.csv <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))
}

map_df_read.csv <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~read.csv(., stringsAsFactors = FALSE))
}


### *dplyr()*
#### `read_csv()`
lapply_read_csv_bind_rows <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    lapply(files, read_csv) %>% bind_rows()
}

map_df_read_csv <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~read_csv(., col_types = cols(.default = "c")))
}

### *data.table* / *purrr* hybrid
map_df_fread <- function(path, pattern = "*.csv") {
    list.files(path, pattern, full.names = TRUE) %>% 
    map_df(~fread(.))
}

### *data.table*
rbindlist_fread <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    rbindlist(lapply(files, function(x) fread(x)))
}

do.call_rbind_fread <- function(path, pattern = "*.csv") {
    files = list.files(path, pattern, full.names = TRUE)
    do.call(rbind, lapply(files, function(x) fread(x, stringsAsFactors = FALSE)))
}


read_results <- function(dir_size){
    microbenchmark(
        # lapply_read.delim = lapply_read.delim(dir_size), # too slow to include in benchmarks
        do.call_rbind_read.csv = do.call_rbind_read.csv(dir_size),
        map_df_read.csv = map_df_read.csv(dir_size),
        lapply_read_csv_bind_rows = lapply_read_csv_bind_rows(dir_size),
        map_df_read_csv = map_df_read_csv(dir_size),
        rbindlist_fread = rbindlist_fread(dir_size),
        do.call_rbind_fread = do.call_rbind_fread(dir_size),
        map_df_fread = map_df_fread(dir_size),
        times = 10L) 
}

read_results_lrg_mid_mid <- read_results('./testFolder/500MB_12.5MB_40files')
print(read_results_lrg_mid_mid, digits = 3)

read_results_sml_mic_mny <- read_results('./testFolder/5MB_5KB_1000files/')
read_results_sml_tny_mod <- read_results('./testFolder/5MB_50KB_100files/')
read_results_sml_sml_few <- read_results('./testFolder/5MB_500KB_10files/')

read_results_med_sml_mny <- read_results('./testFolder/50MB_5OKB_1000files')
read_results_med_sml_mod <- read_results('./testFolder/50MB_5OOKB_100files')
read_results_med_med_few <- read_results('./testFolder/50MB_5MB_10files')

read_results_lrg_sml_mny <- read_results('./testFolder/500MB_500KB_1000files')
read_results_lrg_med_mod <- read_results('./testFolder/500MB_5MB_100files')
read_results_lrg_lrg_few <- read_results('./testFolder/500MB_50MB_10files')

read_results_xlg_lrg_mod <- read_results('./testFolder/5000MB_50MB_100files')


print(read_results_sml_mic_mny, digits = 3)
print(read_results_sml_tny_mod, digits = 3)
print(read_results_sml_sml_few, digits = 3)

print(read_results_med_sml_mny, digits = 3)
print(read_results_med_sml_mod, digits = 3)
print(read_results_med_med_few, digits = 3)

print(read_results_lrg_sml_mny, digits = 3)
print(read_results_lrg_med_mod, digits = 3)
print(read_results_lrg_lrg_few, digits = 3)

print(read_results_xlg_lrg_mod, digits = 3)

# display boxplot of my typical use case results & basic machine max load
par(oma = c(0,0,0,0)) # remove overall margins if present
par(mfcol = c(1,1)) # remove grid if present
par(mar = c(12,5,1,1) + 0.1) # to display just a single boxplot with its complete labels
boxplot(read_results_lrg_mid_mid, las = 2, xlab = "", ylab = "Duration (seconds)", main = "40 files @ 12.5MB (500MB)")
boxplot(read_results_xlg_lrg_mod, las = 2, xlab = "", ylab = "Duration (seconds)", main = "100 files @ 50MB (5GB)")

# generate 3x3 grid boxplots
par(oma = c(12,1,1,1)) # margins for the whole 3 x 3 grid plot
par(mfcol = c(3,3)) # create grid (filling down each column)
par(mar = c(1,4,2,1)) # margins for the individual plots in 3 x 3 grid
boxplot(read_results_sml_mic_mny, las = 2, xlab = "", ylab = "Duration (seconds)", main = "1000 files @ 5KB (5MB)", xaxt = 'n')
boxplot(read_results_sml_tny_mod, las = 2, xlab = "", ylab = "Duration (milliseconds)", main = "100 files @ 50KB (5MB)", xaxt = 'n')
boxplot(read_results_sml_sml_few, las = 2, xlab = "", ylab = "Duration (milliseconds)", main = "10 files @ 500KB (5MB)",)

boxplot(read_results_med_sml_mny, las = 2, xlab = "", ylab = "Duration (microseconds)        ", main = "1000 files @ 50KB (50MB)", xaxt = 'n')
boxplot(read_results_med_sml_mod, las = 2, xlab = "", ylab = "Duration (microseconds)", main = "100 files @ 500KB (50MB)", xaxt = 'n')
boxplot(read_results_med_med_few, las = 2, xlab = "", ylab = "Duration (seconds)", main = "10 files @ 5MB (50MB)")

boxplot(read_results_lrg_sml_mny, las = 2, xlab = "", ylab = "Duration (seconds)", main = "1000 files @ 500KB (500MB)", xaxt = 'n')
boxplot(read_results_lrg_med_mod, las = 2, xlab = "", ylab = "Duration (seconds)", main = "100 files @ 5MB (500MB)", xaxt = 'n')
boxplot(read_results_lrg_lrg_few, las = 2, xlab = "", ylab = "Duration (seconds)", main = "10 files @ 50MB (500MB)")

Middling Use Case

Boxplot Comparison of Elapsed Time my typical use case

Larger Use Case

Boxplot Comparison of Elapsed Time for Extra Large Load

Variety of Use Cases

Rows: file counts (1000, 100, 10)
Columns: final dataframe size (5MB, 50MB, 500MB)
(click on image to view original size) Boxplot Comparison of Directory Size Variations

The base R results are better for the smallest use cases where the overhead of bringing the C libraries of purrr and dplyr to bear outweigh the performance gains that are observed when performing larger scale processing tasks.

if you want to run your own tests you may find this bash script helpful.

for ((i=1; i<=$2; i++)); do 
  cp "$1" "${1:0:8}_${i}.csv";
done

bash what_you_name_this_script.sh "fileName_you_want_copied" 100 will create 100 copies of your file sequentially numbered (after the initial 8 characters of the filename and an underscore).

Attributions and Appreciations

With special thanks to:

  • Tyler Rinker and Akrun for demonstrating microbenchmark.
  • Jake Kaupp for introducing me to map_df() here.
  • David McLaughlin for helpful feedback on improving the visualizations and discussing/confirming the performance inversions observed in the small file, small dataframe analysis results.
  • marbel for pointing out the default behavior for fread(). (I need to study up on data.table.)

"Char cannot be dereferenced" error

A char doesn't have any methods - it's a Java primitive. You're looking for the Character wrapper class.

The usage would be:

if(Character.isLetter(ch)) { //... }

Spring boot: Unable to start embedded Tomcat servlet container

Try to change the port number in application.yaml (or application.properties) to something else.

Start an activity from a fragment

Start new Activity From a Fragment:

Intent intent = new Intent(getActivity(), TargetActivity.class);
startActivity(intent);

Start new Activity From a Activity:

Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);

Convert serial.read() into a useable string using Arduino?

Unlimited string readed:

String content = "";
char character;
    
while(Serial.available()) {
     character = Serial.read();
     content.concat(character);
}
      
if (content != "") {
     Serial.println(content);
}

SQL to add column and comment in table in single command

Add comments for two different columns of the EMPLOYEE table :

COMMENT ON EMPLOYEE
     (WORKDEPT IS 'see DEPARTMENT table for names',
     EDLEVEL IS 'highest grade level passed in school' )

Lock, mutex, semaphore... what's the difference?

Wikipedia has a great section on the differences between Semaphores and Mutexes:

A mutex is essentially the same thing as a binary semaphore and sometimes uses the same basic implementation. The differences between them are:

Mutexes have a concept of an owner, which is the process that locked the mutex. Only the process that locked the mutex can unlock it. In contrast, a semaphore has no concept of an owner. Any process can unlock a semaphore.

Unlike semaphores, mutexes provide priority inversion safety. Since the mutex knows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the mutex.

Mutexes also provide deletion safety, where the process holding the mutex cannot be accidentally deleted. Semaphores do not provide this.

Python - add PYTHONPATH during command line module run

If you are running the command from a POSIX-compliant shell, like bash, you can set the environment variable like this:

PYTHONPATH="/path/to" python somescript.py somecommand

If it's all on one line, the PYTHONPATH environment value applies only to that one command.

$ echo $PYTHONPATH

$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH

text flowing out of div

You should use overflow:hidden; or scroll

http://jsfiddle.net/UJ6zG/1/

or with php you could short the long words...

How does one create an InputStream from a String?

You could do this:

InputStream in = new ByteArrayInputStream(string.getBytes("UTF-8"));

Note the UTF-8 encoding. You should specify the character set that you want the bytes encoded into. It's common to choose UTF-8 if you don't specifically need anything else. Otherwise if you select nothing you'll get the default encoding that can vary between systems. From the JavaDoc:

The behavior of this method when this string cannot be encoded in the default charset is unspecified. The CharsetEncoder class should be used when more control over the encoding process is required.

How to convert file to base64 in JavaScript?

TypeScript version

const file2Base64 = (file:File):Promise<string> => {
    return new Promise<string> ((resolve,reject)=> {
         const reader = new FileReader();
         reader.readAsDataURL(file);
         reader.onload = () => resolve(reader.result.toString());
         reader.onerror = error => reject(error);
     })
    }

What is the use of a cursor in SQL Server?

I would argue you might want to use a cursor when you want to do comparisons of characteristics that are on different rows of the return set, or if you want to write a different output row format than a standard one in certain cases. Two examples come to mind:

  1. One was in a college where each add and drop of a class had its own row in the table. It might have been bad design but you needed to compare across rows to know how many add and drop rows you had in order to determine whether the person was in the class or not. I can't think of a straight forward way to do that with only sql.

  2. Another example is writing a journal total line for GL journals. You get an arbitrary number of debits and credits in your journal, you have many journals in your rowset return, and you want to write a journal total line every time you finish a journal to post it into a General Ledger. With a cursor you could tell when you left one journal and started another and have accumulators for your debits and credits and write a journal total line (or table insert) that was different than the debit/credit line.

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

Excel Date to String conversion

In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.

'01/01/2010 14:30:00

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

How do you check for permissions to write to a directory or file?

Sorry, but none of the previous solutions helped me. I need to check both sides: SecurityManager and SO permissions. I have learned a lot with Josh code and with iain answer, but I'm afraid I need to use Rakesh code (also thanks to him). Only one bug: I found that he only checks for Allow and not for Deny permissions. So my proposal is:

        string folder;
        AuthorizationRuleCollection rules;
        try {
            rules = Directory.GetAccessControl(folder)
                .GetAccessRules(true, true, typeof(System.Security.Principal.NTAccount));
        } catch(Exception ex) { //Posible UnauthorizedAccessException
            throw new Exception("No permission", ex);
        }

        var rulesCast = rules.Cast<FileSystemAccessRule>();
        if(rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Deny)
            || !rulesCast.Any(rule => rule.AccessControlType == AccessControlType.Allow))
            throw new Exception("No permission");

        //Here I have permission, ole!

Can I start the iPhone simulator without "Build and Run"?

To follow up on that the new command from @jimbojw to create a shortcut with the new Xcode (installing through preferences) is:

ln -s /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app /Applications/iPhone\ Simulator.app

Which will create a shortcut in the applications folder for you.

Specific Time Range Query in SQL Server

I (using PostgrSQL on PGadmin4) queried for results that are after or on 21st Nov 2017 at noon, like this (considering the display format of hours on my database):

select * from Table1 where FIELD >='2017-11-21 12:00:00' 

Index Error: list index out of range (Python)

Generally it means that you are providing an index for which a list element does not exist.

E.g, if your list was [1, 3, 5, 7], and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.

How does the Python's range function work?

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).

So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

Select random lines from a file

My preferred option is very fast, I sampled a tab-delimited data file with 13 columns, 23.1M rows, 2.0GB uncompressed.

# randomly sample select 5% of lines in file
# including header row, exclude blank lines, new seed

time \
awk 'BEGIN  {srand()} 
     !/^$/  { if (rand() <= .05 || FNR==1) print > "data-sample.txt"}' data.txt

# awk  tsv004  3.76s user 1.46s system 91% cpu 5.716 total

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

System.BadImageFormatException: Could not load file or assembly (from installutil.exe)

Make sure the newest Framework (the one you compiled your app with) is first in the PATH. That solved the problem for me. (Found on a forum)

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

Instead of initializing the variables with arbitrary values (for example int smallest = 9999, largest = 0) it is safer to initialize the variables with the largest and smallest values representable by that number type (that is int smallest = Integer.MAX_VALUE, largest = Integer.MIN_VALUE).

Since your integer array cannot contain a value larger than Integer.MAX_VALUE and smaller than Integer.MIN_VALUE your code works across all edge cases.

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

How do I find out my root MySQL password?

I'm going to make a bit of an assumption here because I'm not sure. I don't think my MySQL (running on latest 20.04 upgraded) even has a root. I have tried setting one and I remember having problems. I suspect there is not a root user and it will automatically log you in as the MySQL root user if you're logged in as root.

Why do I think this? Because when I do MySQL -u root -p, it will accept any password and log me in as the MySQL root user when I am logged in as root.

I have confirmed that trying that on a non root user doesn't work.

I like this model.

EDIT 2020.12.19: It is no longer a mystery to me why if you are logged in as the root user you get logged into MySQL as the root user. It has to do with the authentication type. Later versions of MySQL are configured with the MySQL plugin 'auth_socket' (maybe you've noticed the /run/mysqld/mysqld.sock file on your system and wondered about it). The plugin uses the SO_PEERCRED option provided by the library auth_socket.so.

You can revert back to password authentication if desired simply by create/update of the password. Showing both ways and options below to make clear.

CREATE USER 'valerie'@'localhost' IDENTIFIED WITH auth_socket;
CREATE USER 'valerie'@'localhost' IDENTIFIED BY 'password';

Delete files or folder recursively on Windows CMD

dir /b %temp% >temp.list
for /f "delims=" %%a in (temp.list) do call rundll32.exe advpack.dll,DelNodeRunDLL32 "%temp%\%%a"

Best way to find the intersection of multiple sets?

If you don't have Python 2.6 or higher, the alternative is to write an explicit for loop:

def set_list_intersection(set_list):
  if not set_list:
    return set()
  result = set_list[0]
  for s in set_list[1:]:
    result &= s
  return result

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print set_list_intersection(set_list)
# Output: set([1])

You can also use reduce:

set_list = [set([1, 2]), set([1, 3]), set([1, 4])]
print reduce(lambda s1, s2: s1 & s2, set_list)
# Output: set([1])

However, many Python programmers dislike it, including Guido himself:

About 12 years ago, Python aquired lambda, reduce(), filter() and map(), courtesy of (I believe) a Lisp hacker who missed them and submitted working patches. But, despite of the PR value, I think these features should be cut from Python 3000.

So now reduce(). This is actually the one I've always hated most, because, apart from a few examples involving + or *, almost every time I see a reduce() call with a non-trivial function argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.

How to convert a NumPy array to PIL image applying matplotlib colormap

The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:

import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')

np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.

Checking if a variable is not nil and not zero in ruby

unless discount.nil? || discount == 0
  # ...
end

Getting the button into the top right corner inside the div box

#button {
    line-height: 12px;
    width: 18px;
    font-size: 8pt;
    font-family: tahoma;
    margin-top: 1px;
    margin-right: 2px;
    position: absolute;
    top: 0;
    right: 0;
}

R cannot be resolved - Android error

After tracking down this problem as well, I found this note in the Android documentation:

http://source.android.com/source/using-eclipse.html

*Note: Eclipse sometimes likes to add an "import android.R" statement at the top of your files that use resources, especially when you ask Eclipse to sort or otherwise manage imports. This will cause your make to break. Look out for these erroneous import statements and delete them.*

While going through the Android sample tutorials, I would often use the Ctrl + Shift + O command to "Organize Imports" and generate any missing import statements. Sometimes this would generate the incorrect import statement which would hide the R.java class that is automatically generated when you build.

Creating multiple log files of different content with log4j

This should get you started:

log4j.rootLogger=QuietAppender, LoudAppender, TRACE
# setup A1
log4j.appender.QuietAppender=org.apache.log4j.RollingFileAppender
log4j.appender.QuietAppender.Threshold=INFO
log4j.appender.QuietAppender.File=quiet.log
...


# setup A2
log4j.appender.LoudAppender=org.apache.log4j.RollingFileAppender
log4j.appender.LoudAppender.Threshold=DEBUG
log4j.appender.LoudAppender.File=loud.log
...

log4j.logger.com.yourpackage.yourclazz=TRACE

Python 3.4.0 with MySQL database

MySQLdb does not support Python 3 but it is not the only MySQL driver for Python.

mysqlclient is essentially just a fork of MySQLdb with Python 3 support merged in (and a few other improvements).

PyMySQL is a pure python MySQL driver, which means it is slower, but it does not require a compiled C component or MySQL libraries and header files to be installed on client machines. It has Python 3 support.

Another option is simply to use another database system like PostgreSQL.

How to check currently internet connection is available or not in android

You can use two method :

1 - for check connection :

   private boolean isNetworkConnected() {
        ConnectivityManager cm = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        return cm.getActiveNetworkInfo() != null;
    }

2 - for check internet :

  public boolean internetIsConnected() {
        try {
            String command = "ping -c 1 google.com";
            return (Runtime.getRuntime().exec(command).waitFor() == 0);
        } catch (Exception e) {
            return false;
        }
    }

Add permissions to manifest :

 <uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

Pytorch reshape tensor dimension

or you can use this, the '-1' means you don't have to specify the number of the elements.

In [3]: a.view(1,-1)
Out[3]:

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

List(of String) or Array or ArrayList

You can do something like this,

  Dim lstOfStrings As New List(Of String) From {"Value1", "Value2", "Value3"}

Collection Initializers

What does "connection reset by peer" mean?

It's fatal. The remote server has sent you a RST packet, which indicates an immediate dropping of the connection, rather than the usual handshake. This bypasses the normal half-closed state transition. I like this description:

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur.

Windows service with timer

First approach with Windows Service is not easy..

A long time ago, I wrote a C# service.

This is the logic of the Service class (tested, works fine):

namespace MyServiceApp
{
    public class MyService : ServiceBase
    {
        private System.Timers.Timer timer;

        protected override void OnStart(string[] args)
        {
            this.timer = new System.Timers.Timer(30000D);  // 30000 milliseconds = 30 seconds
            this.timer.AutoReset = true;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
            this.timer.Start();
        }

        protected override void OnStop()
        {
            this.timer.Stop();
            this.timer = null;
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MyServiceApp.ServiceWork.Main(); // my separate static method for do work
        }

        public MyService()
        {
            this.ServiceName = "MyService";
        }

        // service entry point
        static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new MyService());
        }
    }
}

I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.

Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

Hope this helps!

PostgreSQL query to list all table names?

Open up the postgres terminal with the databse you would like:

psql dbname (run this line in a terminal)

then, run this command in the postgres environment

\d

This will describe all tables by name. Basically a list of tables by name ascending.

Then you can try this to describe a table by fields:

\d tablename.

Hope this helps.

Cannot send a content-body with this verb-type

Please set the request Content Type before you read the response stream;

 request.ContentType = "text/xml";

MySQL JOIN with LIMIT 1 on joined table

Another example with 3 nested tables: 1/ User 2/ UserRoleCompanie 3/ Companie

  • 1 user has many UserRoleCompanie.
  • 1 UserRoleCompanie has 1 user and 1 Company
  • 1 Companie has many UserRoleCompanie
SELECT 
u.id as userId, 
u.firstName,
u.lastName,
u.email,
urc.id ,
urc.companieRole,
c.id as companieId,
c.name as companieName
FROM User as u 
JOIN UserRoleCompanie as urc ON u.id = urc.userId
    AND urc.id = (
        SELECT urc2.id
        FROM UserRoleCompanie urc2 
        JOIN Companie ON urc2.companieId = Companie.id
        AND urc2.userId = u.id 
        AND Companie.isPersonal = false
        order by Companie.createdAt DESC
        
        limit 1
    )
    
LEFT JOIN Companie as c ON urc.companieId = c.id
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| userId                    | firstName | lastName           | email                     | id                        | companieRole | companieId                | companieName      |
+---------------------------+-----------+--------------------+---------------------------+---------------------------+--------------+---------------------------+-------------------+
| cjjt9s9iw037f0748raxmnnde | henry     | pierrot            | [email protected]           | cjtuflye81dwt0748e4hnkiv0 | OWNER        | cjtuflye71dws0748r7vtuqmg | leclerc           |

How to use greater than operator with date?

I have tried but above not working after research found below the solution.

SELECT * FROM my_table where DATE(start_date) > '2011-01-01';

Ref

Installing Python 2.7 on Windows 8

there is a simple procedure to do it go to controlpanel->system and security ->system->advanced system settings->advanced->environment variables then add new path enter this in your variable path and values

enter image description here

Printing 1 to 1000 without loop or conditionals

As it is answer :)

printf("numbers from 1 to 1000 without using any loop or conditional statements. Don't just write the printf() or cout statement 1000 times.");

PKIX path building failed: unable to find valid certification path to requested target

I've run into this a few times and it was due to a certificate chain being incomplete. If you are using the standard java trust store, it may not have a certificate that is needed to complete the certificate chain which is required to validate the certificate of the SSL site you are connecting to.

I ran into this problem with some DigiCert certificates and had to manually add the intermediary cert myself.

How to parse JSON string in Typescript

If you want your JSON to have a validated Typescript type, you will need to do that validation work yourself. This is nothing new. In plain Javascript, you would need to do the same.

Validation

I like to express my validation logic as a set of "transforms". I define a Descriptor as a map of transforms:

type Descriptor<T> = {
  [P in keyof T]: (v: any) => T[P];
};

Then I can make a function that will apply these transforms to arbitrary input:

function pick<T>(v: any, d: Descriptor<T>): T {
  const ret: any = {};
  for (let key in d) {
    try {
      const val = d[key](v[key]);
      if (typeof val !== "undefined") {
        ret[key] = val;
      }
    } catch (err) {
      const msg = err instanceof Error ? err.message : String(err);
      throw new Error(`could not pick ${key}: ${msg}`);
    }
  }
  return ret;
}

Now, not only am I validating my JSON input, but I am building up a Typescript type as I go. The above generic types ensure that the result infers the types from your "transforms".

In case the transform throws an error (which is how you would implement validation), I like to wrap it with another error showing which key caused the error.

Usage

In your example, I would use this as follows:

const value = pick(JSON.parse('{"name": "Bob", "error": false}'), {
  name: String,
  error: Boolean,
});

Now value will be typed, since String and Boolean are both "transformers" in the sense they take input and return a typed output.

Furthermore, the value will actually be that type. In other words, if name were actually 123, it will be transformed to "123" so that you have a valid string. This is because we used String at runtime, a built-in function that accepts arbitrary input and returns a string.

You can see this working here. Try the following things to convince yourself:

  • Hover over the const value definition to see that the pop-over shows the correct type.
  • Try changing "Bob" to 123 and re-run the sample. In your console, you will see that the name has been properly converted to the string "123".

How do I debug jquery AJAX calls?

Just add this after jQuery loads and before your code.

$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
    console.log('data: ' + data);
    console.log('textStatus: ' + textStatus);
        console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

It sounds like the intermediate certificate is missing. As of April 2006, all SSL certificates issued by VeriSign require the installation of an Intermediate CA Certificate.

It could be that you don't have the entire certificate chain loaded on your server. Some businesses do not allow their computers to download additional certificates, causing a failure to complete an SSL handshake.

Here is some information on intermediate chains:
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AR657
https://knowledge.verisign.com/support/ssl-certificates-support/index?page=content&id=AD146

Intermediate CA Certificates

Split a vector into chunks

Credit to @Sebastian for this function

chunk <- function(x,y){
         split(x, factor(sort(rank(row.names(x))%%y)))
         }

Fastest way to check if a string matches a regexp in ruby?

Depending on how complicated your regular expression is, you could possibly just use simple string slicing. I'm not sure about the practicality of this for your application or whether or not it would actually offer any speed improvements.

'testsentence'['stsen']
=> 'stsen' # evaluates to true
'testsentence'['koala']
=> nil # evaluates to false

Call to getLayoutInflater() in places not in activity

Using context object you can get LayoutInflater from following code

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Center the nav in Twitter Bootstrap

For Bootstrap v4 check this:

https://v4-alpha.getbootstrap.com/components/pagination/#alignment

only add class to ul.pagination:

<nav">
  <ul class="pagination justify-content-center">
    <li class="page-item disabled">
      <a class="page-link" href="#" tabindex="-1">Previous</a>
    </li>
    <li class="page-item"><a class="page-link" href="#">1</a></li>
    <li class="page-item"><a class="page-link" href="#">2</a></li>
    <li class="page-item"><a class="page-link" href="#">3</a></li>
    <li class="page-item">
      <a class="page-link" href="#">Next</a>
    </li>
  </ul>
</nav>

How to erase the file contents of text file in Python?

Opening a file in "write" mode clears it, you don't specifically have to write to it:

open("filename", "w").close()

(you should close it as the timing of when the file gets closed automatically may be implementation specific)

Awaiting multiple Tasks with different results

Just await the three tasks separately, after starting them all.

var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();

var cat = await catTask;
var house = await houseTask;
var car = await carTask;

Dynamically change bootstrap progress bar value when checkboxes checked

Bootstrap 4 progress bar

<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>

Javascript

change progress bar on next/previous page actions

var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);        
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');

Simple logical operators in Bash

Here is the code for the short version of if-then-else statement:

( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"

Pay attention to the following:

  1. || and && operands inside if condition (i.e. between round parentheses) are logical operands (or/and)

  2. || and && operands outside if condition mean then/else

Practically the statement says:

if (a=1 or b=2) then "ok" else "nok"

How to get query parameters from URL in Angular 5?

Just stumbled upon the same problem and most answers here seem to only solve it for Angular internal routing, and then some of them for route parameters which is not the same as request parameters.

I am guessing that I have a similar use case to the original question by Lars.

For me the use case is e.g. referral tracking:

Angular running on mycoolpage.com, with hash routing, so mycoolpage.com redirects to mycoolpage.com/#/. For referral, however, a link such as mycoolpage.com?referrer=foo should also be usable. Unfortunately, Angular immediately strips the request parameters, going directly to mycoolpage.com/#/.

Any kind of 'trick' with using an empty component + AuthGuard and getting queryParams or queryParamMap did, unfortunately, not work for me. They were always empty.

My hacky solution ended up being to handle this in a small script in index.html which gets the full URL, with request parameters. I then get the request param value via string manipulation and set it on window object. A separate service then handles getting the id from the window object.

index.html script

const paramIndex = window.location.href.indexOf('referrer=');
if (!window.myRef && paramIndex > 0) {
  let param = window.location.href.substring(paramIndex);
  param = param.split('&')[0];
  param = param.substr(param.indexOf('=')+1);
  window.myRef = param;
}

Service

declare var window: any;

@Injectable()
export class ReferrerService {

  getReferrerId() {
    if (window.myRef) {
      return window.myRef;
    }
    return null;
  }
}

Why are exclamation marks used in Ruby methods?

!

I like to think of this as an explosive change that destroys all that has gone before it. Bang or exclamation mark means that you are making a permanent saved change in your code.

If you use for example Ruby's method for global substitutiongsub!the substitution you make is permanent.

Another way you can imagine it, is opening a text file and doing find and replace, followed by saving. ! does the same in your code.

Another useful reminder if you come from the bash world is sed -i has this similar effect of making permanent saved change.

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

How can I list the scheduled jobs running in my database?

I think you need the SCHEDULER_ADMIN role to see the dba_scheduler tables (however this may grant you too may rights)

see: http://download.oracle.com/docs/cd/B28359_01/server.111/b28310/schedadmin001.htm

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

Twitter bootstrap float div right

bootstrap 3 has a class to align the text within a div

<div class="text-right">

will align the text on the right

<div class="pull-right">

will pull to the right all the content not only the text

Google Map API v3 ~ Simply Close an infowindow?

We can use infowindow.close(map); to close all info windows if you already initialize the info window using infowindow = new google.maps.InfoWindow();

How to change max_allowed_packet size

Many of the answerers spotted the issue and already gave the solution.

I just want to suggest another solution, which is changing the Glogal variable value from within the tool Mysql Workbench. That is ofcourse IF you use Workbench running locally on server (or via SSH connection)

You just connect to your instance and go on menu:

Server -> Options File -> Networking -> max_allowed_packed

You set the desired value and then you need to restart MySql Service.

Is it not possible to stringify an Error using JSON.stringify?

I was working on a JSON format for log appenders and ended up here trying to solve a similar problem. After a while, I realized I could just make Node do the work:

const util = require("util");
...
return JSON.stringify(obj, (name, value) => {
    if (value instanceof Error) {
        return util.format(value);
    } else {
        return value;
    }
}

How to capture the "virtual keyboard show/hide" event in Android?

I have sort of a hack to do this. Although there doesn't seem to be a way to detect when the soft keyboard has shown or hidden, you can in fact detect when it is about to be shown or hidden by setting an OnFocusChangeListener on the EditText that you're listening to.

EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            //hasFocus tells us whether soft keyboard is about to show
        }
    });

NOTE: One thing to be aware of with this hack is that this callback is fired immediately when the EditText gains or loses focus. This will actually fire right before the soft keyboard shows or hides. The best way I've found to do something after the keyboard shows or hides is to use a Handler and delay something ~ 400ms, like so:

EditText et = (EditText) findViewById(R.id.et);
et.setOnFocusChangeListener(new View.OnFocusChangeListener()
    {
        @Override
        public void onFocusChange(View view, boolean hasFocus)
        {
            new Handler().postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        //do work here
                    }
                }, 400);
        }
    });

UITableView - scroll to the top

func scrollToTop() {
        NSIndexPath *topItem = [NSIndexPath indexPathForItem:0 inSection:0];
        [tableView scrollToRowAtIndexPath:topItem atScrollPosition:UITableViewScrollPositionTop animated:YES];
}

call this function wherever you want UITableView scroll to top

c# datagridview doubleclick on row with FullRowSelect

Don't manually edit the .designer files in visual studio that usually leads to headaches. Instead either specify it in the properties section of your DataGridRow which should be contained within a DataGrid element. Or if you just want VS to do it for you find the double click event within the properties page->events (little lightning bolt icon) and double click the text area where you would enter a function name for that event.

This link should help

http://msdn.microsoft.com/en-us/library/6w2tb12s(v=vs.90).aspx

How to get year, month, day, hours, minutes, seconds and milliseconds of the current moment in Java?

Or use java.sql.Timestamp. Calendar is kinda heavy,I would recommend against using it in production code. Joda is better.

import java.sql.Timestamp;

public class DateTest {

    /**
     * @param args
     */
    public static void main(String[] args) {
        System.out.println(new Timestamp(System.currentTimeMillis()));
    }
}

Way to insert text having ' (apostrophe) into a SQL table

I know the question is aimed at the direct escaping of the apostrophe character but I assume that usually this is going to be triggered by some sort of program providing the input.

What I have done universally in the scripts and programs I have worked with is to substitute it with a ` character when processing the formatting of the text being input.

Now I know that in some cases, the backtick character may in fact be part of what you might be trying to save (such as on a forum like this) but if you're simply saving text input from users it's a possible solution.

Going into the SQL database

$newval=~s/\'/`/g;

Then, when coming back out for display, filtered again like this:

$showval=~s/`/\'/g;

This example was when PERL/CGI is being used but it can apply to PHP and other bases as well. I have found it works well because I think it helps prevent possible injection attempts, because all ' are removed prior to attempting an insertion of a record.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

Get the new record primary key ID from MySQL insert query?

From the LAST_INSERT_ID() documentation:

The ID that was generated is maintained in the server on a per-connection basis

That is if you have two separate requests to the script simultaneously they won't affect each others' LAST_INSERT_ID() (unless you're using a persistent connection perhaps).

Bootstrap carousel width and height

I had the same problem.

My height changed to its original height while my slide was animating to the left, ( in a responsive website )

so I fixed it with CSS only :

.carousel .item.left img{
    width: 100% !important;
}

Turn off deprecated errors in PHP 5.3

this error occur when you change your php version: it's very simple to suppress this error message

To suppress the DEPRECATED Error message, just add below code into your index.php file:

init_set('display_errors',False);

How to connect Android app to MySQL database?

Yes you can connect your android app to your PHP to grab results from your database. Use a webservice to connect to your backend script via ASYNC task and http post requests. Check this link for more information Connecting to MySQL

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

Had the same problem until I tried deleting the .git folder. It worked. I guess this type of problem can have different causes.

ReactJS Two components communicating

If you want to explore options of communicating between components and feel like it is getting harder and harder, then you might consider adopting a good design pattern: Flux.

It is simply a collection of rules that defines how you store and mutate application wide state, and use that state to render components.

There are many Flux implementations, and Facebook's official implementation is one of them. Although it is considered the one that contains most boilerplate code, but it is easier to understand since most of the things are explicit.

Some of Other alternatives are flummox fluxxor fluxible and redux.

How to write PNG image to string with the PIL?

For Python3 it is required to use BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

Creating a chart in Excel that ignores #N/A or blank cells

This is what I found as I was plotting only 3 cells from each 4 columns lumped together. My chart has a merged cell with the date which is my x axis. The problem: BC26-BE27 are plotting as ZERO on my chart. enter image description here

I click on the filter on the side of the chart and found where it is showing all the columns for which the data points are charted. I unchecked the boxes that do not have values. enter image description here

It worked for me.

How to print register values in GDB?

  • If only want check it once, info registers show registers.
  • If only want watch one register, for example, display $esp continue display esp registers in gdb command line.
  • If want watch all registers, layout regs continue show registers, with TUI mode.

sizing div based on window width

html, body {
    height: 100%;
    width: 100%;
}

html {
    display: table;
    margin: auto;
}

body {
    padding-top: 50px;
    display: table-cell;
}

div {
    margin: auto;
}

This will center align objects and then also center align the items within them to center align multiple objects with different widths.

Example picture

Why Python 3.6.1 throws AttributeError: module 'enum' has no attribute 'IntFlag'?

For me this error occured after installing of gcloud component app-engine-python in order to integrate into pycharm. Uninstalling the module helped, even if pycharm is now not uploading to app-engine.

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

Showing the same file in both columns of a Sublime Text window

Yes, you can. When a file is open, click on File -> New View Into File. You can then drag the new tab to the other pane and view the file twice.

There are several ways to create a new pane. As described in other answers, on Linux and Windows, you can use AltShift2 (Option ?Command ?2 on OS X), which corresponds to View ? Layout ? Columns: 2 in the menu. If you have the excellent Origami plugin installed, you can use View ? Origami ? Pane ? Create ? Right, or the CtrlK, Ctrl? chord on Windows/Linux (replace Ctrl with ? on OS X).

regular expression for DOT

[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.

How may I sort a list alphabetically using jQuery?

You do not need jQuery to do this...

function sortUnorderedList(ul, sortDescending) {
  if(typeof ul == "string")
    ul = document.getElementById(ul);

  // Idiot-proof, remove if you want
  if(!ul) {
    alert("The UL object is null!");
    return;
  }

  // Get the list items and setup an array for sorting
  var lis = ul.getElementsByTagName("LI");
  var vals = [];

  // Populate the array
  for(var i = 0, l = lis.length; i < l; i++)
    vals.push(lis[i].innerHTML);

  // Sort it
  vals.sort();

  // Sometimes you gotta DESC
  if(sortDescending)
    vals.reverse();

  // Change the list on the page
  for(var i = 0, l = lis.length; i < l; i++)
    lis[i].innerHTML = vals[i];
}

Easy to use...

sortUnorderedList("ID_OF_LIST");

Live Demo →

jQuery append text inside of an existing paragraph tag

Try this...

$('p').append('<span id="add_here">new-dynamic-text</span>');

OR if there is an existing span, do this.

$('p').children('span').text('new-dynamic-text');

DEMO

keytool error bash: keytool: command not found

Please follow the steps:

  1. first set the domain using setDomain.sh command go to domain/bin location and execute ./setDomain.sh command

  2. go to java/bin folder and execute keytool command.

keytool -genkey -keyalg RSA -kaysize 2048 -alias name -kaystore file.jks

Angular Material: mat-select not selecting default

A very simple way to achieve this is using a formControl with a default value, inside a FormGroup (optional) for example. This is an example using an unit selector to an area input:

ts

H_AREA_UNIT = 1;
M_AREA_UNIT = 2;

exampleForm: FormGroup;

this.exampleForm = this.formBuilder.group({
  areaUnit: [this.H_AREA_UNIT],
});

html

<form [formGroup]="exampleForm">
 <mat-form-field>
   <mat-label>Unit</mat-label>
   <mat-select formControlName="areaUnit">
     <mat-option [value]="H_AREA_UNIT">h</mat-option>
     <mat-option [value]="M_AREA_UNIT">m</mat-option>
   </mat-select>
 </mat-form-field>
</form>

keyword not supported data source

I was getting the same error, then updated my connection string as below,

<add name="EmployeeContext" connectionString="data source=*****;initial catalog=EmployeeDB;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework" providerName="System.Data.SqlClient" />

Try this it will solve your issue.

Convert any object to a byte[]

What you're looking for is serialization. There are several forms of serialization available for the .Net platform

jQuery change event on dropdown

The html

<select id="drop"  name="company" class="company btn btn-outline   dropdown-toggle" >
   <option value="demo1">Group Medical</option>
   <option value="demo">Motor Insurance</option>
</select>

Script.js

$("#drop").change(function () {                            
   var category= $('select[name=company]').val() // Here we can get the value of selected item
   alert(category); 
});

Search for string within text column in MySQL

When you are using the wordpress prepare line, the above solutions do not work. This is the solution I used:

   $Table_Name    = $wpdb->prefix.'tablename';
   $SearchField = '%'. $YourVariable . '%';   
   $sql_query     = $wpdb->prepare("SELECT * FROM $Table_Name WHERE ColumnName LIKE %s", $SearchField) ;
 $rows = $wpdb->get_results($sql_query, ARRAY_A);

SQL Server Escape an Underscore

Obviously @Lasse solution is right, but there's another way to solve your problem: T-SQL operator LIKE defines the optional ESCAPE clause, that lets you declare a character which will escape the next character into the pattern.

For your case, the following WHERE clauses are equivalent:

WHERE username LIKE '%[_]d';            -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';

Git: How to update/checkout a single file from remote origin master?

Following code worked for me:

     git fetch
     git checkout <branch from which file needs to be fetched> <filepath> 

find if an integer exists in a list of integers

The best of code and complete is here:

NumbersList.Exists(p => p.Equals(Input)

Use:

List<int> NumbersList = new List<int>();
private void button1_Click(object sender, EventArgs e)
{
    int Input = Convert.ToInt32(textBox1.Text);
    if (!NumbersList.Exists(p => p.Equals(Input)))
    {
       NumbersList.Add(Input);
    }
    else
    {
        MessageBox.Show("The number entered is in the list","Error");
    }
}

Reducing MongoDB database file size

I had the same problem, and solved by simply doing this at the command line:

mongodump -d databasename
echo 'db.dropDatabase()' | mongo databasename
mongorestore dump/databasename

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

For me the database was not created and EF code first should have created it but always endet in this error. The same connection string was working in aspnet core default web project. The solution was to add

_dbContext.Database.EnsureCreated()

before the first database contact (before DB seeding).

How to use a variable for the database name in T-SQL?

You cannot use a variable in a create table statement. The best thing I can suggest is to write the entire query as a string and exec that.

Try something like this:

declare @query varchar(max);
set @query = 'create database TEST...';

exec (@query);

How to return a value from a Form in C#?

I use MDI quite a lot, I like it much more (where it can be used) than multiple floating forms.

But to get the best from it you need to get to grips with your own events. It makes life so much easier for you.

A skeletal example.

Have your own interupt types,

//Clock, Stock and Accoubts represent the actual forms in
//the MDI application. When I have multiple copies of a form
//I also give them an ID, at the time they are created, then
//include that ID in the Args class.
public enum InteruptSource
{
    IS_CLOCK = 0, IS_STOCKS, IS_ACCOUNTS
}
//This particular event type is time based,
//but you can add others to it, such as document
//based.
public enum EVInterupts
{
    CI_NEWDAY = 0, CI_NEWMONTH, CI_NEWYEAR, CI_PAYDAY, CI_STOCKPAYOUT, 
   CI_STOCKIN, DO_NEWEMAIL, DO_SAVETOARCHIVE
}

Then your own Args type

public class ControlArgs
{
    //MDI form source
    public InteruptSource source { get; set; }
    //Interrupt type
    public EVInterupts clockInt { get; set; }
    //in this case only a date is needed
    //but normally I include optional data (as if a C UNION type)
    //the form that responds to the event decides if
    //the data is for it.
    public DateTime date { get; set; }
    //CI_STOCKIN
    public StockClass inStock { get; set; }

}

Then use the delegate within your namespace, but outside of a class

namespace MyApplication
{
public delegate void StoreHandler(object sender, ControlArgs e);
  public partial class Form1 : Form
{
  //your main form
}

Now either manually or using the GUI, have the MDIparent respond to the events of the child forms.

But with your owr Args, you can reduce this to a single function. and you can have provision to interupt the interupts, good for debugging, but can be usefull in other ways too.

Just have al of your mdiparent event codes point to the one function,

        calendar.Friday += new StoreHandler(MyEvents);
        calendar.Saturday += new StoreHandler(MyEvents);
        calendar.Sunday += new StoreHandler(MyEvents);
        calendar.PayDay += new StoreHandler(MyEvents);
        calendar.NewYear += new StoreHandler(MyEvents);

A simple switch mechanism is usually enough to pass events on to appropriate forms.

Export pictures from excel file into jpg using VBA

Dim filepath as string
Sheets("Sheet 1").ChartObjects("Chart 1").Chart.Export filepath & "Name.jpg"

Slimmed down the code to the absolute minimum if needed.

How to convert OutputStream to InputStream?

The easystream open source library has direct support to convert an OutputStream to an InputStream: http://io-tools.sourceforge.net/easystream/tutorial/tutorial.html

// create conversion
final OutputStreamToInputStream<Void> out = new OutputStreamToInputStream<Void>() {
    @Override
    protected Void doRead(final InputStream in) throws Exception {
           LibraryClass2.processDataFromInputStream(in);
           return null;
        }
    };
try {   
     LibraryClass1.writeDataToTheOutputStream(out);
} finally {
     // don't miss the close (or a thread would not terminate correctly).
     out.close();
}

They also list other options: http://io-tools.sourceforge.net/easystream/outputstream_to_inputstream/implementations.html

  • Write the data the data into a memory buffer (ByteArrayOutputStream) get the byteArray and read it again with a ByteArrayInputStream. This is the best approach if you're sure your data fits into memory.
  • Copy your data to a temporary file and read it back.
  • Use pipes: this is the best approach both for memory usage and speed (you can take full advantage of the multi-core processors) and also the standard solution offered by Sun.
  • Use InputStreamFromOutputStream and OutputStreamToInputStream from the easystream library.

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

How to set the custom border color of UIView programmatically?

Write the code in your viewDidLoad()

self.view.layer.borderColor = anyColor().CGColor

And you can set Color with RGB

func anyColor() -> UIColor {
    return UIColor(red: 0.0/255.0, green: 0.0/255.0, blue: 0.0/255.0, alpha: 1.0)
}

Learn something about CALayer in UIKit

How can I fix the 'Missing Cross-Origin Resource Sharing (CORS) Response Header' webfont issue?

In your particular case the issue seem to be with accessing the site from non-canonical url (www.site.com vs. site.com).

Instead of fixing CORS issue (which may require writing proxy to server fonts with proper CORS headers depending on service provider) you can normalize your Urls to always server content on canonical Url and simply redirect if one requests page without "www.".

Alternatively you can upload fonts to different server/CDN that is known to have CORS headers configured or you can easily do so.

show distinct column values in pyspark dataframe: python

You can use df.dropDuplicates(['col1','col2']) to get only distinct rows based on colX in the array.

How to delete all data from solr and hbase

I've used this request to delete all my records but sometimes it's necessary to commit this.

For that, add &commit=true to your request :

http://host:port/solr/core/update?stream.body=<delete><query>*:*</query></delete>&commit=true

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

Add the repository and update apt-get:

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Install Java8 and set it as default:

sudo apt-get install oracle-java8-set-default

Check version:

java -version

How to create a printable Twitter-Bootstrap page

Replace every col-md- with col-xs-

eg: replace every col-md-6 to col-xs-6.

This is the thing that worked for me to get me rid of this problem you can see what you have to replace.

Quick way to retrieve user information Active Directory

I'm not sure how much of your "slowness" will be due to the loop you're doing to find entries with particular attribute values, but you can remove this loop by being more specific with your filter. Try this page for some guidance ... Search Filter Syntax

Any way to make plot points in scatterplot more transparent in R?

If you decide to use ggplot2, you can set transparency of overlapping points using the alpha argument.

e.g.

library(ggplot2)
ggplot(diamonds, aes(carat, price)) + geom_point(alpha = 1/40)

How to use color picker (eye dropper)?

It is just called the eyedropper tool. There is no shortcut key for it that I'm aware of. The only way you can use it now is by clicking on the color picker box in styles sidebar and then clicking on the page as you have already been doing.

How to create a GUID/UUID using iOS

The simplest technique is to use NSString *uuid = [[NSProcessInfo processInfo] globallyUniqueString]. See the NSProcessInfo class reference.

MySQL foreign key constraints, cascade delete

I got confused by the answer to this question, so I created a test case in MySQL, hope this helps

-- Schema
CREATE TABLE T1 (
    `ID` int not null auto_increment,
    `Label` varchar(50),
    primary key (`ID`)
);

CREATE TABLE T2 (
    `ID` int not null auto_increment,
    `Label` varchar(50),
    primary key (`ID`)
);

CREATE TABLE TT (
    `IDT1` int not null,
    `IDT2` int not null,
    primary key (`IDT1`,`IDT2`)
);

ALTER TABLE `TT`
    ADD CONSTRAINT `fk_tt_t1` FOREIGN KEY (`IDT1`) REFERENCES `T1`(`ID`) ON DELETE CASCADE,
    ADD CONSTRAINT `fk_tt_t2` FOREIGN KEY (`IDT2`) REFERENCES `T2`(`ID`) ON DELETE CASCADE;

-- Data
INSERT INTO `T1` (`Label`) VALUES ('T1V1'),('T1V2'),('T1V3'),('T1V4');
INSERT INTO `T2` (`Label`) VALUES ('T2V1'),('T2V2'),('T2V3'),('T2V4');
INSERT INTO `TT` (`IDT1`,`IDT2`) VALUES
(1,1),(1,2),(1,3),(1,4),
(2,1),(2,2),(2,3),(2,4),
(3,1),(3,2),(3,3),(3,4),
(4,1),(4,2),(4,3),(4,4);

-- Delete
DELETE FROM `T2` WHERE `ID`=4; -- Delete one field, all the associated fields on tt, will be deleted, no change in T1
TRUNCATE `T2`; -- Can't truncate a table with a referenced field
DELETE FROM `T2`; -- This will do the job, delete all fields from T2, and all associations from TT, no change in T1

SQL Server: Maximum character length of object names

Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.

And the verification can be easily made with the following script contained in the blog post before:

DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)

What port is used by Java RMI connection?

From the javadoc of java.rmi.registry.Registry

Therefore, a registry's remote object implementation is typically exported with a well-known address, such as with a well-known ObjID and TCP port number (default is 1099).

See more in the javadoc of java.rmi.registry.LocateRegistry.

Android textview usage as label and value

You should implement a Custom List View, such that you define a Layout once and draw it for every row in the list view.

Correct way to populate an Array with a Range in Ruby

This works for me in irb:

irb> (1..4).to_a
=> [1, 2, 3, 4]

I notice that:

irb> 1..4.to_a
(irb):1: warning: default `to_a' will be obsolete
ArgumentError: bad value for range
        from (irb):1

So perhaps you are missing the parentheses?

(I am running Ruby 1.8.6 patchlevel 114)

Convert data.frame column format from character to factor

# To do it for all names
df[] <- lapply( df, factor) # the "[]" keeps the dataframe structure
 col_names <- names(df)
# to do it for some names in a vector named 'col_names'
df[col_names] <- lapply(df[col_names] , factor)

Explanation. All dataframes are lists and the results of [ used with multiple valued arguments are likewise lists, so looping over lists is the task of lapply. The above assignment will create a set of lists that the function data.frame.[<- should successfully stick back into into the dataframe, df

Another strategy would be to convert only those columns where the number of unique items is less than some criterion, let's say fewer than the log of the number of rows as an example:

cols.to.factor <- sapply( df, function(col) length(unique(col)) < log10(length(col)) )
df[ cols.to.factor] <- lapply(df[ cols.to.factor] , factor)

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

Why do we have to specify FromBody and FromUri?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.

There is a lot more information on the web if you google "web api parameter binding".

How to add a primary key to a MySQL table?

Use this query,

alter table `table_name` add primary key(`column_name`);

What are the differences between a superkey and a candidate key?

A super key of an entity set is a set of one or more attributes whose values uniquely determine each entity.

A candidate key of an entity set is a minimal super key.

Let's go on with customer, loan and borrower sets that you can find an image from the link == 1

  • Rectangles represent entity sets == 1
  • Diamonds represent relationship set == 1
  • Elipses represent attributes == 1
  • Underline indicates Primary Keys == 1

customer_id is the candidate key of the customer set, loan_number is the candidate key of the loan set.

Although several candidate keys may exist, one of the candidate keys is selected to be the primary key.

Borrower set is formed customer_id and loan_number as a relationship set.

Is there a method that tells my program to quit?

One way is to do:

sys.exit(0)

You will have to import sys of course.

Another way is to break out of your infinite loop. For example, you could do this:

while True:
    choice = get_input()
    if choice == "a":
        # do something
    elif choice == "q":
        break

Yet another way is to put your main loop in a function, and use return:

def run():
    while True:
        choice = get_input()
        if choice == "a":
            # do something
        elif choice == "q":
            return

if __name__ == "__main__":
    run()

The only reason you need the run() function when using return is that (unlike some other languages) you can't directly return from the main part of your Python code (the part that's not inside a function).

Slice indices must be integers or None or have __index__ method

Your debut and fin values are floating point values, not integers, because taille is a float.

Make those values integers instead:

item = plateau[int(debut):int(fin)]

Alternatively, make taille an integer:

taille = int(sqrt(len(plateau)))