Programs & Examples On #Generated code

No generated R.java file in my project

now you have imported android.R instead of your own R... Try to take a look on your "problems" view if you have errors in one of your xml files... get rid of the import android.R and comment out all usages of R.*

Cleaning should help when your project has no other errors, so check your xml files or file naming in your res folders

How to change color of SVG image using CSS (jQuery SVG image replacement)?

for :hover event animations we can left the styles inside svg file, like a

<svg xmlns="http://www.w3.org/2000/svg">
<defs>
  <style>
  rect {
    fill:rgb(165,225,75);
    stroke:none;
    transition: 550ms ease-in-out;
    transform-origin:125px 125px;
  }
  rect:hover {
    fill:rgb(75,165,225);
    transform:rotate(360deg);
  }
  </style>
</defs>
  <rect x='50' y='50' width='150' height='150'/>
</svg>

check this on svgshare

How to calculate number of days between two dates

I made a quick re-usable function in ES6 using Moment.js.

_x000D_
_x000D_
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
  const getDateAsArray = (date) => {_x000D_
    return moment(date.split(/\D+/), date_format);_x000D_
  }_x000D_
  return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
_x000D_
_x000D_

What is the equivalent of Java's System.out.println() in Javascript?

In java System.out.println() prints something to console. In javascript same can be achieved using console.log().

You need to view browser console by pressing F12 key which opens developer tool and then switch to console tab.

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

Solution using only javascript

function saveFile(fileName,urlFile){
    let a = document.createElement("a");
    a.style = "display: none";
    document.body.appendChild(a);
    a.href = urlFile;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(url);
    a.remove();
}

let textData = `El contenido del archivo
que sera descargado`;
let blobData = new Blob([textData], {type: "text/plain"});
let url = window.URL.createObjectURL(blobData);
//let url = "pathExample/localFile.png"; // LocalFileDownload
saveFile('archivo.txt',url);

Http Get using Android HttpURLConnection

URL url = new URL("https://www.google.com");

//if you are using

URLConnection conn =url.openConnection();

//change it to

HttpURLConnection conn =(HttpURLConnection )url.openConnection();

How to send HTML-formatted email?

Setting isBodyHtml to true allows you to use HTML tags in the message body:

msg = new MailMessage("[email protected]",
                "[email protected]", "Message from PSSP System",
                "This email sent by the PSSP system<br />" +
                "<b>this is bold text!</b>");

msg.IsBodyHtml = true;

Creating a button in Android Toolbar

Toolbar customization can done by following ways

write button and textViews code inside toolbar as shown below

<android.support.v7.widget.Toolbar
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/app_bar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <Button
      android:layout_width="wrap_content"
        android:layout_height="@dimen/btn_height_small"
        android:text="Departure"
        android:layout_gravity="right"
        />
</android.support.v7.widget.Toolbar>

Other way is to use item menu as shown below

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

Regex: ignore case sensitivity

Assuming you want the whole regex to ignore case, you should look for the i flag. Nearly all regex engines support it:

/G[a-b].*/i

string.match("G[a-b].*", "i")

Check the documentation for your language/platform/tool to find how the matching modes are specified.

If you want only part of the regex to be case insensitive (as my original answer presumed), then you have two options:

  1. Use the (?i) and [optionally] (?-i) mode modifiers:

    (?i)G[a-b](?-i).*
    
  2. Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:

    [gG][a-bA-B].*
    

One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.

Oracle database: How to read a BLOB?

SQL Developer can show the blob as an image (at least it works for jpegs). In the Data view, double click on the BLOB field to get the "pencil" icon. Click on the pencil to get a dialog that will allow you to select a "View As Image" checkbox.

iOS - UIImageView - how to handle UIImage image orientation

Inspired from @Aqua Answer.....

in Objective C

- (UIImage *)fixImageOrientation:(UIImage *)img {

   UIGraphicsBeginImageContext(img.size);
   [img drawAtPoint:CGPointZero];

   UIImage *newImg = UIGraphicsGetImageFromCurrentImageContext();
   UIGraphicsEndImageContext();

   if (newImg) {
       return newImg;
   }

   return img;
}

ionic 2 - Error Could not find an installed version of Gradle either in Android Studio

On Ubuntu 18.04, I intalled gradle with:

sudo add-apt-repository ppa:cwchien/gradle
sudo apt-get update
sudo apt-get install gradle

And Ready.

How to set HTML Auto Indent format on Sublime Text 3?

Create a Keybinding

To auto indent on Sublime text 3 with a key bind try going to

Preferences > Key Bindings - users

And adding this code between the square brackets

{"keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false}}

it sets shift + alt + f to be your full page auto indent.

Source here

Note: if this doesn't work correctly then you should convert your indentation to tabs. Also comments in your code can push your code to the wrong indentation level and may have to be moved manually.

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

Change / Add syntax highlighting for a language in Sublime 2/3

The "this" is already coloured in Javascript.

View->Syntax-> and choose your language to highlight.

Opposite of %in%: exclude rows with values specified in a vector

If you look at the code of %in%

 function (x, table) match(x, table, nomatch = 0L) > 0L

then you should be able to write your version of opposite. I use

`%not in%` <- function (x, table) is.na(match(x, table, nomatch=NA_integer_))

Another way is:

function (x, table) match(x, table, nomatch = 0L) == 0L

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

Error handling with PHPMailer

$mail = new PHPMailer();

$mail->AddAddress($email); 
$mail->From     = $from;
$mail->Subject  = $subject; 
$mail->Body     = $body;

if($mail->Send()){
    echo 'Email Successfully Sent!';
}else{
    echo 'Email Sending Failed!';
}

the simplest way to handle email sending successful or failed...

Regular expression to find URLs within a string

I use this Regex:

/((\w+:\/\/\S+)|(\w+[\.:]\w+\S+))[^\s,\.]/ig

It works fine for many URLs, like: http://google.com, https://dev-site.io:8080/home?val=1&count=100, www.regexr.com, localhost:8080/path, ...

How do I pass a command line argument while starting up GDB in Linux?

I'm using GDB7.1.1, as --help shows:

gdb [options] --args executable-file [inferior-arguments ...]

IMHO, the order is a bit unintuitive at first.

In Python, how do I use urllib to see if a website is 404 or 200?

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

How do I determine k when using k-means clustering?

Another approach is using Self Organizing Maps (SOP) to find optimal number of clusters. The SOM (Self-Organizing Map) is an unsupervised neural network methodology, which needs only the input is used to clustering for problem solving. This approach used in a paper about customer segmentation.

The reference of the paper is

Abdellah Amine et al., Customer Segmentation Model in E-commerce Using Clustering Techniques and LRFM Model: The Case of Online Stores in Morocco, World Academy of Science, Engineering and Technology International Journal of Computer and Information Engineering Vol:9, No:8, 2015, 1999 - 2010

How can I remove all my changes in my SVN working directory?

svn status | grep '^M' | sed -e 's/^.//' | xargs rm

svn update

Will remove any file which has been modified. I seem to remember having trouble with revert when files and directories may have been added.

How to set custom location for local installation of npm package?

TL;DR

You can do this by using the --prefix flag and the --global* flag.

pje@friendbear:~/foo $ npm install bower -g --prefix ./vendor/node_modules
[email protected] /Users/pje/foo/vendor/node_modules/bower

*Even though this is a "global" installation, installed bins won't be accessible through the command line unless ~/foo/vendor/node_modules exists in PATH.

TL;DR

Every configurable attribute of npm can be set in any of six different places. In order of priority:

  • Command-Line Flags: --prefix ./vendor/node_modules
  • Environment Variables: NPM_CONFIG_PREFIX=./vendor/node_modules
  • User Config File: $HOME/.npmrc or userconfig param
  • Global Config File: $PREFIX/etc/npmrc or userconfig param
  • Built-In Config File: path/to/npm/itself/npmrc
  • Default Config: node_modules/npmconf/config-defs.js

By default, locally-installed packages go into ./node_modules. global ones go into the prefix config variable (/usr/local by default).

You can run npm config list to see your current config and npm config edit to change it.

PS

In general, npm's documentation is really helpful. The folders section is a good structural overview of npm and the config section answers this question.

How to tell a Mockito mock object to return something different the next time it is called?

For Anyone using spy() and the doReturn() instead of the when() method:

what you need to return different object on different calls is this:

doReturn(obj1).doReturn(obj2).when(this.spyFoo).someMethod();

.

For classic mocks:

when(this.mockFoo.someMethod()).thenReturn(obj1, obj2);

or with an exception being thrown:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenThrow(new IllegalArgumentException())
        .thenReturn(obj2, obj3);

How to send cookies in a post request with the Python Requests library?

Just to extend on the previous answer, if you are linking two requests together and want to send the cookies returned from the first one to the second one (for example, maintaining a session alive across requests) you can do:

import requests
r1 = requests.post('http://www.yourapp.com/login')
r2 = requests.post('http://www.yourapp.com/somepage',cookies=r1.cookies)

Create Hyperlink in Slack

I know you wanted only a hypertext link, but if you copy & paste a link address into Slack that does work very nicely. i.e. if referring to VersionOne ticket number (V1 mouseover the ticket window to open the mouseover window, then right click on the ticket number for the option to "copy link address", then in Slack paste. It'll paste the full ticket URL but then it shows a nice summary of the ticket number and name and you can click it to go right into the ticket.)

How do I add the Java API documentation to Eclipse?

To use offline Java API Documentation in Eclipse, you need to download it first. The link for Java docs are (last updated on 2013-10-21):

Java 6
Page: http://www.oracle.com/technetwork/java/javase/downloads/jdk-6u25-doc-download-355137.html
Direct: http://download.oracle.com/otn-pub/java/jdk/6u30-b12/jdk-6u30-apidocs.zip

Java 7
Page: http://www.oracle.com/technetwork/java/javase/documentation/java-se-7-doc-download-435117.html

Java 8
Page: http://www.oracle.com/technetwork/java/javase/documentation/jdk8-doc-downloads-2133158.html

Java 9
Page:http://www.oracle.com/technetwork/java/javase/documentation/jdk9-doc-downloads-3850606.html

  1. Extract the zip file in your local directory.
  2. From eclipse Window --> Preferences --> Java --> "Installed JREs" select available JRE (jre6: C:\Program Files (x86)\Java\jre6 for instance) and click Edit.
  3. Select all the "JRE System libraries" using Control+A.
  4. Click "Javadoc Location"
  5. Change "Javadoc location path:" from "http://download.oracle.com/javase/6/docs/api/" to "file:/E:/Java/docs/api/".

It must work as it works for me. I don't need Internet connection to view Java API Documentation in Eclipse anymore.

Storing query results into a variable and modifying it inside a Stored Procedure

Yup, this is possible of course. Here are several examples.

-- one way to do this
DECLARE @Cnt int

SELECT @Cnt = COUNT(SomeColumn)
FROM TableName
GROUP BY SomeColumn

-- another way to do the same thing
DECLARE @StreetName nvarchar(100)
SET @StreetName = (SELECT Street_Name from Streets where Street_ID = 123)

-- Assign values to several variables at once
DECLARE @val1 nvarchar(20)
DECLARE @val2 int
DECLARE @val3 datetime
DECLARE @val4 uniqueidentifier
DECLARE @val5 double

SELECT @val1 = TextColumn,
@val2 = IntColumn,
@val3 = DateColumn,
@val4 = GuidColumn,
@val5 = DoubleColumn
FROM SomeTable

PHP Fatal error: Cannot access empty property

This way you can create a new object with a custom property name.

$my_property = 'foo';
$value = 'bar';
$a = (object) array($my_property => $value);

Now you can reach it like:

echo $a->foo;  //returns bar

Creating a BLOB from a Base64 string in JavaScript

For all browser support, especially on Android, perhaps you can add this:

try{
    blob = new Blob(byteArrays, {type : contentType});
}
catch(e){
    // TypeError old Google Chrome and Firefox
    window.BlobBuilder = window.BlobBuilder ||
                         window.WebKitBlobBuilder ||
                         window.MozBlobBuilder ||
                         window.MSBlobBuilder;
    if(e.name == 'TypeError' && window.BlobBuilder){
        var bb = new BlobBuilder();
        bb.append(byteArrays);
        blob = bb.getBlob(contentType);
    }
    else if(e.name == "InvalidStateError"){
        // InvalidStateError (tested on FF13 WinXP)
        blob = new Blob(byteArrays, {type : contentType});
    }
    else{
        // We're screwed, blob constructor unsupported entirely
    }
}

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

As shown below, range only supports integers:

>>> range(15.0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: range() integer end argument expected, got float.
>>> range(15)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>>

However, c/10 is a float because / always returns a float.

Before you put it in range, you need to make c/10 an integer. This can be done by putting it in int:

range(int(c/10))

or by using //, which returns an integer:

range(c//10)

Oracle SqlDeveloper JDK path

On Windows,Close all the SQL Developer windows. Then You need to completely delete the SQL Developer and sqldeveloper folders located in user/AppData/Roaming. Finally, run the program, you will be prompted for new JDK.

Note that AppData is a hidden folder.

How to get the seconds since epoch from the time + date output of gmtime()?

t = datetime.strptime('Jul 9, 2009 @ 20:02:58 UTC',"%b %d, %Y @ %H:%M:%S %Z")

Sorting Characters Of A C++ String

std::sort(str.begin(), str.end());

See here

Get started with Latex on Linux

yum -y install texlive

was not enough for my centos distro to get the latex command.

This site https://gist.github.com/melvincabatuan/350f86611bc012a5c1c6 contains additional packages. In particular:

yum -y install texlive texlive-latex texlive-xetex

was enough but the author also points out these as well:

yum -y install texlive-collection-latex
yum -y install texlive-collection-latexrecommended
yum -y install texlive-xetex-def
yum -y install texlive-collection-xetex

Only if needed:

yum -y install texlive-collection-latexextra

Maven: add a folder or jar file into current classpath

The classpath setting of the compiler plugin are two args. Changed it like this and it worked for me:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<configuration>
  <compilerArgs>
     <arg>-cp</arg>
     <arg>${cp}:${basedir}/lib/bad.jar</arg>
  </compilerArgs>
</configuration>

I used the gmavenplus-plugin to read the path and create the property 'cp':

      <plugin>
    <!--
      Use Groovy to read classpath and store into
      file named value of property <cpfile>

      In second step use Groovy to read the contents of
      the file into a new property named <cp>

      In the compiler plugin this is used to create a
      valid classpath
    -->
    <groupId>org.codehaus.gmavenplus</groupId>
    <artifactId>gmavenplus-plugin</artifactId>
    <version>1.12.0</version>
    <dependencies>
      <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <!-- any version of Groovy \>= 1.5.0 should work here -->
        <version>3.0.6</version>
        <type>pom</type>
        <scope>runtime</scope>
      </dependency>
    </dependencies>
    <executions>
      <execution>
        <id>read-classpath</id>
        <phase>validate</phase>
        <goals>
          <goal>execute</goal>
        </goals>
      </execution>

    </executions>
    <configuration>
      <scripts>
        <script><![CDATA[
                def file = new File(project.properties.cpfile)
                /* create a new property named 'cp'*/
                project.properties.cp = file.getText()
                println '<<< Retrieving classpath into new property named <cp> >>>'
                println 'cp = ' + project.properties.cp
              ]]></script>
      </scripts>
    </configuration>
  </plugin>

String concatenation with Groovy

I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X} as I find it makes it more readable.

Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:

@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*

def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

That gives me the following output on my machine:

Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
    * JRE: 1.6.0_31
    * Total Memory: 81.0625 MB
    * Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64) 

Options
=======
* Warm Up: Auto 
* CPU Time Measurement: Off

String adder               539
GString template           245
Readable GString template  244
StringBuilder              318
StringBuffer               370

So with readability and speed in it's favour, I'd recommend templating ;-)

NB: If you add toString() to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder and StringBuffer beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion

Adding these tests (as it has been asked in the comments)

  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }

Now we get the results:

String adder                        514
GString template                    267
Readable GString template           269
GString template toString           478
Readable GString template toString  480
StringBuilder                       321
StringBuffer                        369

So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...

But still lots more readable.

Edit after comment by ruralcoder below

Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:

@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )

def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
  // Just add the strings
  'String adder' {
    foo + bar + baz
  }
  // Templating
  'GString template' {
    "$foo$bar$baz"
  }
  // I find this more readable
  'Readable GString template' {
    "${foo}${bar}${baz}"
  }
  'GString template toString' {
    "$foo$bar$baz".toString()
  }
  'Readable GString template toString' {
    "${foo}${bar}${baz}".toString()
  }
  // StringBuilder
  'StringBuilder' {
    new StringBuilder().append( foo )
                       .append( bar )
                       .append( baz )
                       .toString()
  }
  'StringBuffer' {
    new StringBuffer().append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
  'StringBuffer with Allocation' {
    new StringBuffer( 512 ).append( foo )
                      .append( bar )
                      .append( baz )
                      .toString()
  }
}.prettyPrint()

gives

Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
    * JRE: 1.7.0_21
    * Total Memory: 467.375 MB
    * Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         630       0  630   647
GString template                      29       0   29    31
Readable GString template             32       0   32    33
GString template toString            429       0  429   443
Readable GString template toString   428       1  429   441
StringBuilder                        383       1  384   396
StringBuffer                         395       1  396   409
StringBuffer with Allocation         277       0  277   286

Where can I find decent visio templates/diagrams for software architecture?

For SOA system architecture, I use the SOACP Visio stencil. It provides the symbols that are used in Thomas Erl's SOA book series.

I use the Visio Network and Database stencils to model most other requirements.

Posting JSON Data to ASP.NET MVC

BeRecursive's answer is the one I used, so that we could standardize on Json.Net (we have MVC5 and WebApi 5 -- WebApi 5 already uses Json.Net), but I found an issue. When you have parameters in your route to which you're POSTing, MVC tries to call the model binder for the URI values, and this code will attempt to bind the posted JSON to those values.

Example:

[HttpPost]
[Route("Customer/{customerId:int}/Vehicle/{vehicleId:int}/Policy/Create"]
public async Task<JsonNetResult> Create(int customerId, int vehicleId, PolicyRequest policyRequest)

The BindModel function gets called three times, bombing on the first, as it tries to bind the JSON to customerId with the error: Error reading integer. Unexpected token: StartObject. Path '', line 1, position 1.

I added this block of code to the top of BindModel:

if (bindingContext.ValueProvider.GetValue(bindingContext.ModelName) != null) {
    return base.BindModel(controllerContext, bindingContext);
}

The ValueProvider, fortunately, has route values figured out by the time it gets to this method.

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

node.js string.replace doesn't work?

Isn't string.replace returning a value, rather than modifying the source string?

So if you wanted to modify variableABC, you'd need to do this:

var variableABC = "A B C";

variableABC = variableABC.replace('B', 'D') //output: 'A D C'

What is the difference between Left, Right, Outer and Inner Joins?

LEFT JOIN and RIGHT JOIN are types of OUTER JOINs.

INNER JOIN is the default -- rows from both tables must match the join condition.

Entity Framework: table without primary key

  1. Change the Table structure and add a Primary Column. Update the Model
  2. Modify the .EDMX file in XML Editor and try adding a New Column under tag for this specific table (WILL NOT WORK)
  3. Instead of creating a new Primary Column to Exiting table, I will make a composite key by involving all the existing columns (WORKED)

Entity Framework: Adding DataTable with no Primary Key to Entity Model.

Style child element when hover on parent

Yes, you can definitely do this. Just use something like

.parent:hover .child {
   /* ... */
}

According to this page it's supported by all major browsers.

How do you compare two version Strings in Java?

I created simple utility for comparing versions on Android platform using Semantic Versioning convention. So it works only for strings in format X.Y.Z (Major.Minor.Patch) where X, Y, and Z are non-negative integers. You can find it on my GitHub.

Method Version.compareVersions(String v1, String v2) compares two version strings. It returns 0 if the versions are equal, 1 if version v1 is before version v2, -1 if version v1 is after version v2, -2 if version format is invalid.

How to remove unused imports in Intellij IDEA on commit?

If you are using IntelliJ IDEA or Android Studio:

Android optimize imports

Go to Settings > Editor > General >Auto Import and check the Optimize imports on the fly checkbox.

react router v^4.0.0 Uncaught TypeError: Cannot read property 'location' of undefined

You're doing a few things wrong.

  1. First, browserHistory isn't a thing in V4, so you can remove that.

  2. Second, you're importing everything from react-router, it should be react-router-dom.

  3. Third, react-router-dom doesn't export a Router, instead, it exports a BrowserRouter so you need to import { BrowserRouter as Router } from 'react-router-dom.

Looks like you just took your V3 app and expected it to work with v4, which isn't a great idea.

How to compile LEX/YACC files on Windows?

What you (probably want) are Flex 2.5.4 (some people are now "maintaining" it and producing newer versions, but IMO they've done more to screw it up than fix any real shortcomings) and byacc 1.9 (likewise). (Edit 2017-11-17: Flex 2.5.4 is not available on Sourceforge any more, and the Flex github repository only goes back to 2.5.5. But you can apparently still get it from a Gnu ftp server at ftp://ftp.gnu.org/old-gnu/gnu-0.2/src/flex-2.5.4.tar.gz.)

Since it'll inevitably be recommended, I'll warn against using Bison. Bison was originally written by Robert Corbett, the same guy who later wrote Byacc, and he openly states that at the time he didn't really know or understand what he was doing. Unfortunately, being young and foolish, he released it under the GPL and now the GPL fans push it as the answer to life's ills even though its own author basically says it should be thought of as essentially a beta test product -- but by the convoluted reasoning of GPL fans, byacc's license doesn't have enough restrictions to qualify as "free"!

How to recursively find and list the latest modified files in a directory with subdirectories and times

Ignoring hidden files — with nice & fast time stamp

Handles spaces in filenames well — not that you should use those!

$ find . -type f -not -path '*/\.*' -printf '%TY.%Tm.%Td %THh%TM %Ta %p\n' |sort -nr |head -n 10

2017.01.28 07h00 Sat ./recent
2017.01.21 10h49 Sat ./hgb
2017.01.16 07h44 Mon ./swx
2017.01.10 18h24 Tue ./update-stations
2017.01.09 10h38 Mon ./stations.json

More find galore can be found by following the link.

What's the scope of a variable initialized in an if statement?

Python variables are scoped to the innermost function, class, or module in which they're assigned. Control blocks like if and while blocks don't count, so a variable assigned inside an if is still scoped to a function, class, or module.

(Implicit functions defined by a generator expression or list/set/dict comprehension do count, as do lambda expressions. You can't stuff an assignment statement into any of those, but lambda parameters and for clause targets are implicit assignment.)

How do I call paint event?

Call control.invalidate and the paint event will be raised.

What is a LAMP stack?

Linux, Apache, MySQL and PHP. free and open-source software. For example, an equivalent installation on the Microsoft Windows family of operating systems is known as WAMP. and for mac as MAMP. and XAMPP for both of them

How do I install Python packages on Windows?

I had problems in installing packages on Windows. Found the solution. It works in Windows7+. Mainly anything with Windows Powershell should be able to make it work. This can help you get started with it.

  • Firstly, you'll need to add python installation to your PATH variable. This should help.
  • You need to download the package in zip format that you are trying to install and unzip it. If it is some odd zip format use 7Zip and it should be extracted.
  • Navigate to the directory extracted with setup.py using Windows Powershell (Use link for it if you have problems)
  • Run the command python setup.py install

That worked for me when nothing else was making any sense. I use Python 2.7 but the documentation suggests that same would work for Python 3.x also.

Import Excel to Datagridview

Since you have not replied to my comment above, I am posting a solution for both.

You are missing ' in Extended Properties

For Excel 2003 try this (TRIED AND TESTED)

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

BTW, I stopped working with Jet longtime ago. I use ACE now.

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xls" + 
                        ";Extended Properties='Excel 8.0;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

enter image description here

For Excel 2007+

    private void button1_Click(object sender, EventArgs e)
    {
        String name = "Items";
        String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
                        "C:\\Sample.xlsx" + 
                        ";Extended Properties='Excel 12.0 XML;HDR=YES;';";

        OleDbConnection con = new OleDbConnection(constr);
        OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
        con.Open();

        OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
        DataTable data = new DataTable();
        sda.Fill(data);
        grid_items.DataSource = data;
    }

Eloquent ->first() if ->exists()

An answer has already been accepted, but in these situations, a more elegant solution in my opinion would be to use error handling.

    try {
        $user = User::where('mobile', Input::get('mobile'))->first();
    } catch (ErrorException $e) {
        // Do stuff here that you need to do if it doesn't exist.
        return View::make('some.view')->with('msg', $e->getMessage());
    }

Iterating through a JSON object

If you can store the json string in a variable jsn_string

import json

jsn_list = json.loads(json.dumps(jsn_string)) 
   for lis in jsn_list:
       for key,val in lis.items():
           print(key, val)

Output :

title Baby (Feat. Ludacris) - Justin Bieber
description Baby (Feat. Ludacris) by Justin Bieber on Grooveshark
link http://listen.grooveshark.com/s/Baby+Feat+Ludacris+/2Bqvdq
pubDate Wed, 28 Apr 2010 02:37:53 -0400
pubTime 1272436673
TinyLink http://tinysong.com/d3wI
SongID 24447862
SongName Baby (Feat. Ludacris)
ArtistID 1118876
ArtistName Justin Bieber
AlbumID 4104002
AlbumName My World (Part II);
http://tinysong.com/gQsw
LongLink 11578982
GroovesharkLink 11578982
Link http://tinysong.com/d3wI
title Feel Good Inc - Gorillaz
description Feel Good Inc by Gorillaz on Grooveshark
link http://listen.grooveshark.com/s/Feel+Good+Inc/1UksmI
pubDate Wed, 28 Apr 2010 02:25:30 -0400
pubTime 1272435930

Reset git proxy to default configuration

You can remove that configuration with:

git config --global --unset core.gitproxy

Read a variable in bash with a default value

The -e and -t parameter does not work together. i tried some expressions and the result was the following code snippet :

QMESSAGE="SHOULD I DO YES OR NO"
YMESSAGE="I DO"
NMESSAGE="I DO NOT"
FMESSAGE="PLEASE ENTER Y or N"
COUNTDOWN=2
DEFAULTVALUE=n
#----------------------------------------------------------------#
function REQUEST ()
{
read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT
    INPUT=${INPUT:-$DEFAULTVALUE}
    if  [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then
        echo -e "\n$YMESSAGE\n"
        #COMMANDEXECUTION
    elif    [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then
        echo -e "\n$NMESSAGE\n"
        #COMMANDEXECUTION
    else
        echo -e "\n$FMESSAGE\n"
    REQUEST
    fi
}
REQUEST

Apply function to each column in a data frame observing each columns existing data type

A solution using retype() from hablar to coerce factors to character or numeric type depending on feasability. I'd use dplyr for applying max to each column.

Code

library(dplyr)
library(hablar)

# Retype() simplifies each columns type, e.g. always removes factors
d <- d %>% retype()

# Check max for each column
d %>% summarise_all(max)

Result

Not the new column types.

     v1 v2       v3 v4   
  <dbl> <chr> <dbl> <chr>
1 0.974 j      1.09 J   

Data

# Sample data borrowed from @joran
d <- data.frame(v1 = runif(10), v2 = letters[1:10], 
                v3 = rnorm(10), v4 = LETTERS[1:10],stringsAsFactors = TRUE)

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;

How to move table from one tablespace to another in oracle 11g

Moving tables:

First run:

SELECT 'ALTER TABLE <schema_name>.' || OBJECT_NAME ||' MOVE TABLESPACE '||' <tablespace_name>; '
FROM ALL_OBJECTS
WHERE OWNER = '<schema_name>'
AND OBJECT_TYPE = 'TABLE' <> '<TABLESPACE_NAME>';

-- Or suggested in the comments (did not test it myself)

SELECT 'ALTER TABLE <SCHEMA>.' || TABLE_NAME ||' MOVE TABLESPACE '||' TABLESPACE_NAME>; ' 
FROM dba_tables 
WHERE OWNER = '<SCHEMA>' 
AND TABLESPACE_NAME <> '<TABLESPACE_NAME>

Where <schema_name> is the name of the user. And <tablespace_name> is the destination tablespace.

As a result you get lines like:

ALTER TABLE SCOT.PARTS MOVE TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Moving indexes:

First run:

SELECT 'ALTER INDEX <schema_name>.'||INDEX_NAME||' REBUILD TABLESPACE <tablespace_name>;' 
FROM ALL_INDEXES
WHERE OWNER = '<schema_name>'
AND TABLESPACE_NAME NOT LIKE '<tablespace_name>';

The last line in this code could save you a lot of time because it filters out the indexes which are already in the correct tablespace.

As a result you should get something like:

ALTER INDEX SCOT.PARTS_NO_PK REBUILD TABLESPACE USERS;

Paste the results in a script or in a oracle sql developer like application and run it.

Last but not least, moving LOBs:

First run:

SELECT 'ALTER TABLE <schema_name>.'||LOWER(TABLE_NAME)||' MOVE LOB('||LOWER(COLUMN_NAME)||') STORE AS (TABLESPACE <table_space>);'
FROM DBA_TAB_COLS
WHERE OWNER = '<schema_name>' AND DATA_TYPE like '%LOB%';

This moves the LOB objects to the other tablespace.

As a result you should get something like:

ALTER TABLE SCOT.bin$6t926o3phqjgqkjabaetqg==$0 MOVE LOB(calendar) STORE AS (TABLESPACE USERS);

Paste the results in a script or in a oracle sql developer like application and run it.

O and there is one more thing:

For some reason I wasn't able to move 'DOMAIN' type indexes. As a work around I dropped the index. changed the default tablespace of the user into de desired tablespace. and then recreate the index again. There is propably a better way but it worked for me.

tqdm in Jupyter Notebook prints new progress bars repeatedly

None of the above works for me. I find that running the following sorts this issue after error (It just clears all the instances of progress bars in the background):

from tqdm import tqdm

# blah blah your code errored

tqdm._instances.clear()

Difference between Date(dateString) and new Date(dateString)

I know this is old but by far the easier solution is to just use

var temp = new Date("2010-08-17T12:09:36");

How to cin Space in c++?

I have the same problem and I just used cin.getline(input,300);.

noskipws and cin.get() sometimes are not easy to use. Since you have the right size of your array try using cin.getline() which does not care about any character and read the whole line in specified character count.

Cannot implicitly convert type 'string' to 'System.Threading.Tasks.Task<string>'

Beyond the problematic use of async as pointed out by @Servy, the other issue is that you need to explicitly get T from Task<T> by calling Task.Result. Note that the Result property will block async code, and should be used carefully.

Try:

private async void button1_Click(object sender, EventArgs e)
{
    var s = await methodAsync();
    MessageBox.Show(s.Result);
}

Adding local .aar files to Gradle build using "flatDirs" is not working

This solution is working with Android Studio 4.0.1.

Apart from creating a new module as suggested in above solution, you can try this solution.

If you have multiple modules in your application and want to add aar to just one of the module then this solution come handy.

In your root project build.gradle

add

repositories {
flatDir {
    dirs 'libs'
}}

Then in the module where you want to add the .aar file locally. simply add below lines of code.

dependencies {
api fileTree(include: ['*.aar'], dir: 'libs')
implementation files('libs/<yourAarName>.aar')

}

Happy Coding :)

Run a shell script with an html button

This is how it look like in pure bash

cat /usr/lib/cgi-bin/index.cgi

#!/bin/bash
echo Content-type: text/html
echo ""
## make POST and GET stings
## as bash variables available
if [ ! -z $CONTENT_LENGTH ] && [ "$CONTENT_LENGTH" -gt 0 ] && [ $CONTENT_TYPE != "multipart/form-data" ]; then
read -n $CONTENT_LENGTH POST_STRING <&0
eval `echo "${POST_STRING//;}"|tr '&' ';'`
fi
eval `echo "${QUERY_STRING//;}"|tr '&' ';'`

echo  "<!DOCTYPE html>"
echo  "<html>"
echo  "<head>"
echo  "</head>"

if [[ "$vote" = "a" ]];then
echo "you pressed A"
  sudo /usr/local/bin/run_a.sh
elif [[ "$vote" = "b" ]];then
echo "you pressed B"
  sudo /usr/local/bin/run_b.sh
fi

echo  "<body>"
echo  "<div id=\"content-container\">"
echo  "<div id=\"content-container-center\">"
echo  "<form id=\"choice\" name='form' method=\"POST\" action=\"/\">"
echo  "<button id=\"a\" type=\"submit\" name=\"vote\" class=\"a\" value=\"a\">A</button>"
echo  "<button id=\"b\" type=\"submit\" name=\"vote\" class=\"b\" value=\"b\">B</button>"
echo  "</form>"
echo  "<div id=\"tip\">"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</div>"
echo  "</body>"
echo  "</html>"

Build with https://github.com/tinoschroeter/bash_on_steroids

Attribute 'nowrap' is considered outdated. A newer construct is recommended. What is it?

You can use it like this, I hope you wont get outdated message now.

  <td valign="top" style="white-space:nowrap" width="237">

As pointed by @ThiefMaster it is recommended to put width and valign to CSS (note: CSS calls it vertical-align).

1)

<td style="white-space:nowrap; width:237px; vertical-align:top;">

2) We can make a CSS class like this, it is more elegant way

In style section

.td-some-name
{
  white-space:nowrap;
  width:237px;
  vertical-align:top;
}

In HTML section

<td class="td-some-name">

Filtering Pandas DataFrames on dates

If the dates are in the index then simply:

df['20160101':'20160301']

Get Today's date in Java at midnight time

Calendar currentDate = Calendar.getInstance(); //Get the current date
SimpleDateFormat formatter= new SimpleDateFormat("yyyy/MMM/dd HH:mm:ss"); //format it as per your requirement
String dateNow = formatter.format(currentDate.getTime());
System.out.println("Now the date is :=>  " + dateNow);

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

Maven dependency for Servlet 3.0 API?

Here is what I use. All of these are in the Central and have sources.

For Tomcat 7 (Java 7, Servlet 3.0)

Note - Servlet, JSP and EL APIs are provided in Tomcat. Only JSTL (if used) needs to be bundled with the web app.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.2</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>2.2.4</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

For Tomcat 8 (Java 8, Servlet 3.1)

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.el</groupId>
    <artifactId>javax.el-api</artifactId>
    <version>3.0.0</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

Set the default value in dropdownlist using jQuery

val() should handle both cases

  <option value="1">it's me</option>      


$('select').val('1'); // selects "it's me"

$('select').val("it's me"); // also selects "it's me"

Fatal error: Call to a member function bind_param() on boolean

This particular error has very little to do with the actual error. Here is my similar experience and the solution...

I had a table that I use in my statement with |database-name|.login composite name. I thought this wouldn't be a problem. It was the problem indeed. Enclosing it inside square brackets solved my problem ([|database-name|].[login]). So, the problem is MySQL preserved words (other way around)... make sure your columns too are not failing to this type of error scenario...

CHECK constraint in MySQL is not working

try with set sql_mode = 'STRICT_TRANS_TABLES' OR SET sql_mode='STRICT_ALL_TABLES'

Change border color on <select> HTML form

select{
    filter: progid:DXImageTransform.Microsoft.dropshadow(OffX=-1, OffY=-1,color=#FF0000) progid:DXImageTransform.Microsoft.dropshadow(OffX=1, OffY=1,color=#FF0000);
}

Works for me.

git ignore vim temporary files

This works on a Mac as noted by Alex Moore-Niemi:

set backupdir=$TMPDIR//
set directory=$TMPDIR//

Make sure to use TMPDIR and not TEMPDIR.

Mockito: List Matchers with generics

Before Java 8 (versions 7 or 6) I use the new method ArgumentMatchers.anyList:

import static org.mockito.Mockito.*;
import org.mockito.ArgumentMatchers;

verify(mock, atLeastOnce()).process(ArgumentMatchers.<Bar>anyList());

how to display employee names starting with a and then b in sql

select employee_name 
from employees
where employee_name LIKE 'A%' OR employee_name LIKE 'B%'
order by employee_name

Python's most efficient way to choose longest string in list?

From the Python documentation itself, you can use max:

>>> mylist = ['123','123456','1234']
>>> print max(mylist, key=len)
123456

Windows- Pyinstaller Error "failed to execute script " When App Clicked

Add this function at the beginning of your script :

import sys, os 
    def resource_path(relative_path):
        if hasattr(sys, '_MEIPASS'):
            return os.path.join(sys._MEIPASS, relative_path)
        return os.path.join(os.path.abspath("."), relative_path)

Refer to your data files by calling the function resource_path(), like this:

resource_path('myimage.gif')

Then use this command:

pyinstaller --onefile --windowed --add-data todo.ico;. script.py

For more information visit this documentation page.

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES['file']['tmp_name']; will contain the temporary file name of the file on the server. This is just a placeholder on your server until you process the file

$_FILES['file']['name']; contains the original name of the uploaded file from the user's computer.

How do I set adaptive multiline UILabel text?

This is much better approach if you are looking for multiline dynamic text label which exactly takes the space based on its text.

No sizeToFit, preferredMaxLayoutWidth used

Below is how it will work.

enter image description here

Lets set up the project. Take a Single View application and in Storyboard Add a UILabel and a UIButton. Define constraints to UILabel as below snapshot:

enter image description here

Set the Label properties as below image:

enter image description here

Add the constraints to the UIButton. Make sure that vertical spacing of 100 is between UILabel and UIButton

enter image description here

Now set the priority of the trailing constraint of UILabel as 749

enter image description here

Now set the Horizontal Content Hugging and Horizontal Content Compression properties of UILabel as 750 and 748

enter image description here

Below is my controller class. You have to connect UILabel property and Button action from storyboard to viewcontroller class.

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var textLabel: UILabel!
var count = 0
let items = ["jackson is not any more in this world", "Jonny jonny yes papa eating sugar no papa", "Ab", "What you do is what will happen to you despite of all measures taken to reverse the phenonmenon of the nature"]


@IBAction func updateLabelText(sender: UIButton) {
    if count > 3 {
        count = 0
    }
    textLabel.text = items[count]
    count = count + 1
}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    //self.textLabel.sizeToFit()
    //self.textLabel.preferredMaxLayoutWidth = 500
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

Thats it. This will automatically resize the UILabel based on its content and also you can see the UIButton is also adjusted accordingly.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Return HTML from ASP.NET Web API

ASP.NET Core. Approach 1

If your Controller extends ControllerBase or Controller you can use Content(...) method:

[HttpGet]
public ContentResult Index() 
{
    return base.Content("<div>Hello</div>", "text/html");
}

ASP.NET Core. Approach 2

If you choose not to extend from Controller classes, you can create new ContentResult:

[HttpGet]
public ContentResult Index() 
{
    return new ContentResult 
    {
        ContentType = "text/html",
        Content = "<div>Hello World</div>"
    };
}

Legacy ASP.NET MVC Web API

Return string content with media type text/html:

public HttpResponseMessage Get()
{
    var response = new HttpResponseMessage();
    response.Content = new StringContent("<div>Hello World</div>");
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
    return response;
}

How are Anonymous inner classes used in Java?

Anonymous inner classes are effectively closures, so they can be used to emulate lambda expressions or "delegates". For example, take this interface:

public interface F<A, B> {
   B f(A a);
}

You can use this anonymously to create a first-class function in Java. Let's say you have the following method that returns the first number larger than i in the given list, or i if no number is larger:

public static int larger(final List<Integer> ns, final int i) {
  for (Integer n : ns)
     if (n > i)
        return n;
  return i;
}

And then you have another method that returns the first number smaller than i in the given list, or i if no number is smaller:

public static int smaller(final List<Integer> ns, final int i) {
   for (Integer n : ns)
      if (n < i)
         return n;
   return i;
}

These methods are almost identical. Using the first-class function type F, we can rewrite these into one method as follows:

public static <T> T firstMatch(final List<T> ts, final F<T, Boolean> f, T z) {
   for (T t : ts)
      if (f.f(t))
         return t;
   return z;
}

You can use an anonymous class to use the firstMatch method:

F<Integer, Boolean> greaterThanTen = new F<Integer, Boolean> {
   Boolean f(final Integer n) {
      return n > 10;
   }
};
int moreThanMyFingersCanCount = firstMatch(xs, greaterThanTen, x);

This is a really contrived example, but its easy to see that being able to pass functions around as if they were values is a pretty useful feature. See "Can Your Programming Language Do This" by Joel himself.

A nice library for programming Java in this style: Functional Java.

Delete column from SQLite table

For simplicity, why not create the backup table from the select statement?

CREATE TABLE t1_backup AS SELECT a, b FROM t1;
DROP TABLE t1;
ALTER TABLE t1_backup RENAME TO t1;

Do while loop in SQL Server 2008

I seem to recall reading this article more than once, and the answer is only close to what I need.

Usually when I think I'm going to need a DO WHILE in T-SQL it's because I'm iterating a cursor, and I'm looking largely for optimal clarity (vs. optimal speed). In T-SQL that seems to fit a WHILE TRUE / IF BREAK.

If that's the scenario that brought you here, this snippet may save you a moment. Otherwise, welcome back, me. Now I can be certain I've been here more than once. :)

DECLARE Id INT, @Title VARCHAR(50)
DECLARE Iterator CURSOR FORWARD_ONLY FOR
SELECT Id, Title FROM dbo.SourceTable
OPEN Iterator
WHILE 1=1 BEGIN
    FETCH NEXT FROM @InputTable INTO @Id, @Title
    IF @@FETCH_STATUS < 0 BREAK
    PRINT 'Do something with ' + @Title
END
CLOSE Iterator
DEALLOCATE Iterator

Unfortunately, T-SQL doesn't seem to offer a cleaner way to singly-define the loop operation, than this infinite loop.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How to find foreign key dependencies in SQL Server?

Because your question is geared towards a single table, you can use this:

EXEC sp_fkeys 'TableName'

I found it on SO here:

https://stackoverflow.com/a/12956348/652519

I found the information I needed pretty quickly. It lists the foreign key's table, column and name.

EDIT

Here's a link to the documentation that details the different parameters that can be used: https://docs.microsoft.com/en-us/sql/relational-databases/system-stored-procedures/sp-fkeys-transact-sql

How to unbind a listener that is calling event.preventDefault() (using jQuery)?

Disable:

document.ontouchstart = function(e){ e.preventDefault(); }

Enable:

document.ontouchstart = function(e){ return true; }

Best way to create enum of strings?

You can use that for string Enum

public enum EnumTest {
    NAME_ONE("Name 1"),
    NAME_TWO("Name 2");

    private final String name;

    /**
     * @param name
     */
    private EnumTest(final String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

And call from main method

public class Test {
    public static void main (String args[]){
        System.out.println(EnumTest.NAME_ONE.getName());
        System.out.println(EnumTest.NAME_TWO.getName());
    }
}

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

Sending and Parsing JSON Objects in Android

GSON is easiest to use and the way to go if the data have a definite structure.

Download gson.

Add it to the referenced libraries.

package com.tut.JSON;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class SimpleJson extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        String jString = "{\"username\": \"tom\", \"message\": \"roger that\"}  ";


        GsonBuilder gsonb = new GsonBuilder();
        Gson gson = gsonb.create();
        Post pst;

        try {
            pst = gson.fromJson(jString,  Post.class);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

Code for Post class

package com.tut.JSON;

public class Post {

    String message;
    String time;
    String username;
    Bitmap icon;
}

What is the --save option for npm install?

npm install --save or npm install --save-dev why we choose 1 options between this two while installing package in our project.

things is clear from the above answers that npm install --save will add entry in the dependency field in pacakage.json file and other one in dev-dependency.

So question arises why we need entry of our installing module in pacakge.json file because whenever we check-in code in git or giving our code to some one we always give it or check it without node-modules because it is very large in size and also available at common place so to avoid this we do that.

so then how other person will get all the modules that is specifically or needed for that project so answers is from the package.json file that have the entry of all the required packages for running or developing that project.

so after getting the code we simply need to run the npm install command it will read the package.json file and install the necessary required packages.

Unrecognized SSL message, plaintext connection? Exception

Another reason is maybe "access denided", maybe you can't access to the URI and received blocking response page for internal network access. If you are not sure your application zone need firewall rule, you try to connect from terminal,command line. For GNU/Linux or Unix, you can try run like this command and see result is coming from blocking rule or really remote address: echo | nc -v yazilimcity.net 443

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Select query with date condition

The semicolon character is used to terminate the SQL statement.

You can either use # signs around a date value or use Access's (ACE, Jet, whatever) cast to DATETIME function CDATE(). As its name suggests, DATETIME always includes a time element so your literal values should reflect this fact. The ISO date format is understood perfectly by the SQL engine.

Best not to use BETWEEN for DATETIME in Access: it's modelled using a floating point type and anyhow time is a continuum ;)

DATE and TABLE are reserved words in the SQL Standards, ODBC and Jet 4.0 (and probably beyond) so are best avoided for a data element names:

Your predicates suggest open-open representation of periods (where neither its start date or the end date is included in the period), which is arguably the least popular choice. It makes me wonder if you meant to use closed-open representation (where neither its start date is included but the period ends immediately prior to the end date):

SELECT my_date
  FROM MyTable
 WHERE my_date >= #2008-09-01 00:00:00#
       AND my_date < #2010-09-01 00:00:00#;

Alternatively:

SELECT my_date
  FROM MyTable
 WHERE my_date >= CDate('2008-09-01 00:00:00')
       AND my_date < CDate('2010-09-01 00:00:00'); 

How to programmatically set cell value in DataGridView?

I came across the same problem and solved it as following for VB.NET. It's the .NET Framework so you should be possible to adapt. Wanted to compare my solution and now I see that nobody seems to solve it my way.

Make a field declaration.

Private _currentDataView as DataView

So looping through all the rows and searching for a cell containing a value that I know is next to the cell I want to change works for me.

Public Sub SetCellValue(ByVal value As String)
    Dim dataView As DataView = _currentDataView

    For i As Integer = 0 To dataView.Count - 1
        If dataView(i).Row.Item("projID").ToString.Equals("139") Then
            dataView(i).Row.Item("Comment") = value
            Exit For ' Exit early to save performance
        End If
    Next
End Sub

So that you can better understand it. I know that ColumnName "projID" is 139. I loop until I find it and then I can change the value of "ColumnNameofCell" in my case "Comment". I use this for comments added on runtime.

dataview

Git workflow and rebase vs merge questions

In your situation I think your partner is correct. What's nice about rebasing is that to the outsider your changes look like they all happened in a clean sequence all by themselves. This means

  • your changes are very easy to review
  • you can continue to make nice, small commits and yet you can make sets of those commits public (by merging into master) all at once
  • when you look at the public master branch you'll see different series of commits for different features by different developers but they won't all be intermixed

You can still continue to push your private development branch to the remote repository for the sake of backup but others should not treat that as a "public" branch since you'll be rebasing. BTW, an easy command for doing this is git push --mirror origin .

The article Packaging software using Git does a fairly nice job explaining the trade offs in merging versus rebasing. It's a little different context but the principals are the same -- it basically comes down to whether your branches are public or private and how you plan to integrate them into the mainline.

ParseError: not well-formed (invalid token) using cElementTree

None of the above fixes worked for me. The only thing that worked was to use BeautifulSoup instead of ElementTree as follows:

from bs4 import BeautifulSoup

with open("data/myfile.xml") as fp:
    soup = BeautifulSoup(fp, 'xml')

Then you can search the tree as:

soup.find_all('mytag')

Return JSON with error status code MVC

The thing that worked for me (and that I took from another stackoverflow response), is to set the flag:

Response.TrySkipIisCustomErrors = true;

How to create a thread?

The following ways work.

// The old way of using ParameterizedThreadStart. This requires a
// method which takes ONE object as the parameter so you need to
// encapsulate the parameters inside one object.
Thread t = new Thread(new ParameterizedThreadStart(StartupA));
t.Start(new MyThreadParams(path, port));

// You can also use an anonymous delegate to do this.
Thread t2 = new Thread(delegate()
{
    StartupB(port, path);
});
t2.Start();

// Or lambda expressions if you are using C# 3.0
Thread t3 = new Thread(() => StartupB(port, path));
t3.Start();

The Startup methods have following signature for these examples.

public void StartupA(object parameters);

public void StartupB(int port, string path);

How to cut an entire line in vim and paste it?

The quickest way I found is through editing mode:

  1. Press yy to copy the line.
  2. Then dd to delete the line.
  3. Then p to paste the line.

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

The path for the heap dump will be provided as a variable right after where you have placed the mentioned variable.

E.g.:

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${DOMAIN_HOME}/logs/mps"

You can view the dump from the console on the mentioned path.

Wget output document and headers to STDOUT

This worked for me for printing response with header:

wget --server-response http://www.example.com/

How to convert an int to a hex string?

With format(), as per format-examples, we can do:

>>> # format also supports binary numbers
>>> "int: {0:d};  hex: {0:x};  oct: {0:o};  bin: {0:b}".format(42)
'int: 42;  hex: 2a;  oct: 52;  bin: 101010'
>>> # with 0x, 0o, or 0b as prefix:
>>> "int: {0:d};  hex: {0:#x};  oct: {0:#o};  bin: {0:#b}".format(42)
'int: 42;  hex: 0x2a;  oct: 0o52;  bin: 0b101010'

Reset the database (purge all), then seed a database

You can use rake db:reset when you want to drop the local database and start fresh with data loaded from db/seeds.rb. This is a useful command when you are still figuring out your schema, and often need to add fields to existing models.

Once the reset command is used it will do the following: Drop the database: rake db:drop Load the schema: rake db:schema:load Seed the data: rake db:seed

But if you want to completely drop your database you can use rake db:drop. Dropping the database will also remove any schema conflicts or bad data. If you want to keep the data you have, be sure to back it up before running this command.

This is a detailed article about the most important rake database commands.

How to list records with date from the last 10 days?

Yes this does work in PostgreSQL (assuming the column "date" is of datatype date) Why don't you just try it?

The standard ANSI SQL format would be:

SELECT Table.date 
FROM Table 
WHERE date > current_date - interval '10' day;

I prefer that format as it makes things easier to read (but it is the same as current_date - 10).

Export from pandas to_excel without row names (index)?

You need to set index=False in to_excel in order for it to not write the index column out, this semantic is followed in other Pandas IO tools, see http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html and http://pandas.pydata.org/pandas-docs/stable/io.html

Show empty string when date field is 1/1/1900

Use this inside of query, no need to create extra variables.

CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN ''  ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'

Works like a charm.

Python Pandas - Missing required dependencies ['numpy'] 1

I've got the same error recently.
Before applying uninstall or install tools, try to update your Jupyter.

How? Go to 'Environments' and type on the Search Packages box 'pandas'.
Afterwards, check the version (if that column shows a blue number with a diagonal arrow, it means that your pandas is out of date).
Click on 'pandas' and a option will pop up (choose 'Apply' and wait for a couple of minutes to update the package).
And then, make a quick test on any notebook to make sure that your Jupyter is running smoothly.

Highlighting Text Color using Html.fromHtml() in Android?

First Convert your string into HTML then convert it into spannable. do as suggest the following codes.

 Spannable spannable = new SpannableString(Html.fromHtml(labelText));
                    
spannable.setSpan(new ForegroundColorSpan(Color.parseColor(color)), spannable.toString().indexOf("•"), spannable.toString().lastIndexOf("•") + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            

col align right

From the documentation, you do it like:

<div class="row">
    <div class="col-md-6">left</div>
    <div class="col-md-push-6">content needs to be right aligned</div>
</div>

Docs

How do I get the computer name in .NET

You can have access of the machine name using Environment.MachineName.

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

What are OLTP and OLAP. What is the difference between them?

oltp- mostly used for business transaction.used to collect business data.In sql we use insert,update and delete command for retrieving small source of data.like wise they are highly normalised.... OLTP Mostly used for maintaining the data integrity.

olap- mostly use for reporting,data mining and business analytic purpose. for the large or bulk data.deliberately it is de-normalised. it stores Historical data..

Capture characters from standard input without waiting for enter to be pressed

If you are on windows, you can use PeekConsoleInput to detect if there's any input,

HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput( handle, &buffer, 1, &events );

then use ReadConsoleInput to "consume" the input character ..

PeekConsoleInput(handle, &buffer, 1, &events);
if(events > 0)
{
    ReadConsoleInput(handle, &buffer, 1, &events);  
    return buffer.Event.KeyEvent.wVirtualKeyCode;
}
else return 0

to be honest this is from some old code I have, so you have to fiddle a bit with it.

The cool thing though is that it reads input without prompting for anything, so the characters are not displayed at all.

Opening Android Settings programmatically

Check out the Programmatically Displaying the Settings Page

    startActivity(context, new Intent(Settings.ACTION_SETTINGS), /*options:*/ null);

In general, you use the predefined constant Settings.ACTION__SETTINGS. The full list can be found here

Arithmetic operation resulted in an overflow. (Adding integers)

The maximum value of an integer (which is signed) is 2147483647. If that value overflows, an exception is thrown to prevent unexpected behavior of your program.

If that exception wouldn't be thrown, you'd have a value of -2145629296 for your Volume, which is most probably not wanted.

Solution: Use an Int64 for your volume. With a max value of 9223372036854775807, you're probably more on the safe side.

MongoDB inserts float when trying to insert integer

A slightly simpler syntax (in Robomongo at least) worked for me:

db.database.save({ Year : NumberInt(2015) });

Java Equivalent of C# async/await?

Check out ea-async which does Java bytecode rewriting to simulate async/await pretty nicely. Per their readme: "It is heavily inspired by Async-Await on the .NET CLR"

How can I use threading in Python?

Given a function, f, thread it like this:

import threading
threading.Thread(target=f).start()

To pass arguments to f

threading.Thread(target=f, args=(a,b,c)).start()

Print raw string from variable? (not getting the answers)

Just simply use r'string'. Hope this will help you as I see you haven't got your expected answer yet:

    test = 'C:\\Windows\Users\alexb\'
    rawtest = r'%s' %test

How to use executeReader() method to retrieve the value of just one cell

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
    cmd.Parameters.AddWithValue("@id", index);
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
        }
    }
}

Cannot add a project to a Tomcat server in Eclipse

In my case:

Project properties ? Project Facets. Make sure "Dynamic Web Module" is checked. Finally, I enter the version number "2.3" instead of "3.0". After that, the Apache Tomcat 5.5 runtime is listed in the "Runtimes" tab.

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

In case anyone still has to support legacy fancybox with jQuery 3.0+ here are some other changes you'll have to make:

.unbind() deprecated

Replace all instances of .unbind with .off

.removeAttribute() is not a function

Change lines 580-581 to use jQuery's .removeAttr() instead:

Old code:

580: content[0].style.removeAttribute('filter');
581: wrap[0].style.removeAttribute('filter');

New code:

580: content.removeAttr('filter');
581: wrap.removeAttr('filter');

This combined with the other patch mentioned above solved my compatibility issues.

How to use Object.values with typescript?

Object.values() is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.

Solution: use es2017 or es2017.object in your --lib compiler option.

For example, using tsconfig.json:

"compilerOptions": {
    "lib": ["es2017", "dom"]
}

Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values), it's up to you to polyfill your project code yourself if you want. And since Object.values is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js will do the job.

How to get the location of the DLL currently executing?

System.Reflection.Assembly.GetExecutingAssembly().Location

Declaring variables inside or outside of a loop

Declaring String str outside of the while loop allows it to be referenced inside & outside the while loop. Declaring String str inside of the while loop allows it to only be referenced inside that while loop.

are there dictionaries in javascript like python?

I realize this is an old question, but it pops up in Google when you search for 'javascript dictionaries', so I'd like to add to the above answers that in ECMAScript 6, the official Map object has been introduced, which is a dictionary implementation:

var dict = new Map();
dict.set("foo", "bar");

//returns "bar"
dict.get("foo");

Unlike javascript's normal objects, it allows any object as a key:

var foo = {};
var bar = {};
var dict = new Map();
dict.set(foo, "Foo");
dict.set(bar, "Bar");

//returns "Bar"
dict.get(bar);

//returns "Foo"
dict.get(foo);

//returns undefined, as {} !== foo and {} !== bar
dict.get({});

how to get 2 digits after decimal point in tsql?

Try cast result to numeric

CAST(sum(cast(datediff(second, IEC.CREATE_DATE, IEC.STATUS_DATE) as float) / 60)
    AS numeric(10,2)) TotalSentMinutes

Input

1
2
3

Output

1.00
2.00
3.00

Pushing empty commits to remote

Is there any disadvantages/consequences of pushing empty commits?

Aside from the extreme confusion someone might get as to why there's a bunch of commits with no content in them on master, not really.

You can change the commit that you pushed to remote, but the sha1 of the commit (basically it's id number) will change permanently, which alters the source tree -- You'd then have to do a git push -f back to remote.

Android dependency has different version for the compile and runtime

If anyone getting this dependency issue in 2019, update Android Studio to 3.4 or later

How to validate phone numbers using regex

Working example for Turkey, just change the

d{9}

according to your needs and start using it.

function validateMobile($phone)
{
    $pattern = "/^(05)\d{9}$/";
    if (!preg_match($pattern, $phone))
    {
        return false;
    }
    return true;
}

$phone = "0532486061";

if(!validateMobile($phone))
{
    echo 'Incorrect Mobile Number!';
}

$phone = "05324860614";
if(validateMobile($phone))
{
    echo 'Correct Mobile Number!';
}

How to change Screen buffer size in Windows Command Prompt from batch script

You can change the buffer size of cmd by clicking the icon at top left corner -->properties --> layout --> screen buffer size.
you can even change it with cmd command

mode con:cols=100 lines=60
Upto lines = 58 the height of the cmd window changes ..
After lines value of 58 the buffer size of the cmd changes...

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

Does GPS require Internet?

GPS does not need any kind of internet or wireless connection, but there are technologies like A-GPS that use the mobile network to shorten the time to first fix, or the initial positioning or increase the precision in situations when there is a low satellite visibility.

Android phones tend to use A-GPS. If there is no connectivity, they use pure GPS. They do not override the data network mode. If you deactivated it, the phone won't use any data connection (which is handy if you are abroad, and do not want to pay expensive data roaming).

Finishing current activity from a fragment

Every time I use finish to close the fragment, the entire activity closes. According to the docs, fragments should remain as long as the parent activity remains.

Instead, I found that I can change views back the the parent activity by using this statement: setContentView(R.layout.activity_main);

This returns me back to the parent activity.

I hope that this helps someone else who may be looking for this.

urlencode vs rawurlencode?

echo rawurlencode('http://www.google.com/index.html?id=asd asd');

yields

http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd%20asd

while

echo urlencode('http://www.google.com/index.html?id=asd asd');

yields

http%3A%2F%2Fwww.google.com%2Findex.html%3Fid%3Dasd+asd

The difference being the asd%20asd vs asd+asd

urlencode differs from RFC 1738 by encoding spaces as + instead of %20

Read whole ASCII file into C++ std::string

Update: Turns out that this method, while following STL idioms well, is actually surprisingly inefficient! Don't do this with large files. (See: http://insanecoding.blogspot.com/2011/11/how-to-read-in-file-in-c.html)

You can make a streambuf iterator out of the file and initialize the string with it:

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator<char>(t)),
                 std::istreambuf_iterator<char>());

Not sure where you're getting the t.open("file.txt", "r") syntax from. As far as I know that's not a method that std::ifstream has. It looks like you've confused it with C's fopen.

Edit: Also note the extra parentheses around the first argument to the string constructor. These are essential. They prevent the problem known as the "most vexing parse", which in this case won't actually give you a compile error like it usually does, but will give you interesting (read: wrong) results.

Following KeithB's point in the comments, here's a way to do it that allocates all the memory up front (rather than relying on the string class's automatic reallocation):

#include <string>
#include <fstream>
#include <streambuf>

std::ifstream t("file.txt");
std::string str;

t.seekg(0, std::ios::end);   
str.reserve(t.tellg());
t.seekg(0, std::ios::beg);

str.assign((std::istreambuf_iterator<char>(t)),
            std::istreambuf_iterator<char>());

Replace negative values in an numpy array

Another minimalist Python solution without using numpy:

[0 if i < 0 else i for i in a]

No need to define any extra functions.

a = [1, 2, 3, -4, -5.23, 6]
[0 if i < 0 else i for i in a]

yields:

[1, 2, 3, 0, 0, 6]

How do I convert an object to an array?

Careful:

$array = (array) $object;

does a shallow conversion ($object->innerObject = new stdClass() remains an object) and converting back and forth using json works but it's not a good idea if performance is an issue.

If you need all objects to be converted to associative arrays here is a better way to do that (code ripped from I don't remember where):

function toArray($obj)
{
    if (is_object($obj)) $obj = (array)$obj;
    if (is_array($obj)) {
        $new = array();
        foreach ($obj as $key => $val) {
            $new[$key] = toArray($val);
        }
    } else {
        $new = $obj;
    }

    return $new;
}

Why boolean in Java takes only true or false? Why not 1 or 0 also?

Because booleans have two values: true or false. Note that these are not strings, but actual boolean literals.

1 and 0 are integers, and there is no reason to confuse things by making them "alternative true" and "alternative false" (or the other way round for those used to Unix exit codes?). With strong typing in Java there should only ever be exactly two primitive boolean values.

EDIT: Note that you can easily write a conversion function if you want:

public static boolean intToBool(int input)
{
   if (input < 0 || input > 1)
   {
      throw new IllegalArgumentException("input must be 0 or 1");
   }

   // Note we designate 1 as true and 0 as false though some may disagree
   return input == 1;
}

Though I wouldn't recommend this. Note how you cannot guarantee that an int variable really is 0 or 1; and there's no 100% obvious semantics of what one means true. On the other hand, a boolean variable is always either true or false and it's obvious which one means true. :-)

So instead of the conversion function, get used to using boolean variables for everything that represents a true/false concept. If you must use some kind of primitive text string (e.g. for storing in a flat file), "true" and "false" are much clearer in their meaning, and can be immediately turned into a boolean by the library method Boolean.valueOf.

How can I declare optional function parameters in JavaScript?

Update

With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

Old answer

Default parameters in JavaScript can be implemented in mainly two ways:

function myfunc(a, b)
{
    // use this if you specifically want to know if b was passed
    if (b === undefined) {
        // b was not passed
    }
    // use this if you know that a truthy value comparison will be enough
    if (b) {
        // b was passed and has truthy value
    } else {
        // b was not passed or has falsy value
    }
    // use this to set b to a default value (using truthy comparison)
    b = b || "default value";
}

The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

Alternative declaration:

function myfunc(a)
{
    var b;

    // use this to determine whether b was passed or not
    if (arguments.length == 1) {
        // b was not passed
    } else {
        b = arguments[1]; // take second argument
    }
}

The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

Further considerations

Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

b === void 0;
typeof b === 'undefined'; // also works for undeclared variables

How to generate and validate a software license key?

I'm one of the developers behind the Cryptolens software licensing platform and have been working on licensing systems since the age of 14. In this answer, I have included some tips based on experience acquired over the years.

The best way of solving this is by setting up a license key server that each instance of the application will call in order to verify a license key.

Benefits of a license key server

The advantages with a license key server is that:

  1. you can always update or block a license key with immediate effect.
  2. each license key can be locked to certain number of machines (this helps to prevent users from publishing the license key online for others to use).

Considerations

Although verifying licenses online gives you more control over each instance of the application, internet connection is not always present (especially if you target larger enterprises), so we need another way of performing the license key verification.

The solution is to always sign the license key response from the server using a public-key cryptosystem such as RSA or ECC (possibly better if you plan to run on embedded systems). Your application should only have the public key to verify the license key response.

So in case there's no internet connection, you can use the previous license key response instead. Make sure to store both the date and the machine identifier in the response and check that it's not too old (eg. you allow users to be offline at most 30 days, etc) and that the license key response belongs to the correct device.

Note you should always check the certificate of license key response, even if you are connected to the internet), in order to ensure that it has not been changed since it left the server (this still has to be done even if your API to the license key server uses https)

Protecting secret algorithms

Most .NET applications can be reverse engineered quite easily (there is both a diassembler provided by Microsoft to get the IL code and some commercial products can even retrieve the source code in eg. C#). Of course, you can always obfuscate the code, but it's never 100% secure.

I most cases, the purpose of any software licensing solution is to help honest people being honest (i.e. that honest users who are willing to pay don't forget to pay after a trial expires, etc).

However, you may still have some code that you by no means want to leak out to the public (eg. an algorithm to predict stock prices, etc). In this case, the only way to go is to create an API endpoint that your application will call each time the method should be executed. It requires internet connection but it ensures that your secret code is never executed by the client machine.

Implementation

If you don't want to implement everything yourself, I would recommend to take a look at this tutorial (part of Cryptolens)

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init part on the ng-form element and the use of furryName. furryName becomes the variable name that contains the variable value for the input's name attribute.

<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
        <!-- animal is furry toggle buttons -->
        <input id="furryRadio{{$index}}"
               type="radio"
               name="{{furryName}}"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolTrue"
               required
                >
        <label for="furryRadio{{$index}}">Furry</label>

        <input id="hairlessRadio{{$index}}"
               name="{{furryName}}"
               type="radio"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolFalse"
               required
               >
        <label for="hairlessRadio{{$index}}">Hairless</label>

        <div ng-messages="animalsForm[furryName].$error"
             class="form-errors"
             ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
            <div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
        </div>
</ng-form>
</ion-item>

New og:image size for Facebook share?

Tried to get the 1200x630 image working. Facebook kept complaining that it couldn't read the image, or that it was too small (it was a jpeg image ~150Kb).

Switched to a 200x200 size image, worked perfectly.

https://developers.facebook.com/tools/debug/og/object?q=drift.team

What is the most efficient way to loop through dataframes with pandas?

look at last one

t = pd.DataFrame({'a': range(0, 10000), 'b': range(10000, 20000)})
B = []
C = []
A = time.time()
for i,r in t.iterrows():
    C.append((r['a'], r['b']))
B.append(round(time.time()-A,5))

C = []
A = time.time()
for ir in t.itertuples():
    C.append((ir[1], ir[2]))    
B.append(round(time.time()-A,5))

C = []
A = time.time()
for r in zip(t['a'], t['b']):
    C.append((r[0], r[1]))
B.append(round(time.time()-A,5))

C = []
A = time.time()
for r in range(len(t)):
    C.append((t.loc[r, 'a'], t.loc[r, 'b']))
B.append(round(time.time()-A,5))

C = []
A = time.time()
[C.append((x,y)) for x,y in zip(t['a'], t['b'])]
B.append(round(time.time()-A,5))
B

0.46424
0.00505
0.00245
0.09879
0.00209

Primitive type 'short' - casting in Java

Given that the "why int by default" question hasn't been answered ...

First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

(5/4) * 1000.0

OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

"Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

byte x = (byte)0xC0;
System.out.println(x >> 2);

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

Programmatically change the src of an img tag

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

If you understand the difference between scope and session then it will be very easy to understand these methods.

A very nice blog post by Adam Anderson describes this difference:

Session means the current connection that's executing the command.

Scope means the immediate context of a command. Every stored procedure call executes in its own scope, and nested calls execute in a nested scope within the calling procedure's scope. Likewise, a SQL command executed from an application or SSMS executes in its own scope, and if that command fires any triggers, each trigger executes within its own nested scope.

Thus the differences between the three identity retrieval methods are as follows:

@@identity returns the last identity value generated in this session but any scope.

scope_identity() returns the last identity value generated in this session and this scope.

ident_current() returns the last identity value generated for a particular table in any session and any scope.

Windows path in Python

Yes, \ in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a, which is collapsed into one character that is ASCII Bell:

>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess

Other common escape sequences include \t (tab), \n (line feed), \r (carriage return):

>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']

As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.

There are a variety of ways to deal with that:

  1. Python will not process escape sequences in string literals prefixed with r or R:

    >>> r'C:\meshes\as'
    'C:\\meshes\\as'
    >>> print(r'C:\meshes\as')
    C:\meshes\as
    
  2. Python on Windows should handle forward slashes, too.

  3. You could use os.path.join ...

    >>> import os
    >>> os.path.join('C:', os.sep, 'meshes', 'as')
    'C:\\meshes\\as'
    
  4. ... or the newer pathlib module

    >>> from pathlib import Path
    >>> Path('C:', '/', 'meshes', 'as')
    WindowsPath('C:/meshes/as')
    

Keep SSH session alive

The ssh daemon (sshd), which runs server-side, closes the connection from the server-side if the client goes silent (i.e., does not send information). To prevent connection loss, instruct the ssh client to send a sign-of-life signal to the server once in a while.

The configuration for this is in the file $HOME/.ssh/config, create the file if it does not exist (the config file must not be world-readable, so run chmod 600 ~/.ssh/config after creating the file). To send the signal every e.g. four minutes (240 seconds) to the remote host, put the following in that configuration file:

Host remotehost
    HostName remotehost.com
    ServerAliveInterval 240

To enable sending a keep-alive signal for all hosts, place the following contents in the configuration file:

Host *
    ServerAliveInterval 240

How do I find the duplicates in a list and create another list with them?

Using pandas:

>>> import pandas as pd
>>> a = [1, 2, 1, 3, 3, 3, 0]
>>> pd.Series(a)[pd.Series(a).duplicated()].values
array([1, 3, 3])

Spring Boot and how to configure connection details to MongoDB?

You can define more details by extending AbstractMongoConfiguration.

@Configuration
@EnableMongoRepositories("demo.mongo.model")
public class SpringMongoConfig extends AbstractMongoConfiguration {
    @Value("${spring.profiles.active}")
    private String profileActive;

    @Value("${spring.application.name}")
    private String proAppName;

    @Value("${spring.data.mongodb.host}")
    private String mongoHost;

    @Value("${spring.data.mongodb.port}")
    private String mongoPort;

    @Value("${spring.data.mongodb.database}")
    private String mongoDB;

    @Override
    public MongoMappingContext mongoMappingContext()
        throws ClassNotFoundException {
        // TODO Auto-generated method stub
        return super.mongoMappingContext();
    }
    @Override
    @Bean
    public Mongo mongo() throws Exception {
        return new MongoClient(mongoHost + ":" + mongoPort);
    }
    @Override
    protected String getDatabaseName() {
        // TODO Auto-generated method stub
        return mongoDB;
    }
}

In Python, how do you convert a `datetime` object to seconds?

For the special date of January 1, 1970 there are multiple options.

For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta object, which as of Python 2.7 has a total_seconds() function.

>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0

The starting date is usually specified in UTC, so for proper results the datetime you feed into this formula should be in UTC as well. If your datetime isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo class that has the proper offset.

As noted in the comments, if you have a tzinfo attached to your datetime then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc if using Python 2 or tzinfo=timezone.utc if using Python 3.

How do I make text bold in HTML?

It’s just <b> instead of <bold>:

Some <b>text</b> that I want bolded.

Note that <b> just changes the appearance of the text. If you want to render it bold because you want to express a strong emphasis, you should better use the <strong> element.

How to create Custom Ratings bar in Android

The following code works:

@Override
protected synchronized void onDraw(Canvas canvas)
{
    int stars = getNumStars();
    float rating = getRating();
    try
    {
        bitmapWidth = getWidth() / stars;
    }
    catch (Exception e)
    {
        bitmapWidth = getWidth();
    }
    float x = 0;

    for (int i = 0; i < stars; i++)
    {
        Bitmap bitmap;
        Resources res = getResources();
        Paint paint = new Paint();

        if ((int) rating > i)
        {
            bitmap = BitmapFactory.decodeResource(res, starColor);
        }
        else
        {
            bitmap = BitmapFactory.decodeResource(res, starDefault);
        }
        Bitmap scaled = Bitmap.createScaledBitmap(bitmap, getHeight(), getHeight(), true);
        canvas.drawBitmap(scaled, x, 0, paint);
        canvas.save();
        x += bitmapWidth;
    }

    super.onDraw(canvas);
}

How to substitute shell variables in complex text files

I know this topic is old, but I have a simpler working solution without export the variables. Can be a oneliner, but I prefer to split using \ on line end.

var1='myVar1'\
var2=2\
var3=${var1}\
envsubst '$var1,$var3' < "source.txt" > "destination.txt"

#         ^^^^^^^^^^^    ^^^^^^^^^^     ^^^^^^^^^^^^^^^
# define which to replace   input            output

The variables need to be defined to the same line as envsubst is to get considered as environment variables.

The '$var1,$var3' is optional to only replace the specified ones. Imagine an input file containing ${VARIABLE_USED_BY_JENKINS} which should not be replaced.

What does $1 [QSA,L] mean in my .htaccess file?

If the following conditions are true, then rewrite the URL:
If the requested filename is not a directory,

RewriteCond %{REQUEST_FILENAME} !-d

and if the requested filename is not a regular file that exists,

RewriteCond %{REQUEST_FILENAME} !-f

and if the requested filename is not a symbolic link,

RewriteCond %{REQUEST_FILENAME} !-l

then rewrite the URL in the following way:
Take the whole request filename and provide it as the value of a "url" query parameter to index.php. Append any query string from the original URL as further query parameters (QSA), and stop processing this .htaccess file (L).

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

Apache docs #flag_qsa

Another Example:

RewriteRule "/pages/(.+)" "/page.php?page=$1" [QSA]

With the [QSA] flag, a request for

/pages/123?one=two

will be mapped to

/page.php?page=123&one=two

Shortcut to open file in Vim

Use tabs, they work when inputting file paths in vim escape mode!

How can I tell jaxb / Maven to generate multiple schema packages?

you should change that to define the plugin only once and do twice execution areas...like the following...and the generateDirectory should be set (based on the docs)..

<plugin>
  <groupId>org.jvnet.jaxb2.maven2</groupId>
  <artifactId>maven-jaxb2-plugin</artifactId>
  <version>0.7.1</version>
  <executions>
    <execution>
      <id>firstrun</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generateDirectory>target/gen1</generateDirectory>
        <schemaDirectory>src/main/resources/dir1</schemaDirectory>
        <schemaIncludes>
          <include>schema1.xsd</include>
        </schemaIncludes>
        <generatePackage>schema1.package</generatePackage>
      </configuration>
    </execution>
    <execution>
      <id>secondrun</id>
      <goals>
        <goal>generate</goal>
      </goals>
      <configuration>
        <generateDirectory>target/gen2</generateDirectory>
        <schemaDirectory>src/main/resources/dir2</schemaDirectory>
        <schemaIncludes>
          <include>schema2.xsd</include>
        </schemaIncludes>
        <generatePackage>schema2.package</generatePackage>
      </configuration>
    </execution>
  </executions>
</plugin>

It seemed to me that you are fighting against single artifact rule of maven...may be you should think about this.

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

How to overlay density plots in R?

I took the above lattice example and made a nifty function. There is probably a better way to do this with reshape via melt/cast. (Comment or edit if you see an improvement.)

multi.density.plot=function(data,main=paste(names(data),collapse = ' vs '),...){
  ##combines multiple density plots together when given a list
  df=data.frame();
  for(n in names(data)){
    idf=data.frame(x=data[[n]],label=rep(n,length(data[[n]])))
    df=rbind(df,idf)
  }
  densityplot(~x,data=df,groups = label,plot.points = F, ref = T, auto.key = list(space = "right"),main=main,...)
}

Example usage:

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1),main='BN1 vs BN2')

multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1))

Mongoose delete array element in document and save

keywords = [1,2,3,4];
doc.array.pull(1) //this remove one item from a array
doc.array.pull(...keywords) // this remove multiple items in a array

if you want to use ... you should call 'use strict'; at the top of your js file; :)

How to force a html5 form validation without submitting it via jQuery

Here is a more general way that is a bit cleaner:

Create your form like this (can be a dummy form that does nothing):

<form class="validateDontSubmit">
...

Bind all forms that you dont really want to submit:

$(document).on('submit','.validateDontSubmit',function (e) {
    //prevent the form from doing a submit
    e.preventDefault();
    return false;
})

Now lets say you have an <a> (within the <form>) that on click you want to validate the form:

$('#myLink').click(function(e){
  //Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
  //has .validateDontSubmit class
  var $theForm = $(this).closest('form');
  //Some browsers don't implement checkValidity
  if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
     return;
  }

  //if you've gotten here - play on playa'
});

Few notes here:

  • I have noticed that you don't have to actually submit the form for validation to occur - the call to checkValidity() is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.
  • The thing that triggers the validation does not have to be within the <form>. This was just a clean and flexible way to have a general purpose solution..

Scatter plot and Color mapping in Python

Subplot Colorbar

For subplots with scatter, you can trick a colorbar onto your axes by building the "mappable" with the help of a secondary figure and then adding it to your original plot.

As a continuation of the above example:

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = x
t = x
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.scatter(x, y, c=t, cmap='viridis')
ax2.scatter(x, y, c=t, cmap='viridis_r')


# Build your secondary mirror axes:
fig2, (ax3, ax4) = plt.subplots(1, 2)

# Build maps that parallel the color-coded data
# NOTE 1: imshow requires a 2-D array as input
# NOTE 2: You must use the same cmap tag as above for it match
map1 = ax3.imshow(np.stack([t, t]),cmap='viridis')
map2 = ax4.imshow(np.stack([t, t]),cmap='viridis_r')

# Add your maps onto your original figure/axes
fig.colorbar(map1, ax=ax1)
fig.colorbar(map2, ax=ax2)
plt.show()

Scatter subplots with COLORBAR

Note that you will also output a secondary figure that you can ignore.

How to get a right click mouse event? Changing EventArgs to MouseEventArgs causes an error in Form1Designer?

This would definitely help Many!

private void axWindowsMediaPlayer1_ClickEvent(object sender, AxWMPLib._WMPOCXEvents_ClickEvent e)
    {
        if(e.nButton==2)
        {
            contextMenuStrip1.Show(MousePosition);
        }
    }

[ e.nbutton==2 ] is like [ e.button==MouseButtons.Right ]

How to wrap text around an image using HTML/CSS

If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.

#container:before {
  content: ' ';
  display: table;
  width: 10em;    /* Min width required */
}
#floated{
    float: left;
    width: 150px;
    background: red;
}

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Try to trigger() event in your function:

$("form").trigger('submit'); // and then... do submit()

.prop() vs .attr()

Before jQuery 1.6 , the attr() method sometimes took property values into account when retrieving attributes, this caused rather inconsistent behavior.

The introduction of the prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

The Docs:

jQuery.attr() Get the value of an attribute for the first element in the set of matched elements.

jQuery.prop() Get the value of a property for the first element in the set of matched elements.

How can I group by date time column without taking time into consideration

In pre Sql 2008 By taking out the date part:

GROUP BY CONVERT(CHAR(8),DateTimeColumn,10)

check if a number already exist in a list in python

You could probably use a set object instead. Just add numbers to the set. They inherently do not replicate.

How to repair a serialized string which has been corrupted by an incorrect byte count length?

public function unserializeKeySkills($string) {
    $output = array();
    $string = trim(preg_replace('/\s\s+/', ' ',$string));
    $string = preg_replace_callback('!s:(\d+):"(.*?)";!', function($m) { return 's:'.strlen($m[2]).':"'.$m[2].'";'; }, utf8_encode( trim(preg_replace('/\s\s+/', ' ',$string)) ));
    try {
        $output =  unserialize($string);
    } catch (\Exception $e) {
        \Log::error("unserialize Data : " .print_r($string,true));
    }
    return $output;
}

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

UndefinedMetricWarning: F-score is ill-defined and being set to 0.0 in labels with no predicted samples

As mentioned in the comments, some labels in y_test don't appear in y_pred. Specifically in this case, label '2' is never predicted:

>>> set(y_test) - set(y_pred)
{2}

This means that there is no F-score to calculate for this label, and thus the F-score for this case is considered to be 0.0. Since you requested an average of the score, you must take into account that a score of 0 was included in the calculation, and this is why scikit-learn is showing you that warning.

This brings me to you not seeing the error a second time. As I mentioned, this is a warning, which is treated differently from an error in python. The default behavior in most environments is to show a specific warning only once. This behavior can be changed:

import warnings
warnings.filterwarnings('always')  # "error", "ignore", "always", "default", "module" or "once"

If you set this before importing the other modules, you will see the warning every time you run the code.

There is no way to avoid seeing this warning the first time, aside for setting warnings.filterwarnings('ignore'). What you can do, is decide that you are not interested in the scores of labels that were not predicted, and then explicitly specify the labels you are interested in (which are labels that were predicted at least once):

>>> metrics.f1_score(y_test, y_pred, average='weighted', labels=np.unique(y_pred))
0.91076923076923078

The warning is not shown in this case.

How can I format date by locale in Java?

SimpleDateFormat has a constructor which takes the locale, have you tried that?

http://java.sun.com/javase/6/docs/api/java/text/SimpleDateFormat.html

Something like new SimpleDateFormat("your-pattern-here", Locale.getDefault());

UIButton Image + Text IOS

I encountered the same problem, and I fix it by creating a new subclass of UIButton and overriding the layoutSubviews: method as below :

-(void)layoutSubviews {
    [super layoutSubviews];

    // Center image
    CGPoint center = self.imageView.center;
    center.x = self.frame.size.width/2;
    center.y = self.imageView.frame.size.height/2;
    self.imageView.center = center;

    //Center text
    CGRect newFrame = [self titleLabel].frame;
    newFrame.origin.x = 0;
    newFrame.origin.y = self.imageView.frame.size.height + 5;
    newFrame.size.width = self.frame.size.width;

    self.titleLabel.frame = newFrame;
    self.titleLabel.textAlignment = UITextAlignmentCenter;

}

I think that the Angel García Olloqui's answer is another good solution, if you place all of them manually with interface builder but I'll keep my solution since I don't have to modify the content insets for each of my button.

Open source face recognition for Android

You can try Microsoft's Face API. It can detect and identify people. learn more about face API here.

Example: Communication between Activity and Service using Messaging

This is how I implemeted Activity->Service Communication: on my Activity i had

private static class MyResultReciever extends ResultReceiver {
     /**
     * Create a new ResultReceive to receive results.  Your
     * {@link #onReceiveResult} method will be called from the thread running
     * <var>handler</var> if given, or from an arbitrary thread if null.
     *
     * @param handler
     */
     public MyResultReciever(Handler handler) {
         super(handler);
     }

     @Override
     protected void onReceiveResult(int resultCode, Bundle resultData) {
         if (resultCode == 100) {
             //dostuff
         }
     }

And then I used this to start my Service

protected void onCreate(Bundle savedInstanceState) {
MyResultReciever resultReciever = new MyResultReciever(handler);
        service = new Intent(this, MyService.class);
        service.putExtra("receiver", resultReciever);
        startService(service);
}

In my Service i had

public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null)
        resultReceiver = intent.getParcelableExtra("receiver");
    return Service.START_STICKY;
}

Hope this Helps

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Get the correct week number of a given date

The question is: How do you define if a week is in 2012 or in 2013? Your supposition, I guess, is that since 6 days of the week are in 2013, this week should be marked as the first week of 2013.

Not sure if this is the right way to go. That week started on 2012 (On monday 31th Dec), so it should be marked as the last week of 2012, therefore it should be the 53rd of 2012. The first week of 2013 should start on monday the 7th.

Now, you can handle the particular case of edge weeks (first and last week of the year) using the day of week information. It all depends on your logic.

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

AttributeError: 'DataFrame' object has no attribute

value_counts is a Series method rather than a DataFrame method (and you are trying to use it on a DataFrame, clean). You need to perform this on a specific column:

clean[column_name].value_counts()

It doesn't usually make sense to perform value_counts on a DataFrame, though I suppose you could apply it to every entry by flattening the underlying values array:

pd.value_counts(df.values.flatten())

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

Bootstrap: How do I identify the Bootstrap version?

The easiest would be to locate the bootstrap file (bootstrap.css OR bootstrap.min.css) and read through the docblock, you'll see something like this

Bootstrap v3.3.6 (http://getbootstrap.com)

Add legend to ggplot2 line plot

Since @Etienne asked how to do this without melting the data (which in general is the preferred method, but I recognize there may be some cases where that is not possible), I present the following alternative.

Start with a subset of the original data:

datos <-
structure(list(fecha = structure(c(1317452400, 1317538800, 1317625200, 
1317711600, 1317798000, 1317884400, 1317970800, 1318057200, 1318143600, 
1318230000, 1318316400, 1318402800, 1318489200, 1318575600, 1318662000, 
1318748400, 1318834800, 1318921200, 1319007600, 1319094000), class = c("POSIXct", 
"POSIXt"), tzone = ""), TempMax = c(26.58, 27.78, 27.9, 27.44, 
30.9, 30.44, 27.57, 25.71, 25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 
26.58, 26.18, 25.19, 24.19, 27.65, 23.92), TempMedia = c(22.88, 
22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52, 19.71, 20.73, 
23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 20.45, 19.42, 19.97, 
19.61), TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 
16.88, 16.82, 14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 
16.95, 17.55, 15.21, 14.22, 16.42)), .Names = c("fecha", "TempMax", 
"TempMedia", "TempMin"), row.names = c(NA, 20L), class = "data.frame")

You can get the desired effect by (and this also cleans up the original plotting code):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMax", "TempMedia", "TempMin"),
                      values = c("red", "green", "blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

The idea is that each line is given a color by mapping the colour aesthetic to a constant string. Choosing the string which is what you want to appear in the legend is the easiest. The fact that in this case it is the same as the name of the y variable being plotted is not significant; it could be any set of strings. It is very important that this is inside the aes call; you are creating a mapping to this "variable".

scale_colour_manual can now map these strings to the appropriate colors. The result is enter image description here

In some cases, the mapping between the levels and colors needs to be made explicit by naming the values in the manual scale (thanks to @DaveRGP for pointing this out):

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

(giving the same figure as before). With named values, the breaks can be used to set the order in the legend and any order can be used in the values.

ggplot(data = datos, aes(x = fecha)) +
  geom_line(aes(y = TempMax, colour = "TempMax")) +
  geom_line(aes(y = TempMedia, colour = "TempMedia")) +
  geom_line(aes(y = TempMin, colour = "TempMin")) +
  scale_colour_manual("", 
                      breaks = c("TempMedia", "TempMax", "TempMin"),
                      values = c("TempMedia"="green", "TempMax"="red", 
                                 "TempMin"="blue")) +
  xlab(" ") +
  scale_y_continuous("Temperatura (C)", limits = c(-10,40)) + 
  labs(title="TITULO")

What is the difference between HTML tags <div> and <span>?

Just for the sake of completeness, I invite you to think about it like this:

  • There are lots of block elements (linebreaks before and after) defined in HTML, and lots of inline tags (no linebreaks).
  • But in modern HTML all elements are supposed to have meanings: a <p> is a paragraph, an <li> is a list item, etc., and we're supposed to use the right tag for the right purpose -- not like in the old days when we indented using <blockquote> whether the content was a quote or not.
  • So, what do you do when there is no meaning to the thing you're trying to do? There's no meaning to a 400px-wide column, is there? You just want your column of text to be 400px wide because that suits your design.
  • For this reason, they added two more elements to HTML: the generic, or meaningless elements <div> and <span>, because otherwise, people would go back to abusing the elements which do have meanings.

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

Command not found after npm install in zsh

In my humble opinion, first, you have to make sure you have any kind of Node version installed. For that type:

nvm ls

And if you don't get any versions it means I was right :) Then you have to type:

nvm install <node_version**>

** the actual version you can find in Node website

Then you will have Node and you will be able to use npm commands

Dynamically converting java object of Object class to a given class when class name is known

I think its pretty straight forward with reflection

MyClass mobj = MyClass.class.cast(obj);

and if class name is different

Object newObj = Class.forName(classname).cast(obj);

Get the time of a datetime using T-SQL?

In case of SQL Server, this should work

SELECT CONVERT(VARCHAR(8),GETDATE(),108) AS HourMinuteSecond

How to automatically import data from uploaded CSV or XLS file into Google Sheets

(Mar 2017) The accepted answer is not the best solution. It relies on manual translation using Apps Script, and the code may not be resilient, requiring maintenance. If your legacy system autogenerates CSV files, it's best they go into another folder for temporary processing (importing [uploading to Google Drive & converting] to Google Sheets files).

My thought is to let the Drive API do all the heavy-lifting. The Google Drive API team released v3 at the end of 2015, and in that release, insert() changed names to create() so as to better reflect the file operation. There's also no more convert flag -- you just specify MIMEtypes... imagine that!

The documentation has also been improved: there's now a special guide devoted to uploads (simple, multipart, and resumable) that comes with sample code in Java, Python, PHP, C#/.NET, Ruby, JavaScript/Node.js, and iOS/Obj-C that imports CSV files into Google Sheets format as desired.

Below is one alternate Python solution for short files ("simple upload") where you don't need the apiclient.http.MediaFileUpload class. This snippet assumes your auth code works where your service endpoint is DRIVE with a minimum auth scope of https://www.googleapis.com/auth/drive.file.

# filenames & MIMEtypes
DST_FILENAME = 'inventory'
SRC_FILENAME = DST_FILENAME + '.csv'
SHT_MIMETYPE = 'application/vnd.google-apps.spreadsheet'
CSV_MIMETYPE = 'text/csv'

# Import CSV file to Google Drive as a Google Sheets file
METADATA = {'name': DST_FILENAME, 'mimeType': SHT_MIMETYPE}
rsp = DRIVE.files().create(body=METADATA, media_body=SRC_FILENAME).execute()
if rsp:
    print('Imported %r to %r (as %s)' % (SRC_FILENAME, DST_FILENAME, rsp['mimeType']))

Better yet, rather than uploading to My Drive, you'd upload to one (or more) specific folder(s), meaning you'd add the parent folder ID(s) to METADATA. (Also see the code sample on this page.) Finally, there's no native .gsheet "file" -- that file just has a link to the online Sheet, so what's above is what you want to do.

If not using Python, you can use the snippet above as pseudocode to port to your system language. Regardless, there's much less code to maintain because there's no CSV parsing. The only thing remaining is to blow away the CSV file temp folder your legacy system wrote to.

How to get the IP address of the server on which my C# application is running on?

The LINQ solution:

Dns.GetHostEntry(Dns.GetHostName()).AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).Select(ip => ip.ToString()).FirstOrDefault() ?? ""

Evenly space multiple views within a container view

I have made a function that might help. This usage example :

 [self.view addConstraints: [NSLayoutConstraint fluidConstraintWithItems:NSDictionaryOfVariableBindings(button1, button2, button3)
                                                                asString:@[@"button1", @"button2", @"button3"]
                                                               alignAxis:@"V"
                                                          verticalMargin:100
                                                        horizontalMargin:50
                                                             innerMargin:25]];

will cause that vertical distribution (sorry don't have the 10 reputation to embed images). And if you change the axis and some margin values :

alignAxis:@"H"
verticalMargin:120
horizontalMargin:20
innerMargin:10

You'll get that horizontal distribution.

I'm newbie in iOS but voilà !

EvenDistribution.h

@interface NSLayoutConstraint (EvenDistribution)

/**
 * Returns constraints that will cause a set of subviews
 * to be evenly distributed along an axis.
 */
+ (NSArray *)  fluidConstraintWithItems:(NSDictionary *) views
                               asString:(NSArray *) stringViews
                              alignAxis:(NSString *) axis
                         verticalMargin:(NSUInteger) vMargin
                       horizontalMargin:(NSUInteger) hMargin
                            innerMargin:(NSUInteger) inner;
@end

EvenDistribution.m

#import "EvenDistribution.h"

@implementation NSLayoutConstraint (EvenDistribution)

+ (NSArray *) fluidConstraintWithItems:(NSDictionary *) dictViews
                              asString:(NSArray *) stringViews
                             alignAxis:(NSString *) axis
                        verticalMargin:(NSUInteger) vMargin
                      horizontalMargin:(NSUInteger) hMargin
                           innerMargin:(NSUInteger) iMargin

{
    NSMutableArray *constraints = [NSMutableArray arrayWithCapacity: dictViews.count];
    NSMutableString *globalFormat = [NSMutableString stringWithFormat:@"%@:|-%d-",
                                     axis,
                                     [axis isEqualToString:@"V"] ? vMargin : hMargin
                                     ];



        for (NSUInteger i = 0; i < dictViews.count; i++) {

            if (i == 0)
                [globalFormat appendString:[NSString stringWithFormat: @"[%@]-%d-", stringViews[i], iMargin]];
            else if(i == dictViews.count - 1)
                [globalFormat appendString:[NSString stringWithFormat: @"[%@(==%@)]-", stringViews[i], stringViews[i-1]]];
            else
               [globalFormat appendString:[NSString stringWithFormat: @"[%@(==%@)]-%d-", stringViews[i], stringViews[i-1], iMargin]];

            NSString *localFormat = [NSString stringWithFormat: @"%@:|-%d-[%@]-%d-|",
                                     [axis isEqualToString:@"V"] ? @"H" : @"V",
                                     [axis isEqualToString:@"V"] ? hMargin : vMargin,
                                     stringViews[i],
                                     [axis isEqualToString:@"V"] ? hMargin : vMargin];

            [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:localFormat
                                                                                     options:0
                                                                                     metrics:nil
                                                                                       views:dictViews]];


    }
    [globalFormat appendString:[NSString stringWithFormat:@"%d-|",
                                [axis isEqualToString:@"V"] ? vMargin : hMargin
                                ]];

    [constraints addObjectsFromArray:[NSLayoutConstraint constraintsWithVisualFormat:globalFormat
                                                                             options:0
                                                                             metrics:nil
                                                                               views:dictViews]];

    return constraints;

}

@end

Division of integers in Java

If you don't explicitly cast one of the two values to a float before doing the division then an integer division will be used (so that's why you get 0). You just need one of the two operands to be a floating point value, so that the normal division is used (and other integer value is automatically turned into a float).

Just try with

float completed = 50000.0f;

and it will be fine.