Programs & Examples On #Fulltext index

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

What is the iBeacon Bluetooth Profile

If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:

{
    kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}

See this answer for more information.

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

How to redirect Valgrind's output to a file?

You can also set the options --log-fd if you just want to read your logs with a less. For example :

valgrind --log-fd=1 ls | less

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 can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How to redirect to an external URL in Angular2?

In your component.ts

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

@Component({
  ...
})
export class AppComponent {
  ...
  goToSpecificUrl(url): void {
    window.location.href=url;
  }

  gotoGoogle() : void {
    window.location.href='https://www.google.com';
  }
}

In your component.html

<button type="button" (click)="goToSpecificUrl('http://stackoverflow.com/')">Open URL</button>
<button type="button" (click)="gotoGoogle()">Open Google</button>

<li *ngFor="item of itemList" (click)="goToSpecificUrl(item.link)"> // (click) don't enable pointer when we hover so we should enable it by using css like: **cursor: pointer;**

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

FOR SQLALCHEMY AND PYTHON

The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.

enter link description here

Adding click event listener to elements with the same class

(ES5) I use forEach to iterate on the collection returned by querySelectorAll and it works well :

document.querySelectorAll('your_selector').forEach(item => { /* do the job with item element */ });

Oracle PL/SQL string compare issue

To fix the core question, "how should I detect that these two variables don't have the same value when one of them is null?", I don't like the approach of nvl(my_column, 'some value that will never, ever, ever appear in the data and I can be absolutely sure of that') because you can't always guarantee that a value won't appear... especially with NUMBERs.

I have used the following:

if (str1 is null) <> (str2 is null) or str1 <> str2 then
  dbms_output.put_line('not equal');
end if;

Disclaimer: I am not an Oracle wizard and I came up with this one myself and have not seen it elsewhere, so there may be some subtle reason why it's a bad idea. But it does avoid the trap mentioned by APC, that comparing a null to something else gives neither TRUE nor FALSE but NULL. Because the clauses (str1 is null) will always return TRUE or FALSE, never null.

(Note that PL/SQL performs short-circuit evaluation, as noted here.)

Git copy changes from one branch to another

Merge the changes from BranchA to BranchB. When you are on BranchB execute git merge BranchA

Deleting folders in python recursively

Here is a recursive solution:

def clear_folder(dir):
    if os.path.exists(dir):
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path)
                else:
                    clear_folder(file_path)
                    os.rmdir(file_path)
            except Exception as e:
                print(e)

Inserting an image with PHP and FPDF

You can use $pdf->GetX() and $pdf->GetY() to get current cooridnates and use them to insert image.

$pdf->Image($image1, 5, $pdf->GetY(), 33.78);

or even

$pdf->Image($image1, 5, null, 33.78);

(ALthough in first case you can add a number to create a bit of a space)

$pdf->Image($image1, 5, $pdf->GetY() + 5, 33.78);

What is the color code for transparency in CSS?

Or you could just put

background-color: rgba(0,0,0,0.0);

That should solve your problem.

Passing variable from Form to Module in VBA

Don't declare the variable in the userform. Declare it as Public in the module.

Public pass As String

In the Userform

Private Sub CommandButton1_Click()
    pass = UserForm1.TextBox1
    Unload UserForm1
End Sub

In the Module

Public pass As String

Public Sub Login()
    '
    '~~> Rest of the code
    '
    UserForm1.Show
    driver.findElementByName("PASSWORD").SendKeys pass
    '
    '~~> Rest of the code
    '
End Sub

You might want to also add an additional check just before calling the driver.find... line?

If Len(Trim(pass)) <> 0 Then

This will ensure that a blank string is not passed.

How do I include negative decimal numbers in this regular expression?

^(-?\d+\.)?-?\d+$

allow:

23425.23425
10.10
100
0
0.00
-100
-10.10
10.-10
-10.-10
-23425.23425
-23425.-23425
0.234

Select method of Range class failed via VBA

Here is a solution worked for me and also, I found all of the above solutions are correct. My excel model got corrupted and which is why my code (similar to this one) stopped working. Here is what worked for me and is working every time-

  1. Calculate the workbook- Formulas->Calculate Now (under calculation section)
  2. Save the workbook
  3. Close and re-open the file. It was fixed and works every time.

Git add and commit in one command

In case someone would like to "add and commit" for a single file, which was my case, I created the script bellow to do just that:

#!/bin/bash

function usage {
    echo "Usage: $(basename $0) <filename> <commit_message>"    
}

function die {
    declare MSG="$@"
    echo -e "$0: Error: $MSG">&2
    exit 1
}

(( "$#" == 2 )) || die "Wrong arguments.\n\n$(usage)"

FILE=$1
COMMIT_MESSAGE=$2

[ -f $FILE ] || die "File $FILE does not exist"

echo -n adding $FILE to git...
git add $FILE || die "git add $FILE has failed."
echo done

echo "commiting $file to git..."
git commit -m "$COMMIT_MESSAGE" || die "git commit has failed."

exit 0

I named it "gitfile.sh" and added it to my $PATH. Then I can run git add and commit for a single file in one command:

gitfile.sh /path/to/file "MY COMMIT MESSAGE"

Https Connection Android

I don't know about the Android specifics for ssl certificates, but it would make sense that Android won't accept a self signed ssl certificate off the bat. I found this post from android forums which seems to be addressing the same issue: http://androidforums.com/android-applications/950-imap-self-signed-ssl-certificates.html

What is the correct wget command syntax for HTTPS with username and password?

It's not that your file is partially downloaded. It fails authentication and hence downloads e.g "index.html" but it names it myfile.zip (since this is what you want to download).

I followed the link suggested by @thomasbabuj and figured it out eventually.

You should try adding --auth-no-challenge and as @thomasbabuj suggested replace your password entry

I.e

wget --auth-no-challenge --user=myusername --ask-password https://test.mydomain.com/files/myfile.zip

Random strings in Python

Answer to the original question:

os.urandom(n)

Quote from: http://docs.python.org/2/library/os.html

Return a string of n random bytes suitable for cryptographic use.

This function returns random bytes from an OS-specific randomness source. The returned data should be unpredictable enough for cryptographic applications, though its exact quality depends on the OS implementation. On a UNIX-like system this will query /dev/urandom, and on Windows it will use CryptGenRandom. If a randomness source is not found, NotImplementedError will be raised.

For an easy-to-use interface to the random number generator provided by your platform, please see random.SystemRandom.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Detecting the onload event of a window opened with window.open

First of all, when your first initial window is loaded, it is cached. Therefore, when creating a new window from the first window, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onload event occurs when you create the new window.

However, in this case, an onpageshow event occurs. It always occurs after the onload event and even when the page is loaded from cache. Plus, it now supported by all major browsers.

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onpageshow = function() {
     alert("Popup has loaded a page");
 };

The w3school website elaborates more on this:

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

You probably do not need to be making lists and appending them to make your array. You can likely just do it all at once, which is faster since you can use numpy to do your loops instead of doing them yourself in pure python.

To answer your question, as others have said, you cannot access a nested list with two indices like you did. You can if you convert mean_data to an array before not after you try to slice it:

R = np.array(mean_data)[:,0]

instead of

R = np.array(mean_data[:,0])

But, assuming mean_data has a shape nx3, instead of

R = np.array(mean_data)[:,0]
P = np.array(mean_data)[:,1]
Z = np.array(mean_data)[:,2]

You can simply do

A = np.array(mean_data).mean(axis=0)

which averages over the 0th axis and returns a length-n array

But to my original point, I will make up some data to try to illustrate how you can do this without building any lists one item at a time:

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

How to use HTTP.GET in AngularJS correctly? In specific, for an external API call?

Using Google Finance as an example to retrieve the ticker's last close price and the updated date & time. You may visit YouTiming.com for the run-time execution.

The service:

MyApp.service('getData', 
  [
    '$http',
    function($http) {

      this.getQuote = function(ticker) {
        var _url = 'https://www.google.com/finance/info?q=' + ticker;
        return $http.get(_url); //Simply return the promise to the caller
      };
    }
  ]
);

The controller:

MyApp.controller('StockREST', 
  [
    '$scope',
    'getData', //<-- the service above
    function($scope, getData) {
      var getQuote = function(symbol) {
        getData.getQuote(symbol)
        .success(function(response, status, headers, config) {
          var _data = response.substring(4, response.length);
          var _json = JSON.parse(_data);
          $scope.stockQuoteData = _json[0];
          // ticker: $scope.stockQuoteData.t
          // last price: $scope.stockQuoteData.l
          // last updated time: $scope.stockQuoteData.ltt, such as "7:59PM EDT"
          // last updated date & time: $scope.stockQuoteData.lt, such as "Sep 29, 7:59PM EDT"
        })
        .error(function(response, status, headers, config) {
          console.log('@@@ Error: in retrieving Google Finance stock quote, ticker = ' + symbol);
        });
      };

      getQuote($scope.ticker.tick.name); //Initialize
      $scope.getQuote = getQuote; //as defined above
    }
  ]
);

The HTML:

<span>{{stockQuoteData.l}}, {{stockQuoteData.lt}}</span>

At the top of YouTiming.com home page, I have placed the notes for how to disable the CORS policy on Chrome and Safari.

Simplest SOAP example

Has anyone tried this? https://github.com/doedje/jquery.soap

Seems very easy to implement.

Example:

$.soap({
url: 'http://my.server.com/soapservices/',
method: 'helloWorld',

data: {
    name: 'Remy Blom',
    msg: 'Hi!'
},

success: function (soapResponse) {
    // do stuff with soapResponse
    // if you want to have the response as JSON use soapResponse.toJSON();
    // or soapResponse.toString() to get XML string
    // or soapResponse.toXML() to get XML DOM
},
error: function (SOAPResponse) {
    // show error
}
});

will result in

<soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <helloWorld>
        <name>Remy Blom</name>
        <msg>Hi!</msg>
    </helloWorld>
  </soap:Body>
</soap:Envelope>

How to fix: "UnicodeDecodeError: 'ascii' codec can't decode byte"

This is the classic "unicode issue". I believe that explaining this is beyond the scope of a StackOverflow answer to completely explain what is happening.

It is well explained here.

In very brief summary, you have passed something that is being interpreted as a string of bytes to something that needs to decode it into Unicode characters, but the default codec (ascii) is failing.

The presentation I pointed you to provides advice for avoiding this. Make your code a "unicode sandwich". In Python 2, the use of from __future__ import unicode_literals helps.

Update: how can the code be fixed:

OK - in your variable "source" you have some bytes. It is not clear from your question how they got in there - maybe you read them from a web form? In any case, they are not encoded with ascii, but python is trying to convert them to unicode assuming that they are. You need to explicitly tell it what the encoding is. This means that you need to know what the encoding is! That is not always easy, and it depends entirely on where this string came from. You could experiment with some common encodings - for example UTF-8. You tell unicode() the encoding as a second parameter:

source = unicode(source, 'utf-8')

How to get a variable type in Typescript?

I have checked a variable if it is a boolean or not as below

console.log(isBoolean(this.myVariable));

Similarly we have

isNumber(this.myVariable);
isString(this.myvariable);

and so on.

How to check the version before installing a package using apt-get?

apt-cache policy <package-name>

$ apt-cache policy redis-server
redis-server:
  Installed: (none)
  Candidate: 2:2.8.4-2
  Version table:
     2:2.8.4-2 0
        500 http://us.archive.ubuntu.com/ubuntu/ trusty/universe amd64 Packages

apt-get install -s <package-name>

$ apt-get install -s redis-server
NOTE: This is only a simulation!
      apt-get needs root privileges for real execution.
      Keep also in mind that locking is deactivated,
      so don't depend on the relevance to the real current situation!
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following extra packages will be installed:
  libjemalloc1 redis-tools
The following NEW packages will be installed:
  libjemalloc1 redis-server redis-tools
0 upgraded, 3 newly installed, 0 to remove and 3 not upgraded.
Inst libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Inst redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Inst redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf libjemalloc1 (3.5.1-2 Ubuntu:14.04/trusty [amd64])
Conf redis-tools (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])
Conf redis-server (2:2.8.4-2 Ubuntu:14.04/trusty [amd64])

apt-cache show <package-name>

$ apt-cache show redis-server
Package: redis-server
Priority: optional
Section: universe/misc
Installed-Size: 744
Maintainer: Ubuntu Developers <[email protected]>
Original-Maintainer: Chris Lamb <[email protected]>
Architecture: amd64
Source: redis
Version: 2:2.8.4-2
Depends: libc6 (>= 2.14), libjemalloc1 (>= 2.1.1), redis-tools (= 2:2.8.4-2), adduser
Filename: pool/universe/r/redis/redis-server_2.8.4-2_amd64.deb
Size: 267446
MD5sum: 066f3ce93331b876b691df69d11b7e36
SHA1: f7ffbf228cc10aa6ff23ecc16f8c744928d7782e
SHA256: 2d273574f134dc0d8d10d41b5eab54114dfcf8b716bad4e6d04ad8452fe1627d
Description-en: Persistent key-value database with network interface
 Redis is a key-value database in a similar vein to memcache but the dataset
 is non-volatile. Redis additionally provides native support for atomically
 manipulating and querying data structures such as lists and sets.
 .
 The dataset is stored entirely in memory and periodically flushed to disk.
Description-md5: 9160ed1405585ab844f8750a9305d33f
Homepage: http://redis.io/
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Origin: Ubunt

dpkg -l <package-name>

$ dpkg -l nginx
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                                     Version                   Architecture              Description
+++-========================================-=========================-=========================-=====================================================================================
ii  nginx                                    1.6.2-1~trusty            amd64                     high performance web server

How to run Spyder in virtual environment?

On Windows:

You can create a shortcut executing

Anaconda3\pythonw.exe Anaconda3\cwp.py Anaconda3\envs\<your_env> Anaconda3\envs\<your env>\pythonw.exe Anaconda3\envs\<your_env>\Scripts\spyder-script.py

However, if you started spyder from your venv inside Anaconda shell, it creates this shortcut for you automatically in the Windows menu. The steps:

  1. install spyder in your venv using the methods mentioned in the other answers here.

  2. (in anaconda:) activate testenv

  3. Look up the windows menu "recently added" or just search for "spyder" in the windows menu, find spyder (testenv) and

  • [add that to taskbar] and / or

  • [look up the file source location] and copy that to your desktop, e.g. from C:\Users\USER\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Anaconda3 (64-bit), where the spyder links for any of my environments can be found.

Now you can directly start spyder from a shortcut without the need to open anaconda prompt.

How to hide Android soft keyboard on EditText

The following line is exactly what is being looked for. This method has been included with API 21, therefore it works for API 21 and above.

edittext.setShowSoftInputOnFocus(false);

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
{
    // ...

    Card(); // <== Declaration of default constructor!

    // ...
};

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {
//nothing
}

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {
//nothing
}

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.


The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.


Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

How to concatenate strings of a string field in a PostgreSQL 'group by' query?

This latest announcement list snippet might be of interest if you'll be upgrading to 8.4:

Until 8.4 comes out with a super-effient native one, you can add the array_accum() function in the PostgreSQL documentation for rolling up any column into an array, which can then be used by application code, or combined with array_to_string() to format it as a list:

http://www.postgresql.org/docs/current/static/xaggr.html

I'd link to the 8.4 development docs but they don't seem to list this feature yet.

String Comparison in Java

Comparing sequencially the letters that have the same position against each other.. more like how you order words in a dictionary

Configure Flask dev server to be visible across the network

I had the same problem, I use PyCharm as an editor and when I created the project, PyCharm created a Flask Server. What I did was create a server with Python in the following way;

Config Python Server PyCharm basically what I did was create a new server but flask if not python

I hope it helps you

set font size in jquery

Try:

$("#"+styleTarget).css({ 'font-size': $(this).val() });

By putting the value in quotes, it becomes a string, and "+$(this).val()+"px is definitely not close to a font value. There are a couple of ways of setting the style properties of an element:

Using a map:

$("#elem").css({
    fontSize: 20
});

Using key and value parameters:

All of these are valid.

$("#elem").css("fontSize", 20);
$("#elem").css("fontSize", "20px");
$("#elem").css("font-size", "20");
$("#elem").css("font-size", "20px");

You can replace "fontSize" with "font-size" but it will have to be quoted then.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

if you use a list of widgets you can use this:

class HomePage extends StatelessWidget {
  bool notNull(Object o) => o != null;
  @override
  Widget build(BuildContext context) {
    var condition = true;
    return Scaffold(
      appBar: AppBar(
        title: Text("Provider Demo"),
      ),
      body: Center(
          child: Column(
        children: <Widget>[
          condition? Text("True"): null,
          Container(
            height: 300,
            width: MediaQuery.of(context).size.width,
            child: Text("Test")
          )
        ].where(notNull).toList(),
      )),
    );
  }
}

java - path to trustStore - set property doesn't work?

Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

should be:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

Hide/Show Action Bar Option Menu Item for different fragments

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

How can I read the contents of an URL with Python?

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Works on python 3 and python 2.
# when server knows where the request is coming from.

import sys

if sys.version_info[0] == 3:
    from urllib.request import urlopen
else:
    from urllib import urlopen
with urlopen('https://www.facebook.com/') as \
    url:
    data = url.read()

print data

# When the server does not know where the request is coming from.
# Works on python 3.

import urllib.request

user_agent = \
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'

url = 'https://www.facebook.com/'
headers = {'User-Agent': user_agent}

request = urllib.request.Request(url, None, headers)
response = urllib.request.urlopen(request)
data = response.read()
print data

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

As johnnyynnoj mentioned ng-repeat creates a new scope. I would in fact use a function to set the value. See plunker

JS:

$scope.setSelected = function(selected) {
  $scope.selected = selected;
}

HTML:

{{ selected }}

<ul>
  <li ng-class="{current: selected == 100}">
     <a href ng:click="setSelected(100)">ABC</a>
  </li>
  <li ng-class="{current: selected == 101}">
     <a href ng:click="setSelected(101)">DEF</a>
  </li>
  <li ng-class="{current: selected == $index }" 
      ng-repeat="x in [4,5,6,7]">
     <a href ng:click="setSelected($index)">A{{$index}}</a>
  </li>
</ul>

<div  
  ng:show="selected == 100">
  100        
</div>
<div  
  ng:show="selected == 101">
  101        
</div>
<div ng-repeat="x in [4,5,6,7]" 
  ng:show="selected == $index">
  {{ $index }}        
</div>

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

I had a similar issue. I was using jQuery.map but I forgot to use jQuery.map(...).get() at the end to work with a normal array.

How does cookie based authentication work?

Cookie-Based Authentication

Cookies based Authentication works normally in these 4 steps-

  1. The user provides a username and password in the login form and clicks Log In.
  2. After the request is made, the server validate the user on the backend by querying in the database. If the request is valid, it will create a session by using the user information fetched from the database and store them, for each session a unique id called session Id is created ,by default session Id is will be given to client through the Browser.
  3. Browser will submit this session Id on each subsequent requests, the session ID is verified against the database, based on this session id website will identify the session belonging to which client and then give access the request.

  4. Once a user logs out of the app, the session is destroyed both client-side and server-side.

How to fetch the row count for all tables in a SQL SERVER database

Don't use SELECT COUNT(*) FROM TABLENAME, since that is a resource intensive operation. One should use SQL Server Dynamic Management Views or System Catalogs to get the row count information for all tables in a database.

cannot make a static reference to the non-static field

You are trying to access non static field directly from static method which is not legal in java. balance is a non static field, so either access it using object reference or make it static.

Position one element relative to another in CSS

position: absolute will position the element by coordinates, relative to the closest positioned ancestor, i.e. the closest parent which isn't position: static.

Have your four divs nested inside the target div, give the target div position: relative, and use position: absolute on the others.

Structure your HTML similar to this:

<div id="container">
  <div class="top left"></div>
  <div class="top right"></div>
  <div class="bottom left"></div>
  <div class="bottom right"></div>
</div>

And this CSS should work:

#container {
  position: relative;
}

#container > * {
  position: absolute;
}

.left {
  left: 0;
}

.right {
  right: 0;
}

.top {
  top: 0;
}

.bottom {
  bottom: 0;
}

...

Writing to a file in a for loop

The main problem was that you were opening/closing files repeatedly inside your loop.

Try this approach:

with open('new.txt') as text_file, open('xyz.txt', 'w') as myfile:  
    for line in text_file:
        var1, var2 = line.split(",");
        myfile.write(var1+'\n')

We open both files at once and because we are using with they will be automatically closed when we are done (or an exception occurs). Previously your output file was repeatedly openend inside your loop.

We are also processing the file line-by-line, rather than reading all of it into memory at once (which can be a problem when you deal with really big files).

Note that write() doesn't append a newline ('\n') so you'll have to do that yourself if you need it (I replaced your writelines() with write() as you are writing a single item, not a list of items).

When opening a file for rread, the 'r' is optional since it's the default mode.

How to set URL query params in Vue with Vue-Router

Without reloading the page or refreshing the dom, history.pushState can do the job.
Add this method in your component or elsewhere to do that:

addParamsToLocation(params) {
  history.pushState(
    {},
    null,
    this.$route.path +
      '?' +
      Object.keys(params)
        .map(key => {
          return (
            encodeURIComponent(key) + '=' + encodeURIComponent(params[key])
          )
        })
        .join('&')
  )
}

So anywhere in your component, call addParamsToLocation({foo: 'bar'}) to push the current location with query params in the window.history stack.

To add query params to current location without pushing a new history entry, use history.replaceState instead.

Tested with Vue 2.6.10 and Nuxt 2.8.1.

Be careful with this method!
Vue Router don't know that url has changed, so it doesn't reflect url after pushState.

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

String "true" and "false" to boolean

You could add to the String class to have the method of to_boolean. Then you could do 'true'.to_boolean or '1'.to_boolean

class String
  def to_boolean
    self == 'true' || self == '1'
  end
end

How to create a foreign key in phpmyadmin

When you create table than you can give like follows.

CREATE TABLE categories(
cat_id int not null auto_increment primary key,
cat_name varchar(255) not null,
cat_description text
) ENGINE=InnoDB;


CREATE TABLE products(
   prd_id int not null auto_increment primary key,
   prd_name varchar(355) not null,
   prd_price decimal,
   cat_id int not null,
   FOREIGN KEY fk_cat(cat_id)
   REFERENCES categories(cat_id)
   ON UPDATE CASCADE
   ON DELETE RESTRICT
)ENGINE=InnoDB;

and when after the table create like this

   ALTER table_name
    ADD CONSTRAINT constraint_name
    FOREIGN KEY foreign_key_name(columns)
    REFERENCES parent_table(columns)
    ON DELETE action
    ON UPDATE action;

Following on example for it.

CREATE TABLE vendors(
    vdr_id int not null auto_increment primary key,
    vdr_name varchar(255)
)ENGINE=InnoDB;

ALTER TABLE products 
ADD COLUMN vdr_id int not null AFTER cat_id;

To add a foreign key to the products table, you use the following statement:

ALTER TABLE products
ADD FOREIGN KEY fk_vendor(vdr_id)
REFERENCES vendors(vdr_id)
ON DELETE NO ACTION
ON UPDATE CASCADE;

For drop the key

ALTER TABLE table_name 
DROP FOREIGN KEY constraint_name;

Hope this help to learn FOREIGN keys works

How to add google-play-services.jar project dependency so my project will run and present map

The quick start guide that keyboardsurfer references will work if you need to get your project to build properly, but it leaves you with a dummy google-play-services project in your Eclipse workspace, and it doesn't properly link Eclipse to the Google Play Services Javadocs.

Here's what I did instead:

  1. Install the Google Play Services SDK using the instructions in the Android Maps V2 Quick Start referenced above, or the instructions to Setup Google Play Services SDK, but do not follow the instructions to add Google Play Services into your project.

  2. Right click on the project in the Package Explorer, select Properties to open the properties for your project.

  3. (Only if you already followed the instructions in the quick start guide!) Remove the dependency on the google-play-services project:

    • Click on the Android category and remove the reference to the google-play-services project.

    • Click on the Java Build Path category, then the Projects tab and remove the reference to the google-play-services project.

  4. Click on the Java Build Path category, then the Libraries tab.

  5. Click Add External JARs... and select the google-play-services.jar file. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\libproject\google-play-services_lib\libs.

  6. Click on the arrow next to the new google-play-services.jar entry, and select the Javadoc Location item.

  7. Click Edit... and select the folder containing the Google Play Services Javadocs. This should be in [Your ADT directory]\sdk\extras\google\google_play_services\docs\reference.

  8. Still in the Java Build Path category, click on the Order and Export tab. Check the box next to the google-play-services.jar entry.

  9. Click OK to save your project properties.

Your project should now have access to the Google Play Services library, and the Javadocs should display properly in Eclipse.

When use getOne and findOne methods Spring Data JPA

1. Why does the getOne(id) method fail?

See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.

2. When I should use the getOne(id) method?

Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.

If you look at the JavaDoc for getOne(ID) under See Also:

See Also:
EntityManager.getReference(Class, Object)

it seems that this method just delegates to the JPA entity manager's implementation.

However, the docs for findOne(ID) do not mention this.

The clue is also in the names of the repositories. JpaRepository is JPA specific and therefore can delegate calls to the entity manager if so needed. CrudRepository is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.

So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID) is more generic than the more specialised getOne(ID). Which one you use is up to you and your project but I would personally stick to the findOne(ID) as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)

What is Activity.finish() method doing exactly?

calling finish in onCreate() will not call onDestroy() directly as @prakash said. The finish() operation will not even begin until you return control to Android.

Calling finish() in onCreate(): onCreate() -> onStart() -> onResume(). If user exit the app will call -> onPause() -> onStop() -> onDestroy()

Calling finish() in onStart() : onCreate() -> onStart() -> onStop() -> onDestroy()

Calling finish() in onResume(): onCreate() -> onStart() -> onResume() -> onPause() -> onStop() -> onDestroy()

For further reference check look at this oncreate continuous after finish & about finish()

Append an empty row in dataframe using pandas

You can add a new series, and name it at the same time. The name will be the index of the new row, and all the values will automatically be NaN.

df.append(pd.Series(name='Afterthought'))

HTTP Error 500.30 - ANCM In-Process Start Failure

In my case it was database connection problem. This error needs to be more clear. I hope they will do it in the future. Basically it is a problem at ConfigureServices function in Startup. My advise is try to add all lines try catch in ConfigureServices function and you can findout where is problem.

How to add a primary key to a MySQL table?

After adding the column, you can always add the primary key:

ALTER TABLE goods ADD PRIMARY KEY(id)

As to why your script wasn't working, you need to specify PRIMARY KEY, not just the word PRIMARY:

alter table goods add column `id` int(10) unsigned primary KEY AUTO_INCREMENT;

Passing arrays as parameters in bash

The basic problem here is that the bash developer(s) that designed/implemented arrays really screwed the pooch. They decided that ${array} was just short hand for ${array[0]}, which was a bad mistake. Especially when you consider that ${array[0]} has no meaning and evaluates to the empty string if the array type is associative.

Assigning an array takes the form array=(value1 ... valueN) where value has the syntax [subscript]=string, thereby assigning a value directly to a particular index in the array. This makes it so there can be two types of arrays, numerically indexed and hash indexed (called associative arrays in bash parlance). It also makes it so that you can create sparse numerically indexed arrays. Leaving off the [subscript]= part is short hand for a numerically indexed array, starting with the ordinal index of 0 and incrementing with each new value in the assignment statement.

Therefore, ${array} should evaluate to the entire array, indexes and all. It should evaluate to the inverse of the assignment statement. Any third year CS major should know that. In that case, this code would work exactly as you might expect it to:

declare -A foo bar
foo=${bar}

Then, passing arrays by value to functions and assigning one array to another would work as the rest of the shell syntax dictates. But because they didn't do this right, the assignment operator = doesn't work for arrays, and arrays can't be passed by value to functions or to subshells or output in general (echo ${array}) without code to chew through it all.

So, if it had been done right, then the following example would show how the usefulness of arrays in bash could be substantially better:

simple=(first=one second=2 third=3)
echo ${simple}

the resulting output should be:

(first=one second=2 third=3)

Then, arrays could use the assignment operator, and be passed by value to functions and even other shell scripts. Easily stored by outputting to a file, and easily loaded from a file into a script.

declare -A foo
read foo <file

Alas, we have been let down by an otherwise superlative bash development team.

As such, to pass an array to a function, there is really only one option, and that is to use the nameref feature:

function funky() {
    local -n ARR

    ARR=$1
    echo "indexes: ${!ARR[@]}"
    echo "values: ${ARR[@]}"
}

declare -A HASH

HASH=([foo]=bar [zoom]=fast)
funky HASH # notice that I'm just passing the word 'HASH' to the function

will result in the following output:

indexes: foo zoom
values: bar fast

Since this is passing by reference, you can also assign to the array in the function. Yes, the array being referenced has to have a global scope, but that shouldn't be too big a deal, considering that this is shell scripting. To pass an associative or sparse indexed array by value to a function requires throwing all the indexes and the values onto the argument list (not too useful if it's a large array) as single strings like this:

funky "${!array[*]}" "${array[*]}"

and then writing a bunch of code inside the function to reassemble the array.

Auto margins don't center image in page

put this in the body's css: background:#3D668F; then add: display: block; margin: auto; to the img's css.

How can I get dict from sqlite query?

Similar like before-mentioned solutions, but most compact:

db.row_factory = lambda C, R: { c[0]: R[i] for i, c in enumerate(C.description) }

iOS download and save image inside app

Since we are on IO5 now, you no longer need to write images to disk neccessarily.
You are now able to set "allow external storage" on an coredata binary attribute. According to apples release notes it means the following:

Small data values like image thumbnails may be efficiently stored in a database, but large photos or other media are best handled directly by the file system. You can now specify that the value of a managed object attribute may be stored as an external record - see setAllowsExternalBinaryDataStorage: When enabled, Core Data heuristically decides on a per-value basis if it should save the data directly in the database or store a URI to a separate file which it manages for you. You cannot query based on the contents of a binary data property if you use this option.

How can I shrink the drawable on a button?

You can call setBounds on the "compound" drawables to modify the size of the image.

Try this code to autosize the drawable of your button:

DroidUtils.scaleButtonDrawables((Button) findViewById(R.id.ButtonTest), 1.0);

defined by this function:

public final class DroidUtils {

    /** scale the Drawables of a button to "fit"
     *  For left and right drawables: height is scaled 
     *  eg. with fitFactor 1 the image has max. the height of the button.
     *  For top and bottom drawables: width is scaled: 
     *  With fitFactor 0.9 the image has max. 90% of the width of the button 
     *  */
    public static void scaleButtonDrawables(Button btn, double fitFactor) {
        Drawable[] drawables = btn.getCompoundDrawables();

        for (int i = 0; i < drawables.length; i++) {
            if (drawables[i] != null) {
                int imgWidth = drawables[i].getIntrinsicWidth();
                int imgHeight = drawables[i].getIntrinsicHeight();
                if ((imgHeight > 0) && (imgWidth > 0)) {    //might be -1
                    float scale;
                    if ((i == 0) || (i == 2)) { //left or right -> scale height
                        scale = (float) (btn.getHeight() * fitFactor) / imgHeight;
                    } else { //top or bottom -> scale width
                        scale = (float) (btn.getWidth() * fitFactor) / imgWidth;                    
                    }
                    if (scale < 1.0) {
                        Rect rect = drawables[i].getBounds();
                        int newWidth = (int)(imgWidth * scale);
                        int newHeight = (int)(imgHeight * scale);
                        rect.left = rect.left + (int)(0.5 * (imgWidth - newWidth)); 
                        rect.top = rect.top + (int)(0.5 * (imgHeight - newHeight));
                        rect.right = rect.left + newWidth;
                        rect.bottom = rect.top + newHeight;
                        drawables[i].setBounds(rect);
                    }
                }
            }
        }
    }
}

Be aware, that this may not be called in onCreate() of an activity, because button height and width are not (yet) available there. Call this in on onWindowFocusChanged() or use this solution to call the function.

Edited:

The first incarnation of this function did not work correctly. It used userSeven7s code to scale the image, but returning ScaleDrawable.getDrawable() does not seem to work (neither does returning ScaleDrawable) for me.

The modified code uses setBounds to provide the bounds for the image. Android fits the image into these bounds.

What are the main performance differences between varchar and nvarchar SQL Server data types?

For that last few years all of our projects have used NVARCHAR for everything, since all of these projects are multilingual. Imported data from external sources (e.g. an ASCII file, etc.) is up-converted to Unicode before being inserted into the database.

I've yet to encounter any performance-related issues from the larger indexes, etc. The indexes do use more memory, but memory is cheap.

Whether you use stored procedures or construct SQL on the fly ensure that all string constants are prefixed with N (e.g. SET @foo = N'Hello world.';) so the constant is also Unicode. This avoids any string type conversion at runtime.

YMMV.

Filtering a data frame by values in a column

The subset command is not necessary. Just use data frame indexing

studentdata[studentdata$Drink == 'water',]

Read the warning from ?subset

This is a convenience function intended for use interactively. For programming it is better to use the standard subsetting functions like ‘[’, and in particular the non-standard evaluation of argument ‘subset’ can have unanticipated consequences.

Getting multiple selected checkbox values in a string in javascript and PHP

This code work fine for me, Here i contvert array to string with ~ sign

    <input type="checkbox" value="created" name="today_check"><strong>&nbsp;Created&nbsp;&nbsp;</strong>
    <input type="checkbox" value="modified" name="today_check"><strong>&nbsp;Modified&nbsp;</strong>    
 <a class="get_tody_btn">Submit</a>

<script type="text/javascript">
        $('.get_tody_btn').click(function(){
            var ck_string = "";
            $.each($("input[name='today_check']:checked"), function(){  
                ck_string += "~"+$(this).val();  
            });
            if (ck_string ){
                ck_string = ck_string .substring(1);
            }else{
                alert('Please choose atleast one value.');
            }


        });
    </script>

How to extract public key using OpenSSL?

openssl rsa -in privkey.pem -pubout > key.pub

That writes the public key to key.pub

Angular 2 filter/search list

This code nearly worked for me...but I wanted a multiple element filter so my mods to the filter pipe are below:

import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({ name: 'jsonFilterBy' })
@Injectable()
export class JsonFilterByPipe implements PipeTransform {

  transform(json: any[], args: any[]): any[] {
    const searchText = args[0];
    const jsonKey = args[1];
    let jsonKeyArray = [];

    if (searchText == null || searchText === 'undefined') { return json; }

    if (jsonKey.indexOf(',') > 0) {
        jsonKey.split(',').forEach( function(key) {
            jsonKeyArray.push(key.trim());
        });
    } else {
        jsonKeyArray.push(jsonKey.trim());
    }

    if (jsonKeyArray.length === 0) { return json; }

    // Start with new Array and push found objects onto it.
    let returnObjects = [];
    json.forEach( function ( filterObjectEntry ) {

        jsonKeyArray.forEach( function (jsonKeyValue) {
            if ( typeof filterObjectEntry[jsonKeyValue] !== 'undefined' &&
            filterObjectEntry[jsonKeyValue].toLowerCase().indexOf(searchText.toLowerCase()) > -1 ) {
                // object value contains the user provided text.
                returnObjects.push(filterObjectEntry);
                }
            });

    });
    return returnObjects;
  }
} 

Now, instead of

jsonFilterBy:[ searchText, 'name']

you can do

jsonFilterBy:[ searchText, 'name, other, other2...']

Rails params explained?

Basically, parameters are user specified data to rails application.

When you post a form, you do it generally with POST request as opposed to GET request. You can think normal rails requests as GET requests, when you browse the site, if it helps.

When you submit a form, the control is thrown back to the application. How do you get the values you have submitted to the form? params is how.

About your code. @vote = Vote.new params[:vote] creates new Vote to database using data of params[:vote]. Given your form user submitted was named under name :vote, all data of it is in this :vote field of the hash.

Next two lines are used to get item and uid user has submitted to the form.

@extant = Vote.find(:last, :conditions => ["item_id = ? AND user_id = ?", item, uid])

finds newest, or last inserted, vote from database with conditions item_id = item and user_id = uid.

Next lines takes last vote time and current time.

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Worth mentioning: you should download the x64 version!

From the main download page (https://www.iis.net/downloads/microsoft/url-rewrite) click "additional downloads" (under the main download button) and download the x64 version (because for some reason - the default download version is x86)

Remove pandas rows with duplicate indices

I would suggest using the duplicated method on the Pandas Index itself:

df3 = df3[~df3.index.duplicated(keep='first')]

While all the other methods work, the currently accepted answer is by far the least performant for the provided example. Furthermore, while the groupby method is only slightly less performant, I find the duplicated method to be more readable.

Using the sample data provided:

>>> %timeit df3.reset_index().drop_duplicates(subset='index', keep='first').set_index('index')
1000 loops, best of 3: 1.54 ms per loop

>>> %timeit df3.groupby(df3.index).first()
1000 loops, best of 3: 580 µs per loop

>>> %timeit df3[~df3.index.duplicated(keep='first')]
1000 loops, best of 3: 307 µs per loop

Note that you can keep the last element by changing the keep argument to 'last'.

It should also be noted that this method works with MultiIndex as well (using df1 as specified in Paul's example):

>>> %timeit df1.groupby(level=df1.index.names).last()
1000 loops, best of 3: 771 µs per loop

>>> %timeit df1[~df1.index.duplicated(keep='last')]
1000 loops, best of 3: 365 µs per loop

How can I remove all files in my git repo and update/push from my local git repo?

First of all, Navigate to your Folder using cd ( change directory) command. Then make sure you are in the correct git branch which you want to work by using the command

git branch

If you want to delete the entire files. you can do the same by using

git rm -r .

for deleting a single file,

git rm file1.txt ( file1.txt - file Name )

for delete a folder,

git rm -r foldername

After deleting the files or folders, you should commit it:

git commit -m "your comment"

Then you can push the branch:

git push
// for example, 
git push origin develop

(it will update the origin repository)

Fastest way to check if a file exist using standard C++/C++11/C?

all_of (begin(R), end(R), [](auto&p){ exists(p); })

where R is your sequence of path-like things, and exists() is from the future std or current boost. If you roll your own, keep it simple,

bool exists (string const& p) { return ifstream{p}; }

The branched solution isn't absolutely terrible and it won't gobble file descriptors,

bool exists (const char* p) {
    #if defined(_WIN32) || defined(_WIN64)
    return p && 0 != PathFileExists (p);
    #else
    struct stat sb;
    return p && 0 == stat (p, &sb);
    #endif
}

Lost httpd.conf file located apache

Get the path of running Apache

$ ps -ef | grep apache
apache   12846 14590  0 Oct20 ?        00:00:00 /usr/sbin/apache2

Append -V argument to the path

$ /usr/sbin/apache2 -V | grep SERVER_CONFIG_FILE
-D SERVER_CONFIG_FILE="/etc/apache2/apache2.conf"

Reference:
http://commanigy.com/blog/2011/6/8/finding-apache-configuration-file-httpd-conf-location

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

How can I add a .npmrc file?

This issue is because of you having some local or private packages. For accessing those packages you have to create .npmrc file for this issue. Just refer the following link for your solution. https://nodesource.com/blog/configuring-your-npmrc-for-an-optimal-node-js-environment

Powershell Execute remote exe with command line arguments on remote computer

I have been trying to achieve this by using 1 row single entry but I ended that Invoke command did not worked successfully because it is killing the process immediately after starting despite it can work if you are entering the session and waiting enough before exiting.

The only working way I could find, for example, to run a command with arguments and space on the remote machine HFVMACHINE1 (running Windows 7) is the following:

([WMICLASS]"\\HFVMACHINE1\ROOT\CIMV2:win32_process").Create('c:\Program Files (x86)\Thinware\vBackup\vBackup.exe -v HFSVR12-WWW')

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

Java generics - get class?

I like the solution from

http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/

public class Dada<T> {

    private Class<T> typeOfT;

    @SuppressWarnings("unchecked")
    public Dada() {
        this.typeOfT = (Class<T>)
                ((ParameterizedType)getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
...

TensorFlow, "'module' object has no attribute 'placeholder'"

It may be the typo if you incorrectly wrote the placeholder word. In my case I misspelled it as placehoder and got the error like this: AttributeError: 'module' object has no attribute 'placehoder'

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

If you have issue with writing into an existing xls file because it is already created you need to put checking part like below:

PATH='filename.xlsx'
if os.path.isfile(PATH):
    print "File exists and will be overwrite NOW"
else:
    print "The file is missing, new one is created"

... and here part with the data you want to add

How to save all console output to file in R?

If you have access to a command line, you might prefer running your script from the command line with R CMD BATCH.

== begin contents of script.R ==

a <- "a"
a
How come I do not see this in log

== end contents of script.R ==

At the command prompt ("$" in many un*x variants, "C:>" in windows), run

$ R CMD BATCH script.R &

The trailing "&" is optional and runs the command in the background. The default name of the log file has "out" appended to the extension, i.e., script.Rout

== begin contents of script.Rout ==

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i686-pc-linux-gnu (32-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]

> a <- "a"
> a
[1] "a"
> How come I do not see this in log
Error: unexpected symbol in "How come"
Execution halted

== end contents of script.Rout ==

Batch file to copy files from one folder to another folder

My favorite one to backup data is:

ROBOCOPY "C:\folder" "C:\new_folder" /mir

/mir is for mirror. You can also use /mov to move files. It reproduce the exact same folder. It can delete/overwrite files as needed. Works great for me. It's way faster than xcopy / copy. It's built in Windows as well.

Source: http://technet.microsoft.com/en-us/library/cc733145.aspx

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

Difference between == and ===

The difference between the loosely == equal operator and the strict === identical operator is exactly explained in the manual:

Comparison Operators

+----------------------------------------------------------------------------------+
¦ Example  ¦ Name      ¦ Result                                                    ¦
+----------+-----------+-----------------------------------------------------------¦
¦$a ==  $b ¦ Equal     ¦ TRUE if $a is equal to $b after type juggling.            ¦
¦$a === $b ¦ Identical ¦ TRUE if $a is equal to $b, and they are of the same type. ¦
+----------------------------------------------------------------------------------+

Loosely == equal comparison

If you are using the == operator, or any other comparison operator which uses loosely comparison such as !=, <> or ==, you always have to look at the context to see what, where and why something gets converted to understand what is going on.

Converting rules

Type comparison table

As reference and example you can see the comparison table in the manual:

Loose comparisons with ==

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ 1       ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ TRUE  ¦ TRUE  ¦
¦ -1      ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ TRUE  ¦
¦ array() ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ TRUE  ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ TRUE  ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

Strict === identical comparison

If you are using the === operator, or any other comparison operator which uses strict comparison such as !== or ===, then you can always be sure that the types won't magically change, because there will be no converting going on. So with strict comparison the type and value have to be the same, not only the value.

Type comparison table

As reference and example you can see the comparison table in the manual:

Strict comparisons with ===

+-----------------------------------------------------------------------------------------------------------+
¦         ¦ TRUE  ¦ FALSE ¦   1   ¦   0   ¦  -1   ¦  "1"  ¦  "0"  ¦ "-1"  ¦ NULL  ¦ array() ¦ "php" ¦  ""   ¦
+---------+-------+-------+-------+-------+-------+-------+-------+-------+-------+---------+-------+-------¦
¦ TRUE    ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ FALSE   ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 1       ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ 0       ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ -1      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "1"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "0"     ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ "-1"    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ NULL    ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE  ¦ FALSE   ¦ FALSE ¦ FALSE ¦
¦ array() ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ TRUE    ¦ FALSE ¦ FALSE ¦
¦ "php"   ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ TRUE  ¦ FALSE ¦
¦ ""      ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE ¦ FALSE   ¦ FALSE ¦ TRUE  ¦
+-----------------------------------------------------------------------------------------------------------+

In Django, how do I check if a user is in a certain group?

I have similar situation, I wanted to test if the user is in a certain group. So, I've created new file utils.py where I put all my small utilities that help me through entire application. There, I've have this definition:

utils.py

def is_company_admin(user):
    return user.groups.filter(name='company_admin').exists()

so basically I am testing if the user is in the group company_admin and for clarity I've called this function is_company_admin.

When I want to check if the user is in the company_admin I just do this:

views.py

from .utils import *

if is_company_admin(request.user):
        data = Company.objects.all().filter(id=request.user.company.id)

Now, if you wish to test same in your template, you can add is_user_admin in your context, something like this:

views.py

return render(request, 'admin/users.html', {'data': data, 'is_company_admin': is_company_admin(request.user)})

Now you can evaluate you response in a template:

users.html

{% if is_company_admin %}
     ... do something ...
{% endif %}

Simple and clean solution, based on answers that can be found earlier in this thread, but done differently. Hope it will help someone.

Tested in Django 3.0.4.

How do I return clean JSON from a WCF Service?

When you are using GET Method the contract must be this.

[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();

with this we have a json without the boot parameter

Aldo Flores @alduar http://alduar.blogspot.com

Excel CSV - Number cell format

I believe when you import the file you can select the Column Type. Make it Text instead of Number. I don't have a copy in front of me at the moment to check though.

How to delete zero components in a vector in Matlab?

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

This retains only those elements of a that are at least as large as your tolerance.

Angularjs -> ng-click and ng-show to show a div

remove class hideByDefault. Div will remain hidden itself till value of myvalue is false.

How to horizontally center an element

_x000D_
_x000D_
<div id="outer" style="width:100%;margin: 0 auto; text-align: center;">  _x000D_
  <div id="inner">Foo foo</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Cutting the videos based on start and end time using ffmpeg

Even though I'm 6 years late, but I think all the answers above didn't properly address the question @kalai is asking. The bash script below will process a text file in the following format:

URL | start_time | end_time | filename

for example

https://www.youtube.com/watch?v=iUDURCrvrMI|00:02:02|00:03:41|1

and loop through the file, downloads the file that youtube-dl supports, calculating duration between start_time and end_time and passing it to ffmpeg, since -t is actually the duration, not the real end_time

Hit me up if you have any question.

    for i in $(<video.txt);
    do
        URL=`echo $i | cut -d "|" -f 1`;
        START=`echo $i | cut -d "|" -f 2`;
        END=`echo $i | cut -d "|" -f 3`;
        FILE=`echo $i | cut -d "|" -f 4`;

        SEC1=`echo $START | sed 's/^/((/; s/:/)*60+/g' | bc`
        SEC2=`echo $END | sed 's/^/((/; s/:/)*60+/g' | bc`

        DIFFSEC=`expr ${SEC2} - ${SEC1}`

        ffmpeg $(youtube-dl -g $URL | sed "s/.*/-ss $START -i &/") -t $DIFFSEC -c copy $FILE".mkv";
        ffmpeg -i $FILE".mkv" -f mp3 -ab 192000 -vn $FILE".mp3";
        rm $FILE".mkv";
    done;

<!--[if !IE]> not working

You need to put a space for the <!-- [if !IE] --> My full css block goes as follows, since IE8 is terrible with media queries

<!-- IE 8 or below -->   
<!--[if lt IE 9]>
<link rel="stylesheet" type="text/css"  href="/Resources/css/master1300.css" />        
<![endif]-->
<!-- IE 9 or above -->
<!--[if gte IE 9]>
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />        
<![endif]-->
<!-- Not IE -->
<!-- [if !IE] -->
<link rel="stylesheet" type="text/css" media="(max-width: 100000px) and (min-width:481px)"
    href="/Resources/css/master1300.css" />
<link rel="stylesheet" type="text/css" media="(max-width: 480px)"
    href="/Resources/css/master480.css" />
<!-- [endif] -->

How to display image from URL on Android

I've same issue. I test this code and works well. This code Get Image from URL and put in - "bmpImage"

URL url = new URL("http://your URL");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(60000 /* milliseconds */);
            conn.setConnectTimeout(65000 /* milliseconds */);
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.connect();
            int response = conn.getResponseCode();
            //Log.d(TAG, "The response is: " + response);
            is = conn.getInputStream();


            BufferedInputStream bufferedInputStream = new BufferedInputStream(is);

            Bitmap bmpImage = BitmapFactory.decodeStream(bufferedInputStream);

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

11. R (or another dependency) is out of date and you don't want to update it.

Warning this is not exactly best practice.

  • Download the package source.
  • Navigate to the DESCRIPTION file.
  • Remove the offending line with your text editor e.g.

    Depends: R (>= 3.1.1)
    
  • Install from local (i.e. from the parent directory of DESCRIPTION) e.g.

    install.packages("foo", type="source", repos=NULL)
    

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

Include servlet-api-3.1.jar in your dependencies.

  • Maven

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
        <scope>provided</scope>
    </dependency>
    
  • Gradle

    configurations {
        provided
    }
    sourceSets {
        main { compileClasspath += configurations.provided }
    }
    dependencies {
        provided 'javax.servlet:javax.servlet-api:3.1.0'
    }
    

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Here is the complete solution for PostgreSQL 9+, updated recently.

CREATE USER readonly  WITH ENCRYPTED PASSWORD 'readonly';
GRANT USAGE ON SCHEMA public to readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly;

-- repeat code below for each database:

GRANT CONNECT ON DATABASE foo to readonly;
\c foo
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO readonly; --- this grants privileges on new tables generated in new database "foo"
GRANT USAGE ON SCHEMA public to readonly; 
GRANT SELECT ON ALL SEQUENCES IN SCHEMA public TO readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO readonly;

Thanks to https://jamie.curle.io/creating-a-read-only-user-in-postgres/ for several important aspects

If anyone find shorter code, and preferably one that is able to perform this for all existing databases, extra kudos.

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

MySql server startup error 'The server quit without updating PID file '

Try this..

  1. Navigate to the problem's parent directory cd YOURPATH/usr/local/mysql
  2. rm -rf *.local.err (deletes file)
  3. touch YOURUSERNAME.local.pid (generates new *.local.pid file the error thrown was complaining about)
  4. cd back into your project and restart mysql using mysql.server start

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

I submit my example for consideration. This is how I call some code from a controller script in the tools I make. The scripts that do the work also need to accept parameters as well, so this example shows how to pass them. It does assume the script being called is in the same directory as the controller script (script making the call).

[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string[]]
$Computername,

[Parameter(Mandatory = $true)]
[DateTime]
$StartTime,

[Parameter(Mandatory = $true)]
[DateTime]
$EndTime
)

$ZAEventLogDataSplat = @{
    "Computername" = $Computername
    "StartTime"    = $StartTime
    "EndTime"      = $EndTime
}

& "$PSScriptRoot\Get-ZAEventLogData.ps1" @ZAEventLogDataSplat

The above is a controller script that accepts 3 parameters. These are defined in the param block. The controller script then calls the script named Get-ZAEventLogData.ps1. For the sake of example, this script also accepts the same 3 parameters. When the controller script calls to the script that does the work, it needs to call it and pass the parameters. The above shows how I do it by splatting.

How can I create a product key for my C# application?

There is the option Microsoft Software Licensing and Protection (SLP) Services as well. After reading about it I really wish I could use it.

I really like the idea of blocking parts of code based on the license. Hot stuff, and the most secure for .NET. Interesting read even if you don't use it!

Microsoft® Software Licensing and Protection (SLP) Services is a software activation service that enables independent software vendors (ISVs) to adopt flexible licensing terms for their customers. Microsoft SLP Services employs a unique protection method that helps safeguard your application and licensing information allowing you to get to market faster while increasing customer compliance.

Note: This is the only way I would release a product with sensitive code (such as a valuable algorithm).

The I/O operation has been aborted because of either a thread exit or an application request

I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).

To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()

Like this :

Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
    ar.AsyncWaitHandle.WaitOne();

Most of the time, ar.IsCompleted will be true.

CSS media query to target only iOS devices

I don't know about targeting iOS as a whole, but to target iOS Safari specifically:

@supports (-webkit-touch-callout: none) {
   /* CSS specific to iOS devices */ 
}

@supports not (-webkit-touch-callout: none) {
   /* CSS for other than iOS devices */ 
}

Apparently as of iOS 13 -webkit-overflow-scrolling no longer responds to @supports, but -webkit-touch-callout still does. Of course that could change in the future...

Converting String to Int using try/except in Python

Here it is:

s = "123"
try:
  i = int(s)
except ValueError as verr:
  pass # do job to handle: s does not contain anything convertible to int
except Exception as ex:
  pass # do job to handle: Exception occurred while converting to int

How do I copy the contents of a String to the clipboard in C#?

You can use System.Windows.Forms.Clipboard.SetText(...).

Add support library to Android Studio project

In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app) file and paste this (at the end) :-

dependencies {
    compile "com.android.support:appcompat-v7:21.0.+"
}

Note that this dependencies is different from the dependencies inside buildscript in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"

Source : https://developer.android.com/tools/support-library/setup.html#add-library

Access elements of parent window from iframe

Have the below js inside the iframe and use ajax to submit the form.

$(function(){

   $("form").submit(e){
        e.preventDefault();

       //Use ajax to submit the form
       $.ajax({
          url: this.action,
          data: $(this).serialize(),
          success: function(){
             window.parent.$("#target").load("urlOfThePageToLoad");
          });
       });

   });

});

Running shell command and capturing the output

According to @senderle, if you use python3.6 like me:

def sh(cmd, input=""):
    rst = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, input=input.encode("utf-8"))
    assert rst.returncode == 0, rst.stderr.decode("utf-8")
    return rst.stdout.decode("utf-8")
sh("ls -a")

Will act exactly like you run the command in bash

Maven: Failed to retrieve plugin descriptor error

In my case, it was not worknig even after passing the proxy credentails.

Mistake was - forgot to remove the comment line.

<!-- proxy
 | Specification for one proxy, to be used in connecting to the network.

<proxy>
  <id>optional</id>
  <active>true</active>
  <protocol>http</protocol>
  <username>345325</username>
  <password>dfgasdfg</password>
  <host>proxy.abc.com</host>
  <port>8080</port>
  <nonProxyHosts>proxy.abc.com</nonProxyHosts>
</proxy>
|-->    ----------REMOVE THIS LINE AND CLOSE It above <proxy> tag

Is it possible to play music during calls so that the partner can hear it ? Android

I think this is possible in one case

1.Some of the native music players in android device where handling this,they restrict the music when call is in TelephonyManager.EXTRA_STATE_OFFHOOK (OFFHOOK STATE) so there is no way of playing the background music using native players and some other players like "poweramp music palyer"

2.By using the MediaPlayer class also it is not possible(clearly mentioned in documentation)

3.It is possible only in one case if your developing custom music player(with out using MediaPlayer class) in that implements

AudioManager.OnAudioFocusChangeListener by using this you can get the state of the audiomanager in the below code "focusChange=AUDIOFOCUS_LOSS_TRANSIENT"(this state calls when music is playing in background any incoming call came) this state is completely in developers hand whether to play or pause the music. As according to your requriment as for question you asked if you want to play the music when call is in OFFHOOK STATE dont pause playing music in OFFHOOK STATE .And this is only possible when headset is disabled

AudioManager am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
     
    OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
        public void onAudioFocusChange(int focusChange) {
            if (focusChange == AUDIOFOCUS_LOSS_TRANSIENT
                // Pause playback (during incoming call) 
            } else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
                // Resume playback (incoming call ends)
            } else if (focusChange == AudioManager.AUDIOFOCUS_LOSS) {
                am.unregisterMediaButtonEventReceiver(RemoteControlReceiver);
                am.abandonAudioFocus(afChangeListener);
                // Stop playback (when any other app playing music  in that situation current app stop the audio)
            }
        }
    };

UICollectionView cell selection and cell reuse

Your observation is correct. This behavior is happening due to the reuse of cells. But you dont have to do any thing with the prepareForReuse. Instead do your check in cellForItem and set the properties accordingly. Some thing like..

 - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cvCell" forIndexPath:indexPath];


if (cell.selected) {
     cell.backgroundColor = [UIColor blueColor]; // highlight selection 
}
else
{
     cell.backgroundColor = [UIColor redColor]; // Default color
}
return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath  {

    UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath];
    datasetCell.backgroundColor = [UIColor blueColor]; // highlight selection
 }  

 -(void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

UICollectionViewCell *datasetCell =[collectionView cellForItemAtIndexPath:indexPath]; 
datasetCell.backgroundColor = [UIColor redColor]; // Default color
}

Cannot instantiate the type List<Product>

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};

Creating object with dynamic keys

You can't define an object literal with a dynamic key. Do this :

var o = {};
o[key] = value;
return o;

There's no shortcut (edit: there's one now, with ES6, see the other answer).

Click toggle with jQuery

<label>
    <input
        type="checkbox"
        onclick="$('input[type=checkbox]').attr('checked', $(this).is(':checked'));"
    />
    Check all
</label>

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

How to get data from Magento System Configuration

you should you use following code

$configValue = Mage::getStoreConfig(
                   'sectionName/groupName/fieldName',
                   Mage::app()->getStore()
               ); 

Mage::app()->getStore() this will add store code in fetch values so that you can get correct configuration values for current store this will avoid incorrect store's values because magento is also use for multiple store/views so must add store code to fetch anything in magento.

if we have more then one store or multiple views configured then this will insure that we are getting values for current store

How do I convert a String to a BigInteger?

According to the documentation:

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

It means that you can use a String to initialize a BigInteger object, as shown in the following snippet:

sum = sum.add(new BigInteger(newNumber));

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

If you have a https certificate on the domain, make sure you have the https binding to the domain name in IIS. In IIS -> Select your domain -> Click on Bindings Site Bindings Window opens up. Add a binding for https.

Proper use of 'yield return'

Populating a temporary list is like downloading the whole video, whereas using yield is like streaming that video.

React hooks useState Array

Try to keep your state minimal. There is no need to store

   const initialValue = [
    { id: 0,value: " --- Select a State ---" }];

as state. Separate the permanent from the changing

const ALL_STATE_VALS = [
    { id: 0,value: " --- Select a State ---" }
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
];

Then you can store just the id as your state:

const StateSelector = () =>{
  const [selectedStateOption, setselectedStateOption] = useState(0);

  return (
    <div>
      <label>Select a State:</label>
      <select>
        {ALL_STATE_VALS.map((option, index) => (
          <option key={option.id} selected={index===selectedStateOption}>{option.value}</option>
        ))}
      </select>
    </div>);
   )
}

Binary Data in JSON String. Something better than Base64

There are 94 Unicode characters which can be represented as one byte according to the JSON spec (if your JSON is transmitted as UTF-8). With that in mind, I think the best you can do space-wise is base85 which represents four bytes as five characters. However, this is only a 7% improvement over base64, it's more expensive to compute, and implementations are less common than for base64 so it's probably not a win.

You could also simply map every input byte to the corresponding character in U+0000-U+00FF, then do the minimum encoding required by the JSON standard to pass those characters; the advantage here is that the required decoding is nil beyond builtin functions, but the space efficiency is bad -- a 105% expansion (if all input bytes are equally likely) vs. 25% for base85 or 33% for base64.

Final verdict: base64 wins, in my opinion, on the grounds that it's common, easy, and not bad enough to warrant replacement.

See also: Base91 and Base122

What is the default font of Sublime Text?

On my system (Windows 8.1), Sublime 2 shows default font "Consolas". You can find yours by following this procedure:

  1. go to View menu and select Show Console
  2. Then enter this command: view.settings().get('font_face')

You will find your default font.

application/x-www-form-urlencoded or multipart/form-data?

Just a little hint from my side for uploading HTML5 canvas image data:

I am working on a project for a print-shop and had some problems due to uploading images to the server that came from an HTML5 canvas element. I was struggling for at least an hour and I did not get it to save the image correctly on my server.

Once I set the contentType option of my jQuery ajax call to application/x-www-form-urlencoded everything went the right way and the base64-encoded data was interpreted correctly and successfully saved as an image.


Maybe that helps someone!

How to close existing connections to a DB

This should disconnect everyone else, and leave you as the only user:

alter database YourDb set single_user with rollback immediate

Note: Don't forget

alter database YourDb set MULTI_USER

after you're done!

Uninstall all installed gems, in OSX?

The only command helped me to cleanup all gems and ignores default gems, which can't be uninstalled

for x in `gem list --no-versions`; do gem uninstall $x -a -x -I; done

Can overridden methods differ in return type?

Overriding and Return Types, and Covariant Returns
the subclass must define a method that matches the inherited version exactly. Or, as of Java 5, you're allowed to change the return type in the

sample code


                                                                                                            class Alpha {
          Alpha doStuff(char c) {
                  return new Alpha();
              }
           }
             class Beta extends Alpha {
                    Beta doStuff(char c) { // legal override in Java 1.5
                    return new Beta();
                    }
             } } 
As of Java 5, this code will compile. If you were to attempt to compile this code with a 1.4 compiler will say attempting to use incompatible return type – sandeep1987 1 min ago

How to use if statements in underscore.js templates?

If you prefer shorter if else statement, you can use this shorthand:

<%= typeof(id)!== 'undefined' ?  id : '' %>

It means display the id if is valid and blank if it wasn't.

What is "X-Content-Type-Options=nosniff"?

The X-Content-Type-Options response HTTP header is a marker used by the server to indicate that the MIME types advertised in the Content-Type headers should not be changed and be followed. This allows to opt-out of MIME type sniffing, or, in other words, it is a way to say that the webmasters knew what they were doing.

Syntax :

X-Content-Type-Options: nosniff

Directives :

nosniff Blocks a request if the requested type is 1. "style" and the MIME type is not "text/css", or 2. "script" and the MIME type is not a JavaScript MIME type.

Note: nosniff only applies to "script" and "style" types. Also applying nosniff to images turned out to be incompatible with existing web sites.

Specification :

https://fetch.spec.whatwg.org/#x-content-type-options-header

Why did Servlet.service() for servlet jsp throw this exception?

It can be caused by a classpath contamination. Check that you /WEB-INF/lib doesn't contain something like jsp-api-*.jar.

Use of #pragma in C

All answers above make nice explanations for #pragma but I wanted to a add small example

I just want to explain a simple OpenMP example that demonstrate some uses of #pragma to doing its work

OpenMp briefly is an implementation for multi-platform shared-memory parallel programming (then we can say it's machine-specific or operating-system-specific)

let's go to the example

#include <stdio.h>
#include <omp.h>// compile with: /openmp

int main() {
   #pragma omp parallel num_threads(4)
   {
      int i = omp_get_thread_num();
      printf_s("Hello from thread %d\n", i);
   }
}

the output is

Hello from thread 0
Hello from thread 1
Hello from thread 2
Hello from thread 3

Note that the order of output can vary on different machines.

now let me tell you what #pragma did...

it tells the OS to run the some block of code on 4 threads

this is just one of many many applications you can do with the little #pragma

sorry for the outside sample OpenMP

How to do URL decoding in Java?

import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;

public class URLDecoding { 

    String decoded = "";

    public String decodeMethod(String url) throws UnsupportedEncodingException
    {
        decoded = java.net.URLDecoder.decode(url, "UTF-8"); 
        return  decoded;
//"You should use java.net.URI to do this, as the URLDecoder class does x-www-form-urlencoded decoding which is wrong (despite the name, it's for form data)."
    }

    public String getPathMethod(String url) throws URISyntaxException 
    {
        decoded = new java.net.URI(url).getPath();  
        return  decoded; 
    }

    public static void main(String[] args) throws UnsupportedEncodingException, URISyntaxException 
    {
        System.out.println(" Here is your Decoded url with decode method : "+ new URLDecoding().decodeMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest_type")); 
        System.out.println("Here is your Decoded url with getPath method : "+ new URLDecoding().getPathMethod("https%3A%2F%2Fmywebsite%2Fdocs%2Fenglish%2Fsite%2Fmybook.do%3Frequest")); 

    } 

}

You can select your method wisely :)

Parse DateTime string in JavaScript

This function handles also the invalid 29.2.2001 date.

function parseDate(str) {
    var dateParts = str.split(".");
    if (dateParts.length != 3)
        return null;
    var year = dateParts[2];
    var month = dateParts[1];
    var day = dateParts[0];

    if (isNaN(day) || isNaN(month) || isNaN(year))
        return null;

    var result = new Date(year, (month - 1), day);
    if (result == null)
        return null;
    if (result.getDate() != day)
        return null;
    if (result.getMonth() != (month - 1))
        return null;
    if (result.getFullYear() != year)
        return null;

    return result;
}

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

Can I set an unlimited length for maxJsonLength in web.config?

I followed vestigal's answer and got to this solution:

When I needed to post a large json to an action in a controller, I would get the famous "Error during deserialization using the JSON JavaScriptSerializer. The length of the string exceeds the value set on the maxJsonLength property.\r\nParameter name: input value provider".

What I did is create a new ValueProviderFactory, LargeJsonValueProviderFactory, and set the MaxJsonLength = Int32.MaxValue in the GetDeserializedObject method

public sealed class LargeJsonValueProviderFactory : ValueProviderFactory
{
private static void AddToBackingStore(LargeJsonValueProviderFactory.EntryLimitedDictionary backingStore, string prefix, object value)
{
    IDictionary<string, object> dictionary = value as IDictionary<string, object>;
    if (dictionary != null)
    {
        foreach (KeyValuePair<string, object> keyValuePair in (IEnumerable<KeyValuePair<string, object>>) dictionary)
            LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakePropertyKey(prefix, keyValuePair.Key), keyValuePair.Value);
    }
    else
    {
        IList list = value as IList;
        if (list != null)
        {
            for (int index = 0; index < list.Count; ++index)
                LargeJsonValueProviderFactory.AddToBackingStore(backingStore, LargeJsonValueProviderFactory.MakeArrayKey(prefix, index), list[index]);
        }
        else
            backingStore.Add(prefix, value);
    }
}

private static object GetDeserializedObject(ControllerContext controllerContext)
{
    if (!controllerContext.HttpContext.Request.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase))
        return (object) null;
    string end = new StreamReader(controllerContext.HttpContext.Request.InputStream).ReadToEnd();
    if (string.IsNullOrEmpty(end))
        return (object) null;

    var serializer = new JavaScriptSerializer {MaxJsonLength = Int32.MaxValue};

    return serializer.DeserializeObject(end);
}

/// <summary>Returns a JSON value-provider object for the specified controller context.</summary>
/// <returns>A JSON value-provider object for the specified controller context.</returns>
/// <param name="controllerContext">The controller context.</param>
public override IValueProvider GetValueProvider(ControllerContext controllerContext)
{
    if (controllerContext == null)
        throw new ArgumentNullException("controllerContext");
    object deserializedObject = LargeJsonValueProviderFactory.GetDeserializedObject(controllerContext);
    if (deserializedObject == null)
        return (IValueProvider) null;
    Dictionary<string, object> dictionary = new Dictionary<string, object>((IEqualityComparer<string>) StringComparer.OrdinalIgnoreCase);
    LargeJsonValueProviderFactory.AddToBackingStore(new LargeJsonValueProviderFactory.EntryLimitedDictionary((IDictionary<string, object>) dictionary), string.Empty, deserializedObject);
    return (IValueProvider) new DictionaryValueProvider<object>((IDictionary<string, object>) dictionary, CultureInfo.CurrentCulture);
}

private static string MakeArrayKey(string prefix, int index)
{
    return prefix + "[" + index.ToString((IFormatProvider) CultureInfo.InvariantCulture) + "]";
}

private static string MakePropertyKey(string prefix, string propertyName)
{
    if (!string.IsNullOrEmpty(prefix))
        return prefix + "." + propertyName;
    return propertyName;
}

private class EntryLimitedDictionary
{
    private static int _maximumDepth = LargeJsonValueProviderFactory.EntryLimitedDictionary.GetMaximumDepth();
    private readonly IDictionary<string, object> _innerDictionary;
    private int _itemCount;

    public EntryLimitedDictionary(IDictionary<string, object> innerDictionary)
    {
        this._innerDictionary = innerDictionary;
    }

    public void Add(string key, object value)
    {
        if (++this._itemCount > LargeJsonValueProviderFactory.EntryLimitedDictionary._maximumDepth)
            throw new InvalidOperationException("JsonValueProviderFactory_RequestTooLarge");
        this._innerDictionary.Add(key, value);
    }

    private static int GetMaximumDepth()
    {
        NameValueCollection appSettings = ConfigurationManager.AppSettings;
        if (appSettings != null)
        {
            string[] values = appSettings.GetValues("aspnet:MaxJsonDeserializerMembers");
            int result;
            if (values != null && values.Length > 0 && int.TryParse(values[0], out result))
                return result;
        }
        return 1000;
     }
  }
}

Then, in the Application_Start method from Global.asax.cs, replace the ValueProviderFactory with the new one:

protected void Application_Start()
{
    ...

    //Add LargeJsonValueProviderFactory
    ValueProviderFactory jsonFactory = null;
    foreach (var factory in ValueProviderFactories.Factories)
    {
        if (factory.GetType().FullName == "System.Web.Mvc.JsonValueProviderFactory")
        {
            jsonFactory = factory;
            break;
        }
    }

    if (jsonFactory != null)
    {
        ValueProviderFactories.Factories.Remove(jsonFactory);
    }

    var largeJsonValueProviderFactory = new LargeJsonValueProviderFactory();
    ValueProviderFactories.Factories.Add(largeJsonValueProviderFactory);
}

Change bundle identifier in Xcode when submitting my first app in IOS

Here's the answer from Apple's official documentation, just tried, it's working.

Setting the Bundle ID

The default bundle ID in your Xcode project is a string formatted as a reverse-domain—for example, com.MyCompany.MyProductName. To create the default bundle ID, Xcode concatenates the company identifier with the product name you entered when creating the project from a template, as described in Setting Properties When Creating Your Xcode Project. (Xcode replaces spaces in the product name to create the default bundle ID.) It may be sufficient to replace the company identifier prefix in the bundle ID or you can replace the entire bundle ID. For example, change the company identifier prefix to match your company domain name or replace the entire bundle ID to match an explicit App ID.

For Mac apps, ensure that every bundle ID is unique within your app bundle. For example, if your app bundle includes a helper app, ensure that its bundle ID is different from your app’s bundle ID.

Follow these steps to change the bundle ID prefix in the General pane in the project editor.

To set the bundle ID prefix

  1. In the project navigator, select the project and your target to display the project editor.

  2. Click General and, if necessary, click the disclosure triangle next to Identity to reveal the settings.

enter image description here

  1. Enter the bundle ID prefix in the “Bundle Identifier” field.

To set the bundle ID

  1. In the project navigator, select the project and your target to display the project editor.

  2. Click Info.

  3. Enter the bundle ID in the Value column of the “Bundle identifier” row.

enter image description here

If you're feeling interested in reading more, please check APP Distribution Guide from Apple.

How to select all columns, except one column in pandas?

Don't use ix. It's deprecated. The most readable and idiomatic way of doing this is df.drop():

>>> df

          a         b         c         d
0  0.175127  0.191051  0.382122  0.869242
1  0.414376  0.300502  0.554819  0.497524
2  0.142878  0.406830  0.314240  0.093132
3  0.337368  0.851783  0.933441  0.949598

>>> df.drop('b', axis=1)

          a         c         d
0  0.175127  0.382122  0.869242
1  0.414376  0.554819  0.497524
2  0.142878  0.314240  0.093132
3  0.337368  0.933441  0.949598

Note that by default, .drop() does not operate inplace; despite the ominous name, df is unharmed by this process. If you want to permanently remove b from df, do df.drop('b', inplace=True).

df.drop() also accepts a list of labels, e.g. df.drop(['a', 'b'], axis=1) will drop column a and b.

Can I prevent text in a div block from overflowing?

Recommendations for how to catch which part of your CSS is causing the issue:

1) set style="height:auto;" on all the <div> elements and retry again.

2) Set style="border: 3px solid red;" on all the <div> elements to see how wide of an area your <div>'s box is taking up.

3) Take away all the css height:#px; properties from your CSS and start over.

So for example:

<div id="I" style="height:auto;border: 3px solid red;">I
    <div id="A" style="height:auto;border: 3px solid purple;">A
        <div id="1A" style="height:auto;border: 3px solid green;">1A
        </div>
        <div id="2A" style="height:auto;border: 3px solid green;">2A
        </div>
    </div>
    <div id="B" style="height:auto;border: 3px solid purple;">B
        <div id="1B" style="height:auto;border: 3px solid green;">1B
        </div>
        <div id="2B" style="height:auto;border: 3px solid green;">2B
        </div>
    </div>
</div>

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

Detect home button press in android

onUserLeaveHint();

override this activity class method.This will detect the home key click . This method is called right before the activity's onPause() callback.But it will not be called when an activity is interrupted like a in-call activity comes into foreground, apart from that interruptions it will call when user click home key.

@Override
protected void onUserLeaveHint() {
    super.onUserLeaveHint();
    Log.d(TAG, "home key clicked");
}

C# Convert List<string> to Dictionary<string, string>

EDIT

another way to deal with duplicate is you can do like this

var dic = slist.Select((element, index)=> new{element,index} )
            .ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);

or


easy way to do is

var res = list.ToDictionary(str => str, str=> str); 

but make sure that there is no string is repeating...again otherewise above code will not work for you

if there is string is repeating than its better to do like this

Dictionary<string,string> dic= new Dictionary<string,string> ();

    foreach(string s in Stringlist)
    {
       if(!dic.ContainsKey(s))
       {
        //  dic.Add( value to dictionary
      }
    }

Byte Array in Python

In Python 3, we use the bytes object, also known as str in Python 2.

# Python 3
key = bytes([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

# Python 2
key = ''.join(chr(x) for x in [0x13, 0x00, 0x00, 0x00, 0x08, 0x00])

I find it more convenient to use the base64 module...

# Python 3
key = base64.b16decode(b'130000000800')

# Python 2
key = base64.b16decode('130000000800')

You can also use literals...

# Python 3
key = b'\x13\0\0\0\x08\0'

# Python 2
key = '\x13\0\0\0\x08\0'

How can I calculate the time between 2 Dates in typescript

In order to calculate the difference you have to put the + operator,

that way typescript converts the dates to numbers.

+new Date()- +new Date("2013-02-20T12:01:04.753Z")

From there you can make a formula to convert the difference to minutes or hours.

Alter SQL table - allow NULL column value

ALTER TABLE MyTable MODIFY Col3 varchar(20) NULL;

How to build a Horizontal ListView with RecyclerView?

Trying to build a horizontal ListView is taking too much time. I have resolved it in two ways.

1.By using a ViewPager whose adapter extends from PagerAdapter.

2.By using RecyclerView just as above. Need to apply LayoutManager as in the following code:

LinearLayoutManager layoutManager
    = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);

RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);

Removing fields from struct or hiding them in JSON Response

You can use tagging attribute "omitifempty" or make optional fields pointers and leave those you want skipped uninitialized.

Remove Android App Title Bar

If you have import android.support.v7.app.ActionBarActivity; and your class extends ActionBarActivity then use this in your OnCreate:

android.support.v7.app.ActionBar AB=getSupportActionBar();
AB.hide();

Easy way of running the same junit test over and over?

I've found that Spring's repeat annotation is useful for that kind of thing:

@Repeat(value = 10)

Latest (Spring Framework 4.3.11.RELEASE API) doc:

css background image in a different folder from css

Html file (/index.html)

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
     <link rel="stylesheet" media="screen" href="assets/css/style.css" />
</head>
<body>
     <h1>Background Image</h1>
</body>
</html>

Css file (/assets/css/style.css)

body{
    background:url(../img/bg.jpg);  
}

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

You can just use an object:

var test = {}
test[2300] = 'Some string';

finding multiples of a number in Python

Based on mathematical concepts, I understand that:

  • all natural numbers that, divided by n, having 0 as remainder, are all multiples of n

Therefore, the following calculation also applies as a solution (multiples between 1 and 100):

>>> multiples_5 = [n for n in range(1, 101) if n % 5 == 0]
>>> multiples_5
[5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100]

For further reading:

How to set a DateTime variable in SQL Server 2008?

You want to make the format/style explicit and don't rely on interpretation based on local settings (which may vary among your clients infrastructure).

DECLARE @Test AS DATETIME
SET @Test = CONVERT(DATETIME, '2011-02-15 00:00:00', 120) -- yyyy-MM-dd hh:mm:ss
SELECT @Test

While there is a plethora of styles, you may want to remember few

  • 126 (ISO 8601): yyyy-MM-ddThh:mm:ss(.mmm)
  • 120: yyyy-MM-dd hh:mm:ss
  • 112: yyyyMMdd

Note that the T in the ISO 8601 is actually the letter T and not a variable.

How do you roll back (reset) a Git repository to a particular commit?

When you say the 'GUI Tool', I assume you're using Git For Windows.

IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.

With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.

Adding two numbers concatenates them instead of calculating the sum

  <input type="text" name="num1" id="num1" onkeyup="sum()">
  <input type="text" name="num2" id="num2" onkeyup="sum()">
  <input type="text" name="num2" id="result">

  <script>
     function sum()
     {

        var number1 = document.getElementById('num1').value;
        var number2 = document.getElementById('num2').value;

        if (number1 == '') {
           number1 = 0
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else if(number2 == '')
        {
           number2 = 0;
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }
        else
        {
           var num3 = parseInt(number1) + parseInt(number2);
           document.getElementById('result').value = num3;
        }

     }
  </script>

Generate random string/characters in JavaScript

Something like this should work

function randomString(len, charSet) {
    charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    var randomString = '';
    for (var i = 0; i < len; i++) {
        var randomPoz = Math.floor(Math.random() * charSet.length);
        randomString += charSet.substring(randomPoz,randomPoz+1);
    }
    return randomString;
}

Call with default charset [a-zA-Z0-9] or send in your own:

var randomValue = randomString(5);

var randomValue = randomString(5, 'PICKCHARSFROMTHISSET');

Convert categorical data in pandas dataframe

@Quickbeam2k1 ,see below -

dataset=pd.read_csv('Data2.csv')
np.set_printoptions(threshold=np.nan)
X = dataset.iloc[:,:].values

Using sklearn enter image description here

from sklearn.preprocessing import LabelEncoder
labelencoder_X=LabelEncoder()
X[:,0] = labelencoder_X.fit_transform(X[:,0])

Windows batch script launch program and exit console

Try to start path\to\cygwin\bin\bash.exe

Leverage browser caching, how on apache or .htaccess?

I was doing the same thing a couple days ago. Added this to my .htaccess file:

ExpiresActive On
ExpiresByType image/gif A2592000
ExpiresByType image/jpeg A2592000
ExpiresByType image/jpg A2592000
ExpiresByType image/png A2592000
ExpiresByType image/x-icon A2592000
ExpiresByType text/css A86400
ExpiresByType text/javascript A86400
ExpiresByType application/x-shockwave-flash A2592000
#
<FilesMatch "\.(gif¦jpe?g¦png¦ico¦css¦js¦swf)$">
Header set Cache-Control "public"
</FilesMatch>

And now when I run google speed page, leverage browwer caching is no longer a high priority.

Hope this helps.

How to properly seed random number generator

OK why so complex!

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {
    rand.Seed( time.Now().UnixNano())
    var bytes int

    for i:= 0 ; i < 10 ; i++{ 
        bytes = rand.Intn(6)+1
        fmt.Println(bytes)
        }
    //fmt.Println(time.Now().UnixNano())
}

This is based off the dystroy's code but fitted for my needs.

It's die six (rands ints 1 =< i =< 6)

func randomInt (min int , max int  ) int {
    var bytes int
    bytes = min + rand.Intn(max)
    return int(bytes)
}

The function above is the exactly same thing.

I hope this information was of use.

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

cut or awk command to print first field of first row

sed -n 1p /etc/*release |cut -d " " -f1

if tab delimited:

sed -n 1p /etc/*release |cut -f1

Default values and initialization in Java

In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.

In the second code sample, a is class member variable, hence it will be initialized to the default value.

Best practice for using assert?

The four purposes of assert

Assume you work on 200,000 lines of code with four colleagues Alice, Bernd, Carl, and Daphne. They call your code, you call their code.

Then assert has four roles:

  1. Inform Alice, Bernd, Carl, and Daphne what your code expects.
    Assume you have a method that processes a list of tuples and the program logic can break if those tuples are not immutable:

    def mymethod(listOfTuples):
        assert(all(type(tp)==tuple for tp in listOfTuples))
    

    This is more trustworthy than equivalent information in the documentation and much easier to maintain.

  2. Inform the computer what your code expects.
    assert enforces proper behavior from the callers of your code. If your code calls Alices's and Bernd's code calls yours, then without the assert, if the program crashes in Alices code, Bernd might assume it was Alice's fault, Alice investigates and might assume it was your fault, you investigate and tell Bernd it was in fact his. Lots of work lost.
    With asserts, whoever gets a call wrong, they will quickly be able to see it was their fault, not yours. Alice, Bernd, and you all benefit. Saves immense amounts of time.

  3. Inform the readers of your code (including yourself) what your code has achieved at some point.
    Assume you have a list of entries and each of them can be clean (which is good) or it can be smorsh, trale, gullup, or twinkled (which are all not acceptable). If it's smorsh it must be unsmorshed; if it's trale it must be baludoed; if it's gullup it must be trotted (and then possibly paced, too); if it's twinkled it must be twinkled again except on Thursdays. You get the idea: It's complicated stuff. But the end result is (or ought to be) that all entries are clean. The Right Thing(TM) to do is to summarize the effect of your cleaning loop as

    assert(all(entry.isClean() for entry in mylist))
    

    This statements saves a headache for everybody trying to understand what exactly it is that the wonderful loop is achieving. And the most frequent of these people will likely be yourself.

  4. Inform the computer what your code has achieved at some point.
    Should you ever forget to pace an entry needing it after trotting, the assert will save your day and avoid that your code breaks dear Daphne's much later.

In my mind, assert's two purposes of documentation (1 and 3) and safeguard (2 and 4) are equally valuable.
Informing the people may even be more valuable than informing the computer because it can prevent the very mistakes the assert aims to catch (in case 1) and plenty of subsequent mistakes in any case.

How to find the highest value of a column in a data frame in R?

To get the max of any column you want something like:

max(ozone$Ozone, na.rm = TRUE)

To get the max of all columns, you want:

apply(ozone, 2, function(x) max(x, na.rm = TRUE))

And to sort:

ozone[order(ozone$Solar.R),]

Or to sort the other direction:

ozone[rev(order(ozone$Solar.R)),]

What does 'var that = this;' mean in JavaScript?

From Crockford

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

JS Fiddle

function usesThis(name) {
    this.myName = name;

    function returnMe() {
        return this;        //scope is lost because of the inner function
    }

    return {
        returnMe : returnMe
    }
}

function usesThat(name) {
    var that = this;
    this.myName = name;

    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }

    return {
        returnMe : returnMe
    }
}

var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);

This alerts...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

How to use font-family lato?

Download it from here and extract LatoOFL.rar then go to TTF and open this font-face-generator click at Choose File choose font which you want to use and click at generate then download it and then go html file open it and you see the code like this

@font-face {
        font-family: "Lato Black";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}
body{
    font-family: "Lato Black";
    direction: ltr;
}

change the src code and give the url where your this font directory placed, now you can use it at your website...

If you don't want to download it use this

<link type='text/css' href='http://fonts.googleapis.com/css?family=Lato:400,700' />

How to programmatically tell if a Bluetooth device is connected?

Big thanks to Skylarsutton for his answer. I'm posting this as a response to his, but because I'm posting code I can't reply as a comment. I already upvoted his answer so am not looking for any points. Just paying it forward.

For some reason BluetoothAdapter.ACTION_ACL_CONNECTED could not be resolved by Android Studio. Perhaps it was deprecated in Android 4.2.2? Here is a modification of his code. The registration code is the same; the receiver code differs slightly. I use this in a service which updates a Bluetooth-connected flag that other parts of the app reference.

    public void onCreate() {
        //...
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_ACL_CONNECTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
        filter.addAction(BluetoothDevice.ACTION_ACL_DISCONNECTED);
        this.registerReceiver(BTReceiver, filter);
    }

    //The BroadcastReceiver that listens for bluetooth broadcasts
    private final BroadcastReceiver BTReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            //Do something if connected
            Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
        }
        else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
            //Do something if disconnected
            Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
        }
        //else if...
    }
};

Using varchar(MAX) vs TEXT on SQL Server

For large text, the full text index is much faster. But you can full text index varchar(max)as well.

Align items in a stack panel?

for windows 10 use relativePanel instead of stack panel, and use

relativepanel.alignrightwithpanel="true"

for the contained elements.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How to mock a final class with mockito

Mockito 2 now supports final classes and methods!

But for now that's an "incubating" feature. It requires some steps to activate it which are described in What's New in Mockito 2:

Mocking of final classes and methods is an incubating, opt-in feature. It uses a combination of Java agent instrumentation and subclassing in order to enable mockability of these types. As this works differently to our current mechanism and this one has different limitations and as we want to gather experience and user feedback, this feature had to be explicitly activated to be available ; it can be done via the mockito extension mechanism by creating the file src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker containing a single line:

mock-maker-inline

After you created this file, Mockito will automatically use this new engine and one can do :

 final class FinalClass {
   final String finalMethod() { return "something"; }
 }

 FinalClass concrete = new FinalClass(); 

 FinalClass mock = mock(FinalClass.class);
 given(mock.finalMethod()).willReturn("not anymore");

 assertThat(mock.finalMethod()).isNotEqualTo(concrete.finalMethod());

In subsequent milestones, the team will bring a programmatic way of using this feature. We will identify and provide support for all unmockable scenarios. Stay tuned and please let us know what you think of this feature!

How to find out what type of a Mat object is with Mat::type() in OpenCV

This was answered by a few others but I found a solution that worked really well for me.

System.out.println(CvType.typeToString(yourMat.type()));

How to prevent line breaks in list items using CSS

Bootstrap 4 has a class named text-nowrap. It is just what you need.

How to ignore deprecation warnings in Python

From documentation of the warnings module:

 #!/usr/bin/env python -W ignore::DeprecationWarning

If you're on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)

String literals and escape characters in postgresql

The warning is issued since you are using backslashes in your strings. If you want to avoid the message, type this command "set standard_conforming_strings=on;". Then use "E" before your string including backslashes that you want postgresql to intrepret.

What are the lesser known but useful data structures?

I like Cache Oblivious datastructures. The basic idea is to lay out a tree in recursively smaller blocks so that caches of many different sizes will take advantage of blocks that convenient fit in them. This leads to efficient use of caching at everything from L1 cache in RAM to big chunks of data read off of the disk without needing to know the specifics of the sizes of any of those caching layers.

How to put a new line into a wpf TextBlock control?

You can try putting a new line in the data:

<data>Foo bar baz 
 baz bar</data>

If that does not work you might need to parse the string manually.

If you need direct XAML that's easy by the way:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>

Read/write to file using jQuery

No, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least. If you wanted to get/store information server-side, though, you can certainly make an Ajax call to a PHP/ASP/Python/etc. script that can then get/store the data in the server. If you meant store data on the client machine, this is impossible with JavaScript alone. I suspect Flash/Java may be able to, but I am not sure.

If you are only trying to store a small amount of information for an unreliable period of time regarding a specific user, I think you want Web Storage API or cookies. I am not sure from your question what you are trying to accomplish, though.

Identify duplicate values in a list in Python

You can print duplicate and Unqiue using below logic using list.

def dup(x):
    duplicate = []
    unique = []
    for i in x:
        if i in unique:
            duplicate.append(i)
        else:
            unique.append(i)
    print("Duplicate values: ",duplicate)
    print("Unique Values: ",unique)

list1 = [1, 2, 1, 3, 2, 5]
dup(list1)

Suppress console output in PowerShell

It is a duplicate of this question, with an answer that contains a time measurement of the different methods.

Conclusion: Use [void] or > $null.

List of all index & index columns in SQL Server DB

--Short and sweet:

SELECT OBJECT_SCHEMA_NAME(T.[object_id],DB_ID()) AS [Schema],  
  T.[name] AS [table_name], I.[name] AS [index_name], AC.[name] AS [column_name],  
  I.[type_desc], I.[is_unique], I.[data_space_id], I.[ignore_dup_key], I.[is_primary_key], 
  I.[is_unique_constraint], I.[fill_factor],    I.[is_padded], I.[is_disabled], I.[is_hypothetical], 
  I.[allow_row_locks], I.[allow_page_locks], IC.[is_descending_key], IC.[is_included_column] 
FROM sys.[tables] AS T  
  INNER JOIN sys.[indexes] I ON T.[object_id] = I.[object_id]  
  INNER JOIN sys.[index_columns] IC ON I.[object_id] = IC.[object_id] 
  INNER JOIN sys.[all_columns] AC ON T.[object_id] = AC.[object_id] AND IC.[column_id] = AC.[column_id] 
WHERE T.[is_ms_shipped] = 0 AND I.[type_desc] <> 'HEAP' 
ORDER BY T.[name], I.[index_id], IC.[key_ordinal]   

Permissions error when connecting to EC2 via SSH on Mac OSx

Are you sure you have used the right instance? I ran into this problem and realized that something like 4 of the ubuntu instances i tried did not have SSH servers installed on them.

For a list of good servers see "Getting the images" about half way down. Sounds like you may be using something else... the default username is ubuntu on these images.

https://help.ubuntu.com/community/EC2StartersGuide

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

This works for me in python 2.7

 select some_date::DATE from some_table;

CSS text-align: center; is not centering things

I assume you want all the items next to each other, and the whole thing to be centered horizontally.

li elements are display: block by default, taking up all the horizontal space.

Add

div#footer ul li { display: inline }

once you've done that, you probably want to get rid of the list's bullets:

div#footer ul { list-style-type: none; padding: 0px; margin: 0px }

The network path was not found

On my end, the problem was an unsuccessful connection to the VPN (while working from home). And yeah, the connectionString was using a context from remote server. Which resulted in the following error:

<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>The network path was not found</ExceptionMessage>
  <ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
  <StackTrace/>
</Error>

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

how to delete all commit history in github?

Deleting the .git folder may cause problems in your git repository. If you want to delete all your commit history but keep the code in its current state, it is very safe to do it as in the following:

  1. Checkout

    git checkout --orphan latest_branch

  2. Add all the files

    git add -A

  3. Commit the changes

    git commit -am "commit message"

  4. Delete the branch

    git branch -D main

  5. Rename the current branch to main

    git branch -m main

  6. Finally, force update your repository

    git push -f origin main

PS: this will not keep your old commit history around

How to submit form on change of dropdown list?

To those in the answer above. It's definitely JavaScript. It's just inline.

BTW the jQuery equivalent if you want to apply to all selects:

$('form select').on('change', function(){
    $(this).closest('form').submit();
});

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Hiding the R code in Rmarkdown/knit and just showing the results

Just aggregating the answers and expanding on the basics. Here are three options:

1) Hide Code (individual chunk)

We can include echo=FALSE in the chunk header:

```{r echo=FALSE}
plot(cars)
```

2) Hide Chunks (globally).

We can change the default behaviour of knitr using the knitr::opts_chunk$set function. We call this at the start of the document and include include=FALSE in the chunk header to suppress any output:

---
output: html_document
---

```{r include = FALSE}
knitr::opts_chunk$set(echo=FALSE)
```

```{r}
plot(cars)
```

3) Collapsed Code Chunks

For HTML outputs, we can use code folding to hide the code in the output file. It will still include the code but can only be seen once a user clicks on this. You can read about this further here.

---
output:
  html_document:
    code_folding: "hide"
---


```{r}
plot(cars)
```

enter image description here

PL/pgSQL checking if a row exists

Use count(*)

declare 
   cnt integer;
begin
  SELECT count(*) INTO cnt
  FROM people
  WHERE person_id = my_person_id;

IF cnt > 0 THEN
  -- Do something
END IF;

Edit (for the downvoter who didn't read the statement and others who might be doing something similar)

The solution is only effective because there is a where clause on a column (and the name of the column suggests that its the primary key - so the where clause is highly effective)

Because of that where clause there is no need to use a LIMIT or something else to test the presence of a row that is identified by its primary key. It is an effective way to test this.

Switch statement fall-through...should it be allowed?

I don't like my switch statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case statements all do exactly the same thing.

If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.

How to call multiple functions with @click in vue?

you can, however, do something like this :

<div onclick="return function()
              {console.log('yaay, another onclick event!')}()" 
              @click="defaultFunction"></div>

yes, by using native onclick html event.

Finding the length of an integer in C

keep dividing by ten until you get zero, then just output the number of divisions.

int intLen(int x)
{
  if(!x) return 1;
  int i;
  for(i=0; x!=0; ++i)
  {
    x /= 10;
  }
  return i;
}

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

You can make use of java.util.Date instead of Timestamp :

String timeStamp = new SimpleDateFormat("yyyy.MM.dd.HH.mm.ss").format(new Date());

Convert laravel object to array

Its very simple. You can use like this :-

Suppose You have one users table and you want to fetch the id only
$users = DB::table('users')->select('id')->get();
$users = json_decode(json_encode($users)); //it will return you stdclass object
$users = json_decode(json_encode($users),true); //it will return you data in array
echo '<pre>'; print_r($users);

Hope it helps

Check if textbox has empty value

Also You can use

$value = $("#txt").val();

if($value == "")
{
    //Your Code Here
}
else
{
   //Your code
}

Try it. It work.