Programs & Examples On #Custom validators

Min / Max Validator in Angular 2 Final

This question has already been answered. I'd like to extend the answer from @amd. Sometimes you might need a default value.

For example, to validate against a specific value, I'd like to provide it as follows-

<input integerMinValue="20" >

But the minimum value of a 32 bit signed integer is -2147483648. To validate against this value, I don't like to provide it. I'd like to write as follows-

<input integerMinValue >

To achieve this you can write your directive as follows

import {Directive, Input} from '@angular/core';
import {AbstractControl, NG_VALIDATORS, ValidationErrors, Validator, Validators} from '@angular/forms';

@Directive({
    selector: '[integerMinValue]',
    providers: [{provide: NG_VALIDATORS, useExisting: IntegerMinValidatorDirective, multi: true}]
})
export class IntegerMinValidatorDirective implements Validator {

    private minValue = -2147483648;

    @Input('integerMinValue') set min(value: number) {
        if (value) {
            this.minValue = +value;
        }
    }

    validate(control: AbstractControl): ValidationErrors | null {
        return Validators.min(this.minValue)(control);
    }

}

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

Find and replace entire mysql database

Update old URL to new URL in word-press mysql Query:

UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl';

UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com');

UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com');

UPDATE wp_posts SET post_excerpt = replace(post_excerpt, 'http://olddomain.com', 'http://newdomain.com');

UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com');

Java FileWriter how to write to next Line

You can call the method newLine() provided by java, to insert the new line in to a file.

For more refernce -http://download.oracle.com/javase/1.4.2/docs/api/java/io/BufferedWriter.html#newLine()

Android marshmallow request permission?

  if (CommonMethod.isNetworkAvailable(MainActivity.this)) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        int permissionCheck = ContextCompat.checkSelfPermission(MainActivity.this,
                                android.Manifest.permission.CAMERA);
                        if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                            //showing dialog to select image
                            callFacebook();
                            Log.e("permission", "granted MarshMallow");
                        } else {
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE,
                                            android.Manifest.permission.WRITE_EXTERNAL_STORAGE, android.Manifest.permission.CAMERA}, 1);
                        }
                    } else {
                        Log.e("permission", "Not Required Less than MarshMallow Version");
                        callFacebook();
                    }
                } else {
                    CommonMethod.showAlert("Internet Connectivity Failure", MainActivity.this);
                }

Does IMDB provide an API?

Here is a Python module providing API's to get data from IMDB website

http://techdiary-viki.blogspot.com/2011/03/imdb-api.html

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123
Connected.

Center align with table-cell

Here is a good starting point.

HTML:

<div class="containing-table">
    <div class="centre-align">
        <div class="content"></div>
    </div>
</div>

CSS:

.containing-table {
    display: table;
    width: 100%;
    height: 400px; /* for demo only */
    border: 1px dotted blue;
}
.centre-align {
    padding: 10px;
    border: 1px dashed gray;
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}
.content {
    width: 50px;
    height: 50px;
    background-color: red;
    display: inline-block;
    vertical-align: top; /* Removes the extra white space below the baseline */
}

See demo at: http://jsfiddle.net/audetwebdesign/jSVyY/

.containing-table establishes the width and height context for .centre-align (the table-cell).

You can apply text-align and vertical-align to alter .centre-align as needed.

Note that .content needs to use display: inline-block if it is to be centered horizontally using the text-align property.

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):

  1. Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )

  2. Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.

  3. Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.

  4. Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:

    CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

  5. Find extension on this site, then put them into the python folder, and install .whl extension with pip:

    python -m pip install extensionname.whl

  6. Enjoy

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

What MIME type should I use for CSV?

For anyone struggling with Google API mimeType for *.csv files. I have found the list of MIME types for google api docs files (look at snipped result)

_x000D_
_x000D_
<table border="1"><thead><tr><th>Google Doc Format</th><th>Conversion Format</th><th>Corresponding MIME type</th></tr></thead><tbody><tr><td>Documents</td><td>HTML</td><td>text/html</td></tr><tr></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td></td><td>Rich text</td><td>application/rtf</td></tr><tr><td></td><td>Open Office doc</td><td>application/vnd.oasis.opendocument.text</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>MS Word document</td><td>application/vnd.openxmlformats-officedocument.wordprocessingml.document</td></tr><tr><td></td><td>EPUB</td><td>application/epub+zip</td></tr><tr><td>Spreadsheets</td><td>MS Excel</td><td>application/vnd.openxmlformats-officedocument.spreadsheetml.sheet</td></tr><tr><td></td><td>Open Office sheet</td><td>application/x-vnd.oasis.opendocument.spreadsheet</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>CSV (first sheet only)</td><td>text/csv</td></tr><tr><td></td><td>TSV (first sheet only)</td><td>text/tab-separated-values</td></tr><tr><td></td><td>HTML (zipped)</td><td>application/zip</td></tr><tr></tr><tr><td>Drawings</td><td>JPEG</td><td>image/jpeg</td></tr><tr><td></td><td>PNG</td><td>image/png</td></tr><tr><td></td><td>SVG</td><td>image/svg+xml</td></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td>Presentations</td><td>MS PowerPoint</td><td>application/vnd.openxmlformats-officedocument.presentationml.presentation</td></tr><tr><td></td><td>Open Office presentation</td><td>application/vnd.oasis.opendocument.presentation</td></tr><tr></tr><tr><td></td><td>PDF</td><td>application/pdf</td></tr><tr><td></td><td>Plain text</td><td>text/plain</td></tr><tr><td>Apps Scripts</td><td>JSON</td><td>application/vnd.google-apps.script+json</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/manage-downloads#downloading_google_documents the table under: "Google Doc formats and supported export MIME types map to each other as follows"

There is also another list

_x000D_
_x000D_
<table border="1"><thead><tr><th>MIME Type</th><th>Description</th></tr></thead><tbody><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>audio</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>document</span></code></td><td>Google Docs</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drawing</span></code></td><td>Google Drawing</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>file</span></code></td><td>Google Drive file</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>folder</span></code></td><td>Google Drive folder</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>form</span></code></td><td>Google Forms</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>fusiontable</span></code></td><td>Google Fusion Tables</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>map</span></code></td><td>Google My Maps</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>photo</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>presentation</span></code></td><td>Google Slides</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>script</span></code></td><td>Google Apps Scripts</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>site</span></code></td><td>Google Sites</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>spreadsheet</span></code></td><td>Google Sheets</td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>unknown</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>video</span></code></td><td></td></tr><tr><td><code><span>application/vnd.<wbr>google-apps.<wbr>drive-sdk</span></code></td><td>3rd party shortcut</td></tr></tbody></table>
_x000D_
_x000D_
_x000D_

Source here: https://developers.google.com/drive/v3/web/mime-types

But the first one was more helpful for my use case..

Happy coding ;)

Purpose of returning by const value?

In the hypothetical situation where you could perform a potentially expensive non-const operation on an object, returning by const-value prevents you from accidentally calling this operation on a temporary. Imagine that + returned a non-const value, and you could write:

(a + b).expensive();

In the age of C++11, however, it is strongly advised to return values as non-const so that you can take full advantage of rvalue references, which only make sense on non-constant rvalues.

In summary, there is a rationale for this practice, but it is essentially obsolete.

How do I set log4j level on the command line?

Based on @lijat, here is a simplified implementation. In my spring-based application I simply load this as a bean.

public static void configureLog4jFromSystemProperties()
{
  final String LOGGER_PREFIX = "log4j.logger.";

  for(String propertyName : System.getProperties().stringPropertyNames())
  {
    if (propertyName.startsWith(LOGGER_PREFIX)) {
      String loggerName = propertyName.substring(LOGGER_PREFIX.length());
      String levelName = System.getProperty(propertyName, "");
      Level level = Level.toLevel(levelName); // defaults to DEBUG
      if (!"".equals(levelName) && !levelName.toUpperCase().equals(level.toString())) {
        logger.error("Skipping unrecognized log4j log level " + levelName + ": -D" + propertyName + "=" + levelName);
        continue;
      }
      logger.info("Setting " + loggerName + " => " + level.toString());
      Logger.getLogger(loggerName).setLevel(level);
    }
  }
}

Displaying the Error Messages in Laravel after being Redirected from controller

A New Laravel Blade Error Directive comes to Laravel 5.8.13

// Before
@if ($errors->has('email'))
    <span>{{ $errors->first('email') }}</span>
@endif

// After:
@error('email')
    <span>{{ $message }}</span>
@enderror

How do I check if a cookie exists?

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}

Iterate Multi-Dimensional Array with Nested Foreach Statement

The 2D array in C# does not lend itself well to a nested foreach, it is not the equivalent of a jagged array (an array of arrays). You could do something like this to use a foreach

foreach (int i in Enumerable.Range(0, array.GetLength(0)))
    foreach (int j in Enumerable.Range(0, array.GetLength(1)))
        Console.WriteLine(array[i, j]);

But you would still use i and j as index values for the array. Readability would be better preserved if you just went for the garden variety for loop instead.

Remove last specific character in a string c#

Try string.Remove();

string str = "1,5,12,34,";
string removecomma = str.Remove(str.Length-1);
MessageBox.Show(removecomma);

Collections.emptyList() returns a List<Object>?

Since Java 8 this kind of code compiles as expected and the type parameter gets inferred by the compiler.

public Person(String name) {
    this(name, Collections.emptyList()); // Inferred to List<String> in Java 8
}

public Person(String name, List<String> nicknames) {
    this.name = name;
    this.nicknames = nicknames;
}

The new thing in Java 8 is that the target type of an expression will be used to infer type parameters of its sub-expressions. Before Java 8 only direct assignments and arguments to methods where used for type parameter inference.

In this case the parameter type of the constructor will be the target type for Collections.emptyList(), and the return value type will get chosen to match the parameter type.

This mechanism was added in Java 8 mainly to be able to compile lambda expressions, but it improves type inferences generally.

Java is getting closer to proper Hindley–Milner type inference with every release!

How to determine previous page URL in Angular?

@GünterZöchbauer also you can save it in localstorage but I not prefer it ) better to save in service and get this value from there

 constructor(
        private router: Router
      ) {
        this.router.events
          .subscribe((event) => {
            if (event instanceof NavigationEnd) {
              localStorage.setItem('previousUrl', event.url);
            }
          });
      }

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales.

How do I line up 3 divs on the same row?

Check out the foundation rapid prototyping framework they handled this quite nicely, basically they allow you to use HTML like this:

<div class="row">
    <div class="four columns">
    </div>
    <div class="four columns">
    </div>
    <div class="four columns">
    </div>
</div>

This is the simplest HTML/CSS grid system that I've come across, it's based on 12 column grid.

Basically the columns are given a % width and left margin relative to the parent row. They columns have float set to left, position set to relative, and display set to block.

The row has several properties set on it that care core of an issue that normally causes the containing div to collapse to height of 0 preventing the following divs from getting 'pushed' down as they should.

You can find examples of using the foundation grid system here: http://foundation.zurb.com/docs/grid.php

If you don't want to use the entire framework the following CSS should do the trick with the example code I provided:

.row:after {
    content: "";
    clear: both;
    display: table;
}

.four.column {
    float: left;
    width: 33%;
}

If you really specifically want a left center and right columns then use code like this:

CSS:

.row:after {
    content: "";
    clear: both;
    display: table;
}

.left {
    float: left;
    width: 100px;
}

.center {
    margin: 0 auto;
    width: 100px;
}

.right {
    float: right;
    width: 100px;
}

HTML:

<div class="row">
    <div class="left">left</div>
    <div class="right">right</div>
    <div class="center">center</div>
</div>

Test if a string contains a word in PHP?

_x000D_
_x000D_
use _x000D_
_x000D_
if(stripos($str,'job')){_x000D_
   // do your work_x000D_
}
_x000D_
_x000D_
_x000D_

Difference between java.exe and javaw.exe

java.exe is the command where it waits for application to complete untill it takes the next command. javaw.exe is the command which will not wait for the application to complete. you can go ahead with another commands.

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How to link to apps on the app store

Despite there being loads of answers here, none of the suggestions for linking to the developers apps seem to work anymore.

When I last visited I was able to get it working using the format:

itms-apps://itunes.apple.com/developer/developer-name/id123456789

This no longer works, but removing the developer name does:

itms-apps://itunes.apple.com/developer/id123456789

Deleting rows with MySQL LEFT JOIN

Try this:

DELETE `deadline`
FROM `deadline`
INNER JOIN `job` ON `deadline`.`job_id` = `job`.`id`
WHERE `job`.`id` = 123

Why do you use typedef when declaring an enum in C++?

You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.

typedef enum MyEnum { 
  //...
} MyEnum;

allowed functions taking a parameter of the enum to be defined as

void f( MyEnum x )

instead of the longer

void f( enum MyEnum x )

Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.

In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.

// C++
enum MyEnum {
   // ...
};
void f( MyEnum x ); // Correct C++, Error in C

TreeMap sort by value

polygenelubricants answer is almost perfect. It has one important bug though. It will not handle map entries where the values are the same.

This code:...

Map<String, Integer> nonSortedMap = new HashMap<String, Integer>();
nonSortedMap.put("ape", 1);
nonSortedMap.put("pig", 3);
nonSortedMap.put("cow", 1);
nonSortedMap.put("frog", 2);

for (Entry<String, Integer> entry  : entriesSortedByValues(nonSortedMap)) {
    System.out.println(entry.getKey()+":"+entry.getValue());
}

Would output:

ape:1
frog:2
pig:3

Note how our cow dissapeared as it shared the value "1" with our ape :O!

This modification of the code solves that issue:

static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) {
        SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(
            new Comparator<Map.Entry<K,V>>() {
                @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) {
                    int res = e1.getValue().compareTo(e2.getValue());
                    return res != 0 ? res : 1; // Special fix to preserve items with equal values
                }
            }
        );
        sortedEntries.addAll(map.entrySet());
        return sortedEntries;
    }

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

How do I remove my IntelliJ license in 2019.3?

I think there are more solutions!

You can start the app, and here are 3 things you can do:

  1. If the app shows for the first time the "import settings" dialog and then the "create/open a project" dialog, you can click on Settings > Manage License... > Remove License, and that removes for all Jetbrains products*.
  2. If you open products like IntelliJ IDEA and have projects currently active (like the app open automatically the all IDE without prompt), then click on File > Close Project, and follow the first step.
  3. Inside any app of IntelliJ, click on Help > Register... > Remove license.

*In case you have a license for a pack of products. If not, you have to remove the license per product individually. Check the 3rd step.

How to use font-family lato?

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

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

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

If you don't want to download it use this

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

Get the client IP address using PHP

It also works fine for internal IP addresses:

 function get_client_ip()
 {
      $ipaddress = '';
      if (getenv('HTTP_CLIENT_IP'))
          $ipaddress = getenv('HTTP_CLIENT_IP');
      else if(getenv('HTTP_X_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
      else if(getenv('HTTP_X_FORWARDED'))
          $ipaddress = getenv('HTTP_X_FORWARDED');
      else if(getenv('HTTP_FORWARDED_FOR'))
          $ipaddress = getenv('HTTP_FORWARDED_FOR');
      else if(getenv('HTTP_FORWARDED'))
          $ipaddress = getenv('HTTP_FORWARDED');
      else if(getenv('REMOTE_ADDR'))
          $ipaddress = getenv('REMOTE_ADDR');
      else
          $ipaddress = 'UNKNOWN';

      return $ipaddress;
 }

Calling a Sub and returning a value

Private Sub Main()
    Dim value = getValue()
    'do something with value
End Sub

Private Function getValue() As Integer
    Return 3
End Function

jQuery Selector: Id Ends With?

An example: to select all <a>s with ID ending in _edit:

jQuery("a[id$=_edit]")

or

jQuery("a[id$='_edit']")

What's an object file in C?

Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.

In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.

Reading NFC Tags with iPhone 6 / iOS 8

From digging into the iOS 8 docs that are available as of Sept 9th 3:30pm there is no mention of developer access to the NFC controller to perform any NFC operations; that includes reading tags, writing tags, pairing, payments, tag emulation... Given its an NXP controller the hardware has the capability to perform these features. They did mention a 3rd party app for the watch that allowed a hotel guest to open their room door with NFC. This is a classic use case for NFC and gives some indication that the NFC controller will be open to developers at some point. Remember, the watch is not supposed to be released until Q1 2015. So for now I'd say it's closed but will be open soon. Given the 'newness' of contactless payments for the general US consumer and the recent security breaches its not surprising Apple wants to keep this closed for a while.

Disclosure: Im the CEO of GoToTags, an NFC company with obvious vested interest in Apple opening up NFC to developers.

--- Correction & Update ---

The hotel app actually uses Bluetooth, not NFC. NFC is still often used for door unlocking, just not in this one example. NFC could be used if the watch has an open NFC controller.

I do know that Apple is aware of all of this and is discussing this with their top developers and stakeholders. There has already been massive negative push back on the lack of support for reading tags. As often the case in the past, I expect Apple to eventually open this up to developers for non-payment related functionality (reading tags, pairing). I do not think Apple will ever allow other wallets though. File sharing will likely be left to AirDrop as well.

--- Update on March 23rd 2016 ---

I am continually asked for updates about this topic, often with people referencing this post. With Apple releasing the iPhone SE, many are again asking why Apple has not supported tag reading yet. In summary Apple is more focused on Apple Pay succeeding than the other use cases for NFC for now. Apple could make a lot of money from Apple Pay, and has less to make from the other uses for NFC. Apple will likely open up NFC tag reading when they feel that consumer trust and security with NFC and Apple Pay is such that it wont put Apple Pay at risk. Further information here.

--- Update on May 24th 2017 ---

A developer in Greece has hacked the iPhone 6s to get it to read NFC tags via the NFC private frameworks; more info & video. While this isn't a long term solution, it provides some guidance on some outstanding question: Is there enough power in the iPhone's NFC controller to power an NFC tag? Looks like the answer is yes. From initial testing the range is a few cm, which isn't too bad. It might also be the power is tunable; this is being investigated at this time. The implications of this are significant. If the older model phones do have enough RF power for tag reading/writing, then when Apple does open up the SDK it means there will be 100Ms of iPhones that can read NFC tags, vs the case where only the new iPhones could.

How to format a float in javascript?

One more problem to be aware of, is that toFixed() can produce unnecessary zeros at the end of the number. For example:

var x=(23-7.37)
x
15.629999999999999
x.toFixed(6)
"15.630000"

The idea is to clean up the output using a RegExp:

function humanize(x){
  return x.toFixed(6).replace(/\.?0*$/,'');
}

The RegExp matches the trailing zeros (and optionally the decimal point) to make sure it looks good for integers as well.

humanize(23-7.37)
"15.63"
humanize(1200)
"1200"
humanize(1200.03)
"1200.03"
humanize(3/4)
"0.75"
humanize(4/3)
"1.333333"

How to shuffle an ArrayList

Use this method and pass your array in parameter

Collections.shuffle(arrayList);

This method return void so it will not give you a new list but as we know that array is passed as a reference type in Java so it will shuffle your array and save shuffled values in it. That's why you don't need any return type.

You can now use arraylist which is shuffled.

How do I check if a column is empty or null in MySQL?

You can also do

SELECT * FROM table WHERE column_name LIKE ''

The inverse being

SELECT * FROM table WHERE column_name NOT LIKE ''

How to allow http content within an iframe on a https site

Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

Caesar Cipher Function in Python

message = 'The quick brown fox jumped over the lazy dog. 1234567890 !@#$%^&*()_+-'
encrypted = ''.join(chr(ord(char)+3) for char in message)
decrypted = ''.join(chr(ord(char)-3) for char in encrypted)
print(encrypted)
print(decrypted)
# Wkh#txlfn#eurzq#ir{#mxpshg#ryhu#wkh#od}|#grj1#456789:;<3#$C&'(a)-+,b.0
# The quick brown fox jumped over the lazy dog. 1234567890 !@#$%^&*()_+-

Update a dataframe in pandas while iterating row by row

You can assign values in the loop using df.set_value:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.set_value(i,'ifor',ifor_val)

If you don't need the row values you could simply iterate over the indices of df, but I kept the original for-loop in case you need the row value for something not shown here.

update

df.set_value() has been deprecated since version 0.21.0 you can use df.at() instead:

for i, row in df.iterrows():
    ifor_val = something
    if <condition>:
        ifor_val = something_else
    df.at[i,'ifor'] = ifor_val

Is a DIV inside a TD a bad idea?

Two ways of dealing with it

  1. put div inside tbody tag
  2. put div inside tr tag

Both approaches are valid, if you see feference: https://stackoverflow.com/a/23440419/2305243

How do you delete all text above a certain line

dgg

will delete everything from your current line to the top of the file.

d is the deletion command, and gg is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.

Also

dG

will delete all lines at or below the current one

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

In my case, I forgot to add my component in the Declaration array of app.module.ts, and voila! the issue was fixed.

Difference between using Throwable and Exception in a try catch

The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception.

Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be caught as well.

Updating the list view when the adapter data changes

Change this line:

mMyListView.setAdapter(new ArrayAdapter<String>(this, 
                           android.R.layout.simple_list_item_1, 
                           listItems));

to:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                   android.R.layout.simple_list_item_1, 
                                   listItems)
mMyListView.setAdapter(adapter);

and after updating the value of a list item, call:

adapter.notifyDataSetChanged();

How to enable LogCat/Console in Eclipse for Android?

In the Window menu, open Show View -> Other ... and type log to find it.

Regex matching in a Bash if statement

I'd prefer to use [:punct:] for that. Also, a-zA-Z09-9 could be just [:alnum:]:

[[ $TEST =~ ^[[:alnum:][:blank:][:punct:]]+$ ]]

How to connect to a remote Windows machine to execute commands using python?

I have personally found pywinrm library to be very effective. However, it does require some commands to be run on the machine and some other setup before it will work.

What's the most efficient way to test two integer ranges for overlap?

Think in the inverse way: how to make the 2 ranges not overlap? Given [x1, x2], then [y1, y2] should be outside [x1, x2], i.e., y1 < y2 < x1 or x2 < y1 < y2 which is equivalent to y2 < x1 or x2 < y1.

Therefore, the condition to make the 2 ranges overlap: not(y2 < x1 or x2 < y1), which is equivalent to y2 >= x1 and x2 >= y1 (same with the accepted answer by Simon).

Make a div fill the height of the remaining screen space

This is my own minimal version of Pebbl's solution. Took forever to find the trick to get it to work in IE11. (Also tested in Chrome, Firefox, Edge, and Safari.)

_x000D_
_x000D_
html {
  height: 100%;
}

body {
  height: 100%;
  margin: 0;
}

section {
  display: flex;
  flex-direction: column;
  height: 100%;
}

div:first-child {
  background: gold;
}

div:last-child {
  background: plum;
  flex-grow: 1;
}
_x000D_
<body>
  <section>
    <div>FIT</div>
    <div>GROW</div>
  </section>
</body>
_x000D_
_x000D_
_x000D_

using lodash .groupBy. how to add your own keys for grouped output?

Example groupBy and sum of a column using Lodash 4.17.4

   var data = [{
                "name": "jim",
                "color": "blue",
                "amount": 22
                }, {
                "name": "Sam",
                "color": "blue",
                "amount": 33
                }, {
               "name": "eddie",
               "color": "green",
               "amount": 77
              }];

      var result = _(data)
                   .groupBy(x => x.color)
                   .map((value, key) => 
                   ({color: key,
                    totalamount: _.sumBy(value,'amount'),
                    users: value})).value();

                    console.log(result);

Getter and Setter of Model object in Angular 4

The way you declare the date property as an input looks incorrect but its hard to say if it's the only problem without seeing all your code. Rather than using @Input('date') declare the date property like so: private _date: string;. Also, make sure you are instantiating the model with the new keyword. Lastly, access the property using regular dot notation.

Check your work against this example from https://www.typescriptlang.org/docs/handbook/classes.html :

let passcode = "secret passcode";

class Employee {
    private _fullName: string;

    get fullName(): string {
        return this._fullName;
    }

    set fullName(newName: string) {
        if (passcode && passcode == "secret passcode") {
            this._fullName = newName;
        }
        else {
            console.log("Error: Unauthorized update of employee!");
        }
    }
}

let employee = new Employee();
employee.fullName = "Bob Smith";
if (employee.fullName) {
    console.log(employee.fullName);
}

And here is a plunker demonstrating what it sounds like you're trying to do: https://plnkr.co/edit/OUoD5J1lfO6bIeME9N0F?p=preview

How to get date in BAT file

set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause

Java Runtime.getRuntime(): getting output from executing a command line program

Also we can use streams for obtain command output:

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

        Runtime runtime = Runtime.getRuntime();
        String[] commands  = {"free", "-h"};
        Process process = runtime.exec(commands);

        BufferedReader lineReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        lineReader.lines().forEach(System.out::println);

        BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
        errorReader.lines().forEach(System.out::println);
    }

$_SERVER['HTTP_REFERER'] missing

From the documentation:

The address of the page (if any) which referred the user agent to the current page. This is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. In short, it cannot really be trusted.

http://php.net/manual/en/reserved.variables.server.php

Capturing mobile phone traffic on Wireshark

For Android phone I used tPacketCapture: https://play.google.com/store/apps/details?id=jp.co.taosoftware.android.packetcapture&hl=en

This app was a lifesaver I was debugging a problem with failure of SSL/TLS handshake on my Android app. Tried to setup ad hoc networking so I could use wireshark on my laptop. It did not work for me. This app quickly allowed me to capture network traffic, share it on my Google Drive so I could download on my laptop where I could examine it with Wireshark! Awesome and no root required!

"Large data" workflows using pandas

I spotted this a little late, but I work with a similar problem (mortgage prepayment models). My solution has been to skip the pandas HDFStore layer and use straight pytables. I save each column as an individual HDF5 array in my final file.

My basic workflow is to first get a CSV file from the database. I gzip it, so it's not as huge. Then I convert that to a row-oriented HDF5 file, by iterating over it in python, converting each row to a real data type, and writing it to a HDF5 file. That takes some tens of minutes, but it doesn't use any memory, since it's only operating row-by-row. Then I "transpose" the row-oriented HDF5 file into a column-oriented HDF5 file.

The table transpose looks like:

def transpose_table(h_in, table_path, h_out, group_name="data", group_path="/"):
    # Get a reference to the input data.
    tb = h_in.getNode(table_path)
    # Create the output group to hold the columns.
    grp = h_out.createGroup(group_path, group_name, filters=tables.Filters(complevel=1))
    for col_name in tb.colnames:
        logger.debug("Processing %s", col_name)
        # Get the data.
        col_data = tb.col(col_name)
        # Create the output array.
        arr = h_out.createCArray(grp,
                                 col_name,
                                 tables.Atom.from_dtype(col_data.dtype),
                                 col_data.shape)
        # Store the data.
        arr[:] = col_data
    h_out.flush()

Reading it back in then looks like:

def read_hdf5(hdf5_path, group_path="/data", columns=None):
    """Read a transposed data set from a HDF5 file."""
    if isinstance(hdf5_path, tables.file.File):
        hf = hdf5_path
    else:
        hf = tables.openFile(hdf5_path)

    grp = hf.getNode(group_path)
    if columns is None:
        data = [(child.name, child[:]) for child in grp]
    else:
        data = [(child.name, child[:]) for child in grp if child.name in columns]

    # Convert any float32 columns to float64 for processing.
    for i in range(len(data)):
        name, vec = data[i]
        if vec.dtype == np.float32:
            data[i] = (name, vec.astype(np.float64))

    if not isinstance(hdf5_path, tables.file.File):
        hf.close()
    return pd.DataFrame.from_items(data)

Now, I generally run this on a machine with a ton of memory, so I may not be careful enough with my memory usage. For example, by default the load operation reads the whole data set.

This generally works for me, but it's a bit clunky, and I can't use the fancy pytables magic.

Edit: The real advantage of this approach, over the array-of-records pytables default, is that I can then load the data into R using h5r, which can't handle tables. Or, at least, I've been unable to get it to load heterogeneous tables.

RegEx for Javascript to allow only alphanumeric

Save this constant

const letters = /^[a-zA-Z0-9]+$/

now, for checking part use .match()

const string = 'Hey there...' // get string from a keyup listner
let id = ''
// iterate through each letters
for (var i = 0; i < string.length; i++) {
  if (string[i].match(letters) ) {
    id += string[i]
  } else {
    // In case you want to replace with something else
    id += '-'  
  }
}
return id

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

Checkout remote branch using git svn

Standard Subversion layout

Create a git clone of that includes your Subversion trunk, tags, and branches with

git svn clone http://svn.example.com/project -T trunk -b branches -t tags

The --stdlayout option is a nice shortcut if your Subversion repository uses the typical structure:

git svn clone http://svn.example.com/project --stdlayout

Make your git repository ignore everything the subversion repo does:

git svn show-ignore >> .git/info/exclude

You should now be able to see all the Subversion branches on the git side:

git branch -r

Say the name of the branch in Subversion is waldo. On the git side, you'd run

git checkout -b waldo-svn remotes/waldo

The -svn suffix is to avoid warnings of the form

warning: refname 'waldo' is ambiguous.

To update the git branch waldo-svn, run

git checkout waldo-svn
git svn rebase

Starting from a trunk-only checkout

To add a Subversion branch to a trunk-only clone, modify your git repository's .git/config to contain

[svn-remote "svn-mybranch"]
        url = http://svn.example.com/project/branches/mybranch
        fetch = :refs/remotes/mybranch

You'll need to develop the habit of running

git svn fetch --fetch-all

to update all of what git svn thinks are separate remotes. At this point, you can create and track branches as above. For example, to create a git branch that corresponds to mybranch, run

git checkout -b mybranch-svn remotes/mybranch

For the branches from which you intend to git svn dcommit, keep their histories linear!


Further information

You may also be interested in reading an answer to a related question.

Java Mouse Event Right Click

To avoid any ambiguity, use the utilities methods from SwingUtilities :

SwingUtilities.isLeftMouseButton(MouseEvent anEvent) SwingUtilities.isRightMouseButton(MouseEvent anEvent) SwingUtilities.isMiddleMouseButton(MouseEvent anEvent)

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

Getting the size of an array in an object

Arrays have a property .length that returns the number of elements.

var st =
    {
        "itema":{},
        "itemb":
        [
            {"id":"s01","cd":"c01","dd":"d01"},
            {"id":"s02","cd":"c02","dd":"d02"}
        ]
    };

st.itemb.length // 2

startActivityForResult() from a Fragment and finishing child Activity, doesn't call onActivityResult() in Fragment

You must write onActivityResult() in your FirstActivity.Java as follows

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    for (Fragment fragment : getSupportFragmentManager().getFragments()) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

This will trigger onActivityResult method of fragments on FirstActivity.java

How can I select from list of values in Oracle

There are various ways to take a comma-separated list and parse it into multiple rows of data. In SQL

SQL> ed
Wrote file afiedt.buf

  1  with x as (
  2    select '1,2,3,a,b,c,d' str from dual
  3  )
  4   select regexp_substr(str,'[^,]+',1,level) element
  5     from x
  6* connect by level <= length(regexp_replace(str,'[^,]+')) + 1
SQL> /

ELEMENT
----------------------------------------------------
1
2
3
a
b
c
d

7 rows selected.

Or in PL/SQL

SQL> create type str_tbl is table of varchar2(100);
  2  /

Type created.

SQL> create or replace function parse_list( p_list in varchar2 )
  2    return str_tbl
  3    pipelined
  4  is
  5  begin
  6    for x in (select regexp_substr( p_list, '[^,]', 1, level ) element
  7                from dual
  8             connect by level <= length( regexp_replace( p_list, '[^,]+')) + 1)
  9    loop
 10      pipe row( x.element );
 11    end loop
 12    return;
 13  end;
 14
 15  /

Function created.

SQL> select *
  2    from table( parse_list( 'a,b,c,1,2,3,d,e,foo' ));

COLUMN_VALUE
--------------------------------------------------------------------------------
a
b
c
1
2
3
d
e
f

9 rows selected.

Add Custom Headers using HttpWebRequest

A simple method of creating the service, adding headers and reading the JSON response,

private static void WebRequest()
{
    const string WEBSERVICE_URL = "<<Web Service URL>>";
    try
    {
        var webRequest = System.Net.WebRequest.Create(WEBSERVICE_URL);
        if (webRequest != null)
        {
            webRequest.Method = "GET";
            webRequest.Timeout = 20000;
            webRequest.ContentType = "application/json";
            webRequest.Headers.Add("Authorization", "Basic dcmGV25hZFzc3VudDM6cGzdCdvQ=");
            using (System.IO.Stream s = webRequest.GetResponse().GetResponseStream())
            {
                using (System.IO.StreamReader sr = new System.IO.StreamReader(s))
                {
                    var jsonResponse = sr.ReadToEnd();
                    Console.WriteLine(String.Format("Response: {0}", jsonResponse));
                }
            }
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
    }
}

How do I make a placeholder for a 'select' box?

Input [type="text"] Style Placeholder for Select Elements

The following solution simulates a placeholder as it relates to an input[type="text"] element:

_x000D_
_x000D_
$('.example').change(function () {
  $(this).css('color', $(this).val() === '' ? '#999' : '#555');
});
_x000D_
.example {
  color: #999;
}

.example > option {
  color: #555;
}

.example > option[value=""] {
  color: #999;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select class="example">
  <option value="">Select Option</option>
  <option>Option 1</option>
  <option>Option 2</option>
  <option>Option 3</option>
</select>
_x000D_
_x000D_
_x000D_

Passing a String by Reference in Java?

All arguments in Java are passed by value. When you pass a String to a function, the value that's passed is a reference to a String object, but you can't modify that reference, and the underlying String object is immutable.

The assignment

zText += foo;

is equivalent to:

zText = new String(zText + "foo");

That is, it (locally) reassigns the parameter zText as a new reference, which points to a new memory location, in which is a new String that contains the original contents of zText with "foo" appended.

The original object is not modified, and the main() method's local variable zText still points to the original (empty) string.

class StringFiller {
  static void fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value:

If you want to modify the string, you can as noted use StringBuilder or else some container (an array or an AtomicReference or a custom container class) that gives you an additional level of pointer indirection. Alternatively, just return the new value and assign it:

class StringFiller2 {
  static String fillString(String zText) {
    zText += "foo";
    System.out.println("Local value: " + zText);
    return zText;
  }

  public static void main(String[] args) {
    String zText = "";
    System.out.println("Original value: " + zText);
    zText = fillString(zText);
    System.out.println("Final value: " + zText);
  }
}

prints:

Original value:
Local value: foo
Final value: foo

This is probably the most Java-like solution in the general case -- see the Effective Java item "Favor immutability."

As noted, though, StringBuilder will often give you better performance -- if you have a lot of appending to do, particularly inside a loop, use StringBuilder.

But try to pass around immutable Strings rather than mutable StringBuilders if you can -- your code will be easier to read and more maintainable. Consider making your parameters final, and configuring your IDE to warn you when you reassign a method parameter to a new value.

Http post and get request in angular 6

You can do a post/get using a library which allows you to use HttpClient with strongly-typed callbacks.

The data and the error are available directly via these callbacks.

The library is called angular-extended-http-client.

angular-extended-http-client library on GitHub

angular-extended-http-client library on NPM

Very easy to use.

Traditional approach

In the traditional approach you return Observable<HttpResponse<T>> from Service API. This is tied to HttpResponse.

With this approach you have to use .subscribe(x => ...) in the rest of your code.

This creates a tight coupling between the http layer and the rest of your code.

Strongly-typed callback approach

You only deal with your Models in these strongly-typed callbacks.

Hence, The rest of your code only knows about your Models.

Sample usage

The strongly-typed callbacks are

Success:

  • IObservable<T>
  • IObservableHttpResponse
  • IObservableHttpCustomResponse<T>

Failure:

  • IObservableError<TError>
  • IObservableHttpError
  • IObservableHttpCustomError<TError>

Add package to your project and in your app module

import { HttpClientExtModule } from 'angular-extended-http-client';

and in the @NgModule imports

  imports: [
    .
    .
    .
    HttpClientExtModule
  ],

Your Models


export class SearchModel {
    code: string;
}

//Normal response returned by the API.
export class RacingResponse {
    result: RacingItem[];
}

//Custom exception thrown by the API.
export class APIException {
    className: string;
}

Your Service

In your Service, you just create params with these callback types.

Then, pass them on to the HttpClientExt's get method.

import { Injectable, Inject } from '@angular/core'
import { SearchModel, RacingResponse, APIException } from '../models/models'
import { HttpClientExt, IObservable, IObservableError, ResponseType, ErrorType } from 'angular-extended-http-client';
.
.

@Injectable()
export class RacingService {

    //Inject HttpClientExt component.
    constructor(private client: HttpClientExt, @Inject(APP_CONFIG) private config: AppConfig) {

    }

    //Declare params of type IObservable<T> and IObservableError<TError>.
    //These are the success and failure callbacks.
    //The success callback will return the response objects returned by the underlying HttpClient call.
    //The failure callback will return the error objects returned by the underlying HttpClient call.
    searchRaceInfo(model: SearchModel, success: IObservable<RacingResponse>, failure?: IObservableError<APIException>) {
        let url = this.config.apiEndpoint;

        this.client.post<SearchModel, RacingResponse>(url, model, 
                                                      ResponseType.IObservable, success, 
                                                      ErrorType.IObservableError, failure);
    }
}

Your Component

In your Component, your Service is injected and the searchRaceInfo API called as shown below.

  search() {    


    this.service.searchRaceInfo(this.searchModel, response => this.result = response.result,
                                                  error => this.errorMsg = error.className);

  }

Both, response and error returned in the callbacks are strongly typed. Eg. response is type RacingResponse and error is APIException.

How to get WooCommerce order details

You can get all details by order object.

   // Get $order object from order ID
      
    $order = wc_get_order( $order_id );
      
    // Now you have access to (see above)...
      
    if ( $order ) {
       // Get Order ID and Key
    $order->get_id();
    $order->get_order_key();
     
    // Get Order Totals $0.00
    $order->get_formatted_order_total();
    $order->get_cart_tax();
    $order->get_currency();
    $order->get_discount_tax();
    $order->get_discount_to_display();
    $order->get_discount_total();
    $order->get_fees();
    $order->get_formatted_line_subtotal();
    $order->get_shipping_tax();
    $order->get_shipping_total();
    $order->get_subtotal();
    $order->get_subtotal_to_display();
    $order->get_tax_location();
    $order->get_tax_totals();
    $order->get_taxes();
    $order->get_total();
    $order->get_total_discount();
    $order->get_total_tax();
    $order->get_total_refunded();
    $order->get_total_tax_refunded();
    $order->get_total_shipping_refunded();
    $order->get_item_count_refunded();
    $order->get_total_qty_refunded();
    $order->get_qty_refunded_for_item();
    $order->get_total_refunded_for_item();
    $order->get_tax_refunded_for_item();
    $order->get_total_tax_refunded_by_rate_id();
    $order->get_remaining_refund_amount();
    }

Java: How to convert a File object to a String object in java?

Readin file with file inputstream and append file content to string.

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class CopyOffileInputStream {

    public static void main(String[] args) {

        //File file = new File("./store/robots.txt");
        File file = new File("swingloggingsscce.log");

        FileInputStream fis = null;
        String str = "";

        try {
            fis = new FileInputStream(file);
            int content;
            while ((content = fis.read()) != -1) {
                // convert to char and display it
                str += (char) content;
            }

            System.out.println("After reading file");
            System.out.println(str);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Oracle PL Sql Developer cannot find my tnsnames.ora file

Check if tnsnames.ora not saved as text file with an additional hidden .txt extension. Windows File Explorer will not show it by deafult settings.

Is there a way to delete all the data from a topic or delete the topic before every run?

As of kafka 2.3.0 version, there is an alternate way to soft deletion of Kafka (old approach are deprecated ).

Update retention.ms to 1 sec (1000ms) then set it again after a min, to default setting i.e 7 days (168 hours, 604,800,000 in ms )

Soft deletion:- (rentention.ms=1000) (using kafka-configs.sh)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=1000
Completed Updating config for entity: topic 'kafka_topic3p3r'.

Setting to default:- 7 days (168 hours , retention.ms= 604800000)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=604800000

How to frame two for loops in list comprehension python

return=[entry for tag in tags for entry in entries if tag in entry for entry in entry]

Return from a promise then()

You cannot return value after resolving promise. Instead call another function when promise is resolved:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

Which command do I use to generate the build of a Vue app?

To deploy your application to prod environment add

"build": "vue-cli-service build --mode prod"

in your scripts in package.json file.

Open your main.js and add

Vue.config.productionTip = false;

right after your imports. Then open your cli in the project folder and run this command

npm run build

This will make a dist folder in your project directory you may upload that dist folder in your host and your website will be live

Algorithm to find Largest prime factor of a number

All numbers can be expressed as the product of primes, eg:

102 = 2 x 3 x 17
712 = 2 x 2 x 2 x 89

You can find these by simply starting at 2 and simply continuing to divide until the result isn't a multiple of your number:

712 / 2 = 356 .. 356 / 2 = 178 .. 178 / 2 = 89 .. 89 / 89 = 1

using this method you don't have to actually calculate any primes: they'll all be primes, based on the fact that you've already factorised the number as much as possible with all preceding numbers.

number = 712;
currNum = number;    // the value we'll actually be working with
for (currFactor in 2 .. number) {
    while (currNum % currFactor == 0) {
        // keep on dividing by this number until we can divide no more!
        currNum = currNum / currFactor     // reduce the currNum
    }
    if (currNum == 1) return currFactor;    // once it hits 1, we're done.
}

How to get first two characters of a string in oracle query?

take a look here

SELECT SUBSTR('Take the first four characters', 1, 4) FIRST_FOUR FROM DUAL;

How to connect to remote Redis server?

redis-cli -h XXX.XXX.XXX.XXX -p YYYY

xxx.xxx.xxx.xxx is the IP address and yyyy is the port

EXAMPLE from my dev environment

redis-cli -h 10.144.62.3 -p 30000

REDIS CLI COMMANDS

Host, port, password and database By default redis-cli connects to the server at 127.0.0.1 port 6379. As you can guess, you can easily change this using command line options. To specify a different host name or an IP address, use -h. In order to set a different port, use -p.

redis-cli -h redis15.localnet.org -p 6390 ping

What's the difference between KeyDown and KeyPress in .NET?

Easiest explanation:

I held down the 'd' key for a second and then released.

dddddd

the keydown event happened once before the first d appeared on the screen, the keypress event happened 6 times and the keyup event happened after the last d appeared on the screen.

How to stop text from taking up more than 1 line?

Just to be crystal clear, this works nicely with paragraphs and headers etc. You just need to specify display: block.

For instance:

<h5 style="display: block; text-overflow: ellipsis; white-space: nowrap; overflow: hidden">
  This is a really long title, but it won't exceed the parent width
</h5>

(forgive the inline styles)

How to transform array to comma separated words string?

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

http://php.net/manual/en/function.implode.php

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

You're not adding columns to your DataGridView

DataGridView dataGridView1 = new DataGridView();//Create new grid

dataGridView1.Columns[0].Name = "ItemID";// refer to column which is not there 

Is it clear now why you get an exception?

Add this line before you use columns to fix the error

dataGridView1.ColumnCount = 5;

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

Adding multiple class using ng-class

Other way we can create a function to control "using multiple class"

CSS

 <style>
    .Red {
        color: Red;
    }
    .Yellow {
        color: Yellow;
    }
      .Blue {
        color: Blue;
    }
      .Green {
        color: Green;
    }
    .Gray {
        color: Gray;
    }
    .b {
         font-weight: bold;
    }
</style>

Script

<script>
    angular.module('myapp', [])
            .controller('ExampleController', ['$scope', function ($scope) {
                $scope.MyColors = ['It is Red', 'It is Yellow', 'It is Blue', 'It is Green', 'It is Gray'];
                $scope.getClass = function (strValue) {
                    if (strValue == ("It is Red"))
                        return "Red";
                    else if (strValue == ("It is Yellow"))
                        return "Yellow";
                    else if (strValue == ("It is Blue"))
                        return "Blue";
                    else if (strValue == ("It is Green"))
                        return "Green";
                    else if (strValue == ("It is Gray"))
                        return "Gray";
                }
        }]);
</script>

Using it

<body ng-app="myapp" ng-controller="ExampleController">

<h2>AngularJS ng-class if example</h2>
<ul >
    <li ng-repeat="icolor in MyColors" >
        <p ng-class="[getClass(icolor), 'b']">{{icolor}}</p>
    </li>
</ul>

You can refer to full code page at ng-class if example

Call PowerShell script PS1 from another PS1 script inside Powershell ISE

This is just additional info to answers in order to pass argument into the another file

Where you expect argument

PrintName.ps1

Param(
    [Parameter( Mandatory = $true)]
    $printName = "Joe"    
)


Write-Host $printName

How to call the file

Param(
    [Parameter( Mandatory = $false)]
    $name = "Joe"    
)


& ((Split-Path $MyInvocation.InvocationName) + "\PrintName.ps1") -printName $name

If you do not do not provide any input it will default to "Joe" and this will be passed as argument into printName argument in PrintName.ps1 file which will in turn print out the "Joe" string

Timestamp with a millisecond precision: How to save them in MySQL

You can use BIGINT as follows:

CREATE TABLE user_reg (
user_id INT NOT NULL AUTO_INCREMENT,
identifier INT,
phone_number CHAR(11) NOT NULL,
verified TINYINT UNSIGNED NOT NULL,
reg_time BIGINT,
last_active_time BIGINT,
PRIMARY KEY (user_id),
INDEX (phone_number, user_id, identifier)
   );

Order a List (C#) by many fields?

Use ThenBy:

var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)

See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx

reading HttpwebResponse json response, C#

I'd use RestSharp - https://github.com/restsharp/RestSharp

Create class to deserialize to:

public class MyObject {
    public string Id { get; set; }
    public string Text { get; set; }
    ...
}

And the code to get that object:

RestClient client = new RestClient("http://whatever.com");
RestRequest request = new RestRequest("path/to/object");
request.AddParameter("id", "123");

// The above code will make a request URL of 
// "http://whatever.com/path/to/object?id=123"
// You can pick and choose what you need

var response = client.Execute<MyObject>(request);

MyObject obj = response.Data;

Check out http://restsharp.org/ to get started.

"Expected BEGIN_OBJECT but was STRING at line 1 column 1"

I had a similar problem recently and found an interesting solution. Basically I needed to deserialize following nested JSON String into my POJO:

"{\"restaurant\":{\"id\":\"abc-012\",\"name\":\"good restaurant\",\"foodType\":\"American\",\"phoneNumber\":\"123-456-7890\",\"currency\":\"USD\",\"website\":\"website.com\",\"location\":{\"address\":{\"street\":\" Good Street\",\"city\":\"Good City\",\"state\":\"CA\",\"country\":\"USA\",\"postalCode\":\"12345\"},\"coordinates\":{\"latitude\":\"00.7904692\",\"longitude\":\"-000.4047208\"}},\"restaurantUser\":{\"firstName\":\"test\",\"lastName\":\"test\",\"email\":\"[email protected]\",\"title\":\"server\",\"phone\":\"0000000000\"}}}"

I ended up using regex to remove the open quotes from beginning and the end of JSON and then used apache.commons unescapeJava() method to unescape it. Basically passed the unclean JSON into following method to get back a cleansed one:

private String removeQuotesAndUnescape(String uncleanJson) {
    String noQuotes = uncleanJson.replaceAll("^\"|\"$", "");

    return StringEscapeUtils.unescapeJava(noQuotes);
}

then used Google GSON to parse it into my own Object:

MyObject myObject = new.Gson().fromJson(this.removeQuotesAndUnescape(uncleanJson));

How to get HttpRequestMessage data

From this answer:

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
    string jsonContent = content.ReadAsStringAsync().Result;
}

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

How to save a git commit message from windows cmd?

If you enter git commit but omit to enter a comment using the –m parameter, then Git will open up the default editor for you to edit your check-in note. By default that is Vim. Now you can do two things:

Alternative 1 – Exit Vim without entering any comment and repeat

A blank or unsaved comment will be counted as an aborted attempt to commit your changes and you can exit Vim by following these steps:

  1. Press Esc to make sure you are not in edit mode (you can press Esc several times if you are uncertain)

  2. Type :q! enter
    (that is, colon, letter q, exclamation mark, enter), this tells Vim to discard any changes and exit)
    Git will then respond:

    Aborting commit due to empty commit message

    and you are once again free to commit using:

    git commit –m "your comment here"
    

Alternative 2 – Use Vim to write a comment

Follow the following steps to use Vim for writing your comments

  1. Press i to enter Edit Mode (or Insert Mode).
    That will leave you with a blinking cursor on the first line. Add your comment. Press Esc to make sure you are not in edit mode (you can press Esc several time if you are uncertain)
  2. Type :wq enter
    (that is colon, letter w, letter q, enter), this will tell Vim to save changes and exit)

Response from https://blogs.msdn.microsoft.com/kristol/2013/07/02/the-git-command-line-101-for-windows-users/

How do I check if a file exists in Java?

I would recommend using isFile() instead of exists(). Most of the time you are looking to check if the path points to a file not only that it exists. Remember that exists() will return true if your path points to a directory.

new File("path/to/file.txt").isFile();

new File("C:/").exists() will return true but will not allow you to open and read from it as a file.

How to check if a file exists in a folder?

To check file exists or not you can use

System.IO.File.Exists(path)

Sending POST parameters with Postman doesn't work, but sending GET parameters does

Check your content-type in the header. I was having issue with this sending raw JSON and my content-type as application/json in the POSTMAN header.

my php was seeing jack all in the request post. It wasn't until i change the content-type to application/x-www-form-urlencoded with the JSON in the RAW textarea and its type as JSON, did my PHP app start to see the post data. not what i expected when deal with raw json but its now working for what i need.

postman POST request

How to update RecyclerView Adapter Data?

I'm working with RecyclerView and both the remove and the update work well.

1) REMOVE: There are 4 steps to remove an item from a RecyclerView

list.remove(position);
recycler.removeViewAt(position);
mAdapter.notifyItemRemoved(position);                 
mAdapter.notifyItemRangeChanged(position, list.size());

These line of codes work for me.

2) UPDATE THE DATA: The only things I had to do is

mAdapter.notifyDataSetChanged();

You had to do all of this in the Actvity/Fragment code not in the RecyclerView Adapter code.

What does double question mark (??) operator mean in PHP

$x = $y ?? 'dev'

is short hand for x = y if y is set, otherwise x = 'dev'

There is also

$x = $y =="SOMETHING" ? 10 : 20

meaning if y equals 'SOMETHING' then x = 10, otherwise x = 20

How do you make a HTTP request with C++?

CppRest SDK by MS is what I just found and after about 1/2 hour had my first simple web service call working. Compared that to others mentioned here where I was not able to get anything even installed after hours of looking, I'd say it is pretty impressive

https://github.com/microsoft/cpprestsdk

Scroll down and click on Documentation, then click on Getting Started Tutorial and you will have a simple app running in no time.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

If you NEED to do it on your phone, I use a terminal emulator and standard linux commands.

Example:

  1. su
  2. cd data
  3. cd com.yourappp
  4. ls or cd into cache/shared_prefs

http://www.appbrain.com/app/android-terminal-emulator/jackpal.androidterm

Understanding "VOLUME" instruction in DockerFile

The VOLUME command in a Dockerfile is quite legit, totally conventional, absolutely fine to use and it is not deprecated in anyway. Just need to understand it.

We use it to point to any directories which the app in the container will write to a lot. We don't use VOLUME just because we want to share between host and container like a config file.

The command simply needs one param; a path to a folder, relative to WORKDIR if set, from within the container. Then docker will create a volume in its graph(/var/lib/docker) and mount it to the folder in the container. Now the container will have somewhere to write to with high performance. Without the VOLUME command the write speed to the specified folder will be very slow because now the container is using it's copy on write strategy in the container itself. The copy on write strategy is a main reason why volumes exist.

If you mount over the folder specified by the VOLUME command, the command is never run because VOLUME is only executed when the container starts, kind of like ENV.

Basically with VOLUME command you get performance without externally mounting any volumes. Data will save across container runs too without any external mounts. Then when ready simply mount something over it.

Some good example use cases:
- logs
- temp folders

Some bad use cases:
- static files
- configs
- code

C# string reference type?

For curious minds and to complete the conversation: Yes, String is a reference type:

unsafe
{
     string a = "Test";
     string b = a;
     fixed (char* p = a)
     {
          p[0] = 'B';
     }
     Console.WriteLine(a); // output: "Best"
     Console.WriteLine(b); // output: "Best"
}

But note that this change only works in an unsafe block! because Strings are immutable (From MSDN):

The contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

string b = "h";  
b += "ello";  

And keep in mind that:

Although the string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references.

In Angular, how to add Validator to FormControl after control is created?

I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".

As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.

But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.

findViewById in Fragment

agreed with calling findViewById() on the View.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View V = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView) V.findViewById(R.id.my_image);

    return V;
}

How can I debug a Perl script?

If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:

Given test:

use v5.14;
say 1;
say 2;
say 3;

Start a listener on whatever host and port on terminal 1 (here localhost:12345):

$ nc -v -l localhost -p 12345

For readline support use rlwrap (you can use on perl -d too):

$ rlwrap nc -v -l localhost -p 12345

And start the test on another terminal (say terminal 2):

$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test

Input/Output on terminal 1:

Connection from 127.0.0.1:42994

Loading DB routines from perl5db.pl version 1.49
Editor support available.

Enter h or 'h h' for help, or 'man perldebug' for more help.

main::(test:2):    say 1;
  DB<1> n
main::(test:3):    say 2;
  DB<1> select $DB::OUT

  DB<2> n
2
main::(test:4):    say 3;
  DB<2> n
3
Debugged program terminated.  Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
  DB<2>

Output on terminal 2:

1

Note the sentence if you want output on debug terminal

select $DB::OUT

If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.

Javascript: The prettiest way to compare one value against multiple values

What i use to do, is put those multiple values in an array like

var options = [foo, bar];

and then, use indexOf()

if(options.indexOf(foobar) > -1){
   //do something
}

for prettiness:

if([foo, bar].indexOf(foobar) +1){
   //you can't get any more pretty than this :)
}

and for the older browsers:
( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/IndexOf )

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

Find where python is installed (if it isn't default dir)

Platform independent solution in one line is

Python 2:

python -c "import sys; print sys.executable"

Python 3:

python -c "import sys; print(sys.executable)"

Add Header and Footer for PDF using iTextsharp

The answers to this question, while they are correct, are very unnecessarily complicated. It doesn't take that much code for text to show up in the header/footer. Here is a simple example of adding text to the header/footer.

The current version of iTextSharp works by implementing a callback class which is defined by the IPdfPageEvent interface. From what I understand, it's not a good idea to add things during the OnStartPage method, so instead I will be using the OnEndPage page method. The events are triggered depending on what is happening to the PdfWriter

First, create a class which implements IPdfPageEvent. In the:

public void OnEndPage(PdfWriter writer, Document document)

function, obtain the PdfContentByte object by calling

PdfContentByte cb = writer.DirectContent;

Now you can add text very easily:

ColumnText ct = new ColumnText(cb);

cb.BeginText();
cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
//Note, (0,0) in this case is at the bottom of the document
cb.SetTextMatrix(document.LeftMargin, document.BottomMargin); 
cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
cb.EndText();

So the full for the OnEndPage function will be:

public void OnEndPage(PdfWriter writer, Document document)
{
    PdfContentByte cb = writer.DirectContent;
    ColumnText ct = new ColumnText(cb);

    cb.BeginText();
    cb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 12.0f);
    cb.SetTextMatrix(document.LeftMargin, document.BottomMargin);
    cb.ShowText(String.Format("{0} {1}", "Testing Text", "Like this"));
    cb.EndText();

}

This will show up at the bottom of your document. One last thing. Don't forget to assign the IPdfPageEvent like this:

writter.PageEvent = new PDFEvents();

To the PdfWriter writter object

For the header it is very similar. Just flip the SetTextMatrix y coordinate:

cb.SetTextMatrix(document.LeftMargin, document.PageSize.Height - document.TopMargin);

Check if a input box is empty

To auto check a checkbox if input field is not empty.

 <md-content>
            <md-checkbox ng-checked="myField.length"> Other </md-checkbox>
            <input  ng-model="myField" placeholder="Please Specify" type="text">
 </md-content>

How to set radio button selected value using jquery

for multiple dropdowns

$('[id^=RBLExperienceApplicable][value='+ SelectedVAlue +']').attr("checked","checked");

here RBLExperienceApplicable is the matching part of the radio button groups input tag ids. and [id^=RBLExperienceApplicable] matches all the radio button whose id start with RBLExperienceApplicable

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How to select id with max date group by category in PostgreSQL?

SELECT id FROM tbl GROUP BY cat HAVING MAX(date)

Buiding Hadoop with Eclipse / Maven - Missing artifact jdk.tools:jdk.tools:jar:1.6

I also faced this problem because I just only installed JRE not with JDK. So , adding dependency for jdk.tools can't fix for me because tools.jar was not exist at my ${JAVA_HOME}/lib/ directory.

Now I downloaded and installed JDK to fix it.

jQuery add text to span within a div

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

How do I convert two lists into a dictionary?

>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> dict(zip(keys, values))
{'food': 'spam', 'age': 42, 'name': 'Monty'}

How to include jQuery in ASP.Net project?

You might be looking for this Microsoft Ajax Content Delivery Network So you could just add

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

To your aspx page.

Remove duplicated rows

This problem can also be solved by selecting first row from each group where the group are the columns based on which we want to select unique values (in the example shared it is just 1st column).

Using base R :

subset(df, ave(V2, V1, FUN = seq_along) == 1)

#                      V1  V2 V3     V4 V5
#1 platform_external_dbus 202 16 google  1

In dplyr

library(dplyr)
df %>% group_by(V1) %>% slice(1L)

Or using data.table

library(data.table)
setDT(df)[, .SD[1L], by = V1]

If we need to find out unique rows based on multiple columns just add those column names in grouping part for each of the above answer.

data

df <- structure(list(V1 = structure(c(1L, 1L, 1L, 1L, 1L), 
.Label = "platform_external_dbus", class = "factor"), 
V2 = c(202L, 202L, 202L, 202L, 202L), V3 = c(16L, 16L, 16L, 
16L, 16L), V4 = structure(c(1L, 4L, 3L, 5L, 2L), .Label = c("google", 
"hughsie", "localhost", "space-ghost.verbum", "users.sourceforge"
), class = "factor"), V5 = c(1L, 1L, 1L, 8L, 1L)), class = "data.frame", 
row.names = c(NA, -5L))

What is __main__.py?

What is the __main__.py file for?

When creating a Python module, it is common to make the module execute some functionality (usually contained in a main function) when run as the entry point of the program. This is typically done with the following common idiom placed at the bottom of most Python files:

if __name__ == '__main__':
    # execute only if run as the entry point into the program
    main()

You can get the same semantics for a Python package with __main__.py, which might have the following structure:

.
+-- demo
    +-- __init__.py
    +-- __main__.py

To see this, paste the below into a Python 3 shell:

from pathlib import Path

demo = Path.cwd() / 'demo'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo/__main__.py executed')

from demo import main

main()
""")

We can treat demo as a package and actually import it, which executes the top-level code in the __init__.py (but not the main function):

>>> import demo
demo/__init__.py executed

When we use the package as the entry point to the program, we perform the code in the __main__.py, which imports the __init__.py first:

$ python -m demo
demo/__init__.py executed
demo/__main__.py executed
main() executed

You can derive this from the documentation. The documentation says:

__main__ — Top-level script environment

'__main__' is the name of the scope in which top-level code executes. A module’s __name__ is set equal to '__main__' when read from standard input, a script, or from an interactive prompt.

A module can discover whether or not it is running in the main scope by checking its own __name__, which allows a common idiom for conditionally executing code in a module when it is run as a script or with python -m but not when it is imported:

if __name__ == '__main__':
     # execute only if run as a script
     main()

For a package, the same effect can be achieved by including a __main__.py module, the contents of which will be executed when the module is run with -m.

Zipped

You can also zip up this directory, including the __main__.py, into a single file and run it from the command line like this - but note that zipped packages can't execute sub-packages or submodules as the entry point:

from pathlib import Path

demo = Path.cwd() / 'demo2'
demo.mkdir()

(demo / '__init__.py').write_text("""
print('demo2/__init__.py executed')

def main():
    print('main() executed')
""")

(demo / '__main__.py').write_text("""
print('demo2/__main__.py executed')

from __init__ import main

main()
""")

Note the subtle change - we are importing main from __init__ instead of demo2 - this zipped directory is not being treated as a package, but as a directory of scripts. So it must be used without the -m flag.

Particularly relevant to the question - zipapp causes the zipped directory to execute the __main__.py by default - and it is executed first, before __init__.py:

$ python -m zipapp demo2 -o demo2zip
$ python demo2zip
demo2/__main__.py executed
demo2/__init__.py executed
main() executed

Note again, this zipped directory is not a package - you cannot import it either.

How to prompt for user input and read command-line arguments

If you are running Python <2.7, you need optparse, which as the doc explains will create an interface to the command line arguments that are called when your application is run.

However, in Python =2.7, optparse has been deprecated, and was replaced with the argparse as shown above. A quick example from the docs...

The following code is a Python program that takes a list of integers and produces either the sum or the max:

import argparse

parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')

args = parser.parse_args()
print args.accumulate(args.integers)

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

HTML Entity Decode

I recommend against using the jQuery code that was accepted as the answer. While it does not insert the string to decode into the page, it does cause things such as scripts and HTML elements to get created. This is way more code than we need. Instead, I suggest using a safer, more optimized function.

var decodeEntities = (function() {
  // this prevents any overhead from creating the object each time
  var element = document.createElement('div');

  function decodeHTMLEntities (str) {
    if(str && typeof str === 'string') {
      // strip script/html tags
      str = str.replace(/<script[^>]*>([\S\s]*?)<\/script>/gmi, '');
      str = str.replace(/<\/?\w(?:[^"'>]|"[^"]*"|'[^']*')*>/gmi, '');
      element.innerHTML = str;
      str = element.textContent;
      element.textContent = '';
    }

    return str;
  }

  return decodeHTMLEntities;
})();

http://jsfiddle.net/LYteC/4/

To use this function, just call decodeEntities("&amp;") and it will use the same underlying techniques as the jQuery version will—but without jQuery's overhead, and after sanitizing the HTML tags in the input. See Mike Samuel's comment on the accepted answer for how to filter out HTML tags.

This function can be easily used as a jQuery plugin by adding the following line in your project.

jQuery.decodeEntities = decodeEntities;

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Android studio - Failed to find target android-18

Target with hash string 'android-18' is corresponding to the SDK level 18. You need to install SDK 18 from SDK manager.

How to convert 2D float numpy array to 2D int numpy array?

you can use np.int_:

>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. ,  2.3],
       [ 1.3,  2.9]])
>>> np.int_(x)
array([[1, 2],
       [1, 2]])

Array to String PHP?

Yet another way, PHP var_export() with short array syntax (square brackets) indented 4 spaces:

function varExport($expression, $return = true) {
    $export = var_export($expression, true);
    $export = preg_replace("/^([ ]*)(.*)/m", '$1$1$2', $export);
    $array = preg_split("/\r\n|\n|\r/", $export);
    $array = preg_replace(["/\s*array\s\($/", "/\)(,)?$/", "/\s=>\s$/"], [null, ']$1', ' => ['], $array);
    $export = join(PHP_EOL, array_filter(["["] + $array));
    
    if ((bool) $return) return $export; else echo $export;
}

Taken here.

JavaScript/regex: Remove text between parentheses

var str = "Hello, this is Mike (example)";

alert(str.replace(/\s*\(.*?\)\s*/g, ''));

That'll also replace excess whitespace before and after the parentheses.

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

I was with Angular 8 and the only thing which worked for me was this:

  getCustomHeaders(): HttpHeaders {
    const headers = new HttpHeaders()
      .set('Content-Type', 'application/json')
      .set('Api-Key', 'xxx');
    return headers;
  }

Django Multiple Choice Field / Checkbox Select Multiple

Brant's solution is absolutely correct, but I needed to modify it to make it work with multiple select checkboxes and commit=false. Here is my solution:

models.py

class Choices(models.Model):
    description = models.CharField(max_length=300)

class Profile(models.Model):
   user = models.ForeignKey(User, blank=True, unique=True, verbose_name_('user'))
   the_choices = models.ManyToManyField(Choices)

forms.py

class ProfileForm(forms.ModelForm):
    the_choices = forms.ModelMultipleChoiceField(queryset=Choices.objects.all(), required=False, widget=forms.CheckboxSelectMultiple)

    class Meta:
        model = Profile
        exclude = ['user']

views.py

if request.method=='POST':
    form = ProfileForm(request.POST)
    if form.is_valid():
        profile = form.save(commit=False)
        profile.user = request.user
        profile.save()
        form.save_m2m() # needed since using commit=False
    else:
        form = ProfileForm()

return render_to_response(template_name, {"profile_form": form}, context_instance=RequestContext(request))

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

How do I pass an object from one activity to another on Android?

It depends on the type of data you need access to. If you have some kind of data pool that needs to persist across Activitys then Erich's answer is the way to go. If you just need to pass a few objects from one activity to another then you can have them implement Serializable and pass them in the extras of the Intent to start the new Activity.

Getting first and last day of the current month

var now = DateTime.Now;
var first = new DateTime(now.Year, now.Month, 1);
var last = first.AddMonths(1).AddDays(-1);

You could also use DateTime.DaysInMonth method:

var last = new DateTime(now.Year, now.Month, DateTime.DaysInMonth(now.Year, now.Month));

Define the selected option with the old input in Laravel / Blade

Laravel 6 or above: just use the old() function for instance @if (old('cat')==$cat->id), it will do the rest of the work for you.

How its works: select tag store the selected option value into its name attribute in bellow case if you select any option it will store into cat. At the first time when page loaded there is nothing inside cat, when user chose a option the value of that selected option is stored into cat so when user were redirected old() function pull the previous value from cat.

 {!!Form::open(['action'=>'CategoryController@storecat', 'method'=>'POST']) !!}
        <div class="form-group">
            <select name="cat" id="cat" class="form-control input-lg">
                <option value="">Select App</option>
                @foreach ($cats as $cat)
                    @if (old('cat')==$cat->id)
                        <option value={{$cat->id}} selected>{{ $cat->title }}</option>
                    @else
                        <option value={{$cat->id}} >{{ $cat->title }}</option>
                    @endif
                @endforeach
            </select>
        </div>

        <div class="from-group">
            {{Form::label('name','Category name:')}}
            {{Form::text('name','',['class'=>'form-control', 'placeholder'=>'Category name'])}}
        </div>
    <br>
    {!!Form::submit('Submit', ['class'=>'btn btn-primary'])!!}
    {!!Form::close()!!}

Moving items around in an ArrayList

As Mikkel posted before Collections.rotate is a simple way. I'm using this method for moving items up- and downward in a List.

public static <T> void moveItem(int sourceIndex, int targetIndex, List<T> list) {
    if (sourceIndex <= targetIndex) {
        Collections.rotate(list.subList(sourceIndex, targetIndex + 1), -1);
    } else {
        Collections.rotate(list.subList(targetIndex, sourceIndex + 1), 1);
    }
}

What is a stack pointer used for in microprocessors?

Should you ever crave deeper understanding, I heartily recommend Patterson and Hennessy as an intro and Hennessy and Patterson as an intermediate to advanced text. They're pricey, but truly non-pareil; I just wish either or both were available when I got my Masters' degree and entered the workforce designing chips, systems, and parts of system software for them (but, alas!, that was WAY too long ago;-). Stack pointers are so crucial (and the distinction between a microprocessor and any other kind of CPU so utterly meaningful in this context... or, for that matter, in ANY other context, in the last few decades...!-) that I doubt anything but a couple of thorough from-the-ground-up refreshers can help!-)

How many bits is a "word"?

On x86/x64 processors, a byte is 8 bits, and there are 256 possible binary states in 8 bits, 0 thru 255. This is how the OS translates your keyboard key strokes into letters on the screen. When you press the 'A' key, the keyboard sends a binary signal equal to the number 97 to the computer, and the computer prints a lowercase 'a' on the screen. You can confirm this in any Windows text editing software by holding an ALT key, typing 97 on the NUMPAD, then releasing the ALT key. If you replace '97' with any number from 0 to 255, you will see the character associated with that number on the system's character code page printed on the screen.

If a character is 8 bits, or 1 byte, then a WORD must be at least 2 characters, so 16 bits or 2 bytes. Traditionally, you might think of a word as a varying number of characters, but in a computer, everything that is calculable is based on static rules. Besides, a computer doesn't know what letters and symbols are, it only knows how to count numbers. So, in computer language, if a WORD is equal to 2 characters, then a double-word, or DWORD, is 2 WORDs, which is the same as 4 characters or bytes, which is equal to 32 bits. Furthermore, a quad-word, or QWORD, is 2 DWORDs, same as 4 WORDs, 8 characters, or 64 bits.

Note that these terms are limited in function to the Windows API for developers, but may appear in other circumstances (eg. the Linux dd command uses numerical suffixes to compound byte and block sizes, where c is 1 byte and w is bytes).

Escaping HTML strings with jQuery

Plain JavaScript escaping example:

function escapeHtml(text) {
    var div = document.createElement('div');
    div.innerText = text;
    return div.innerHTML;
}

escapeHtml("<script>alert('hi!');</script>")
// "&lt;script&gt;alert('hi!');&lt;/script&gt;"

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

Angular @ViewChild() error: Expected 2 arguments, but got 1

That also resolved my issue.

@ViewChild('map', {static: false}) googleMap;

How to add title to seaborn boxplot

Try adding this at the end of your code:

import matplotlib.pyplot as plt

plt.title('add title here')

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

To hide static cells in UITable:

  1. Add this method:

In your UITableView controller delegate class:

Objective-C:

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell* cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];

    if(cell == self.cellYouWantToHide)
        return 0; //set the hidden cell's height to 0

    return [super tableView:tableView heightForRowAtIndexPath:indexPath];
}

Swift:

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    var cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)

    if cell == self.cellYouWantToHide {
        return 0
    }

    return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}

This method will get called for each cell in the UITable. Once it calls it for the cell you want to hide, we set its height to 0. We identify the target cell by creating an outlet for it:

  1. In the designer, create an outlet for the cell(s) you want to hide. The outlet for one such cell is called "cellYouWantToHide" above.
  2. Check "Clip Subviews" in the IB for the cells you want to hide. The cells you are hiding need to have ClipToBounds = YES. Otherwise the text will pile up in the UITableView.

Importing CSV with line breaks in Excel 2007

Excel (at least in Office 2007 on XP) can behave differently depending on whether a CSV file is imported by opening it from the File->Open menu or by double-clicking on the file in Explorer.

I have a CSV file that is in UTF-8 encoding and contains newlines in some cells. If I open this file from Excel's File->Open menu, the "import CSV" wizard pops up and the file cannot be correctly imported: the newlines start a new row even when quoted. If I open this file by double-clicking on it in an Explorer window, then it opens correctly without the intervention of the wizard.

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

Create some public Properties on your sub-form like so

public string ReturnValue1 {get;set;} 
public string ReturnValue2 {get;set;}

then set this inside your sub-form ok button click handler

private void btnOk_Click(object sender,EventArgs e)
{
    this.ReturnValue1 = "Something";
    this.ReturnValue2 = DateTime.Now.ToString(); //example
    this.DialogResult = DialogResult.OK;
    this.Close();
}

Then in your frmHireQuote form, when you open the sub-form

using (var form = new frmImportContact())
{
    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1;            //values preserved after close
        string dateString = form.ReturnValue2;
        //Do something here with these values

        //for example
        this.txtSomething.Text = val;
    }
}

Additionaly if you wish to cancel out of the sub-form you can just add a button to the form and set its DialogResult to Cancel and you can also set the CancelButton property of the form to said button - this will enable the escape key to cancel out of the form.

Node.js fs.readdir recursive directory search

klaw and klaw-sync are worth considering for this sort of thing. These were part of node-fs-extra.

Android : change button text and background color

Just complementing @Jonsmoke's answer.

For API level 21 and above you can use :

android:backgroundTint="@android:color/white"

in XML for the button layout.

For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.

For example:

<android.support.v7.widget.AppCompatButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    app:backgroundTint="@android:color/white" />

How do I replace text in a selection?

As @JOPLOmacedo stated, ctrl + F is what you need, but if you can't use that shortcut you can check in menu:

  • Find -> Find..

    and there you have it.
    You can also set a custom keybind for Find going in:

  • Preferences -> Key Bindings - User

    As your request for the selection only request, there is a button right next to the search field where you can opt-in for "in selection".

  • Inserting created_at data with Laravel

    Currently (Laravel 5.4) the way to achieve this is:

    $model = new Model();
    $model->created_at = Carbon::now();
    $model->save(['timestamps' => false]);
    

    Changing column names of a data frame

    You can just do the editing by:

    newprice <- edit(newprice)
    

    and change the column name manually.

    mySQL convert varchar to date

    select date_format(str_to_date('31/12/2010', '%d/%m/%Y'), '%Y%m'); 
    

    or

    select date_format(str_to_date('12/31/2011', '%m/%d/%Y'), '%Y%m'); 
    

    hard to tell from your example

    How do you replace double quotes with a blank space in Java?

    Strings are immutable, so you need to say

    sInputString = sInputString("\"","");
    

    not just the right side of the =

    C++ "Access violation reading location" Error

    Vertex *f=(findvertex(from));
    if(!f) {
        cerr << "vertex not found" << endl;
        exit(1) // or return;
    }
    

    Because findVertex can return NULL if it can't find the vertex.

    Otherwise this f->adj; is trying to do

    NULL->adj;
    

    Which causes access violation.

    ERROR: Cannot open source file " "

    Just in case there is someone out there who's a bit new like me, double check that you are spelling your header folders correctly.

    For example:

    <#include "Component/BoxComponent.h"
    

    This will result in the error. Instead, it needs to be:

    <#include "Components/BoxComponent.h"
    

    Get element by id - Angular2

    if you want to set value than you can do the same in some function on click or on some event fire.

    also you can get value using ViewChild using local variable like this

    <input type='text' id='loginInput' #abc/>
    

    and get value like this

    this.abc.nativeElement.value
    

    here is working example

    Update

    okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

    ngAfterViewInit(){
        document.getElementById('loginInput').value = '123344565';
      }
    

    ngAfterViewInit will not throw any error because it will render after template loading

    MongoDB running but can't connect using shell

    Not so much an answer but more of an FYI:I've just hit this and found this question as a result of searching. Here is the details of my experience:

    Shell error

    markdsievers@ip-xx-xx-xx-xx:~$ mongo
    MongoDB shell version: 2.0.1
    connecting to: test
    Wed Dec 21 03:36:13 Socket recv() errno:104 Connection reset by peer 127.0.0.1:27017
    Wed Dec 21 03:36:13 SocketException: remote: 127.0.0.1:27017 error: 9001 socket exception [1] server [127.0.0.1:27017] 
    Wed Dec 21 03:36:13 DBClientCursor::init call() failed
    Wed Dec 21 03:36:13 Error: Error during mongo startup. :: caused by :: DBClientBase::findN: transport error: 127.0.0.1 query: { whatsmyuri: 1 } shell/mongo.js:84
    exception: connect failed
    

    Mongo logs reveal

    Wed Dec 21 03:35:04 [initandlisten] connection accepted from 127.0.0.1:50273 #6612
    Wed Dec 21 03:35:04 [initandlisten] connection refused because too many open connections: 819
    

    This perhaps indicates the other answer (JaKi) was experiencing the same thing, where some connections were purged and access made possible again for the shell (other clients)

    What does ellipsize mean in android?

    Text:

     This is my first android application and
     I am trying to make a funny game,
     It seems android is really very easy to play.
    

    Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

    This is my first android application and
    ...t seems android is really very easy to play.
    

    with end attribute

     This is my first android application and
     I am trying to make a funny game,...
    

    How to Git stash pop specific stash in 1.8.3?

    As Robert pointed out, quotation marks might do the trick for you:

    git stash pop stash@"{1}"
    

    How to sort an array of objects by multiple fields?

    Here's my solution based on the Schwartzian transform idiom, hope you find it useful.

    function sortByAttribute(array, ...attrs) {
      // generate an array of predicate-objects contains
      // property getter, and descending indicator
      let predicates = attrs.map(pred => {
        let descending = pred.charAt(0) === '-' ? -1 : 1;
        pred = pred.replace(/^-/, '');
        return {
          getter: o => o[pred],
          descend: descending
        };
      });
      // schwartzian transform idiom implementation. aka: "decorate-sort-undecorate"
      return array.map(item => {
        return {
          src: item,
          compareValues: predicates.map(predicate => predicate.getter(item))
        };
      })
      .sort((o1, o2) => {
        let i = -1, result = 0;
        while (++i < predicates.length) {
          if (o1.compareValues[i] < o2.compareValues[i]) result = -1;
          if (o1.compareValues[i] > o2.compareValues[i]) result = 1;
          if (result *= predicates[i].descend) break;
        }
        return result;
      })
      .map(item => item.src);
    }
    

    Here's an example how to use it:

    let games = [
      { name: 'Pako',              rating: 4.21 },
      { name: 'Hill Climb Racing', rating: 3.88 },
      { name: 'Angry Birds Space', rating: 3.88 },
      { name: 'Badland',           rating: 4.33 }
    ];
    
    // sort by one attribute
    console.log(sortByAttribute(games, 'name'));
    // sort by mupltiple attributes
    console.log(sortByAttribute(games, '-rating', 'name'));
    

    How to display with n decimal places in Matlab

    i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

    Amazon S3 boto - how to create a folder?

    Apparently you can now create folders in S3. I'm not sure since when, but I have a bucket in "Standard" zone and can choose Create Folder from Action dropdown.

    Split Java String by New Line

    String lines[] =String.split( System.lineSeparator())

    How to know if a DateTime is between a DateRange in C#

    You can use:

    return (dateTocheck >= startDate && dateToCheck <= endDate);
    

    How to find the nearest parent of a Git branch?

    An alternative: git rev-list master | grep "$(git rev-list HEAD)" | head -1

    Get the last commit that it's both my branch and master (or whatever branch you want to specify)

    Valid characters in a Java class name

    What other rules govern Java class names (for instance, Java class names cannot begin with a number)?

    • Java class names usually begin with a capital letter.
    • Java class names cannot begin with a number.
    • if there are multiple words in the class name like "MyClassName" each word should begin with a capital letter. eg- "MyClassName".This naming convention is based on CamelCase Type.

    How exactly to use Notification.Builder

    I have used

    Intent intent = new Intent(this, MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
                    PendingIntent.FLAG_ONE_SHOT);
    
            Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("Firebase Push Notification")
                    .setContentText(messageBody)
                    .setAutoCancel(true)
                    .setSound(defaultSoundUri)
                    .setContentIntent(pendingIntent);
    
            NotificationManager notificationManager =
                    (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    
            notificationManager.notify(0, notificationBuilder.build());
    

    gson throws MalformedJsonException

    I suspect that result1 has some characters at the end of it that you can't see in the debugger that follow the closing } character. What's the length of result1 versus result2? I'll note that result2 as you've quoted it has 169 characters.

    GSON throws that particular error when there's extra characters after the end of the object that aren't whitespace, and it defines whitespace very narrowly (as the JSON spec does) - only \t, \n, \r, and space count as whitespace. In particular, note that trailing NUL (\0) characters do not count as whitespace and will cause this error.

    If you can't easily figure out what's causing the extra characters at the end and eliminate them, another option is to tell GSON to parse in lenient mode:

    Gson gson = new Gson();
    JsonReader reader = new JsonReader(new StringReader(result1));
    reader.setLenient(true);
    Userinfo userinfo1 = gson.fromJson(reader, Userinfo.class);
    

    Notice: Trying to get property of non-object error

    This is because $pjs is an one-element-array of objects, so first you should access the array element, which is an object and then access its attributes.

    echo $pjs[0]->player_name;
    

    Actually dump result that you pasted tells it very clearly.

    CSS center content inside div

    You just need

    .parent-div { text-align: center }
    

    mysql delete under safe mode

    I have a far more simple solution, it is working for me; it is also a workaround but might be usable and you dont have to change your settings. I assume you can use value that will never be there, then you use it on your WHERE clause

    DELETE FROM MyTable WHERE MyField IS_NOT_EQUAL AnyValueNoItemOnMyFieldWillEverHave

    I don't like that solution either too much, that's why I am here, but it works and it seems better than what it has been answered

    AttributeError: 'str' object has no attribute 'append'

    Why myList[1] is considered a 'str' object?

    Because it is a string. What else is 'from form', if not a string? (Actually, strings are sequences too, i.e. they can be indexed, sliced, iterated, etc. as well - but that's part of the str class and doesn't make it a list or something).

    mList[1] returns the first item in the list 'from form'

    If you mean that myList is 'from form', no it's not!!! The second (indexing starts at 0) element is 'from form'. That's a BIG difference. It's the difference between a house and a person.

    Also, myList doesn't have to be a list from your short code sample - it could be anything that accepts 1 as index - a dict with 1 as index, a list, a tuple, most other sequences, etc. But that's irrelevant.

    but I cannot append to item 1 in the list myList

    Of course not, because it's a string and you can't append to string. String are immutable. You can concatenate (as in, "there's a new object that consists of these two") strings. But you cannot append (as in, "this specific object now has this at the end") to them.

    curl_init() function not working

    For linux you can install it via

    sudo apt-get install php5-curl
    

    For Windows(removing the ;) from php.ini

    ;extension=php_curl.dll
    

    Restart apache server.

    INSERT ... ON DUPLICATE KEY (do nothing)

    Yes, use INSERT ... ON DUPLICATE KEY UPDATE id=id (it won't trigger row update even though id is assigned to itself).

    If you don't care about errors (conversion errors, foreign key errors) and autoincrement field exhaustion (it's incremented even if the row is not inserted due to duplicate key), then use INSERT IGNORE.

    Returning first x items from array

    You can use array_slice function, but do you will use another values? or only the first 5? because if you will use only the first 5 you can use the LIMIT on SQL.

    Ruby Array find_first object?

    use array detect method if you wanted to return first value where block returns true

    [1,2,3,11,34].detect(&:even?) #=> 2
    
    OR
    
    [1,2,3,11,34].detect{|i| i.even?} #=> 2
    

    If you wanted to return all values where block returns true then use select

    [1,2,3,11,34].select(&:even?)  #=> [2, 34]
    

    Using HTML and Local Images Within UIWebView

    I just ran into this problem too. In my case, I was dealing with some images that were not localized and others that were--in multiple languages. A base URL didn't get the images inside localized folders for me. I solved this by doing the following:

    // make sure you have the image name and extension (for demo purposes, I'm using "myImage" and "png" for the file "myImage.png", which may or may not be localized)
    NSString *imageFileName = @"myImage";
    NSString *imageFileExtension = @"png";
    
    // load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version)
    NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension];
    
    // generate the html tag for the image (don't forget to use file:// for local paths)
    NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=\"file://%@\" />", imagePath];
    

    Then, use imgHTMLTag in your UIWebView HTML code when you load the contents.

    I hope this helps anyone who ran into the same problem.

    How to trim a list in Python

    You just subindex it with [:5] indicating that you want (up to) the first 5 elements.

    >>> [1,2,3,4,5,6,7,8][:5]
    [1, 2, 3, 4, 5]
    >>> [1,2,3][:5]
    [1, 2, 3]
    >>> x = [6,7,8,9,10,11,12]
    >>> x[:5]
    [6, 7, 8, 9, 10]
    

    Also, putting the colon on the right of the number means count from the nth element onwards -- don't forget that lists are 0-based!

    >>> x[5:]
    [11, 12]
    

    Downloading and unzipping a .zip file without writing to disk

    All of these answers appear too bulky and long. Use requests to shorten the code, e.g.:

    import requests, zipfile, io
    r = requests.get(zip_file_url)
    z = zipfile.ZipFile(io.BytesIO(r.content))
    z.extractall("/path/to/directory")
    

    Initialize class fields in constructor or at declaration?

    The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.

    If you can, make the fields final.

    String Array object in Java

    First, as for your Athlete class, you can remove your Getter and Setter methods since you have declared your instance variables with an access modifier of public. You can access the variables via <ClassName>.<variableName>.

    However, if you really want to use that Getter and Setter, change the public modifier to private instead.

    Second, for the constructor, you're trying to do a simple technique called shadowing. Shadowing is when you have a method having a parameter with the same name as the declared variable. This is an example of shadowing:
    ----------Shadowing sample----------
    You have the following class:

    public String name;
    
    public Person(String name){
        this.name = name; // This is Shadowing
    }
    

    In your main method for example, you instantiate the Person class as follow:
    Person person = new Person("theolc");

    Variable name will be equal to "theolc".
    ----------End of shadowing----------

    Let's go back to your question, if you just want to print the first element with your current code, you may remove the Getter and Setter. Remove your parameters on your constructor.

    public class Athlete {
    
    public String[] name = {"Art", "Dan", "Jen"};
    public String[] country = {"Canada", "Germany", "USA"};
    
    public Athlete() {
    
    }
    

    In your main method, you could do this.

    public static void main(String[] args) {
           Athlete art = new Athlete();   
    
           System.out.println(art.name[0]);
           System.out.println(art.country[0]);
        }
    }
    

    List of <p:ajax> events

    Unfortunatelly, Ajax events are poorly documented and I haven't found any comprehensive list. For example, User Guide v. 3.5 lists itemChange event for p:autoComplete, but forgets to mention change event.

    If you want to find out which events are supported:

    1. Download and unpack primefaces source jar
    2. Find the JavaScript file, where your component is defined (for example, most form components such as SelectOneMenu are defined in forms.js)
    3. Search for this.cfg.behaviors references

    For example, this section is responsible for launching toggleSelect event in SelectCheckboxMenu component:

    fireToggleSelectEvent: function(checked) {
        if(this.cfg.behaviors) {
            var toggleSelectBehavior = this.cfg.behaviors['toggleSelect'];
    
            if(toggleSelectBehavior) {
                var ext = {
                    params: [{name: this.id + '_checked', value: checked}]
                }
            }
    
            toggleSelectBehavior.call(this, null, ext);
        }
    },
    

    What does "static" mean in C?

    It depends:

    int foo()
    {
       static int x;
       return ++x;
    }
    

    The function would return 1, 2, 3, etc. --- the variable is not on the stack.

    a.c:

    static int foo()
    {
    }
    

    It means that this function has scope only in this file. So a.c and b.c can have different foo()s, and foo is not exposed to shared objects. So if you defined foo in a.c you couldn't access it from b.c or from any other places.

    In most C libraries all "private" functions are static and most "public" are not.

    is inaccessible due to its protection level

    You organized class interface such that public members begin with "my". Therefore you must use only those members. Instead of

    myScoreonHole.hole = Console.ReadLine();
    

    you should write

    myScoreonHole.myhole = Console.ReadLine();
    

    How to set a default row for a query that returns no rows?

    *SQL solution

    Suppose you have a review table which has primary key "id".

    SELECT * FROM review WHERE id = 1555
    UNION ALL
    SELECT * FROM review WHERE NOT EXISTS ( SELECT * FROM review where id = 1555 ) AND id = 1
    

    if table doesn't have review with 1555 id then this query will provide a review of id 1.

    Fastest way to extract frames using ffmpeg?

    Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:

    time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp
    

    1m36.029s

    This takes long because ffmpeg parses the entire video file to get the desired frames.

    time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4   -frames:v 1 period_down_$i.bmp ; done
    

    0m4.689s

    This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek is the default , and make sure you add -ss before the input video -i option.

    Note that it's better to use -filter:v -fps=fps=... instead of -r as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.

    Javascript: Load an Image from url and display

    Are you after something like this:

     <html>
     <head>
        <title>Z Test</title>
     </head>
     <body>
    
    <div id="img_home"></div>
    
    <button onclick="addimage()" type="button">Add an image</button>
    
    <script>
    function addimage() {
        var img = new Image();
        img.src = "https://www.google.com/images/srpr/logo4w.png"
        img_home.appendChild(img);
    }
    </script>
    </body>
    

    PersistenceContext EntityManager injection NullPointerException

    If the component is an EJB, then, there shouldn't be a problem injecting an EM.

    But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

    This is probably the problem.

    How to determine the IP address of a Solaris system

    The following worked pretty well for me:

    ping -s my_host_name
    

    How to read/write from/to file using Go?

    Try this:

    package main
    
    import (
      "io"; 
      )
    
    
    func main() {
      contents,_ := io.ReadFile("filename");
      println(string(contents));
      io.WriteFile("filename", contents, 0644);
    }
    

    Implementation difference between Aggregation and Composition in Java

    Both types are of course associations, and not really mapped strictly to language elements like that. The difference is in the purpose, context, and how the system is modeled.

    As a practical example, compare two different types of systems with similar entities:

    • A car registration system that primarily keep track of cars, and their owners, etc. Here we are not interested in the engine as a separate entity, but we may still have engine related attributes, like power, and type of fuel. Here the Engine may be a composite part of the car entity.

    • A car service shop management system that manages car parts, servicing cars, and replace parts, maybe complete engines. Here we may even have engines stocked and need to keep track of them and other parts separately and independent of the cars. Here the Engine may be an aggregated part of the car entity.

    How you implement this in your language is of minor concern since at that level things like readability is much more important.

    Select distinct using linq

    Using morelinq you can use DistinctBy:

    myList.DistinctBy(x => x.id);
    

    Otherwise, you can use a group:

    myList.GroupBy(x => x.id)
          .Select(g => g.First());
    

    Remove portion of a string after a certain character

    Why...

    This is likely overkill for most people's needs, but, it addresses a number of things that each individual answer above does not. Of the items it addresses, three of them were needed for my needs. With tight bracketing and dropping the comments, this could still remain readable at only 13 lines of code.

    This addresses the following:

    • Performance impact of using REGEX vs strrpos/strstr/strripos/stristr.
    • Using strripos/strrpos when character/string not found in string.
    • Removing from left or right side of string (first or last occurrence) .
    • CaSe Sensitivity.
    • Wanting the ability to return back the original string unaltered if search char/string not found.

    Usage:

    Send original string, search char/string, "R"/"L" for start on right or left side, true/false for case sensitivity. For example, search for "here" case insensitive, in string, start right side.

    echo TruncStringAfterString("Now Here Are Some Words Here Now","here","R",false);
    

    Output would be "Now Here Are Some Words ". Changing the "R" to an "L" would output: "Now ".

    Here's the function:

    function TruncStringAfterString($origString,$truncChar,$startSide,$caseSensitive)
    {
        if ($caseSensitive==true && strstr($origString,$truncChar)!==false)
        {
            // IF START RIGHT SIDE:
            if (strtoupper($startSide)=="R" || $startSide==false)
            {   // Found, strip off all chars from truncChar to end
                return substr($origString,0,strrpos($origString,$truncChar));
            }
    
            // IF START LEFT SIDE: 
            elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
            {   // Found, strip off all chars from truncChar to end
                return strstr($origString,$truncChar,true);
            }           
        }
        elseif ($caseSensitive==false && stristr($origString,$truncChar)!==false)
        {           
            // IF START RIGHT SIDE: 
            if (strtoupper($startSide)=="R" || $startSide==false)
            {   // Found, strip off all chars from truncChar to end
                return substr($origString,0,strripos($origString,$truncChar));
            }
    
            // IF START LEFT SIDE: 
            elseif (strtoupper($startSide)=="L" || $startSide="" || $startSide==true)
            {   // Found, strip off all chars from truncChar to end
                return stristr($origString,$truncChar,true);
            }
        }       
        else
        {   // NOT found - return origString untouched
            return $origString;     // Nothing to do here
        }           
    
    }
    

    XAMPP installation on Win 8.1 with UAC Warning

    You can solve the issue by

    1. Ignore the warning and Install XAMPP directly under C:/ folder. It will solve your issue
    2. You can deactivate the UAC which i don't recommend. It's makes your PC less secure.

    Does adding a duplicate value to a HashSet/HashMap replace the previous value

    It the case of HashSet, it does NOT replace it.

    From the docs:

    http://docs.oracle.com/javase/6/docs/api/java/util/HashSet.html#add(E)

    "Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false."

    How to remove RVM (Ruby Version Manager) from my system

    If you're still getting a env: ruby_executable_hooks: No such file or directory when calling some Ruby package, that means RVM left a little gift for you in your $PATH.

    Run the following to find the offending scripts:

    grep '#!/usr/bin/env ruby_executable_hooks' /usr/local/bin/*
    

    Then rm all the matches. You'll have to reinstall all of those libraries with an RVM-free gem, of course.

    Select all from table with Laravel and Eloquent

    If your table is very big, you can also process rows by "small packages" (not all at oce) (laravel doc: Eloquent> Chunking Results )

    Post::chunk(200, function($posts)
    {
        foreach ($posts as $post)
        {
            // process post here.
        }
    });
    

    jQuery using append with effects

    Why don't you simply hide, append, then show, like this:

    <div id="parent1" style="  width: 300px; height: 300px; background-color: yellow;">
        <div id="child" style=" width: 100px; height: 100px; background-color: red;"></div>
    </div>
    
    
    <div id="parent2" style="  width: 300px; height: 300px; background-color: green;">
    </div>
    
    <input id="mybutton" type="button" value="move">
    
    <script>
        $("#mybutton").click(function(){
            $('#child').hide(1000, function(){
                $('#parent2').append($('#child'));
                $('#child').show(1000);
            });
    
        });
    </script>
    

    Tool to Unminify / Decompress JavaScript

    Most of the IDEs also offer auto-formatting features. For example in NetBeans, just press CTRL+K.