Programs & Examples On #Decoupling

Decoupling is the reduction of dependencies between computational parts.

Type List vs type ArrayList in Java

I am wondering if anyone uses (2)?

Yes. But rarely for a sound reason (IMO).

And people get burned because they used ArrayList when they should have used List:

  • Utility methods like Collections.singletonList(...) or Arrays.asList(...) don't return an ArrayList.

  • Methods in the List API don't guarantee to return a list of the same type.

For example of someone getting burned, in https://stackoverflow.com/a/1481123/139985 the poster had problems with "slicing" because ArrayList.sublist(...) doesn't return an ArrayList ... and he had designed his code to use ArrayList as the type of all of his list variables. He ended up "solving" the problem by copying the sublist into a new ArrayList.

The argument that you need to know how the List behaves is largely addressed by using the RandomAccess marker interface. Yes, it is a bit clunky, but the alternative is worse.

Also, how often does the situation actually require using (1) over (2) (i.e. where (2) wouldn't suffice..aside 'coding to interfaces' and best practices etc.)

The "how often" part of the question is objectively unanswerable.

(and can I please get an example)

Occasionally, the application may require that you use methods in the ArrayList API that are not in the List API. For example, ensureCapacity(int), trimToSize() or removeRange(int, int). (And the last one will only arise if you have created a subtype of ArrayList that declares the method to be public.)

That is the only sound reason for coding to the class rather than the interface, IMO.

(It is theoretically possible that you will get a slight improvement in performance ... under certain circumstances ... on some platforms ... but unless you really need that last 0.05%, it is not worth doing this. This is not a sound reason, IMO.)


You can’t write efficient code if you don’t know whether random access is efficient or not.

That is a valid point. However, Java provides better ways to deal with that; e.g.

public <T extends List & RandomAccess> void test(T list) {
    // do stuff
}

If you call that with a list that does not implement RandomAccess you will get a compilation error.

You could also test dynamically ... using instanceof ... if static typing is too awkward. And you could even write your code to use different algorithms (dynamically) depending on whether or not a list supported random access.

Note that ArrayList is not the only list class that implements RandomAccess. Others include CopyOnWriteList, Stack and Vector.

I've seen people make the same argument about Serializable (because List doesn't implement it) ... but the approach above solves this problem too. (To the extent that it is solvable at all using runtime types. An ArrayList will fail serialization if any element is not serializable.)

How to delete multiple values from a vector?

There is also subset which might be useful sometimes:

a <- sample(1:10)
bad <- c(2, 3, 5)

> subset(a, !(a %in% bad))
[1]  9  7 10  6  8  1  4

Calculating the position of points in a circle

PHP Solution:

class point{
    private $x = 0;
    private $y = 0;
    public function setX($xpos){
        $this->x = $xpos;
    }
    public function setY($ypos){
        $this->y = $ypos;
    }
    public function getX(){
        return $this->x;
    }
    public function getY(){
        return $this->y;
    }
    public function printX(){
        echo $this->x;
    }
    public function printY(){
        echo $this->y;
    }
}
function drawCirclePoints($points, $radius, &$center){
    $pointarray = array();
    $slice = (2*pi())/$points;
    for($i=0;$i<$points;$i++){
        $angle = $slice*$i;
        $newx = (int)($center->getX() + ($radius * cos($angle)));
        $newy = (int)($center->getY() + ($radius * sin($angle)));
        $point = new point();
        $point->setX($newx);
        $point->setY($newy);
        array_push($pointarray,$point);
    }
    return $pointarray;
}

Android XXHDPI resources

According to the post linked in the G+ resource:

The gorgeous screen on the Nexus 10 falls into the XHDPI density bucket. On tablets, Launcher uses icons from one density bucket up [0] to render them slightly larger. To ensure that your launcher icon (arguably your apps most important asset) is crisp you need to add a 144*144px icon in the drawable-xxhdpi or drawable-480dpi folder.

So it looks like the xxhdpi is set for 480dpi. According to that, tablets use the assets from one dpi bucket higher than the one they're in for the launcher. The Nexus 10 being in bucket xhdpi will pull the launcher icon from the xxhdpi.

Source

Also, was not aware that tablets take resources from the asset bucket above their level. Noted.

How to get name of calling function/method in PHP?

You can also use the info provided by a php exception, it's an elegant solution:


function GetCallingMethodName(){
    $e = new Exception();
    $trace = $e->getTrace();
    //position 0 would be the line that called this function so we ignore it
    $last_call = $trace[1];
    print_r($last_call);
}

function firstCall($a, $b){
    theCall($a, $b);
}

function theCall($a, $b){
    GetCallingMethodName();
}

firstCall('lucia', 'php');

And you get this... (voilà!)

Array
(
    [file] => /home/lufigueroa/Desktop/test.php
    [line] => 12
    [function] => theCall
    [args] => Array
        (
            [0] => lucia
            [1] => php
        )

)

What is SYSNAME data type in SQL Server?

Let me list a use case below. Hope it helps. Here I'm trying to find the Table Owner of the Table 'Stud_dtls' from the DB 'Students'. As Mikael mentioned, sysname could be used when there is a need for creating some dynamic sql which needs variables holding table names, column names and server names. Just thought of providing a simple example to supplement his point.

USE Students

DECLARE @TABLE_NAME sysname

SELECT @TABLE_NAME = 'Stud_dtls'

SELECT TABLE_SCHEMA 
  FROM INFORMATION_SCHEMA.Tables
 WHERE TABLE_NAME = @TABLE_NAME

TestNG ERROR Cannot find class in classpath

I just had this problem and I'm pretty confident that it's a bug in the TestNG Plugin for eclipse, since I was able to run my tests from the command line just fine.

The fix that seems to be working for me and others is just to clean your project (Project ? Clean). One person had to re-install the whole plugin.

How do I run a program with a different working directory from current, from Linux shell?

Call the program like this:

(cd /c; /a/helloworld)

The parentheses cause a sub-shell to be spawned. This sub-shell then changes its working directory to /c, then executes helloworld from /a. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from.

Error handling: To avoid running the program without having changed the directory, e.g. when having misspelled /c, make the execution of helloworld conditional:

(cd /c && /a/helloworld)

Reducing memory usage: To avoid having the subshell waste memory while hello world executes, call helloworld via exec:

(cd /c && exec /a/helloworld)

[Thanks to Josh and Juliano for giving tips on improving this answer!]

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

tl;dr the "standards" are a hodge-podge mess; it depends who you ask!

Overall, there appears to be no MIME type image/jpg. Yet, in practice, nearly all software handles image files named "*.jpg" just fine.
This particular topic is confusing because the varying association of file name extension associated to a MIME type depends which organization created the table of file name extensions to MIME types. In other words, file name extension .jpg could be many different things.

For example, here are three "complete lists" and one RFC that with varying JPEG Image format file name extensions and the associated MIME types.

These "complete lists" and RFC do not have MIME type image/jpg! But for MIME type image/jpeg some lists do have varying file name extensions (.jpeg, .jpg, …). Other lists do not mention image/jpeg.

Also, there are different types of JPEG Image formats (e.g. Progressive JPEG Image format, JPEG 2000, etcetera) and "JPEG Extensions" that may or may not overlap in file name extension and declared MIME type.

Another confusing thing is RFC 3745 does not appear to match IANA Media Types yet the same RFC is supposed to inform the IANA Media Types document. For example, in RFC 3745 .jpf is preferred file extension for image/jpx but in IANA Media Types the name jpf is not present (and that IANA document references RFC 3745!).

Another confusing thing is IANA Media Types lists "names" but does not list "file name extensions". This is on purpose, but confuses the endeavor of mapping file name extensions to MIME types.

Another confusing thing: is it "mime", or "MIME", or "MIME type", or "mime type", or "mime/type", or "media type"?


The most official seeming document by IANA is surprisingly inadequate. No MIME type is registered for file extension .jpg yet there exists the odd vnd.sealedmedia.softseal.jpg. File extension.JPEG is only known as a video type while file extension .jpeg is an image type (when did lowercase and uppercase letters start mattering!?). At the same time, jpeg2000 is type video yet RFC 3745 considers JPEG 2000 an image type! The IANA list seems to cater to company-specific jpeg formats (e.g. vnd.sealedmedia.softseal.jpg).


In summary...

Because of the prior confusions, it is difficult to find an industry-accepted canonical document that maps file name extensions to MIME types, particularly for the JPEG Image File Format.



Related question "List of ALL MimeTypes on the Planet, mapped to File Extensions?".

Basic example for sharing text or image with UIActivityViewController in Swift

Just as a note you can also use this for iPads:

activityViewController.popoverPresentationController?.sourceView = sender

So the popover pops from the sender (the button in that case).

Error: unmappable character for encoding UTF8 during maven compilation

This happens in the following scenario: When working on Windows, the IDE is more than likely configured to edit files in Cp1252, which is a Microsoft adaptation of latin-11. The developer checks in, and the Continuous Integration server (usually running on Linux, which nowadays is all utf8) picks up the file, and tries to compile as a UTF-8 file, hence the warning.

Try changing the encoding to cp1252. This works. To avoid future problems of this kind, use the same encoding on all the developer machines.

Good luck...

Returning data from Axios API

axiosTest() is firing asynchronously and not being waited for.

A then() function needs to be hooked up afterwards in order to capture the response variable (axiosTestData).

See Promise for more info.

See Async to level up.

_x000D_
_x000D_
// Dummy Url._x000D_
const url = 'https://jsonplaceholder.typicode.com/posts/1'_x000D_
_x000D_
// Axios Test._x000D_
const axiosTest = axios.get_x000D_
_x000D_
// Axios Test Data._x000D_
axiosTest(url).then(function(axiosTestResult) {_x000D_
  console.log('response.JSON:', {_x000D_
    message: 'Request received',_x000D_
    data: axiosTestResult.data_x000D_
  })_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
_x000D_
_x000D_
_x000D_

How to get the top 10 values in postgresql?

For this you can use limit

select *
from scores
order by score desc
limit 10

If performance is important (when is it not ;-) look for an index on score.


Starting with version 8.4, you can also use the standard (SQL:2008) fetch first

select *
from scores
order by score desc
fetch first 10 rows only

As @Raphvanns pointed out, this will give you the first 10 rows literally. To remove duplicate values, you have to select distinct rows, e.g.

select distinct *
from scores
order by score desc
fetch first 10 rows only

SQL Fiddle

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

Running an outside program (executable) in Python?

Those whitespaces can really be a bother. Try os.chdir('C:/Documents\ and\ Settings/') followed by relative paths for os.system, subprocess methods, or whatever...

If best-effort attempts to bypass the whitespaces-in-path hurdle keep failing, then my next best suggestion is to avoid having blanks in your crucial paths. Couldn't you make a blanks-less directory, copy the crucial .exe file there, and try that? Are those havoc-wrecking space absolutely essential to your well-being...?

URL to load resources from the classpath in Java

You can also set the property programmatically during startup:

final String key = "java.protocol.handler.pkgs";
String newValue = "org.my.protocols";
if (System.getProperty(key) != null) {
    final String previousValue = System.getProperty(key);
    newValue += "|" + previousValue;
}
System.setProperty(key, newValue);

Using this class:

package org.my.protocols.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(final URL u) throws IOException {
        final URL resourceUrl = ClassLoader.getSystemClassLoader().getResource(u.getPath());
        return resourceUrl.openConnection();
    }
}

Thus you get the least intrusive way to do this. :) java.net.URL will always use the current value from the system properties.

How can I execute a PHP function in a form action?

Is it really a function call on the action attribute? or it should be on the onSUbmit attribute, because by convention action attribute needs a page/URL.

I think you should use AJAX with that,

There are plenty PHP AJAX Frameworks to choose from

http://www.phplivex.com/example/submitting-html-forms-with-ajax

http://www.xajax-project.org/en/docs-tutorials/learn-xajax-in-10-minutes/

ETC.

Or the classic way

http://www.w3schools.com/php/php_ajax_php.asp

I hope these links help

how to update the multiple rows at a time using linq to sql?

To update one column here are some syntax options:

Option 1

var ls=new int[]{2,3,4};
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>a.status=true);
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
     db.SomeTable
       .Where(x=>ls.Contains(x.friendid))
       .ToList()
       .ForEach(a=>a.status=true);

     db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
    }
    db.SubmitChanges();
}

Update

As requested in the comment it might make sense to show how to update multiple columns. So let's say for the purpose of this exercise that we want not just to update the status at ones. We want to update name and status where the friendid is matching. Here are some syntax options for that:

Option 1

var ls=new int[]{2,3,4};
var name="Foo";
using (var db=new SomeDatabaseContext())
{
    var some= db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList();
    some.ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 2

using (var db=new SomeDatabaseContext())
{
    db.SomeTable
        .Where(x=>ls.Contains(x.friendid))
        .ToList()
        .ForEach(a=>
                    {
                        a.status=true;
                        a.name=name;
                    }
                );
    db.SubmitChanges();
}

Option 3

using (var db=new SomeDatabaseContext())
{
    foreach (var some in db.SomeTable.Where(x=>ls.Contains(x.friendid)).ToList())
    {
        some.status=true;
        some.name=name;
    }
    db.SubmitChanges();
}

Update 2

In the answer I was using LINQ to SQL and in that case to commit to the database the usage is:

db.SubmitChanges();

But for Entity Framework to commit the changes it is:

db.SaveChanges()

How to declare a variable in a PostgreSQL query

Dynamic Config Settings

you can "abuse" dynamic config settings for this:

-- choose some prefix that is unlikely to be used by postgres
set session my.vars.id = '1';

select *
from person 
where id = current_setting('my.vars.id')::int;

Config settings are always varchar values, so you need to cast them to the correct data type when using them. This works with any SQL client whereas \set only works in psql

The above requires Postgres 9.2 or later.

For previous versions, the variable had to be declared in postgresql.conf prior to being used, so it limited its usability somewhat. Actually not the variable completely, but the config "class" which is essentially the prefix. But once the prefix was defined, any variable could be used without changing postgresql.conf

How can I close a browser window without receiving the "Do you want to close this window" prompt?

Create a JavaScript function

<script type="text/javascript">
    function closeme() {
        window.open('', '_self', '');
        window.close();
    }
</script>

Now write this code and call the above JavaScript function

<a href="Help.aspx" target="_blank" onclick="closeme();">Help</a>

Or simply:

<a href="" onclick="closeme();">close</a>

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

You can replace

document.getElementById(this.state.baction).addPrecent(10);

with

this.refs[this.state.baction].addPrecent(10);


  <Progressbar completed={25} ref="Progress1" id="Progress1"/>

Sorting arraylist in alphabetical order (case insensitive)

def  lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"]; 

println lst.sort { a, b -> a.compareToIgnoreCase b }

This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists

How can I replace newline or \r\n with <br/>?

nl2br() as you have it should work fine:

$description = nl2br($description);

It's more likely that the unclosed ' on the first line of your example code is causing your issue. Remove the ' after $description...

...$description');

"Unorderable types: int() < str()"

The issue here is that input() returns a string in Python 3.x, so when you do your comparison, you are comparing a string and an integer, which isn't well defined (what if the string is a word, how does one compare a string and a number?) - in this case Python doesn't guess, it throws an error.

To fix this, simply call int() to convert your string to an integer:

int(input(...))

As a note, if you want to deal with decimal numbers, you will want to use one of float() or decimal.Decimal() (depending on your accuracy and speed needs).

Note that the more pythonic way of looping over a series of numbers (as opposed to a while loop and counting) is to use range(). For example:

def main():
    print("Let me Retire Financial Calculator")
    deposit = float(input("Please input annual deposit in dollars: $"))
    rate = int(input ("Please input annual rate in percentage: %")) / 100
    time = int(input("How many years until retirement?"))
    value = 0
    for x in range(1, time+1):
        value = (value * rate) + deposit
        print("The value of your account after" + str(x) + "years will be $" + str(value))

Telnet is not recognized as internal or external command

You have to go to Control Panel>Programs>Turn Windows features on or off. Then, check "Telnet Client" and save the changes. You might have to wait about a few minutes before the change could take effect.

How do I set up Android Studio to work completely offline?

Android Studio 1.3.1 has neither

Gradle > Global Gradle settings > Offline work

nor a

Compiler

menu. To access the compiler menu, go to :

File > Settings > Build, Execution & Deployment > Compiler > Compiler

and de-select Configure on demand

The above still uses data but is faster, I was able to load images and maps. However, in addition, if you want to be completely offline, you need to do the following:

 File -> Settings ->Build, Execution,Deployment -> Build Tools -> Gradle -> 

check Offline work

Click the OK button.

For Android Studio 2.0 it is the same procedure.

How to read file using NPOI

It might be helpful to rely on the Workbook factory to instantiate the workbook object since the factory method will do the detection of xls or xlsx for you. Reference: http://apache-poi.1045710.n5.nabble.com/How-to-check-for-valid-excel-files-using-POI-without-checking-the-file-extension-td2341055.html

IWorkbook workbook = WorkbookFactory.Create(inputStream);

If you're not sure of the Sheet's name but you are sure of the index (0 based), you can grab the sheet like this:

ISheet sheet = workbook.GetSheetAt(sheetIndex);

You can then iterate through the rows using code supplied by the accepted answer from mj82

.gitignore exclude folder but include specific subfolder

Commit 59856de from Karsten Blees (kblees) for Git 1.9/2.0 (Q1 2014) clarifies that case:

gitignore.txt: clarify recursive nature of excluded directories

An optional prefix "!" which negates the pattern; any matching file excluded by a previous pattern will become included again.

It is not possible to re-include a file if a parent directory of that file is excluded. (*)
(*: unless certain conditions are met in git 2.8+, see below)
Git doesn't list excluded directories for performance reasons, so any patterns on contained files have no effect, no matter where they are defined.

Put a backslash ("\") in front of the first "!" for patterns that begin with a literal "!", for example, "\!important!.txt".

Example to exclude everything except a specific directory foo/bar (note the /* - without the slash, the wildcard would also exclude everything within foo/bar):

 --------------------------------------------------------------
     $ cat .gitignore
     # exclude everything except directory foo/bar
     /*
     !/foo
     /foo/*
     !/foo/bar
 --------------------------------------------------------------

In your case:

application/*
!application/**/
application/language/*
!application/language/**/
!application/language/gr/**

You must white-list folders first, before being able to white-list files within a given folder.


Update Feb/March 2016:

Note that with git 2.9.x/2.10 (mid 2016?), it might be possible to re-include a file if a parent directory of that file is excluded if there is no wildcard in the path re-included.

Nguy?n Thái Ng?c Duy (pclouds) is trying to add this feature:

So with git 2.9+, this could have actually worked, but was ultimately reverted:

application/
!application/language/gr/

What exactly are DLL files, and how do they work?

According to Microsoft

(DLL) Dynamic link libraries are files that contain data, code, or resources needed for the running of applications. These are files that are created by the windows ecosystem and can be shared between two or more applications.

When a program or software runs on Windows, much of how the application works depends on the DLL files of the program. For instance, if a particular application had several modules, then how each module interacts with each other is determined by the Windows DLL files.

If you want detailed explanation, check these useful resources

What are dll files , About Dll files

How to set DataGrid's row Background, based on a property value using data bindings

The same can be done without DataTrigger too:

 <DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
             <Setter.Value>
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                     <Binding.ConverterParameter>
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>
                         </x:Array>
                     </Binding.ConverterParameter>
                 </Binding>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.RowStyle>

Where BooleanToBrushConverter is the following class:

public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
        {
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
        }
        else
        {
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How to calculate UILabel height dynamically?

CGSize maxSize = CGSizeMake(lbl.frame.size.width, CGFLOAT_MAX);
CGSize requiredSize = [lbl sizeThatFits:maxSize];
CGFloat height=requiredSize.height

Getting Java version at runtime

Here's the implementation in JOSM:

/**
 * Returns the Java version as an int value.
 * @return the Java version as an int value (8, 9, etc.)
 * @since 12130
 */
public static int getJavaVersion() {
    String version = System.getProperty("java.version");
    if (version.startsWith("1.")) {
        version = version.substring(2);
    }
    // Allow these formats:
    // 1.8.0_72-ea
    // 9-ea
    // 9
    // 9.0.1
    int dotPos = version.indexOf('.');
    int dashPos = version.indexOf('-');
    return Integer.parseInt(version.substring(0,
            dotPos > -1 ? dotPos : dashPos > -1 ? dashPos : 1));
}

Conditionally change img src based on model data

Instead of src you need ng-src.

AngularJS views support binary operators

condition && true || false

So your img tag would look like this

<img ng-src="{{interface == 'UP' && 'green-checkmark.png' || 'big-black-X.png'}}"/>

Note : the quotes (ie 'green-checkmark.png') are important here. It won't work without quotes.

plunker here (open dev tools to see the produced HTML)

How do I install Eclipse with C++ in Ubuntu 12.10 (Quantal Quetzal)?

There is a package called eclipse-cdt in the Ubuntu 12.10 repositories, this is what you want. If you haven't got g++ already, you need to install that as well, so all you need is:

sudo apt-get install eclipse eclipse-cdt g++

Whether you messed up your system with your previous installation attempts depends heavily on how you did it. If you did it the safe way for trying out new packages not from repositories (i.e., only installed in your home folder, no sudos blindly copied from installation manuals...) you're definitely fine. Otherwise, you may well have thousands of stray files all over your file system now. In that case, run all uninstall scripts you can find for the things you installed, then install using apt-get and hope for the best.

What is the App_Data folder used for in Visual Studio?

It's a place to put an embedded database, such as Sql Server Express, Access, or SQLite.

How to prevent scrollbar from repositioning web page?

Expanding on the answer using this:

body {
    width: calc(100vw - 17px);
}

One commentor suggested adding left-padding as well to maintain the centering:

body {
    padding-left: 17px;
    width: calc(100vw - 17px);
}

But then things don't look correct if your content is wider than the viewport. To fix that, you can use media queries, like this:

@media screen and (min-width: 1058px) {
    body {
        padding-left: 17px;
        width: calc(100vw - 17px);
    }
}

Where the 1058px = content width + 17 * 2

This lets a horizontal scrollbar handle the x overflow and keeps the centered content centered when the viewport is wide enough to contain your fixed-width content

Difference between "managed" and "unmanaged"

This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.

Error: the entity type requires a primary key

Removed and added back in the table using Scaffold-DbContext and the error went away

What characters are forbidden in Windows and Linux directory names?

A “comprehensive guide” of forbidden filename characters is not going to work on Windows because it reserves filenames as well as characters. Yes, characters like * " ? and others are forbidden, but there are a infinite number of names composed only of valid characters that are forbidden. For example, spaces and dots are valid filename characters, but names composed only of those characters are forbidden.

Windows does not distinguish between upper-case and lower-case characters, so you cannot create a folder named A if one named a already exists. Worse, seemingly-allowed names like PRN and CON, and many others, are reserved and not allowed. Windows also has several length restrictions; a filename valid in one folder may become invalid if moved to another folder. The rules for naming files and folders are on the Microsoft docs.

You cannot, in general, use user-generated text to create Windows directory names. If you want to allow users to name anything they want, you have to create safe names like A, AB, A2 et al., store user-generated names and their path equivalents in an application data file, and perform path mapping in your application.

If you absolutely must allow user-generated folder names, the only way to tell if they are invalid is to catch exceptions and assume the name is invalid. Even that is fraught with peril, as the exceptions thrown for denied access, offline drives, and out of drive space overlap with those that can be thrown for invalid names. You are opening up one huge can of hurt.

What exactly are iterator, iterable, and iteration?

Before dealing with the iterables and iterator the major factor that decide the iterable and iterator is sequence

Sequence: Sequence is the collection of data

Iterable: Iterable are the sequence type object that support __iter__ method.

Iter method: Iter method take sequence as an input and create an object which is known as iterator

Iterator: Iterator are the object which call next method and transverse through the sequence. On calling the next method it returns the object that it traversed currently.

example:

x=[1,2,3,4]

x is a sequence which consists of collection of data

y=iter(x)

On calling iter(x) it returns a iterator only when the x object has iter method otherwise it raise an exception.If it returns iterator then y is assign like this:

y=[1,2,3,4]

As y is a iterator hence it support next() method

On calling next method it returns the individual elements of the list one by one.

After returning the last element of the sequence if we again call the next method it raise an StopIteration error

example:

>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
StopIteration

How to get label text value form a html page?

For cases where the data element is inside the label like in this example:

<label for="subscription">Subscription period
    <select id='subscription' name='subscription'>
        <option></option>
        <option>1 year</option>
        <option>2 years</option>
        <option>3 years</option>
    </select>
</label>

all the previous answers will give an unexpected result:

"Subscription period


                    1 year
                    2 years
                    3 years

            "

While the expected result would be:

"Subscription period"

So, the correct solution will be like this:

const label = document.getElementById('yourLableId');
const labelText = Array.prototype.filter
    .call(label.childNodes, x => x.nodeName === "#text")
    .map(x => x.textContent)
    .join(" ")
    .trim();

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

How to link a folder with an existing Heroku app

Heroku links your projects based on the heroku git remote (and a few other options, see the update below). To add your Heroku remote as a remote in your current repository, use the following command:

git remote add heroku [email protected]:project.git

where project is the name of your Heroku project (the same as the project.heroku.com subdomain). Once you've done so, you can use the heroku xxxx commands (assuming you have the Heroku Toolbelt installed), and can push to Heroku as usual via git push heroku master. As a shortcut, if you're using the command line tool, you can type:

heroku git:remote -a project

where, again, project is the name of your Heroku project (thanks, Colonel Panic). You can name the Git remote anything you want by passing -r remote_name.

[Update]

As mentioned by Ben in the comments, the remote doesn't need to be named heroku for the gem commands to work. I checked the source, and it appears it works like this:

  1. If you specify an app name via the --app option (e.g. heroku info --app myapp), it will use that app.
  2. If you specify a Git remote name via the --remote option (e.g. heroku info --remote production), it will use the app associated with that Git remote.
  3. If you specify no option and you have heroku.remote set in your Git config file, it will use the app associated with that remote (for example, to set the default remote to "production" use git config heroku.remote production in your repository, and Heroku will run git config heroku.remote to read the value of this setting)
  4. If you specify no option, the gem finds no configuration in your .git/config file, and the gem only finds one remote in your Git remotes that has "heroku.com" in the URL, it will use that remote.
  5. If none of these work, it raises an error instructing you to pass --app to your command.

How to include route handlers in multiple files in Express?

you can put all route functions in other files(modules) , and link it to the main server file. in the main express file, add a function that will link the module to the server:

   function link_routes(app, route_collection){
       route_collection['get'].forEach(route => app.get(route.path, route.func));
       route_collection['post'].forEach(route => app.post(route.path, route.func));
       route_collection['delete'].forEach(route => app.delete(route.path, route.func));
       route_collection['put'].forEach(route => app.put(route.path, route.func));
   }

and call that function for each route model:

link_routes(app, require('./login.js'))

in the module files(for example - login.js file), define the functions as usual:

const login_screen = (req, res) => {
    res.sendFile(`${__dirname}/pages/login.html`);
};

const forgot_password = (req, res) => {
    console.log('we will reset the password here')
}

and export it with the request method as a key and the value is an array of objects, each with path and function keys.

module.exports = {
   get: [{path:'/',func:login_screen}, {...} ],
   post: [{path:'/login:forgotPassword', func:forgot_password}]
};   

Integer division with remainder in JavaScript?

This will always truncate towards zero. Not sure if it is too late, but here it goes:

function intdiv(dividend, divisor) { 
    divisor = divisor - divisor % 1;
    if (divisor == 0) throw new Error("division by zero");
    dividend = dividend - dividend % 1;
    var rem = dividend % divisor;
    return { 
        remainder: rem, 
        quotient: (dividend - rem) / divisor
    };
}

Android ADB doesn't see device

On Windows it is most probably that the device drivers are not installed properly.

First, install Google USB Driver from Android SDK Manager.

Then, go to Start, right-click on My Computer, select Properties and go to Device Manager on the left. Locate you device under Other Devices (Unknown devices, USB Devices). Right-click on it and select Properties. Navigate to Driver tab. Select Update Driver and then Browse my computer for driver software. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver directory. Windows should find and install drivers there. Then run adb kill-server. Next time you do adb devices the device should be in the list.

HAX kernel module is not installed

After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)

How is VIP swapping + CNAMEs better than IP swapping + A records?

A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

One-to-one: Use a foreign key to the referenced table:

student: student_id, first_name, last_name, address_id
address: address_id, address, city, zipcode, student_id # you can have a
                                                        # "link back" if you need

You must also put a unique constraint on the foreign key column (addess.student_id) to prevent multiple rows in the child table (address) from relating to the same row in the referenced table (student).

One-to-many: Use a foreign key on the many side of the relationship linking back to the "one" side:

teachers: teacher_id, first_name, last_name # the "one" side
classes:  class_id, class_name, teacher_id  # the "many" side

Many-to-many: Use a junction table (example):

student: student_id, first_name, last_name
classes: class_id, name, teacher_id
student_classes: class_id, student_id     # the junction table

Example queries:

 -- Getting all students for a class:

    SELECT s.student_id, last_name
      FROM student_classes sc 
INNER JOIN students s ON s.student_id = sc.student_id
     WHERE sc.class_id = X

 -- Getting all classes for a student: 

    SELECT c.class_id, name
      FROM student_classes sc 
INNER JOIN classes c ON c.class_id = sc.class_id
     WHERE sc.student_id = Y

Remove commas from the string using JavaScript

Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:

const numFormatter = new Intl.NumberFormat('en-US', {
  style: "decimal",
  maximumFractionDigits: 2
})

// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123

// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24

// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN

// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN

Use the international date local via format. This cleans up any bad inputs, if there is one it returns a string of NaN you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace.

ParseFloat converts the this type definition from string to number

If you use React, this is what your calculate function could look like:

updateCalculationInput = (e) => {
    let value;
    value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
    if(value === 'NaN') return; // locale returns string of NaN if fail
    value = value.replace(/,/g, ""); // remove commas
    value = parseFloat(value); // now parse to float should always be clean input

    // Do the actual math and setState calls here
}

Loading/Downloading image from URL on Swift

Swift 4: A simple loader for small images (ex: thumbnails) that uses NSCache and always runs on the main thread:

class ImageLoader {

  private static let cache = NSCache<NSString, NSData>()

  class func image(for url: URL, completionHandler: @escaping(_ image: UIImage?) -> ()) {

    DispatchQueue.global(qos: DispatchQoS.QoSClass.background).async {

      if let data = self.cache.object(forKey: url.absoluteString as NSString) {
        DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
        return
      }

      guard let data = NSData(contentsOf: url) else {
        DispatchQueue.main.async { completionHandler(nil) }
        return
      }

      self.cache.setObject(data, forKey: url.absoluteString as NSString)
      DispatchQueue.main.async { completionHandler(UIImage(data: data as Data)) }
    }
  }

}

Usage:

ImageLoader.image(for: imageURL) { image in
  self.imageView.image = image
}

Naming Conventions: What to name a boolean variable?

A simple semantic name would be last. This would allow code always positive code like:

if (item.last)
    ...

do {
   ...
} until (item.last);

Using "&times" word in html changes to ×

You need to escape:

<div class="test">&amp;times</div>

And then read the value using text() to get the unescaped value:

alert($(".test").text()); // outputs: &times

Where is the Docker daemon log?

If your OS is using systemd then you can view docker daemon log with:

sudo journalctl -fu docker.service

How to update a claim in ASP.NET Identity?

    if (HttpContext.User.Identity is ClaimsIdentity identity)
        {
            identity.RemoveClaim(identity.FindFirst("userId"));
            identity.AddClaim(new Claim("userId", userInfo?.id.ToString()));
            await HttpContext.SignInAsync(
                CookieAuthenticationDefaults.AuthenticationScheme,
                new ClaimsPrincipal(HttpContext.User.Identity));
        }

push() a two-dimensional array

var r = 3; //start from rows 3
var c = 5; //start from col 5

var rows = 8;

var cols = 7;


for (var i = 0; i < rows; i++)

{

 for (var j = 0; j < cols; j++)

 {
    if(j <= c && i <= r) {
      myArray[i][j] = 1;
    } else {
      myArray[i][j] = 0;
    }
}

}

How to modify memory contents using GDB?

Expanding on the answers provided here.

You can just do set idx = 1 to set a variable, but that syntax is not recommended because the variable name may clash with a set sub-command. As an example set w=1 would not be valid.

This means that you should prefer the syntax: set variable idx = 1 or set var idx = 1.

Last but not least, you can just use your trusty old print command, since it evaluates an expression. The only difference being that he also prints the result of the expression.

(gdb) p idx = 1
$1 = 1

You can read more about gdb here.

How to get just numeric part of CSS property with jQuery?

$(this).css('marginBottom').replace('px','')

How to efficiently check if variable is Array or Object (in NodeJS & V8)?

If you know that a parameter will definitely be either an array or an object, it may be easier to check for an array compared to checking for an object with something like this.

function myIsArray (arr) {
    return (arr.constructor === Array);
}

How to update attributes without validation

All the validation from model are skipped when we use validate: false

user = User.new(....)
user.save(validate: false)

Mysql command not found in OS X 10.7

I had same issue after installing mariadb via HomeBrew, brew doctor suggested to run brew link mariadb - which fixed the issue.

What is a non-capturing group in regular expressions?

One interesting thing that I came across is the fact that you can have a capturing group inside a non-capturing group. Have a look at below regex for matching web urls:

var parse_url_regex = /^(?:([A-Za-z]+):)(\/{0,3})([0-9.\-A-Za-z]+)(?::(\d+))?(?:\/([^?#]*))?(?:\?([^#]*))?(?:#(.*))?$/;

Input url string:

var url = "http://www.ora.com:80/goodparts?q#fragment";

The first group in my regex (?:([A-Za-z]+):) is a non-capturing group which matches the protocol scheme and colon : character i.e. http: but when I was running below code, I was seeing the 1st index of the returned array was containing the string http when I was thinking that http and colon : both will not get reported as they are inside a non-capturing group.

console.debug(parse_url_regex.exec(url));

enter image description here

I thought if the first group (?:([A-Za-z]+):) is a non-capturing group then why it is returning http string in the output array.

So if you notice that there is a nested group ([A-Za-z]+) inside the non-capturing group. That nested group ([A-Za-z]+) is a capturing group (not having ?: at the beginning) in itself inside a non-capturing group (?:([A-Za-z]+):). That's why the text http still gets captured but the colon : character which is inside the non-capturing group but outside the capturing group doesn't get reported in the output array.

Trying to check if username already exists in MySQL database using PHP

$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")

Use prepared statements, do not use mysql as it is deprecated.

// check if name is taken already
$stmt = $link->prepare("SELECT username FROM users WHERE username = :username");
$stmt->execute([
    'username' => $username
]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);

if (isset($user) && !empty($user)){
    // Username already taken
}

Relation between CommonJS, AMD and RequireJS?

Quoting

AMD:

  • One browser-first approach
  • Opting for asynchronous behavior and simplified backwards compatibility
  • It doesn't have any concept of File I/O.
  • It supports objects, functions, constructors, strings, JSON and many other types of modules.

CommonJS:

  • One server-first approach
  • Assuming synchronous behavior
  • Cover a broader set of concerns such as I/O, File system, Promises and more.
  • Supports unwrapped modules, it can feel a little more close to the ES.next/Harmony specifications, freeing you of the define() wrapper that AMD enforces.
  • Only support objects as modules.

How set the android:gravity to TextView from Java side in Android

Use this code

        TextView textView = new TextView(YourActivity.this);
        textView.setGravity(Gravity.CENTER | Gravity.TOP);
        textView.setText("some text");

How do I validate a date string format in python?

I think the full validate function should look like this:

from datetime import datetime

def validate(date_text):
    try:
        if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
            raise ValueError
        return True
    except ValueError:
        return False

Executing just

datetime.strptime(date_text, "%Y-%m-%d") 

is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example

datetime.strptime("2016-5-3", '%Y-%m-%d')

will be executed without errors.

You are trying to add a non-nullable field 'new_field' to userprofile without a default

If you are early into the development cycle you can try this -

Remove/comment that model and all its usages. Apply migrations. That would delete that model and then add the model again, run migrations and you have a clean model with the new field added.

No converter found capable of converting from type to type

Return ABDeadlineType from repository:

public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
    List<ABDeadlineType> findAllSummarizedBy();
}

and then convert to DeadlineType. Manually or use mapstruct.

Or call constructor from @Query annotation:

public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {

    @Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
    List<DeadlineType> findAllSummarizedBy();
}

Or use @Projection:

@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {

    @Value("#{target.id}")
    String getId();

    @Value("#{target.code}")
    String getText();

}

Update: Spring can work without @Projection annotation:

public interface DeadlineType {
    String getId();    
    String getText();
}

What is the simplest C# function to parse a JSON string into an object?

DataContractJsonSerializer serializer = 
    new DataContractJsonSerializer(typeof(YourObjectType));

YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream);

You could also use the JavaScriptSerializer, but DataContractJsonSerializer is supposedly better able to handle complex types.

Oddly enough JavaScriptSerializer was once deprecated (in 3.5) and then resurrected because of ASP.NET MVC (in 3.5 SP1). That would definitely be enough to shake my confidence and lead me to use DataContractJsonSerializer since it is hard baked for WCF.

Fastest way to add an Item to an Array

Case C) is the fastest. Having this as an extension:

Public Module MyExtensions
    <Extension()> _
    Public Sub Add(Of T)(ByRef arr As T(), item As T)
        Array.Resize(arr, arr.Length + 1)
        arr(arr.Length - 1) = item
    End Sub
End Module

Usage:

Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)

' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec

Laravel blank white screen

Sometimes in route.php you may have

Route::get('/{id}', 'Controller@show'..

written before

Route::get('/add', 'Controller@add'..

It can be empty method Controller::show() when you begin to develop your controller from scratch. In this case you will get empty blank page when requesting /add url. It happens because the request was handled by /{id} route, and its method returns nothing.

Just try to place /add route before /{id}

Failed to allocate memory: 8

I had the same issue but before I got the issue it asked me to capture a video source.

I disabled the camera support and I was able to use 1024MB of RAM.

Using Windows 64bit, Xoom (Android 3.0).

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

How to set border on jPanel?

JPanel jPanel = new JPanel();

jPanel.setBorder(BorderFactory.createLineBorder(Color.black));

Here not only jPanel, you can add border to any Jcomponent

How do you read from stdin?

You can read from stdin and then store inputs into "data" as follows:

data = ""
for line in sys.stdin:
    data += line

jQuery: How to detect window width on the fly?

Put your if condition inside resize function:

var windowsize = $(window).width();

$(window).resize(function() {
  windowsize = $(window).width();
  if (windowsize > 440) {
    //if the window is greater than 440px wide then turn on jScrollPane..
      $('#pane1').jScrollPane({
         scrollbarWidth:15, 
         scrollbarMargin:52
      });
  }
});

HTML: how to force links to open in a new tab, not new window

I didn't try this but I think it works in all browsers:

target="_parent"

Android - java.lang.SecurityException: Permission Denial: starting Intent

I was facing this issue on a react-native project and it came after adding a splash screen activity and making it the launcher activity.

This is the change i made in my android manifest XML file on the MainActivity configuration.

_x000D_
_x000D_
<activity_x000D_
        android:name=".MainActivity"_x000D_
        android:label="@string/app_name"_x000D_
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
        android:windowSoftInputMode="adjustResize"/>_x000D_
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
_x000D_
_x000D_
_x000D_

I added the android:exported=true and the activity configuration looked like this.

_x000D_
_x000D_
 <activity_x000D_
        android:name=".MainActivity"_x000D_
        android:exported="true"_x000D_
        android:label="@string/app_name"_x000D_
        android:configChanges="keyboard|keyboardHidden|orientation|screenSize"_x000D_
        android:windowSoftInputMode="adjustResize"/>_x000D_
      <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />_x000D_
   
_x000D_
_x000D_
_x000D_

Creating a config file in PHP

Well - it would be sort of difficult to store your database configuration data in a database - don't ya think?

But really, this is a pretty heavily opinionated question because any style works really and it's all a matter of preference. Personally, I'd go for a configuration variable rather than constants - generally because I don't like things in the global space unless necessary. None of the functions in my codebase should be able to easily access my database password (except my database connection logic) - so I'd use it there and then likely destroy it.

Edit: to answer your comment - none of the parsing mechanisms would be the fastest (ini, json, etc) - but they're also not the parts of your application that you'd really need to focus on optimizing since the speed difference would be negligible on such small files.

Pause in Python

One way is to leave a raw_input() at the end so the script waits for you to press Enter before it terminates.

Algorithm for solving Sudoku

I wrote a simple program that solved the easy ones. It took its input from a file which was just a matrix with spaces and numbers. The datastructure to solve it was just a 9 by 9 matrix of a bit mask. The bit mask would specify which numbers were still possible on a certain position. Filling in the numbers from the file would reduce the numbers in all rows/columns next to each known location. When that is done you keep iterating over the matrix and reducing possible numbers. If each location has only one option left you're done. But there are some sudokus that need more work. For these ones you can just use brute force: try all remaining possible combinations until you find one that works.

How to specify the download location with wget?

"-P" is the right option, please read on for more related information:

wget -nd -np -P /dest/dir --recursive http://url/dir1/dir2

Relevant snippets from man pages for convenience:

   -P prefix
   --directory-prefix=prefix
       Set directory prefix to prefix.  The directory prefix is the directory where all other files and subdirectories will be saved to, i.e. the top of the retrieval tree.  The default is . (the current directory).

   -nd
   --no-directories
       Do not create a hierarchy of directories when retrieving recursively.  With this option turned on, all files will get saved to the current directory, without clobbering (if a name shows up more than once, the
       filenames will get extensions .n).


   -np
   --no-parent
       Do not ever ascend to the parent directory when retrieving recursively.  This is a useful option, since it guarantees that only the files below a certain hierarchy will be downloaded.

Check if all checkboxes are selected

Alternatively, you could have also used every():

// Cache DOM Lookup
var abc = $(".abc");

// On Click
abc.on("click",function(){

    // Check if all items in list are selected
    if(abc.toArray().every(areSelected)){
        //do something
    }

    function areSelected(element, index, array){
        return array[index].checked;
    }
});

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

Color different parts of a RichTextBox string

Using Selection in WPF, aggregating from several other answers, no other code is required (except Severity enum and GetSeverityColor function)

 public void Log(string msg, Severity severity = Severity.Info)
    {
        string ts = "[" + DateTime.Now.ToString("HH:mm:ss") + "] ";
        string msg2 = ts + msg + "\n";
        richTextBox.AppendText(msg2);

        if (severity > Severity.Info)
        {
            int nlcount = msg2.ToCharArray().Count(a => a == '\n');
            int len = msg2.Length + 3 * (nlcount)+2; //newlines are longer, this formula works fine
            TextPointer myTextPointer1 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-len);
            TextPointer myTextPointer2 = richTextBox.Document.ContentEnd.GetPositionAtOffset(-1);

            richTextBox.Selection.Select(myTextPointer1,myTextPointer2);
            SolidColorBrush scb = new SolidColorBrush(GetSeverityColor(severity));
            richTextBox.Selection.ApplyPropertyValue(TextElement.BackgroundProperty, scb);

        }

        richTextBox.ScrollToEnd();
    }

Sending and Receiving SMS and MMS in Android (pre Kit Kat Android 4.4)

SmsListenerClass

public class SmsListener extends BroadcastReceiver {

static final String ACTION =
        "android.provider.Telephony.SMS_RECEIVED";

@Override
public void onReceive(Context context, Intent intent) {

    Log.e("RECEIVED", ":-:-" + "SMS_ARRIVED");

    // TODO Auto-generated method stub
    if (intent.getAction().equals(ACTION)) {

        Log.e("RECEIVED", ":-" + "SMS_ARRIVED");

        StringBuilder buf = new StringBuilder();
        Bundle bundle = intent.getExtras();
        if (bundle != null) {

            Object[] pdus = (Object[]) bundle.get("pdus");

            SmsMessage[] messages = new SmsMessage[pdus.length];
            SmsMessage message = null;

            for (int i = 0; i < messages.length; i++) {

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    String format = bundle.getString("format");
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i], format);
                } else {
                    messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
                }

                message = messages[i];
                buf.append("Received SMS from  ");
                buf.append(message.getDisplayOriginatingAddress());
                buf.append(" - ");
                buf.append(message.getDisplayMessageBody());
            }

            MainActivity inst = MainActivity.instance();
            inst.updateList(message.getDisplayOriginatingAddress(),message.getDisplayMessageBody());

        }

        Log.e("RECEIVED:", ":" + buf.toString());

        Toast.makeText(context, "RECEIVED SMS FROM :" + buf.toString(), Toast.LENGTH_LONG).show();

    }
}

Activity

@Override
public void onStart() {
    super.onStart();
    inst = this;
}

public static MainActivity instance() {
    return inst;
}

public void updateList(final String msg_from, String msg_body) {

    tvMessage.setText(msg_from + " :- " + msg_body);

    sendSMSMessage(msg_from, msg_body);

}

protected void sendSMSMessage(String phoneNo, String message) {

    try {
        SmsManager smsManager = SmsManager.getDefault();
        smsManager.sendTextMessage(phoneNo, null, message, null, null);
        Toast.makeText(getApplicationContext(), "SMS sent.", Toast.LENGTH_LONG).show();
    } catch (Exception e) {
        Toast.makeText(getApplicationContext(), "SMS faild, please try again.", Toast.LENGTH_LONG).show();
        e.printStackTrace();
    }
}

Manifest

<uses-permission android:name="android.permission.RECEIVE_SMS"/>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<receiver android:name=".SmsListener">
        <intent-filter>
            <action android:name="android.provider.Telephony.SMS_RECEIVED" />
        </intent-filter>
    </receiver>

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

Mocking methods of local scope objects with Mockito

No way. You'll need some dependency injection, i.e. instead of having the obj1 instantiated it should be provided by some factory.

MyObjectFactory factory;

public void setMyObjectFactory(MyObjectFactory factory)
{
  this.factory = factory;
}

void method1()
{
  MyObject obj1 = factory.get();
  obj1.method();
}

Then your test would look like:

@Test
public void testMethod1() throws Exception
{
  MyObjectFactory factory = Mockito.mock(MyObjectFactory.class);
  MyObject obj1 = Mockito.mock(MyObject.class);
  Mockito.when(factory.get()).thenReturn(obj1);
  
  // mock the method()
  Mockito.when(obj1.method()).thenReturn(Boolean.FALSE);

  SomeObject someObject = new SomeObject();
  someObject.setMyObjectFactory(factory);
  someObject.method1();

  // do some assertions
}

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

How to add items to a spinner in Android?

This code basically reads a JSON array object and convert each row into an option in the spinner that is passed as a parameter:

public ArrayAdapter<String> getArrayAdapterFromArrayListForSpinner(ArrayList<JSONObject> aArrayList, String aField)
{
    ArrayAdapter<String> aArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item);
    aArrayAdapter.setDropDownViewResource(R.layout.multiline_spinner_dropdown_item); //android.R.layout.simple_spinner_dropdown_item
    try {
        for (int i = 0; i < aArrayList.size(); i++)
        {
            aArrayAdapter.add(aArrayList.get(i).getString(aField)); 
        }
    } catch (JSONException e) {
        e.printStackTrace();
        ShowMessage("Error while reading the JSON list");
    }
    return aArrayAdapter;       
}

How to add leading zeros?

Here's a generalizable base R function:

pad_left <- function(x, len = 1 + max(nchar(x)), char = '0'){

    unlist(lapply(x, function(x) {
        paste0(
            paste(rep(char, len - nchar(x)), collapse = ''),
            x
        )
    }))
}

pad_left(1:100)

I like sprintf but it comes with caveats like:

however the actual implementation will follow the C99 standard and fine details (especially the behaviour under user error) may depend on the platform

How to append something to an array?

If you're only appending a single variable, then push() works just fine. If you need to append another array, use concat():

_x000D_
_x000D_
var ar1 = [1, 2, 3];_x000D_
var ar2 = [4, 5, 6];_x000D_
_x000D_
var ar3 = ar1.concat(ar2);_x000D_
_x000D_
alert(ar1);_x000D_
alert(ar2);_x000D_
alert(ar3);
_x000D_
_x000D_
_x000D_

The concat does not affect ar1 and ar2 unless reassigned, for example:

_x000D_
_x000D_
var ar1 = [1, 2, 3];_x000D_
var ar2 = [4, 5, 6];_x000D_
_x000D_
ar1 = ar1.concat(ar2);_x000D_
alert(ar1);
_x000D_
_x000D_
_x000D_

Lots of great info here.

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How to get the number of columns in a matrix?

Use the size() function.

>> size(A,2)

Ans =

   3

The second argument specifies the dimension of which number of elements are required which will be '2' if you want the number of columns.

Official documentation.

How to correctly use the ASP.NET FileUpload control

I have noticed that when intellisence doesn't work for an object there is usually an error somewhere in the class above line you are working on.

The other option is that you didn't instantiated the FileUpload object as an instance variable. make sure the code:

FileUpload fileUpload = new FileUpload();

is not inside a function in your code behind.

Is there any way to do HTTP PUT in python

You should have a look at the httplib module. It should let you make whatever sort of HTTP request you want.

Binary Data Posting with curl

You don't need --header "Content-Length: $LENGTH".

curl --request POST --data-binary "@template_entry.xml" $URL

Note that GET request does not support content body widely.

Also remember that POST request have 2 different coding schema. This is first form:

  $ nc -l -p 6666 &
  $ curl  --request POST --data-binary "@README" http://localhost:6666

POST / HTTP/1.1
User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6
Host: localhost:6666
Accept: */*
Content-Length: 9309
Content-Type: application/x-www-form-urlencoded
Expect: 100-continue

.. -*- mode: rst; coding: cp1251; fill-column: 80 -*-
.. rst2html.py README README.html
.. contents::

You probably request this:

-F/--form name=content
           (HTTP) This lets curl emulate a filled-in form in
              which a user has pressed the submit button. This
              causes curl to POST data using the Content- Type
              multipart/form-data according to RFC2388. This
              enables uploading of binary files etc. To force the
              'content' part to be a file, prefix the file name
              with an @ sign. To just get the content part from a
              file, prefix the file name with the symbol <. The
              difference between @ and < is then that @ makes a
              file get attached in the post as a file upload,
              while the < makes a text field and just get the
              contents for that text field from a file.

jQuery UI Dialog OnBeforeUnload

You can also make an exception for leaving the page via submitting a particular form:

$(window).bind('beforeunload', function(){
    return "Do you really want to leave now?";
});

$("#form_id").submit(function(){
    $(window).unbind("beforeunload");
});

How do I make a comment in a Dockerfile?

Use the # syntax for comments

From: https://docs.docker.com/engine/reference/builder/#format

# My comment here
RUN echo 'we are running some cool things'

$lookup on ObjectId's in an array

I have to disagree, we can make $lookup work with IDs array if we preface it with $match stage.

_x000D_
_x000D_
// replace IDs array with lookup results_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
            localField: "products",_x000D_
            foreignField: "_id",_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

It becomes more complicated if we want to pass the lookup result to a pipeline. But then again there's a way to do so (already suggested by @user12164):

_x000D_
_x000D_
// replace IDs array with lookup results passed to pipeline_x000D_
db.products.aggregate([_x000D_
    { $match: { products : { $exists: true } } },_x000D_
    {_x000D_
        $lookup: {_x000D_
            from: "products",_x000D_
             let: { products: "$products"},_x000D_
             pipeline: [_x000D_
                 { $match: { $expr: {$in: ["$_id", "$$products"] } } },_x000D_
                 { $project: {_id: 0} } // suppress _id_x000D_
             ],_x000D_
            as: "productObjects"_x000D_
        }_x000D_
    }_x000D_
])
_x000D_
_x000D_
_x000D_

How do you get the index of the current iteration of a foreach loop?

This way you can use the index and value using LINQ:

ListValues.Select((x, i) => new { Value = x, Index = i }).ToList().ForEach(element =>
    {
        // element.Index
        // element.Value

    });

Make Bootstrap's Carousel both center AND responsive?

Now (on Boostrap 3 and 4) its simply :

.carousel-inner img {
  margin: auto;
}

Vertically align text next to an image?

Using flex property in css.

To align text vertically center by using in flex using align-items:center; if you want to align text horizontally center by using in flex using justify-content:center;.

_x000D_
_x000D_
div{
  display: flex;
  align-items: center;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Using table-cell in css.

_x000D_
_x000D_
div{
  display: table;
}
div *{
  display: table-cell;
  vertical-align: middle;
}
_x000D_
<div>
  <img src="http://lorempixel.com/30/30/" alt="small img" />
  <span>It works.</span>
</div>
_x000D_
_x000D_
_x000D_

Succeeded installing but could not start apache 2.4 on my windows 7 system

The most likely culprit is Microsoft Internet Information Server. You can stop the service from the command line on Windows 7/Vista:

net stop was /y

or XP:

net stop iisadmin /y

read this http://www.sitepoint.com/unblock-port-80-on-windows-run-apache/

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

Adding git branch on the Bash command prompt

Follow the steps as below: (Linux)

Edit the file ~/.bashrc, to enter following lines at its end (In case, of Mac, file would be ~/.bash_profile)

# Git branch in prompt.
parse_git_branch() {
    git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "

Now, start the new terminal window, and try entering to any git-repo. The current branch would be shown, with the prompt.

4 More Info - MAC/Linux

Refresh Excel VBA Function Results

The Application.Volatile doesn't work for recalculating a formula with my own function inside. I use the following function: Application.CalculateFull

How do I get the current date and current time only respectively in Django?

import datetime

datetime.date.today()  # Returns 2018-01-15

datetime.datetime.now() # Returns 2018-01-15 09:00

Any shortcut to initialize all array elements to zero?

How it Reduces the Performance of your application....? Read Following.

In Java Language Specification the Default / Initial Value for any Object can be given as Follows.

For type byte, the default value is zero, that is, the value of (byte) is 0.

For type short, the default value is zero, that is, the value of (short) is 0.

For type int, the default value is zero, that is, 0.

For type long, the default value is zero, that is, 0L.

For type float, the default value is positive zero, that is, 0.0f.

For type double, the default value is positive zero, that is, 0.0d.

For type char, the default value is the null character, that is, '\u0000'.

For type boolean, the default value is false.

For all reference types, the default value is null.

By Considering all this you don't need to initialize with zero values for the array elements because by default all array elements are 0 for int array.

Because An array is a container object that holds a fixed number of values of a single type. Now the Type of array for you is int so consider the default value for all array elements will be automatically 0 Because it is holding int type.

Now consider the array for String type so that all array elements has default value is null.

Why don't do that......?

you can assign null value by using loop as you suggest in your Question.

int arr[] = new int[10];
for(int i=0;i<arr.length;i++)
    arr[i] = 0;

But if you do so then it will an useless loss of machine cycle. and if you use in your application where you have many arrays and you do that for each array then it will affect the Application Performance up-to considerable level.

The more use of machine cycle ==> More time to Process the data ==> Output time will be significantly increase. so that your application data processing can be considered as a low level(Slow up-to some Level).

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

Python Iterate Dictionary by Index

Some of the comments are right in saying that these answers do not correspond to the question.

One reason one might want to loop through a dictionary using "indexes" is for example to compute a distance matrix for a set of objects in a dictionary. To put it as an example (going a bit to the basics on the bullet below):

  • Assuming one have 1000 objects on a dictionary, the distance square matrix consider all combinations from one object to any other and so it would have dimensions of 1000x1000 elements. But if the distance from object 1 to object 2 is the same as from object 2 to object 1, one need to compute the distance only to less than half of the square matrix, since the diagonal will have distance 0 and the values are mirrored above and below the diagonal.

This is why most packages use a condensed distance matrix ( How does condensed distance matrix work? (pdist) )

But consider the case one is implementing the computation of a distance matrix, or any kind of permutation of the sort. In such case you need to skip the results from more than half of the cases. This means that a FOR loop that runs through all the dictionary is just hitting an IF and jumping to the next iteration without performing really any job most of the time. For large datasets this additional "IFs" and loops add up to a relevant amount on the processing time and could be avoided if, at each loop, one starts one "index" further on the dictionary.

Going than to the question, my conclusion right now is that the answer is NO. One has no way to directly access the dictionary values by any index except the key or an iterator.

I understand that most of the answers up to now applies different approaches to perform this task but really don't allow any index manipulation, that would be useful in a case such as exemplified.

The only alternative I see is to use a list or other variable as a sequential index to the dictionary. Here than goes an implementation to exemplify such case:

#!/usr/bin/python3

dishes = {'spam': 4.25, 'eggs': 1.50, 'sausage': 1.75, 'bacon': 2.00}
print("Dictionary: {}\n".format(dishes))

key_list = list(dishes.keys())
number_of_items = len(key_list)

condensed_matrix = [0]*int(round(((number_of_items**2)-number_of_items)/2,0))
c_m_index = 0

for first_index in range(0,number_of_items):
    for second_index in range(first_index+1,number_of_items):
        condensed_matrix[c_m_index] = dishes[key_list[first_index]] - dishes[key_list[second_index]]
        print("{}. {}-{} = {}".format(c_m_index,key_list[first_index],key_list[second_index],condensed_matrix[c_m_index]))
        c_m_index+=1

The output is:

Dictionary: {'spam': 4.25, 'eggs': 1.5, 'sausage': 1.75, 'bacon': 2.0}

0. spam-eggs = 2.75
1. spam-sausage = 2.5
2. spam-bacon = 2.25
3. eggs-sausage = -0.25
4. eggs-bacon = -0.5
5. sausage-bacon = -0.25

Its also worth mentioning that are packages such as intertools that allows one to perform similar tasks in a shorter format.

How to add an image in Tkinter?

It's a Python version problem. If you are using the latest, then your old syntax won't work and give you this error. Please follow @Josav09's code and you will be fine.

Error #2032: Stream Error

Just to clarify my comment (it's illegible in a single line)

I think the best answer is the comment by Mike Chambers in this link (http://www.judahfrangipane.com/blog/2007/02/15/error-2032-stream-error/) by Hunter McMillen.

A note from Mike Chambers:

If you run into this using URLLoader, listen for the:

flash.events.HTTPStatusEvent.HTTP_STATUS

and in AIR :

flash.events.HTTPStatusEvent.HTTP_RESPONSE_STATUS

It should give you some more information (such as the status code being returned from the server).

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

I'll try to give the benchmark of the three most common way (also mentioned above):

from timeit import repeat

setup = """
import numpy as np;
import random;
x = np.linspace(0,100);
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) * (x <= ub)]', 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'

for _ in range(3):
    for stmt in stmts:
        t = min(repeat(stmt, setup, number=100_000))
        print('%.4f' % t, stmt)
    print()

result:

0.4808 x[(x > lb) * (x <= ub)]
0.4726 x[(x > lb) & (x <= ub)]
0.4904 x[np.logical_and(x > lb, x <= ub)]

0.4725 x[(x > lb) * (x <= ub)]
0.4806 x[(x > lb) & (x <= ub)]
0.5002 x[np.logical_and(x > lb, x <= ub)]

0.4781 x[(x > lb) * (x <= ub)]
0.4336 x[(x > lb) & (x <= ub)]
0.4974 x[np.logical_and(x > lb, x <= ub)]

But, * is not supported in Panda Series, and NumPy Array is faster than pandas data frame (arround 1000 times slower, see number):

from timeit import repeat

setup = """
import numpy as np;
import random;
import pandas as pd;
x = pd.DataFrame(np.linspace(0,100));
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
"""
stmts = 'x[(x > lb) & (x <= ub)]', 'x[np.logical_and(x > lb, x <= ub)]'

for _ in range(3):
    for stmt in stmts:
        t = min(repeat(stmt, setup, number=100))
        print('%.4f' % t, stmt)
    print()

result:

0.1964 x[(x > lb) & (x <= ub)]
0.1992 x[np.logical_and(x > lb, x <= ub)]

0.2018 x[(x > lb) & (x <= ub)]
0.1838 x[np.logical_and(x > lb, x <= ub)]

0.1871 x[(x > lb) & (x <= ub)]
0.1883 x[np.logical_and(x > lb, x <= ub)]

Note: adding one line of code x = x.to_numpy() will need about 20 µs.

For those who prefer %timeit:

import numpy as np
import random
lb, ub = np.sort([random.random() * 100, random.random() * 100]).tolist()
lb, ub
x = pd.DataFrame(np.linspace(0,100))

def asterik(x):
    x = x.to_numpy()
    return x[(x > lb) * (x <= ub)]

def and_symbol(x):
    x = x.to_numpy()
    return x[(x > lb) & (x <= ub)]

def numpy_logical(x):
    x = x.to_numpy()
    return x[np.logical_and(x > lb, x <= ub)]

for i in range(3):
    %timeit asterik(x)
    %timeit and_symbol(x)
    %timeit numpy_logical(x)
    print('\n')

result:

23 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
35.6 µs ± 9.53 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
31.3 µs ± 8.9 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)


21.4 µs ± 3.35 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
21.9 µs ± 1.02 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
21.7 µs ± 500 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)


25.1 µs ± 3.71 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
36.8 µs ± 18.3 µs per loop (mean ± std. dev. of 7 runs, 100000 loops each)
28.2 µs ± 5.97 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

SQL Server : Transpose rows to columns

Another option that may be suitable in this situation is using XML

The XML option to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation. 

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

Vertical expansion

Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

Horizontal expansion

Unlike the PIVOT, newly added documents can be displayed without altering the script.

Performance breakdown

In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

"Auth Failed" error with EGit and GitHub

Have you tried to use the ssh protocol instead on git+ssh ? I've got the same problem, and that solved it, even though official documentation tells to use git+ssh

Equivalent of "continue" in Ruby

next

also, look at redo which redoes the current iteration.

How do I get extra data from intent on Android?

Just a suggestion:

Instead of using "id" or "name" in your i.putExtra("id".....), I would suggest, when it makes sense, using the current standard fields that can be used with putExtra(), i.e. Intent.EXTRA_something.

A full list can be found at Intent (Android Developers).

How to convert unix timestamp to calendar date moment.js

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment(value, 'MM/DD/YYYY', false).calendar(); 
    alert(dateString);
});

There is a strict mode and a Forgiving mode.

While strict mode works better in most situations, forgiving mode can be very useful when the format of the string being passed to moment may vary.

In a later release, the parser will default to using strict mode. Strict mode requires the input to the moment to exactly match the specified format, including separators. Strict mode is set by passing true as the third parameter to the moment function.

A common scenario where forgiving mode is useful is in situations where a third party API is providing the date, and the date format for that API could change. Suppose that an API starts by sending dates in 'YYYY-MM-DD' format, and then later changes to 'MM/DD/YYYY' format.

In strict mode, the following code results in 'Invalid Date' being displayed:

moment('01/12/2016', 'YYYY-MM-DD', true).format()
"Invalid date"

In forgiving mode using a format string, you get a wrong date:

moment('01/12/2016', 'YYYY-MM-DD').format()
"2001-12-20T00:00:00-06:00"

another way would be

$(document).ready(function() {
    var value = $("#unixtime").val(); //this retrieves the unix timestamp
    var dateString = moment.unix(value).calendar(); 
    alert(dateString);
});

Assign variable value inside if-statement

Because I know it's possible in while conditions, but I'm not sure if I'm doing it wrong for the if-statement or if it's just not possible.

HINT: what type while and if condition should be ??

If it can be done with while, it can be done with if statement as weel, as both of them expect a boolean condition.

How to get multiple selected values of select box in php?

If you want PHP to treat $_GET['select2'] as an array of options just add square brackets to the name of the select element like this: <select name="select2[]" multiple …

Then you can acces the array in your PHP script

<?php
header("Content-Type: text/plain");

foreach ($_GET['select2'] as $selectedOption)
    echo $selectedOption."\n";

$_GET may be substituted by $_POST depending on the <form method="…" value.

How to hide a <option> in a <select> menu with CSS?

// Simplest way

var originalContent = $('select').html();

$('select').change(function() {
    $('select').html(originalContent); //Restore Original Content
    $('select option[myfilter=1]').remove(); // Filter my options
});

What does "opt" mean (as in the "opt" directory)? Is it an abbreviation?

In the old days, "/opt" was used by UNIX vendors like AT&T, Sun, DEC and 3rd-party vendors to hold "Option" packages; i.e. packages that you might have paid extra money for. I don't recall seeing "/opt" on Berkeley BSD UNIX. They used "/usr/local" for stuff that you installed yourself.

But of course, the true "meaning" of the different directories has always been somewhat vague. That is arguably a good thing, because if these directories had precise (and rigidly enforced) meanings you'd end up with a proliferation of different directory names.

According to the Filesystem Hierarchy Standard, /opt is for "the installation of add-on application software packages". /usr/local is "for use by the system administrator when installing software locally".

Do you use NULL or 0 (zero) for pointers in C++?

There are a few arguments (one of which is relatively recent) which I believe contradict Bjarne's position on this.

  1. Documentation of intent

    Using NULL allows for searches on its use and it also highlights that the developer wanted to use a NULL pointer, irrespective of whether it is being interpreted by the compiler as NULL or not.

  2. Overload of pointer and 'int' is relatively rare

    The example that everybody quotes is:

     void foo(int*);
     void foo (int);
    
     void bar() {
       foo (NULL);  // Calls 'foo(int)'
     }
    

    However, at least in my opinion, the problem with the above is not that we're using NULL for the null pointer constant: it's that we have overloads of foo() which take very different kinds of arguments. The parameter must be an int too, as any other type will result in an ambiguous call and so generate a helpful compiler warning.

  3. Analysis tools can help TODAY!

    Even in the absence of C++0x, there are tools available today that verify that NULL is being used for pointers, and that 0 is being used for integral types.

  4. C++ 11 will have a new std::nullptr_t type.

    This is the newest argument to the table. The problem of 0 and NULL is being actively addressed for C++0x, and you can guarantee that for every implementation that provides NULL, the very first thing that they will do is:

     #define NULL  nullptr
    

    For those who use NULL rather than 0, the change will be an improvement in type-safety with little or no effort - if anything it may also catch a few bugs where they've used NULL for 0. For anybody using 0 today... well, hopefully they have a good knowledge of regular expressions...

force browsers to get latest js and css files in asp.net application

Starting from the above answer I modified a little bit the code to make the helper work with CSS files too and add a version every time when you do some change in the files and not only when you do the build

public static class HtmlHelperExtensions
{
    public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename)
    {
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
    }

    public static MvcHtmlString IncludeVersionedCss(this HtmlHelper helper, string filename)
    {
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<link href='" + filename + version + "' type ='text/css' rel='stylesheet'/>");
    }

    private static string GetVersion(this HtmlHelper helper, string filename)
    {
        var context = helper.ViewContext.RequestContext.HttpContext;
        var physicalPath = context.Server.MapPath(filename);
        var version = "?v=" +
        new System.IO.FileInfo(physicalPath).LastWriteTime
        .ToString("yyyyMMddHHmmss");
        context.Cache.Add(physicalPath, version, null,
          DateTime.Now.AddMinutes(1), TimeSpan.Zero,
          CacheItemPriority.Normal, null);

        if (context.Cache[filename] == null)
        {
            context.Cache[filename] = version;
            return version;
        }
        else
        {
            if (version != context.Cache[filename].ToString())
            {
                context.Cache[filename] = version;
                return version;
            }
            return context.Cache[filename] as string;
        }
    }
}

PHP display current server path

here is a test script to run on your server to see what is reliabel.

<?php
$host = gethostname();
$ip = gethostbyname($host);
echo "gethostname and gethostbyname: $host at $ip<br>";
$server = $_SERVER['SERVER_ADDR'];
echo "_SERVER[SERVER_ADDR]: $server<br>";
$my_current_ip=exec("ifconfig | grep -Eo 'inet (addr:)?([0-9]*\.){3}[0-9]*' | grep -Eo '([0-9]*\.){3}[0-9]*' | grep -v '127.0.0.1'");
echo "exec ifconfig ... : $my_current_ip<br>";
$external_ip = file_get_contents("http://ipecho.net/plain");
echo "get contents ipecho.net: $external_ip<br>";
?>

The only different option in there is using fiel_get_contents rather than curl for the extrernal website lookup.

This is the result of hitting the web page on a shared hosting, free account. (actual server name and IP changed)

gethostname and gethostbyname: freesites.servercluster.com at 345.27.413.51
_SERVER[SERVER_ADDR]: 127.0.0.7
exec ifconfig ... :
get contents ipecho.net: 345.27.413.51

Why needed this? Decided to point A record at server to see if it opens the web page. Later ran script to save ip and update on ghost site on same server to lookup IP and alert if changed.

In this case, good results optained by:

gethostname() & 
gethostbyname($host)
or 
file_get_contents("http://ipecho.net/plain")

How to insert newline in string literal?

I like more the "pythonic way"

List<string> lines = new List<string> {
    "line1",
    "line2",
    String.Format("{0} - {1} | {2}", 
        someVar,
        othervar, 
        thirdVar
    )
};

if(foo)
    lines.Add("line3");

return String.Join(Environment.NewLine, lines);

android button selector

Best way to implement the selector is by using the xml instead of using programatic way as its more easy to implemnt with xml.

    <?xml version="1.0" encoding="utf-8"?>    
<selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:drawable="@drawable/button_bg_selected" android:state_selected="true"></item>
        <item android:drawable="@drawable/button_bg_pressed" android:state_pressed="true"></item>
        <item android:drawable="@drawable/button_bg_normal"></item>

    </selector>

For more information i implemented using this link http://www.blazin.in/2016/03/how-to-use-selectors-for-botton.html

updating Google play services in Emulator

Based from Google documentation,

If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.

Try to navigate to settings--> apps in your emulator and then find Google Play Services. Check the version number and use it in you build.gradle. To update it with the latest version, you can see it in these documentation and SO question.

How do I verify that an Android apk is signed with a release certificate?

Use console command:

apksigner verify --print-certs application-development-release.apk

You could find apksigner in ../sdk/build-tools/24.0.3/apksigner.bat. Only for build tools v. 24.0.3 and higher.

Also read google docs: https://developer.android.com/studio/command-line/apksigner.html

Invert "if" statement to reduce nesting

Many good reasons about how the code looks like. But what about results?

Let's take a look to some C# code and its IL compiled form:

using System;

public class Test {
    public static void Main(string[] args) {
        if (args.Length == 0) return;
        if ((args.Length+2)/3 == 5) return;
        Console.WriteLine("hey!!!");
    }
}

This simple snippet can be compiled. You can open the generated .exe file with ildasm and check what is the result. I won't post all the assembler thing but I'll describe the results.

The generated IL code does the following:

  1. If the first condition is false, jumps to the code where the second is.
  2. If it's true jumps to the last instruction. (Note: the last instruction is a return).
  3. In the second condition the same happens after the result is calculated. Compare and: got to the Console.WriteLine if false or to the end if this is true.
  4. Print the message and return.

So it seems that the code will jump to the end. What if we do a normal if with nested code?

using System;

public class Test {
    public static void Main(string[] args) {
        if (args.Length != 0 && (args.Length+2)/3 != 5) 
        {
            Console.WriteLine("hey!!!");
        }
    }
}

The results are quite similar in IL instructions. The difference is that before there were two jumps per condition: if false go to next piece of code, if true go to the end. And now the IL code flows better and has 3 jumps (the compiler optimized this a bit):

  1. First jump: when Length is 0 to a part where the code jumps again (Third jump) to the end.
  2. Second: in the middle of the second condition to avoid one instruction.
  3. Third: if the second condition is false, jump to the end.

Anyway, the program counter will always jump.

Simple export and import of a SQLite database on Android

Import and Export of a SQLite database on Android

Here is my function for export database into device storage

private void exportDB(){
    String DatabaseName = "Sycrypter.db";
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Here is my function for import database from device storage into android application

private void importDB(){
    String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
    File sd = new File(dir);
    File data = Environment.getDataDirectory();
    FileChannel source = null;
    FileChannel destination = null;
    String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
    String currentDBPath = "Sycrypter.db";
    File currentDB = new File(sd, currentDBPath);
    File backupDB = new File(data, backupDBPath);

    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

ValueError: all the input arrays must have same number of dimensions

(n,) and (n,1) are not the same shape. Try casting the vector to an array by using the [:, None] notation:

n_lists = np.append(n_list_converted, n_last[:, None], axis=1)

Alternatively, when extracting n_last you can use

n_last = n_list_converted[:, -1:]

to get a (20, 1) array.

ImportError: No module named requests

On OSX, the command will depend on the flavour of python installation you have.

Python 2.x - Default

sudo pip install requests

Python 3.x

sudo pip3 install requests

Get POST data in C#/ASP.NET

Try using:

string ap = c.Request["AP"];

That reads from the cookies, form, query string or server variables.

Alternatively:

string ap = c.Request.Form["AP"];

to just read from the form's data.

Angular 6: How to set response type as text while making http call

Have you tried not setting the responseType and just type casting the response?

This is what worked for me:

/**
 * Client for consuming recordings HTTP API endpoint.
 */
@Injectable({
  providedIn: 'root'
})
export class DownloadUrlClientService {
  private _log = Log.create('DownloadUrlClientService');


  constructor(
    private _http: HttpClient,
  ) {}

  private async _getUrl(url: string): Promise<string> {
    const httpOptions = {headers: new HttpHeaders({'auth': 'false'})};
    // const httpOptions = {headers: new HttpHeaders({'auth': 'false'}), responseType: 'text'};
    const res = await (this._http.get(url, httpOptions) as Observable<string>).toPromise();
    // const res = await (this._http.get(url, httpOptions)).toPromise();
    return res;
  }
}

Generate a dummy-variable

This one liner in base R

model.matrix( ~ iris$Species - 1)

gives

    iris$Speciessetosa iris$Speciesversicolor iris$Speciesvirginica
1                    1                      0                     0
2                    1                      0                     0
3                    1                      0                     0
4                    1                      0                     0
5                    1                      0                     0
6                    1                      0                     0
7                    1                      0                     0
8                    1                      0                     0
9                    1                      0                     0
10                   1                      0                     0
11                   1                      0                     0
12                   1                      0                     0
13                   1                      0                     0
14                   1                      0                     0
15                   1                      0                     0
16                   1                      0                     0
17                   1                      0                     0
18                   1                      0                     0
19                   1                      0                     0
20                   1                      0                     0
21                   1                      0                     0
22                   1                      0                     0
23                   1                      0                     0
24                   1                      0                     0
25                   1                      0                     0
26                   1                      0                     0
27                   1                      0                     0
28                   1                      0                     0
29                   1                      0                     0
30                   1                      0                     0
31                   1                      0                     0
32                   1                      0                     0
33                   1                      0                     0
34                   1                      0                     0
35                   1                      0                     0
36                   1                      0                     0
37                   1                      0                     0
38                   1                      0                     0
39                   1                      0                     0
40                   1                      0                     0
41                   1                      0                     0
42                   1                      0                     0
43                   1                      0                     0
44                   1                      0                     0
45                   1                      0                     0
46                   1                      0                     0
47                   1                      0                     0
48                   1                      0                     0
49                   1                      0                     0
50                   1                      0                     0
51                   0                      1                     0
52                   0                      1                     0
53                   0                      1                     0
54                   0                      1                     0
55                   0                      1                     0
56                   0                      1                     0
57                   0                      1                     0
58                   0                      1                     0
59                   0                      1                     0
60                   0                      1                     0
61                   0                      1                     0
62                   0                      1                     0
63                   0                      1                     0
64                   0                      1                     0
65                   0                      1                     0
66                   0                      1                     0
67                   0                      1                     0
68                   0                      1                     0
69                   0                      1                     0
70                   0                      1                     0
71                   0                      1                     0
72                   0                      1                     0
73                   0                      1                     0
74                   0                      1                     0
75                   0                      1                     0
76                   0                      1                     0
77                   0                      1                     0
78                   0                      1                     0
79                   0                      1                     0
80                   0                      1                     0
81                   0                      1                     0
82                   0                      1                     0
83                   0                      1                     0
84                   0                      1                     0
85                   0                      1                     0
86                   0                      1                     0
87                   0                      1                     0
88                   0                      1                     0
89                   0                      1                     0
90                   0                      1                     0
91                   0                      1                     0
92                   0                      1                     0
93                   0                      1                     0
94                   0                      1                     0
95                   0                      1                     0
96                   0                      1                     0
97                   0                      1                     0
98                   0                      1                     0
99                   0                      1                     0
100                  0                      1                     0
101                  0                      0                     1
102                  0                      0                     1
103                  0                      0                     1
104                  0                      0                     1
105                  0                      0                     1
106                  0                      0                     1
107                  0                      0                     1
108                  0                      0                     1
109                  0                      0                     1
110                  0                      0                     1
111                  0                      0                     1
112                  0                      0                     1
113                  0                      0                     1
114                  0                      0                     1
115                  0                      0                     1
116                  0                      0                     1
117                  0                      0                     1
118                  0                      0                     1
119                  0                      0                     1
120                  0                      0                     1
121                  0                      0                     1
122                  0                      0                     1
123                  0                      0                     1
124                  0                      0                     1
125                  0                      0                     1
126                  0                      0                     1
127                  0                      0                     1
128                  0                      0                     1
129                  0                      0                     1
130                  0                      0                     1
131                  0                      0                     1
132                  0                      0                     1
133                  0                      0                     1
134                  0                      0                     1
135                  0                      0                     1
136                  0                      0                     1
137                  0                      0                     1
138                  0                      0                     1
139                  0                      0                     1
140                  0                      0                     1
141                  0                      0                     1
142                  0                      0                     1
143                  0                      0                     1
144                  0                      0                     1
145                  0                      0                     1
146                  0                      0                     1
147                  0                      0                     1
148                  0                      0                     1
149                  0                      0                     1
150                  0                      0                     1

Selecting Values from Oracle Table Variable / Array?

The sql array type is not neccessary. Not if the element type is a primitive one. (Varchar, number, date,...)

Very basic sample:

declare
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;
  pidms TPidmList;
begin
  select distinct sgbstdn_pidm
  bulk collect into pidms
  from sgbstdn
  where sgbstdn_majr_code_1 = 'HS04'
  and sgbstdn_program_1 = 'HSCOMPH';

  -- do something with pidms

  open :someCursor for
    select value(t) pidm
    from table(pidms) t;
end;

When you want to reuse it, then it might be interesting to know how that would look like. If you issue several commands than those could be grouped in a package. The private package variable trick from above has its downsides. When you add variables to a package, you give it state and now it doesn't act as a stateless bunch of functions but as some weird sort of singleton object instance instead.

e.g. When you recompile the body, it will raise exceptions in sessions that already used it before. (because the variable values got invalided)

However, you could declare the type in a package (or globally in sql), and use it as a paramter in methods that should use it.

create package Abc as
  type TPidmList is table of sgbstdn.sgbstdn_pidm%type;

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList;

  function Test1(list in TPidmList) return PLS_Integer;
  -- "in" to make it immutable so that PL/SQL can pass a pointer instead of a copy
  procedure Test2(list in TPidmList);
end;

create package body Abc as

  function CreateList(majorCode in Varchar, 
                      program in Varchar) return TPidmList is
    result TPidmList;
  begin
    select distinct sgbstdn_pidm
    bulk collect into result
    from sgbstdn
    where sgbstdn_majr_code_1 = majorCode
    and sgbstdn_program_1 = program;

    return result;
  end;

  function Test1(list in TPidmList) return PLS_Integer is
    result PLS_Integer := 0;
  begin
    if list is null or list.Count = 0 then
      return result;
    end if;

    for i in list.First .. list.Last loop
      if ... then
        result := result + list(i);
      end if;
    end loop;
  end;

  procedure Test2(list in TPidmList) as
  begin
    ...
  end;

  return result;
end;

How to call it:

declare
  pidms constant Abc.TPidmList := Abc.CreateList('HS04', 'HSCOMPH');
  xyz PLS_Integer;
begin
  Abc.Test2(pidms);
  xyz := Abc.Test1(pidms);
  ...

  open :someCursor for
    select value(t) as Pidm,
           xyz as SomeValue
    from   table(pidms) t;
end;

What causes a java.lang.StackOverflowError

Stack Overflow exceptions can occur when a thread stack continues to grow in size until reaching the maximum limit.

Adjusting the Stack Sizes (Xss and Xmso) options...

I suggest you see this link: http://www-01.ibm.com/support/docview.wss?uid=swg21162896 There are many possible causes to a StackOverflowError, as you can see in the link....

How to work offline with TFS

See this reference for information on how to bind/unbind your solution or project from source control. NOTE: this doesn't apply if you are using GIT and may not apply to versions later than VS2008.

Quoting from the reference:

To disconnect a solution or project from source control

  1. In Visual Studio, open Solution Explorer and select the item(s) to disconnect.

  2. On the File menu, click Source Control, then Change Source Control.

  3. In the Change Source Control dialog box, click Disconnect.

  4. Click OK.

When should I use cross apply over inner join?

Well I am not sure if this qualifies as a reason to use Cross Apply versus Inner Join, but this query was answered for me in a Forum Post using Cross Apply, so I am not sure if there is an equalivent method using Inner Join:

Create PROCEDURE [dbo].[Message_FindHighestMatches]

-- Declare the Topical Neighborhood
@TopicalNeighborhood nchar(255)

AS BEGIN

-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON

Create table  #temp
(
    MessageID         int,
    Subjects          nchar(255),
    SubjectsCount    int
)

Insert into #temp Select MessageID, Subjects, SubjectsCount From Message

Select Top 20 MessageID, Subjects, SubjectsCount,
    (t.cnt * 100)/t3.inputvalues as MatchPercentage

From #temp 

cross apply (select count(*) as cnt from dbo.Split(Subjects,',') as t1
             join dbo.Split(@TopicalNeighborhood,',') as t2
             on t1.value = t2.value) as t
cross apply (select count(*) as inputValues from dbo.Split(@TopicalNeighborhood,',')) as t3

Order By MatchPercentage desc

drop table #temp

END

Import Error: No module named numpy

For installing NumPy via Anaconda(use below commands):

  • conda install -c conda-forge numpy
  • conda install -c conda-forge/label/broken numpy

How to write string literals in python without having to escape them?

If you're dealing with very large strings, specifically multiline strings, be aware of the triple-quote syntax:

a = r"""This is a multiline string
with more than one line
in the source code."""

Set environment variables on Mac OS X Lion

Simplified Explanation

This post/question is kind of old, so I will answer a simplified version for OS X Lion users. By default, OSX Lion does not have any of the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

At most, if you've done anything in the terminal you might see ~/.bash_history

What It Means

You must create the file to set your default bash commands (commonly in ~/.bashrc). To do this, use any sort of editor, though it's more simple to do it within the terminal:

  1. %> emacs .profile
  2. [from w/in emacs type:] source ~/.bashrc
  3. [from w/in emacs type:] Ctrl + x Ctrl + s (to save the file)
  4. [from w/in emacs type:] Ctrl + x Ctrl + c (to close emacs)
  5. %> emacs .bashrc
  6. [from w/in emacs type/paste all your bash commands, save, and exit]

The next time you quit and reload the terminal, it should load all your bash preferences. For good measure, it's usually a good idea to separate your commands into useful file names. For instance, from within ~/.bashrc, you should have a source ~/.bash_aliases and put all your alias commands in ~/.bash_aliases.

The name does not exist in the namespace error in XAML

This problem can also be caused if the assembly that you're referencing isn't actually built. For example, if your xaml is in Assembly1 and you're referencing a class also in Assembly1, but that assembly has errors and isn't building, this error will be shown.

I feel silly about it, but in my case I was tearing asunder a user control and had all sorts of errors in the related classes as a result. As I was attempting to fix them all I started with the errors in question, not realising that xaml relies on built assemblies to find these references (unlike c#/vb code which can work it out even before you build).

Completely cancel a rebase

Use git rebase --abort. From the official Linux kernel documentation for git rebase:

git rebase --continue | --skip | --abort | --edit-todo

Change background image opacity

You can't use transparency on background-images directly, but you can achieve this effect with something like this:

http://jsfiddle.net/m4TgL/

HTML:

<div class="container">
    <div class="content">//my blog post</div>
</div>?

CSS:

.container {  position: relative; }

.container:before {
    content: "";
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 1;
    background-image: url('image.jpg');
   opacity: 0.5;
}

.content {
    position: relative; 
    z-index: 2;
}?

Find the max of two or more columns with pandas

@DSM's answer is perfectly fine in almost any normal scenario. But if you're the type of programmer who wants to go a little deeper than the surface level, you might be interested to know that it is a little faster to call numpy functions on the underlying .to_numpy() (or .values for <0.24) array instead of directly calling the (cythonized) functions defined on the DataFrame/Series objects.

For example, you can use ndarray.max() along the first axis.

# Data borrowed from @DSM's post.
df = pd.DataFrame({"A": [1,2,3], "B": [-2, 8, 1]})
df
   A  B
0  1 -2
1  2  8
2  3  1

df['C'] = df[['A', 'B']].values.max(1)
# Or, assuming "A" and "B" are the only columns, 
# df['C'] = df.values.max(1) 
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

If your data has NaNs, you will need numpy.nanmax:

df['C'] = np.nanmax(df.values, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3 

You can also use numpy.maximum.reduce. numpy.maximum is a ufunc (Universal Function), and every ufunc has a reduce:

df['C'] = np.maximum.reduce(df['A', 'B']].values, axis=1)
# df['C'] = np.maximum.reduce(df[['A', 'B']], axis=1)
# df['C'] = np.maximum.reduce(df, axis=1)
df

   A  B  C
0  1 -2  1
1  2  8  8
2  3  1  3

enter image description here

np.maximum.reduce and np.max appear to be more or less the same (for most normal sized DataFrames)—and happen to be a shade faster than DataFrame.max. I imagine this difference roughly remains constant, and is due to internal overhead (indexing alignment, handling NaNs, etc).

The graph was generated using perfplot. Benchmarking code, for reference:

import pandas as pd
import perfplot

np.random.seed(0)
df_ = pd.DataFrame(np.random.randn(5, 1000))

perfplot.show(
    setup=lambda n: pd.concat([df_] * n, ignore_index=True),
    kernels=[
        lambda df: df.assign(new=df.max(axis=1)),
        lambda df: df.assign(new=df.values.max(1)),
        lambda df: df.assign(new=np.nanmax(df.values, axis=1)),
        lambda df: df.assign(new=np.maximum.reduce(df.values, axis=1)),
    ],
    labels=['df.max', 'np.max', 'np.maximum.reduce', 'np.nanmax'],
    n_range=[2**k for k in range(0, 15)],
    xlabel='N (* len(df))',
    logx=True,
    logy=True)

Key existence check in HashMap

You can also use the computeIfAbsent() method in the HashMap class.

In the following example, map stores a list of transactions (integers) that are applied to the key (the name of the bank account). To add 2 transactions of 100 and 200 to checking_account you can write:

HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("checking_account", key -> new ArrayList<>())
   .add(100)
   .add(200);

This way you don't have to check to see if the key checking_account exists or not.

  • If it does not exist, one will be created and returned by the lambda expression.
  • If it exists, then the value for the key will be returned by computeIfAbsent().

Really elegant!

Facebook login "given URL not allowed by application configuration"

I kept getting this error, when using wildcard subdomains with my app. I had the site url set to: http://myapp.com and app domain also to http://myapp.com, and also the same value for the Valid OAuth redirect URIs in the advanced tab of the settings app. I tried different combinations but only setting the http://subdomain.myapp.com as the redirect value worked, of course only for that subdomain.

The solution was to empty the redirect fields, leave it blank, that worked! ;)

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

How to wrap async function calls into a sync function in Node.js or Javascript?

deasync turns async function into sync, implemented with a blocking mechanism by calling Node.js event loop at JavaScript layer. As a result, deasync only blocks subsequent code from running without blocking entire thread, nor incuring busy wait. With this module, here is the answer to the jsFiddle challenge:

function AnticipatedSyncFunction(){
  var ret;
  setTimeout(function(){
      ret = "hello";
  },3000);
  while(ret === undefined) {
    require('deasync').runLoopOnce();
  }
  return ret;    
}


var output = AnticipatedSyncFunction();
//expected: output=hello (after waiting for 3 sec)
console.log("output="+output);
//actual: output=hello (after waiting for 3 sec)

(disclaimer: I am the co-author of deasync. The module was created after posting this question and found no workable proposal.)

401 Unauthorized: Access is denied due to invalid credentials

In case anyone is still looking for this, this solved the problem for us:

To whoever this may help, this saved my life...

IIS 7 was difficult for figuring out why i was getting the 401 - Unauthorized: Access is denied due to invalid credentials... until i did this...

  1. Open IIS and select the website that is causing the 401
  2. Open the "Authentication" property under the "IIS" header
  3. Click the "Windows Authentication" item and click "Providers"
  4. For me the issue was that Negotiate was above NTLM. I assume that there was some kind of handshake going on behind the scenes, but i was never really authenticated. I moved the NTLM to the top most spot, and BAM that fixed it.

Here is the link where this was found.

JavaScript, getting value of a td with id name

Again with getElementById, but instead .value, use .innerText

<td id="test">Chicken</td>
document.getElementById('test').innerText; //the value of this will be 'Chicken'

How to make --no-ri --no-rdoc the default for gem install?

On Linux (and probably Mac):

echo 'gem: --no-document' >> ~/.gemrc

This one-liner used to be in comments here, but somehow disappeared.

Get MD5 hash of big files in Python

A Python 2/3 portable solution

To calculate a checksum (md5, sha1, etc.), you must open the file in binary mode, because you'll sum bytes values:

To be py27/py3 portable, you ought to use the io packages, like this:

import hashlib
import io


def md5sum(src):
    md5 = hashlib.md5()
    with io.open(src, mode="rb") as fd:
        content = fd.read()
        md5.update(content)
    return md5

If your files are big, you may prefer to read the file by chunks to avoid storing the whole file content in memory:

def md5sum(src, length=io.DEFAULT_BUFFER_SIZE):
    md5 = hashlib.md5()
    with io.open(src, mode="rb") as fd:
        for chunk in iter(lambda: fd.read(length), b''):
            md5.update(chunk)
    return md5

The trick here is to use the iter() function with a sentinel (the empty string).

The iterator created in this case will call o [the lambda function] with no arguments for each call to its next() method; if the value returned is equal to sentinel, StopIteration will be raised, otherwise the value will be returned.

If your files are really big, you may also need to display progress information. You can do that by calling a callback function which prints or logs the amount of calculated bytes:

def md5sum(src, callback, length=io.DEFAULT_BUFFER_SIZE):
    calculated = 0
    md5 = hashlib.md5()
    with io.open(src, mode="rb") as fd:
        for chunk in iter(lambda: fd.read(length), b''):
            md5.update(chunk)
            calculated += len(chunk)
            callback(calculated)
    return md5

How to reposition Chrome Developer Tools

Place your pointer on the dock button and long click it (some seconds) or right & left mouse click depending on the browser version.

enter image description here enter image description here

How to print in C

printf is a fair bit more complicated than that. You have to supply a format string, and then the variables to apply to the format string. If you just supply one variable, C will assume that is the format string and try to print out all the bytes it finds in it until it hits a terminating nul (0x0).

So if you just give it an integer, it will merrily march through memory at the location your integer is stored, dumping whatever garbage is there to the screen, until it happens to come across a byte containing 0.

For a Java programmer, I'd imagine this is a rather rude introduction to C's lack of type checking. Believe me, this is only the tip of the iceberg. This is why, while I applaud your desire to expand your horizons by learning C, I highly suggest you do whatever you can to avoid writing real programs in it.

(This goes for everyone else reading this too.)

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I took a different approach. I switched to use $.post and the error has gone since then.

CSS: Fix row height

_x000D_
_x000D_
    _x000D_
    table tbody_x000D_
    {_x000D_
        border:1px solid red;_x000D_
    }_x000D_
    table td_x000D_
    {_x000D_
        background:yellow;_x000D_
        _x000D_
        border-bottom:1px solid green;_x000D_
        _x000D_
        _x000D_
    }_x000D_
    .tr0{_x000D_
        line-height:0;_x000D_
     }_x000D_
     .tr0 td{_x000D_
        background:red;_x000D_
     }
_x000D_
<table>_x000D_
<tbody>_x000D_
    <tr><td>test</td></tr>_x000D_
    <tr><td>test</td></tr>    _x000D_
    <tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How do I convert ticks to minutes?

A single tick represents one hundred nanoseconds or one ten-millionth of a second. FROM MSDN.

So 28 000 000 000 * 1/10 000 000 = 2 800 sec. 2 800 sec /60 = 46.6666min

Or you can do it programmaticly with TimeSpan:

    static void Main()
    {
        TimeSpan ts = TimeSpan.FromTicks(28000000000);
        double minutesFromTs = ts.TotalMinutes;
        Console.WriteLine(minutesFromTs);
        Console.Read();
    }

Both give me 46 min and not 480 min...

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

How to determine a user's IP address in node

_x000D_
_x000D_
function getCallerIP(request) {_x000D_
    var ip = request.headers['x-forwarded-for'] ||_x000D_
        request.connection.remoteAddress ||_x000D_
        request.socket.remoteAddress ||_x000D_
        request.connection.socket.remoteAddress;_x000D_
    ip = ip.split(',')[0];_x000D_
    ip = ip.split(':').slice(-1); //in case the ip returned in a format: "::ffff:146.xxx.xxx.xxx"_x000D_
    return ip;_x000D_
}
_x000D_
_x000D_
_x000D_

Apply multiple functions to multiple groupby columns

Ted's answer is amazing. I ended up using a smaller version of that in case anyone is interested. Useful when you are looking for one aggregation that depends on values from multiple columns:

create a dataframe

df=pd.DataFrame({'a': [1,2,3,4,5,6], 'b': [1,1,0,1,1,0], 'c': ['x','x','y','y','z','z']})


   a  b  c
0  1  1  x
1  2  1  x
2  3  0  y
3  4  1  y
4  5  1  z
5  6  0  z

grouping and aggregating with apply (using multiple columns)

df.groupby('c').apply(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

c
x    2.0
y    4.0
z    5.0

grouping and aggregating with aggregate (using multiple columns)

I like this approach since I can still use aggregate. Perhaps people will let me know why apply is needed for getting at multiple columns when doing aggregations on groups.

It seems obvious now, but as long as you don't select the column of interest directly after the groupby, you will have access to all the columns of the dataframe from within your aggregation function.

only access to the selected column

df.groupby('c')['a'].aggregate(lambda x: x[x>1].mean())

access to all columns since selection is after all the magic

df.groupby('c').aggregate(lambda x: x[(x['a']>1) & (x['b']==1)].mean())['a']

or similarly

df.groupby('c').aggregate(lambda x: x['a'][(x['a']>1) & (x['b']==1)].mean())

I hope this helps.

No ConcurrentList<T> in .Net 4.0?

In cases where reads greatly outnumber writes, or (however frequent) writes are non-concurrent, a copy-on-write approach may be appropriate.

The implementation shown below is

  • lockless
  • blazingly fast for concurrent reads, even while concurrent modifications are ongoing - no matter how long they take
  • because "snapshots" are immutable, lockless atomicity is possible, i.e. var snap = _list; snap[snap.Count - 1]; will never (well, except for an empty list of course) throw, and you also get thread-safe enumeration with snapshot semantics for free.. how I LOVE immutability!
  • implemented generically, applicable to any data structure and any type of modification
  • dead simple, i.e. easy to test, debug, verify by reading the code
  • usable in .Net 3.5

For copy-on-write to work, you have to keep your data structures effectively immutable, i.e. no one is allowed to change them after you made them available to other threads. When you want to modify, you

  1. clone the structure
  2. make modifications on the clone
  3. atomically swap in the reference to the modified clone

Code

static class CopyOnWriteSwapper
{
    public static void Swap<T>(ref T obj, Func<T, T> cloner, Action<T> op)
        where T : class
    {
        while (true)
        {
            var objBefore = Volatile.Read(ref obj);
            var newObj = cloner(objBefore);
            op(newObj);
            if (Interlocked.CompareExchange(ref obj, newObj, objBefore) == objBefore)
                return;
        }
    }
}

Usage

CopyOnWriteSwapper.Swap(ref _myList,
    orig => new List<string>(orig),
    clone => clone.Add("asdf"));

If you need more performance, it will help to ungenerify the method, e.g. create one method for every type of modification (Add, Remove, ...) you want, and hard code the function pointers cloner and op.

N.B. #1 It is your responsibility to make sure the no one modifies the (supposedly) immutable data structure. There's nothing we can do in a generic implementation to prevent that, but when specializing to List<T>, you could guard against modification using List.AsReadOnly()

N.B. #2 Be careful about the values in the list. The copy on write approach above guards their list membership only, but if you'd put not strings, but some other mutable objects in there, you have to take care of thread safety (e.g. locking). But that is orthogonal to this solution and e.g. locking of the mutable values can be easily used without issues. You just need to be aware of it.

N.B. #3 If your data structure is huge and you modify it frequently, the copy-all-on-write approach might be prohibitive both in terms of memory consumption and the CPU cost of copying involved. In that case, you might want to use MS's Immutable Collections instead.

How to retrieve a single file from a specific revision in Git?

The easiest way is to write:

git show HASH:file/path/name.ext > some_new_name.ext

where:

  • HASH is the Git revision SHA-1 hash number
  • file/path/name.ext is name of the file you are looking for
  • some_new_name.ext is path and name where the old file should be saved

Example

git show 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8:my_file.txt > my_file.txt.OLD

This will save my_file.txt from revision 27cf8e as a new file with name my_file.txt.OLD

It was tested with Git 2.4.5.

If you want to retrieve deleted file you can use HASH~1 (one commit before specified HASH).

EXAMPLE:

git show 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8~1:deleted_file.txt > deleted_file.txt

When restoring a backup, how do I disconnect all active connections?

None of the above worked for me. My database didn't show any active connections using Activity Monitor or sp_who. I ultimately had to:

  • Right click the database node
  • Select "Detach..."
  • Check the "Drop Connections" box
  • Reattach

Not the most elegant solution but it works and it doesn't require restarting SQL Server (not an option for me, since the DB server hosted a bunch of other databases)

Dark Theme for Visual Studio 2010 With Productivity Power Tools

You can also try this handy online tool, which generates .vssettings file for you.

Visual Studio Color Theme Generator

Disabling browser print options (headers, footers, margins) from page?

This worked for me with about 1cm margin

@page 
{
    size:  auto;   /* auto is the initial value */
    margin: 0mm;  /* this affects the margin in the printer settings */
}
html
{
    background-color: #FFFFFF; 
    margin: 0mm;  /* this affects the margin on the html before sending to printer */
}
body
{
    padding:30px; /* margin you want for the content */
}

What is use of c_str function In c++

Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.

Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is

float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);

This is pretty common use I suppose.

TypeScript: correct way to do string equality?

If you know x and y are both strings, using === is not strictly necessary, but is still good practice.

Assuming both variables actually are strings, both operators will function identically. However, TS often allows you to pass an object that meets all the requirements of string rather than an actual string, which may complicate things.

Given the possibility of confusion or changes in the future, your linter is probably correct in demanding ===. Just go with that.

Label axes on Seaborn Barplot

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

I am Using Design Support Library. And just by using custom theme I achived transparent Status Bar when Opened Navigation Drawer.

enter image description here

enter image description here

<style name="NavigationStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryColorDark</item>

    <!-- To Make Navigation Drawer Fill Status Bar and become Transparent Too -->
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>

</style>

Finally add theme in Manifest File

<activity
  ........
  ........
 android:theme="@style/NavigationStyle"> 
</activity>

Do not forget to use the property, android:fitsSystemWindows="true" in "DrawerLayout"

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

Convert or extract TTC font to TTF - how to?

Assuming that Windows doesn't really know how to deal with TTC files (which I honestly find strange), you can "split" the combined fonts in an easy way if you use fontforge.

The steps are:

  1. Download the file.
  2. Unzip it (e.g., unzip "STHeiti Medium.ttc.zip").
  3. Load Fontforge.
  4. Open it with Fontforge (e.g., File > Open).
  5. Fontforge will tell you that there are two fonts "packed" in this particular TTC file (at least as of 2014-01-29) and ask you to choose one.
  6. After the font is loaded (it may take a while, as this font is very large), you can ask Fontforge to generate the TTF file via the menu File > Generate Fonts....

Repeat the steps of loading 4--6 for the other font and you will have your TTFs readily usable for you.

Note that I emphasized generating instead of saving above: saving the font will create a file in Fontforge's specific SFD format, which is probably useless to you, unless you want to develop fonts with Fontforge.

If you want to have a more programmatic/automatic way of manipulating fonts, then you might be interested in my answer to a similar (but not exactly the same) question.

Addenda

Further comments: One reason why some people may be interested in performing the splitting mentioned above (or using a font converter after all) is to convert the fonts to web formats (like WOFF). That's great, but be careful to see if the license of the fonts that you are splitting/converting allows such wide redistribution.

Of course, for Free ("as in Freedom") fonts, you don't need to worry (and one of the most prominent licenses of such fonts is the OFL).

How to find elements by class

This works for me to access the class attribute (on beautifulsoup 4, contrary to what the documentation says). The KeyError comes a list being returned not a dictionary.

for hit in soup.findAll(name='span'):
    print hit.contents[1]['class']

XMLHttpRequest module not defined/found

Since the last update of the xmlhttprequest module was around 2 years ago, in some cases it does not work as expected.

So instead, you can use the xhr2 module. In other words:

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhr = new XMLHttpRequest();

becomes:

var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest();

But ... of course, there are more popular modules like Axios, because -for example- uses promises:

// Make a request for a user with a given ID
axios.get('/user?ID=12345').then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

What exactly is node.js used for?

Directly from the tag wiki, make sure watch some of the talk videos linked there to get a better idea.


Node.js is an event based, asynchronous I/O framework that uses Google's V8 JavaScript Engine.

Node.js - or just Node as it's commonly called - is used for developing applications that make heavy use of the ability to run JavaScript both on the client, as well as on server side and therefore benefit from the re-usability of code and the lack of context switching.

It's also possible to use matured JavaScript frameworks like YUI and jQuery for server side DOM manipulation.

To ease the development of complex JavaScript further, Node.js supports the CommonJS standard that allows for modularized development and the distribution of software in packages via the Node Package Manager.

Applications that can be written using Node.js include, but are not limited to:

  • Static file servers
  • Web Application frameworks
  • Messaging middle ware
  • Servers for HTML5 multi player games

'console' is undefined error for Internet Explorer

I'm using fauxconsole; I modified the css a bit so that it looks nicer but works very well.

Windows 10 SSH keys

2019-04-07 UPDATE: I tested today with a new version of windows 10 (build 1809, "2018 October's update") and not only the open SSH client is no longer in beta, as it is already installed. So, all you need to do is create the key and set your client to use open SSH instead of putty(pagent):

  1. open command prompt (cmd)
  2. enter ssh-keygenand press enter
  3. press enter to all settings. now your key is saved in c:\Users\.ssh\id_rsa.pub
  4. Open your git client and set it to use open SSH

I tested on Git Extensions and Source Tree and it worked with my personal repo in GitHub. If you are in an earlier windows version or prefer a graphical client for SSH, please read below.

2018-06-04 UDPATE:

On windows 10, starting with version 1709 (win+R and type winver to find the build number), Microsoft is releasing a beta of the OpenSSH client and server. To be able to create a key, you'll need to install the OpenSSH server. To do this follow these steps:

  1. open the start menu
  2. Type "optional feature"
  3. select "Add an optional feature"
  4. Click "Add a feature"
  5. Install "Open SSH Client"
  6. Restart the computer

Now you can open a prompt and ssh-keygen and the client will be recognized by windows. I have not tested this. If you do not have windows 10 or do not want to use the beta, follow the instructions below on how to use putty.


ssh-keygen does not come installed with windows. Here's how to create an ssh key with Putty:

  1. Install putty
  2. Open PuttyGen
  3. Check the Type of key and number of bytes to usePuttyGen parameters
  4. Move the mouse over the progress bar generating key with mouse input
  5. Now you can define a passphrase and save the public and private keys key created dialog

For openssh keys, a few more steps are required:

  1. copy the text from "Public key for pasting" textbox and save it as "id_rsa.pub"
  2. To save the private key in the openssh format, go to Conversions->Export OpenSSH key ( if you did not define a passkey it will ask you to confirm that you do not want a pass key) menu for converting key to OpenSSH format
  3. Save it as "id_rsa"

Now that the keys are saved. Start pagent and add the private key there ( the ppk file in Putty's format) pagent keys dialog

Remember that pagent must be running for the authentication to work

How to fully delete a git repository created with init?

If you really want to remove all of the repository, leaving only the working directory then it should be as simple as this.

rm -rf .git

The usual provisos about rm -rf apply. Make sure you have an up to date backup and are absolutely sure that you're in the right place before running the command. etc., etc.

How do I ignore all files in a folder with a Git repository in Sourcetree?

  • Ignore all files in folder with Git in Sourcetree:

Ignore all files in folder with Git in Sourcetree

How to select date without time in SQL

For 2008 older version :

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

Get generic type of java.util.List

As others have said, the only correct answer is no, the type has been erased.

If the list has a non-zero number of elements, you could investigate the type of the first element ( using it's getClass method, for instance ). That won't tell you the generic type of the list, but it would be reasonable to assume that the generic type was some superclass of the types in the list.

I wouldn't advocate the approach, but in a bind it might be useful.

Python conditional assignment operator

I would use

x = 'default' if not x else x

Much shorter than all of your alternatives suggested here, and straight to the point. Read, "set x to 'default' if x is not set otherwise keep it as x." If you need None, 0, False, or "" to be valid values however, you will need to change this behavior, for instance:

valid_vals = ("", 0, False) # We want None to be the only un-set value

x = 'default' if not x and x not in valid_vals else x

This sort of thing is also just begging to be turned into a function you can use everywhere easily:

setval_if = lambda val: 'default' if not val and val not in valid_vals else val

at which point, you can use it as:

>>> x = None # To set it to something not valid
>>> x = setval_if(x) # Using our special function is short and sweet now!
>>> print x # Let's check to make sure our None valued variable actually got set
'default'

Finally, if you are really missing your Ruby infix notation, you could overload ||=| (or something similar) by following this guy's hack: http://code.activestate.com/recipes/384122-infix-operators/

Check element CSS display with JavaScript

To find out if it's visible with plain JavaScript, check whether the display property is 'none' (don't check for 'block', it could also be blank or 'inline' and still be visible):

var isVisible = (elt.style.display != "none");

If you are using jQuery, you can use this instead:

var isVisible = $elt.is(":visible");

How to hide the bar at the top of "youtube" even when mouse hovers over it?

To remove you tube controls and title you can do something like this.

<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>

check this example how it look

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

How can I generate Unix timestamps?

With NodeJS, just open a terminal and type:
node -e "console.log(new Date().getTime())" or node -e "console.log(Date.now())"

Illegal string offset Warning PHP

just use

$memcachedConfig = array();

before

 print $memcachedConfig['host'];
 print $memcachedConfig['port'];


 Warning: Illegal string offset 'host' in ....
 Warning: Illegal string offset 'port' in ....

this is because you never define what is $memcachedConfig, so by default are treated by string not arrays..

org.hibernate.PersistentObjectException: detached entity passed to persist

Two solutions 1. use merge if you want to update the object 2. use save if you want to just save new object (make sure identity is null to let hibernate or database generate it) 3. if you are using mapping like
@OneToOne(fetch = FetchType.EAGER,cascade=CascadeType.ALL) @JoinColumn(name = "stock_id")

Then use CascadeType.ALL to CascadeType.MERGE

thanks Shahid Abbasi

Simple JavaScript login form validation

<form name="loginform" onsubmit="validateForm()">

instead of putting the onsubmit on the actual input button

How can I create a correlation matrix in R?

Have a look at qtlcharts. It allows you to create interactive correlation matrices:

library(qtlcharts)
data(iris)
iris$Species <- NULL
iplotCorr(iris, reorder=TRUE)

enter image description here

It's more impressive when you correlate more variables, like in the package's vignette: enter image description here