Programs & Examples On #Vistadb

VistaDB is an Embedded SQL Database Engine for .Net (SQL Server compatible)

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

As an update to Austyn Mahoney's answer, configuration 'compile' is obsolete and has been replaced with 'implementation' and 'api'.

It will be removed at the end of 2018. For more information see here.

Which characters make a URL invalid?

All valid characters that can be used in a URI (a URL is a type of URI) are defined in RFC 3986.

All other characters can be used in a URL provided that they are "URL Encoded" first. This involves changing the invalid character for specific "codes" (usually in the form of the percent symbol (%) followed by a hexadecimal number).

This link, HTML URL Encoding Reference, contains a list of the encodings for invalid characters.

Is it possible to install both 32bit and 64bit Java on Windows 7?

Yes, it is absolutely no problem. You could even have multiple versions of both 32bit and 64bit Java installed at the same time on the same machine.

In fact, i have such a setup myself.

How to remove all of the data in a table using Django

Inside a manager:

def delete_everything(self):
    Reporter.objects.all().delete()

def drop_table(self):
    cursor = connection.cursor()
    table_name = self.model._meta.db_table
    sql = "DROP TABLE %s;" % (table_name, )
    cursor.execute(sql)

What is the difference between a cer, pvk, and pfx file?

In Windows platform, these file types are used for certificate information. Normally used for SSL certificate and Public Key Infrastructure (X.509).

  • CER files: CER file is used to store X.509 certificate. Normally used for SSL certification to verify and identify web servers security. The file contains information about certificate owner and public key. A CER file can be in binary (ASN.1 DER) or encoded with Base-64 with header and footer included (PEM), Windows will recognize either of these layout.
  • PVK files: Stands for Private Key. Windows uses PVK files to store private keys for code signing in various Microsoft products. PVK is proprietary format.
  • PFX files Personal Exchange Format, is a PKCS12 file. This contains a variety of cryptographic information, such as certificates, root authority certificates, certificate chains and private keys. It’s cryptographically protected with passwords to keep private keys private and preserve the integrity of the root certificates. The PFX file is also used in various Microsoft products, such as IIS.

for more information visit:Certificate Files: .Cer x .Pvk x .Pfx

How can I fill a column with random numbers in SQL? I get the same value in every row

If you are on SQL Server 2008 you can also use

 CRYPT_GEN_RANDOM(2) % 10000

Which seems somewhat simpler (it is also evaluated once per row as newid is - shown below)

DECLARE @foo TABLE (col1 FLOAT)

INSERT INTO @foo SELECT 1 UNION SELECT 2

UPDATE @foo
SET col1 =  CRYPT_GEN_RANDOM(2) % 10000

SELECT *  FROM @foo

Returns (2 random probably different numbers)

col1
----------------------
9693
8573

Mulling the unexplained downvote the only legitimate reason I can think of is that because the random number generated is between 0-65535 which is not evenly divisible by 10,000 some numbers will be slightly over represented. A way around this would be to wrap it in a scalar UDF that throws away any number over 60,000 and calls itself recursively to get a replacement number.

CREATE FUNCTION dbo.RandomNumber()
RETURNS INT
AS
  BEGIN
      DECLARE @Result INT

      SET @Result = CRYPT_GEN_RANDOM(2)

      RETURN CASE
               WHEN @Result < 60000
                     OR @@NESTLEVEL = 32 THEN @Result % 10000
               ELSE dbo.RandomNumber()
             END
  END  

How to initialize var?

Well, as others have stated, ambiguity in type is the issue. So the answer is no, C# doesn't let that happen because it's a strongly typed language, and it deals only with compile time known types. The compiler could have been designed to infer it as of type object, but the designers chose to avoid the extra complexity (in C# null has no type).

One alternative is

var foo = new { }; //anonymous type

Again note that you're initializing to a compile time known type, and at the end its not null, but anonymous object. It's only a few lines shorter than new object(). You can only reassign the anonymous type to foo in this one case, which may or may not be desirable.

Initializing to null with type not being known is out of question.

Unless you're using dynamic.

dynamic foo = null;
//or
var foo = (dynamic)null; //overkill

Of course it is pretty useless, unless you want to reassign values to foo variable. You lose intellisense support as well in Visual Studio.

Lastly, as others have answered, you can have a specific type declared by casting;

var foo = (T)null;

So your options are:

//initializes to non-null; I like it; cant be reassigned a value of any type
var foo = new { }; 

//initializes to non-null; can be reassigned a value of any type
var foo = new object();

//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic foo = null;
var foo = (dynamic)null;

//initializes to null; more conventional; can be reassigned a value of any type
object foo = null;

//initializes to null; cannot be reassigned a value of any type
var foo = (T)null;

Multiple simultaneous downloads using Wget?

use xargs to make wget working in multiple file in parallel

#!/bin/bash

mywget()
{
    wget "$1"
}

export -f mywget

# run wget in parallel using 8 thread/connection
xargs -P 8 -n 1 -I {} bash -c "mywget '{}'" < list_urls.txt

Aria2 options, The right way working with file smaller than 20mb

aria2c -k 2M -x 10 -s 10 [url]

-k 2M split file into 2mb chunk

-k or --min-split-size has default value of 20mb, if you not set this option and file under 20mb it will only run in single connection no matter what value of -x or -s

javascript convert int to float

toFixed() method formats a number using fixed-point notation. Read MDN Web Docs for full reference.

var fval = 4;

console.log(fval.toFixed(2)); // prints 4.00

How to change fontFamily of TextView in Android

I am using excellent library Calligraphy by Chris Jenx designed to allow you to use custom fonts in your android application. Give it a try!

div hover background-color change?

if you want the color to change when you have simply add the :hover pseudo

div.e:hover {
    background-color:red;
}

SQL update from one Table to another based on a ID match

I believe an UPDATE FROM with a JOIN will help:

MS SQL

UPDATE
    Sales_Import
SET
    Sales_Import.AccountNumber = RAN.AccountNumber
FROM
    Sales_Import SI
INNER JOIN
    RetrieveAccountNumber RAN
ON 
    SI.LeadID = RAN.LeadID;

MySQL and MariaDB

UPDATE
    Sales_Import SI,
    RetrieveAccountNumber RAN
SET
    SI.AccountNumber = RAN.AccountNumber
WHERE
    SI.LeadID = RAN.LeadID;

Ignore 'Security Warning' running script from command line

None of this worked in my specific instance. What did was changing to a NetBIOS name from the FQDN.

Instead of:
\\server.domain.net\file.ps1
use:
\\server\file.ps1

Using the name bypasses the "automatically detect intranet network" config in IE.

See Option 1 in the blog here: http://setspn.blogspot.com/2011/05/running-powershell-scripts-from-unc.html

Echo a blank (empty) line to the console from a Windows batch file

Any of the below three options works for you:

echo[

echo(

echo. 

For example:

@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo( 
echo The above line is also blank.
echo. 
echo The above line is also blank.

How can I use external JARs in an Android project?

If using Android Studio, do the following (I've copied and modified @Vinayak Bs answer):

  1. Select the Project view in the Project sideview (instead of Packages or Android)
  2. Create a folder called libs in your project's root folder
  3. Copy your JAR files to the libs folder
  4. The sideview will be updated and the JAR files will show up in your project
  5. Now right click on each JAR file you want to import and then select "Add as Library...", which will include it in your project
  6. After that, all you need to do is reference the new classes in your code, eg. import javax.mail.*

Serialize form data to JSON

My contribution:

function serializeToJson(serializer){
    var _string = '{';
    for(var ix in serializer)
    {
        var row = serializer[ix];
        _string += '"' + row.name + '":"' + row.value + '",';
    }
    var end =_string.length - 1;
    _string = _string.substr(0, end);
    _string += '}';
    console.log('_string: ', _string);
    return JSON.parse(_string);
}

var params = $('#frmPreguntas input').serializeArray();
params = serializeToJson(params);

Replace words in the body text

I am new to Javascript and just started learning these skills. Please check if the below method is useful to replace the text.

<script>

    var txt=document.getElementById("demo").innerHTML;
    var pos = txt.replace(/Hello/g, "hi")
    document.getElementById("demo").innerHTML = pos;

</script>

Tomcat 7 is not running on browser(http://localhost:8080/ )

1)Goto Server tab 2)Right on server -> general -> click on switch location. 3)Double click on the server -> under server location -> select tomcat installation. 4) restart the server.

Bootstrap DatePicker, how to set the start date for tomorrow?

1) use for tommorow's date startDate: '+1d'

2) use for yesterday's date startDate: '-1d'

3) use for today's date startDate: new Date()

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

Change

die (mysqli_error()); 

to

die('Error: ' . mysqli_error($myConnection));

in the query

$query = mysqli_query($myConnection, $sqlCommand) or die (mysqli_error()); 

Tab key == 4 spaces and auto-indent after curly braces in Vim

As has been pointed out in a couple of other answers, the preferred method now is NOT to use smartindent, but instead use the following (in your .vimrc):

filetype plugin indent on
" show existing tab with 4 spaces width
set tabstop=4
" when indenting with '>', use 4 spaces width
set shiftwidth=4
" On pressing tab, insert 4 spaces
set expandtab

In your [.vimrc:][1] file:
set smartindent
set tabstop=4
set shiftwidth=4
set expandtab

The help files take a bit of time to get used to, but the more you read, the better Vim gets:

:help smartindent

Even better, you can embed these settings in your source for portability:

:help auto-setting

To see your current settings:

:set all

As graywh points out in the comments, smartindent has been replaced by cindent which "Works more cleverly", although still mainly for languages with C-like syntax:

:help C-indenting

MySQL vs MongoDB 1000 reads

MongoDB is not magically faster. If you store the same data, organised in basically the same fashion, and access it exactly the same way, then you really shouldn't expect your results to be wildly different. After all, MySQL and MongoDB are both GPL, so if Mongo had some magically better IO code in it, then the MySQL team could just incorporate it into their codebase.

People are seeing real world MongoDB performance largely because MongoDB allows you to query in a different manner that is more sensible to your workload.

For example, consider a design that persisted a lot of information about a complicated entity in a normalised fashion. This could easily use dozens of tables in MySQL (or any relational db) to store the data in normal form, with many indexes needed to ensure relational integrity between tables.

Now consider the same design with a document store. If all of those related tables are subordinate to the main table (and they often are), then you might be able to model the data such that the entire entity is stored in a single document. In MongoDB you can store this as a single document, in a single collection. This is where MongoDB starts enabling superior performance.

In MongoDB, to retrieve the whole entity, you have to perform:

  • One index lookup on the collection (assuming the entity is fetched by id)
  • Retrieve the contents of one database page (the actual binary json document)

So a b-tree lookup, and a binary page read. Log(n) + 1 IOs. If the indexes can reside entirely in memory, then 1 IO.

In MySQL with 20 tables, you have to perform:

  • One index lookup on the root table (again, assuming the entity is fetched by id)
  • With a clustered index, we can assume that the values for the root row are in the index
  • 20+ range lookups (hopefully on an index) for the entity's pk value
  • These probably aren't clustered indexes, so the same 20+ data lookups once we figure out what the appropriate child rows are.

So the total for mysql, even assuming that all indexes are in memory (which is harder since there are 20 times more of them) is about 20 range lookups.

These range lookups are likely comprised of random IO — different tables will definitely reside in different spots on disk, and it's possible that different rows in the same range in the same table for an entity might not be contiguous (depending on how the entity has been updated, etc).

So for this example, the final tally is about 20 times more IO with MySQL per logical access, compared to MongoDB.

This is how MongoDB can boost performance in some use cases.

How do I POST an array of objects with $.ajax (jQuery or Zepto)

Try the following:

$.ajax({
  url: _saveDeviceUrl
, type: 'POST'
, contentType: 'application/json'
, dataType: 'json'
, data: {'myArray': postData}
, success: _madeSave.bind(this)
//, processData: false //Doesn't help
});

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

Android Studio doesn't recognize my device

On Windows 7 , the only thing that worked for me is this. Go to Device Manager -> Under Android Phone -> Right Click and select 'enable'

enter image description here

Use of Custom Data Types in VBA

It looks like you want to define Truck as a Class with properties NumberOfAxles, AxleWeights & AxleSpacings.

This can be defined in a CLASS MODULE (here named clsTrucks)

Option Explicit

Private tID As String
Private tNumberOfAxles As Double
Private tAxleSpacings As Double


Public Property Get truckID() As String
    truckID = tID
End Property

Public Property Let truckID(value As String)
    tID = value
End Property

Public Property Get truckNumberOfAxles() As Double
    truckNumberOfAxles = tNumberOfAxles
End Property

Public Property Let truckNumberOfAxles(value As Double)
    tNumberOfAxles = value
End Property

Public Property Get truckAxleSpacings() As Double
    truckAxleSpacings = tAxleSpacings
End Property

Public Property Let truckAxleSpacings(value As Double)
    tAxleSpacings = value
End Property

then in a MODULE the following defines a new truck and it's properties and adds it to a collection of trucks and then retrieves the collection.

Option Explicit

Public TruckCollection As New Collection

Sub DefineNewTruck()
Dim tempTruck As clsTrucks
Dim i As Long

    'Add 5 trucks
    For i = 1 To 5
        Set tempTruck = New clsTrucks
        'Random data
        tempTruck.truckID = "Truck" & i
        tempTruck.truckAxleSpacings = 13.5 + i
        tempTruck.truckNumberOfAxles = 20.5 + i

        'tempTruck.truckID is the collection key
        TruckCollection.Add tempTruck, tempTruck.truckID
    Next i

    'retrieve 5 trucks
    For i = 1 To 5
        'retrieve by collection index
        Debug.Print TruckCollection(i).truckAxleSpacings
        'retrieve by key
        Debug.Print TruckCollection("Truck" & i).truckAxleSpacings

    Next i

End Sub

There are several ways of doing this so it really depends on how you intend to use the data as to whether an a class/collection is the best setup or arrays/dictionaries etc.

Java 8 Stream API to find Unique Object matching a property value

Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Refer the below code for usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

Person matchingPerson = objects.stream
                        .filter(p -> p.email().equals("testemail"))
                        .collect(onlyElement());

python "TypeError: 'numpy.float64' object cannot be interpreted as an integer"

N=np.floor(np.divide(l,delta))
...
for j in range(N[i]/2):

N[i]/2 will be a float64 but range() expects an integer. Just cast the call to

for j in range(int(N[i]/2)):

Can I call a constructor from another constructor (do constructor chaining) in C++?

Another option that has not been shown yet is to split your class into two, wrapping a lightweight interface class around your original class in order to achieve the effect you are looking for:

class Test_Base {
    public Test_Base() {
        DoSomething();
    }
};

class Test : public Test_Base {
    public Test() : Test_Base() {
    }

    public Test(int count) : Test_Base() {
        DoSomethingWithCount(count);
    }
};

This could get messy if you have many constructors that must call their "next level up" counterpart, but for a handful of constructors, it should be workable.

Does --disable-web-security Work In Chrome Anymore?

The new tag for recent Chrome and Chromium browsers is :

--disable-web-security --user-data-dir=c:\my\data

Disable click outside of bootstrap modal area to close modal

If you are using @ng-bootstrap use the following:

Component

import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit {

  constructor(
    private ngbModal: NgbModal
  ) {}

  ngOnInit(): void {
  }

  openModal(exampleModal: any, $event: any) {
    this.ngbModal.open(exampleModal, {
      size: 'lg', // set modal size
      backdrop: 'static', // disable modal from closing on click outside
      keyboard: false, // disable modal closing by keyboard esc
    });
  }
}

Template

<div (click)="openModal(exampleModal, $event)"> </div>
    <ng-template #exampleModal let-modal>
        <div class="modal-header">
            <h5 class="modal-title">Test modal</h5>
        </div>
        <div class="modal-body p-3">
            <form action="">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="">Test field 1</label>
                        <input type="text" class="form-control">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="">Test field 2</label>
                        <input type="text" class="form-control">
                    </div>

                    <div class="text-right pt-4">
                        <button type="button" class="btn btn-light" (click)="modal.dismiss('Close')">Close</button>
                        <button class="btn btn-primary ml-1">Save</button>
                    </div>
            </form>
        </div>
    </ng-template>

This code was tested on angular 9 using:

  1. "@ng-bootstrap/ng-bootstrap": "^6.1.0",

  2. "bootstrap": "^4.4.1",

When to use the JavaScript MIME type application/javascript instead of text/javascript?

The problem with Javascript's MIME type is that there hasn't been a standard for years. Now we've got application/javascript as an official MIME type.

But actually, the MIME type doesn't matter at all, as the browser can determine the type itself. That's why the HTML5 specs state that the type="text/javascript" is no longer required.

How do I split a string, breaking at a particular character?

This string.split("~")[0]; gets things done.

source: String.prototype.split()


Another functional approach using curry and function composition.

So the first thing would be the split function. We want to make this "john smith~123 Street~Apt 4~New York~NY~12345" into this ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

const split = (separator) => (text) => text.split(separator);
const splitByTilde = split('~');

So now we can use our specialized splitByTilde function. Example:

splitByTilde("john smith~123 Street~Apt 4~New York~NY~12345") // ["john smith", "123 Street", "Apt 4", "New York", "NY", "12345"]

To get the first element we can use the list[0] operator. Let's build a first function:

const first = (list) => list[0];

The algorithm is: split by the colon and then get the first element of the given list. So we can compose those functions to build our final getName function. Building a compose function with reduce:

const compose = (...fns) => (value) => fns.reduceRight((acc, fn) => fn(acc), value);

And now using it to compose splitByTilde and first functions.

const getName = compose(first, splitByTilde);

let string = 'john smith~123 Street~Apt 4~New York~NY~12345';
getName(string); // "john smith"

How do I set adaptive multiline UILabel text?

I know it's a bit old but since I recently looked into it :

let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .ByWordWrapping
l.text = "BLAH BLAH BLAH BLAH BLAH"
l.frame.size.width = 300
l.sizeToFit()

First set the numberOfLines property to 0 so that the device understands you don't care how many lines it needs. Then specify your favorite BreakMode Then the width needs to be set before sizeToFit() method. Then the label knows it must fit in the specified width

select dept names who have more than 2 employees whose salary is greater than 1000

hope this helps

select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2

Get line number while using grep

In order to display the results with the line numbers, you might try this

grep -nr "word to search for" /path/to/file/file 

The result should be something like this:

linenumber: other data "word to search for" other data

Eclipse CDT: no rule to make target all

Yet another solution:

I got inside objects.mk file

################################################################################
# Automatically-generated file. Do not edit!
################################################################################

USER_OBJS := /home/../mylib.so

LIBS := -lstdc++fs -lGL -lGLU -lGLEW -lglut -lm -lmylib

then didn't read first line. Then altered next line. It was another projects' folder because I copied this using "copy/clone project" feature and this was causing the error for me. I changed myLib.so into /proper_address/reallyMyLib.so and it worked.

Warning: It may harm some unknown places! Backup whole project before doing this. Because it says "do not edit".

Cannot find JavaScriptSerializer in .Net 4.0

You have to add the reference to the project.

In Assemblies, there is a System.Web.Extensions Add that.

Once that is done put:

    using System.Web;
    using System.Web.Script;
    using System.Web.Script.Serialization;

That worked for me.

VS 2017 Metadata file '.dll could not be found

Double check the name of your project folder. In my case my project folder was named with spaces in it. When I cloned the project from Team Foundation Server using git bash the spaces in the folder name were converted to: "%20". Changing those back to spaces fixed the problem for me.

align images side by side in html

I suggest to use a container for each img p like this:

<div class="image123">
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif" height="200" width="200"  />
        <p style="text-align:center;">This is image 1</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 2</p>
    </div>
    <div style="float:left;margin-right:5px;">
        <img src="/images/tv.gif/" height="200" width="200" />
        <p style="text-align:center;">This is image 3</p>
    </div>
</div>

Then apply float:left to each container. I add and 5px margin right so there is a space between each image. Also alway close your elements. Maybe in html img tag is not important to close but in XHTML is.

fiddle

Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:

html

<div class="image123">
    <div>
        <img src="/images/tv.gif" />
        <p>This is image 1</p>
    </div>
    <div>
        <img class="middle-img" src="/images/tv.gif/" />
        <p>This is image 2</p>
    </div>
    <div>
        <img src="/images/tv.gif/" />
        <p>This is image 3</p>
    </div>
</div>

css

div{
    float:left;
    margin-right:5px;
}

div > img{
   height:200px;
    width:200px;
}

p{
    text-align:center;
}

It's generally recommended that you use linked style sheets because:

  • They can be cached by browsers for performance
  • Generally a lot easier to maintain for a development perspective

source

fiddle

Install a Nuget package in Visual Studio Code

Nuget Gallery provides a GUI similar to the full Visual Studio. See below.

enter image description here

How To Use:

  1. Install Nuget Gallery from extension marketplace.
  2. Launch from the menu bar View > Command Palette or ??P (Ctrl+Shift+P on Windows and Linux). Type Nuget: Open Gallery.
  3. The GUI above is displayed. You can filter just like in regular Visual Studio.
  4. Make sure the .csproj file checkbox is selected, select version from dropdown, and click install button.

UPDATE

Earlier versions, as noted in the comments, had an issue where the .csproj checkbox was not visible when a package in the csproj file was missing a version number like below.

<PackageReference Include="Microsoft.AspNetCore.App" />

This has been fixed in newer versions of the extension so if you have an older version with this issue, please update it to the latest version.

Python: finding lowest integer

To find the minimum value of a list, you might just as well use min:

x = min(float(s) for s in l) # min of a generator

Or, if you want the result as a string, rather than a float, use a key function:

x = min(l, key=float)

Why won't bundler install JSON gem?

Run this command then everything will be ok

sudo apt-get install libgmp-dev

C# binary literals

Though the string parsing solution is the most popular, I don't like it, because parsing string can be a great performance hit in some situations.

When there is needed a kind of a bitfield or binary mask, I'd rather write it like

long bitMask = 1011001;

And later

int bit5 = BitField.GetBit(bitMask, 5);

Or

bool flag5 = BitField.GetFlag(bitMask, 5);`

Where BitField class is

public static class BitField
{
    public static int GetBit(int bitField, int index)
    {
        return (bitField / (int)Math.Pow(10, index)) % 10;
    }

    public static bool GetFlag(int bitField, int index)
    {
        return GetBit(bitField, index) == 1;
    }
}

Recover unsaved SQL query scripts

Use the following location where you can find all ~AutoRecover.~vs*.sql (autorecovery files):

C:\Users\<YourUserName>\Documents\SQL Server Management Studio\Backup Files\Solution1

Find commit by hash SHA in Git

There are two ways to do this.

1. providing the SHA of the commit you want to see to git log

git log -p a2c25061

Where -p is short for patch

2. use git show

git show a2c25061

The output for both commands will be:

  • the commit
  • the author
  • the date
  • the commit message
  • the patch information

How do I do a HTTP GET in Java?

If you dont want to use external libraries, you can use URL and URLConnection classes from standard Java API.

An example looks like this:

String urlString = "http://wherever.com/someAction?param1=value1&param2=value2....";
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
InputStream is = conn.getInputStream();
// Do what you want with that stream

Simulating Button click in javascript

try this

document.getElementById("datapicker").addEventListener("submit", function())

Progress during large file copy (Copy-Item & Write-Progress?)

This recursive function copies files and directories recursively from source path to destination path

If file already exists on destination path, it copies them only with newer files.

Function Copy-FilesBitsTransfer(
        [Parameter(Mandatory=$true)][String]$sourcePath, 
        [Parameter(Mandatory=$true)][String]$destinationPath, 
        [Parameter(Mandatory=$false)][bool]$createRootDirectory = $true)
{
    $item = Get-Item $sourcePath
    $itemName = Split-Path $sourcePath -leaf
    if (!$item.PSIsContainer){ #Item Is a file

        $clientFileTime = Get-Item $sourcePath | select LastWriteTime -ExpandProperty LastWriteTime

        if (!(Test-Path -Path $destinationPath\$itemName)){
            Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
            if (!$?){
                return $false
            }
        }
        else{
            $serverFileTime = Get-Item $destinationPath\$itemName | select LastWriteTime -ExpandProperty LastWriteTime

            if ($serverFileTime -lt $clientFileTime)
            {
                Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
                if (!$?){
                    return $false
                }
            }
        }
    }
    else{ #Item Is a directory
        if ($createRootDirectory){
            $destinationPath = "$destinationPath\$itemName"
            if (!(Test-Path -Path $destinationPath -PathType Container)){
                if (Test-Path -Path $destinationPath -PathType Leaf){ #In case item is a file, delete it.
                    Remove-Item -Path $destinationPath
                }

                New-Item -ItemType Directory $destinationPath | Out-Null
                if (!$?){
                    return $false
                }

            }
        }
        Foreach ($fileOrDirectory in (Get-Item -Path "$sourcePath\*"))
        {
            $status = Copy-FilesBitsTransfer $fileOrDirectory $destinationPath $true
            if (!$status){
                return $false
            }
        }
    }

    return $true
}

Password Strength Meter

Password Strength Algorithm:

Password Length:
    5 Points: Less than 4 characters
    10 Points: 5 to 7 characters
    25 Points: 8 or more

Letters:
    0 Points: No letters
    10 Points: Letters are all lower case
    20 Points: Letters are upper case and lower case

Numbers:
    0 Points: No numbers
    10 Points: 1 number
    20 Points: 3 or more numbers

Characters:
    0 Points: No characters
    10 Points: 1 character
    25 Points: More than 1 character

Bonus:
    2 Points: Letters and numbers
    3 Points: Letters, numbers, and characters
    5 Points: Mixed case letters, numbers, and characters

Password Text Range:

    >= 90: Very Secure
    >= 80: Secure
    >= 70: Very Strong
    >= 60: Strong
    >= 50: Average
    >= 25: Weak
    >= 0: Very Weak

Settings Toggle to true or false, if you want to change what is checked in the password

var m_strUpperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var m_strLowerCase = "abcdefghijklmnopqrstuvwxyz";
var m_strNumber = "0123456789";
var m_strCharacters = "!@#$%^&*?_~"

Check password


function checkPassword(strPassword)
{
    // Reset combination count
    var nScore = 0;

    // Password length
    // -- Less than 4 characters
    if (strPassword.length < 5)
    {
        nScore += 5;
    }
    // -- 5 to 7 characters
    else if (strPassword.length > 4 && strPassword.length < 8)
    {
        nScore += 10;
    }
    // -- 8 or more
    else if (strPassword.length > 7)
    {
        nScore += 25;
    }

    // Letters
    var nUpperCount = countContain(strPassword, m_strUpperCase);
    var nLowerCount = countContain(strPassword, m_strLowerCase);
    var nLowerUpperCount = nUpperCount + nLowerCount;
    // -- Letters are all lower case
    if (nUpperCount == 0 && nLowerCount != 0) 
    { 
        nScore += 10; 
    }
    // -- Letters are upper case and lower case
    else if (nUpperCount != 0 && nLowerCount != 0) 
    { 
        nScore += 20; 
    }

    // Numbers
    var nNumberCount = countContain(strPassword, m_strNumber);
    // -- 1 number
    if (nNumberCount == 1)
    {
        nScore += 10;
    }
    // -- 3 or more numbers
    if (nNumberCount >= 3)
    {
        nScore += 20;
    }

    // Characters
    var nCharacterCount = countContain(strPassword, m_strCharacters);
    // -- 1 character
    if (nCharacterCount == 1)
    {
        nScore += 10;
    }   
    // -- More than 1 character
    if (nCharacterCount > 1)
    {
        nScore += 25;
    }

    // Bonus
    // -- Letters and numbers
    if (nNumberCount != 0 && nLowerUpperCount != 0)
    {
        nScore += 2;
    }
    // -- Letters, numbers, and characters
    if (nNumberCount != 0 && nLowerUpperCount != 0 && nCharacterCount != 0)
    {
        nScore += 3;
    }
    // -- Mixed case letters, numbers, and characters
    if (nNumberCount != 0 && nUpperCount != 0 && nLowerCount != 0 && nCharacterCount != 0)
    {
        nScore += 5;
    }


    return nScore;
}

// Runs password through check and then updates GUI 


function runPassword(strPassword, strFieldID) 
{
    // Check password
    var nScore = checkPassword(strPassword);


     // Get controls
        var ctlBar = document.getElementById(strFieldID + "_bar"); 
        var ctlText = document.getElementById(strFieldID + "_text");
        if (!ctlBar || !ctlText)
            return;

        // Set new width
        ctlBar.style.width = (nScore*1.25>100)?100:nScore*1.25 + "%";

    // Color and text
    // -- Very Secure
    /*if (nScore >= 90)
    {
        var strText = "Very Secure";
        var strColor = "#0ca908";
    }
    // -- Secure
    else if (nScore >= 80)
    {
        var strText = "Secure";
        vstrColor = "#7ff67c";
    }
    // -- Very Strong
    else 
    */
    if (nScore >= 80)
    {
        var strText = "Very Strong";
        var strColor = "#008000";
    }
    // -- Strong
    else if (nScore >= 60)
    {
        var strText = "Strong";
        var strColor = "#006000";
    }
    // -- Average
    else if (nScore >= 40)
    {
        var strText = "Average";
        var strColor = "#e3cb00";
    }
    // -- Weak
    else if (nScore >= 20)
    {
        var strText = "Weak";
        var strColor = "#Fe3d1a";
    }
    // -- Very Weak
    else
    {
        var strText = "Very Weak";
        var strColor = "#e71a1a";
    }

    if(strPassword.length == 0)
    {
    ctlBar.style.backgroundColor = "";
    ctlText.innerHTML =  "";
    }
else
    {
    ctlBar.style.backgroundColor = strColor;
    ctlText.innerHTML =  strText;
}
}

// Checks a string for a list of characters
function countContain(strPassword, strCheck)
{ 
    // Declare variables
    var nCount = 0;

    for (i = 0; i < strPassword.length; i++) 
    {
        if (strCheck.indexOf(strPassword.charAt(i)) > -1) 
        { 
                nCount++;
        } 
    } 

    return nCount; 
} 

You can customize by yourself according to your requirement.

Python - Dimension of Data Frame

Summary of all ways to get info on dimensions of DataFrame or Series

There are a number of ways to get information on the attributes of your DataFrame or Series.

Create Sample DataFrame and Series

df = pd.DataFrame({'a':[5, 2, np.nan], 'b':[ 9, 2, 4]})
df

     a  b
0  5.0  9
1  2.0  2
2  NaN  4

s = df['a']
s

0    5.0
1    2.0
2    NaN
Name: a, dtype: float64

shape Attribute

The shape attribute returns a two-item tuple of the number of rows and the number of columns in the DataFrame. For a Series, it returns a one-item tuple.

df.shape
(3, 2)

s.shape
(3,)

len function

To get the number of rows of a DataFrame or get the length of a Series, use the len function. An integer will be returned.

len(df)
3

len(s)
3

size attribute

To get the total number of elements in the DataFrame or Series, use the size attribute. For DataFrames, this is the product of the number of rows and the number of columns. For a Series, this will be equivalent to the len function:

df.size
6

s.size
3

ndim attribute

The ndim attribute returns the number of dimensions of your DataFrame or Series. It will always be 2 for DataFrames and 1 for Series:

df.ndim
2

s.ndim
1

The tricky count method

The count method can be used to return the number of non-missing values for each column/row of the DataFrame. This can be very confusing, because most people normally think of count as just the length of each row, which it is not. When called on a DataFrame, a Series is returned with the column names in the index and the number of non-missing values as the values.

df.count() # by default, get the count of each column

a    2
b    3
dtype: int64


df.count(axis='columns') # change direction to get count of each row

0    2
1    2
2    1
dtype: int64

For a Series, there is only one axis for computation and so it just returns a scalar:

s.count()
2

Use the info method for retrieving metadata

The info method returns the number of non-missing values and data types of each column

df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 2 columns):
a    2 non-null float64
b    3 non-null int64
dtypes: float64(1), int64(1)
memory usage: 128.0 bytes

How to force cp to overwrite without confirmation

cp -u ...
cp --update ...

also works.

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

This will capture requests for files like version, release, and README.md, etc. which should be treated either as endpoints, if defined (as in the case of /release), or as "not found."

c++ parse int from string

Some handy quick functions (if you're not using Boost):

template<typename T>
std::string ToString(const T& v)
{
    std::ostringstream ss;
    ss << v;
    return ss.str();
}

template<typename T>
T FromString(const std::string& str)
{
    std::istringstream ss(str);
    T ret;
    ss >> ret;
    return ret;
}

Example:

int i = FromString<int>(s);
std::string str = ToString(i);

Works for any streamable types (floats etc). You'll need to #include <sstream> and possibly also #include <string>.

How to restrict user to type 10 digit numbers in input element?

HTML

<input type="text" id="youridher" size="10">

Use JQuery,

SIZE = 10
$(document).ready(function() {
      $("#youridher").bind('keyup', function() { 
            if($("#youridher").val().length <= SIZE && PHONE_REGEX) {
                return true;
            }
            else {
                return false;
            }  
      });
});

How to insert blank lines in PDF?

You can trigger a newline by inserting Chunk.NEWLINE into your document. Here's an example.

public static void main(String args[]) {
    try {
        // create a new document
        Document document = new Document( PageSize.A4, 20, 20, 20, 20 );
        PdfWriter.getInstance( document, new FileOutputStream( "HelloWorld.pdf" ) );

        document.open();

        document.add( new Paragraph( "Hello, World!" ) );
        document.add( new Paragraph( "Hello, World!" ) );

        // add a couple of blank lines
        document.add( Chunk.NEWLINE );
        document.add( Chunk.NEWLINE );

        // add one more line with text
        document.add( new Paragraph( "Hello, World!" ) );

        document.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Below is a screen shot showing part of the PDF that the code above produces.

Hello PDF with blank lines inserted

How do I change the root directory of an Apache server?

This is for Ubunutu 14.04:

In file /etc/apache2/apache2.conf it should be as below without the directory name:

<Directory /home/username>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>

And in file /etc/apache2/sites-available/000-default.conf you should include the custom directory name, i.e., www:

DocumentRoot /home/username/www

If it is not as above, it will give you an error when loading the server:

Forbidden You don't have permission to access / on this server

How can I get selector from jQuery object

I've released a jQuery plugin: jQuery Selectorator, you can get selector like this.

$("*").on("click", function(){
  alert($(this).getSelector().join("\n"));
  return false;
});

Convert character to Date in R

library(lubridate) if your date format is like this '04/24/2017 05:35:00'then change it like below prods.all$Date2<-gsub("/","-",prods.all$Date2) then change the date format parse_date_time(prods.all$Date2, orders="mdy hms")

How to show full column content in a Spark Dataframe?

The other solutions are good. If these are your goals:

  1. No truncation of columns,
  2. No loss of rows,
  3. Fast and
  4. Efficient

These two lines are useful ...

    df.persist
    df.show(df.count, false) // in Scala or 'False' in Python

By persisting, the 2 executor actions, count and show, are faster & more efficient when using persist or cache to maintain the interim underlying dataframe structure within the executors. See more about persist and cache.

Array String Declaration

I think the beginning to the resolution to this issue is the fact that the use of the for loop or any other function or action can not be done in the class definition but needs to be included in a method/constructor/block definition inside of a class.

Play/pause HTML 5 video using JQuery

<video style="min-width: 100%; min-height: 100%; " id="vid" width="auto" height="auto" controls autoplay="true" loop="loop" preload="auto" muted="muted">
<source src="video/sample.mp4" type="video/mp4">
<source src="video/sample.ogg" type="video/ogg">
</video>
<script> 
$(document).ready(function(){
document.getElementById('vid').play(); });
</script> 

Safely casting long to int in Java

A new method has been added with Java 8 to do just that.

import static java.lang.Math.toIntExact;

long foo = 10L;
int bar = toIntExact(foo);

Will throw an ArithmeticException in case of overflow.

See: Math.toIntExact(long)

Several other overflow safe methods have been added to Java 8. They end with exact.

Examples:

  • Math.incrementExact(long)
  • Math.subtractExact(long, long)
  • Math.decrementExact(long)
  • Math.negateExact(long),
  • Math.subtractExact(int, int)

how to get javaScript event source element?

You can pass this when you call the function

<button onclick="doSomething('param',this)" id="id_button">action</button>

<script>
    function doSomething(param,me){

    var source = me
    console.log(source);
}
</script>

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I also had the same problem. I added the following. It works for me

Microsoft.EntityFrameworkCore.SqlServer

XAMPP - MySQL shutdown unexpectedly

My Xampp MySQL worked just follows as below:

01.Go to mysql/data/ directory
02. delete the ibdata1 & ib_logfile*(ib_logfile0,ib_logfile1,ib_logfile101) file
03. restart xampp server

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

for example I have this

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"

use RelativeLayout layout like this

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

HttpServletRequest - how to obtain the referring URL?

Actually it's: request.getHeader("Referer"), or even better, and to be 100% sure, request.getHeader(HttpHeaders.REFERER), where HttpHeaders is com.google.common.net.HttpHeaders

Understanding generators in Python

There is no Java equivalent.

Here is a bit of a contrived example:

#! /usr/bin/python
def  mygen(n):
    x = 0
    while x < n:
        x = x + 1
        if x % 3 == 0:
            yield x

for a in mygen(100):
    print a

There is a loop in the generator that runs from 0 to n, and if the loop variable is a multiple of 3, it yields the variable.

During each iteration of the for loop the generator is executed. If it is the first time the generator executes, it starts at the beginning, otherwise it continues from the previous time it yielded.

Can I limit the length of an array in JavaScript?

arr.length = Math.min(arr.length, 5)

Laravel 5 PDOException Could Not Find Driver

sudo apt-get update

For Mysql Database

sudo apt-get install php-mysql

For PostgreSQL Database

sudo apt-get install php-pgsql

Than

php artisan migrate

remove item from stored array in angular 2

You can delete the data from array

this.data.splice(index, 1);

How do I force a favicon refresh?

When you request the favicon from Google, you can take a look at the response headers.

Last-Modified: Fri, 09 Jan 2009 16:35:02 GMT
Date: Thu, 01 Dec 2010 00:00:01 GMT
Expires: Fri, 01 Dec 2011 00:00:01 GMT
Cache-Control: public, max-age=31536000
Age: 7

If you put an "Expires: " header on the response, client browsers will re-request the icon after that timestamp. While doing active development, you could set the expires timestamp to a second or two in the future, and always have it fetch this, although that's a poor longterm plan.

HTTP POST with URL query parameters -- good idea or not?

Everyone is right: stick with POST for non-idempotent requests.

What about using both an URI query string and request content? Well it's valid HTTP (see note 1), so why not?!

It is also perfectly logical: URLs, including their query string part, are for locating resources. Whereas HTTP method verbs (POST - and its optional request content) are for specifying actions, or what to do with resources. Those should be orthogonal concerns. (But, they are not beautifully orthogonal concerns for the special case of ContentType=application/x-www-form-urlencoded, see note 2 below.)

Note 1: HTTP specification (1.1) does not state that query parameters and content are mutually exclusive for a HTTP server that accepts POST or PUT requests. So any server is free to accept both. I.e. if you write the server there's nothing to stop you choosing to accept both (except maybe an inflexible framework). Generally, the server can interpret query strings according to whatever rules it wants. It can even interpret them with conditional logic that refers to other headers like Content-Type too, which leads to Note 2:

Note 2: if a web browser is the primary way people are accessing your web application, and application/x-www-form-urlencoded is the Content-Type they are posting, then you should follow the rules for that Content-Type. And the rules for application/x-www-form-urlencoded are much more specific (and frankly, unusual): in this case you must interpret the URI as a set of parameters, and not a resource location. [This is the same point of usefulness Powerlord raised; that it may be hard to use web forms to POST content to your server. Just explained a little differently.]

Note 3: what are query strings originally for? RFC 3986 defines HTTP query strings as an URI part that works as a non-hierarchical way of locating a resource.

In case readers asking this question wish to ask what is good RESTful architecture: the RESTful architecture pattern doesn't require URI schemes to work a specific way. RESTful architecture concerns itself with other properties of the system, like cacheability of resources, the design of the resources themselves (their behavior, capabilities, and representations), and whether idempotence is satisfied. Or in other words, achieving a design which is highly compatible with HTTP protocol and its set of HTTP method verbs. :-) (In other words, RESTful architecture is not very presciptive with how the resources are located.)

Final note: sometimes query parameters get used for yet other things, which are neither locating resources nor encoding content. Ever seen a query parameter like 'PUT=true' or 'POST=true'? These are workarounds for browsers that don't allow you to use PUT and POST methods. While such parameters are seen as part of the URL query string (on the wire), I argue that they are not part of the URL's query in spirit.

Use CSS to remove the space between images

I found that the only option that worked for me was

font-size:0;

I was also using overflow and white-space: nowrap; float: left; seems to mess things up

UIGestureRecognizer on UIImageView

For Blocks lover you can use ALActionBlocks to add action of gestures in block

__weak ALViewController *wSelf = self;
imageView.userInteractionEnabled = YES;
UITapGestureRecognizer *gr = [[UITapGestureRecognizer alloc] initWithBlock:^(UITapGestureRecognizer *weakGR) {
    NSLog(@"pan %@", NSStringFromCGPoint([weakGR locationInView:wSelf.view]));
}];
[self.imageView addGestureRecognizer:gr];

simulate background-size:cover on <video> or <img>

i'm gunna post this solution as well, since i had this problem but the other solutions did not work for my situation...

i think to properly simulate the background-size:cover; css property on an element instead of an elements background-image property, you'd have to compare the images aspect ratio to the current windows aspect ratio, so no matter what size (and also in case the image is taller than wider) the window is the element is filling the window (and also centering it, though i don't know if that was a requirement)....

using an image, just for simplicity's sake, i'm sure a video element would work fine too.

first get the elements aspect ratio (once it's loaded), then attach the window resize handler, trigger it once for initial sizing:

var img = document.getElementById( "background-picture" ),
    imgAspectRatio;

img.onload = function() {
    // get images aspect ratio
    imgAspectRatio = this.height / this.width;
    // attach resize event and fire it once
    window.onresize = resizeBackground;
    window.onresize();
}

then in your resize handler you should first determine whether to fill width or fill height by comparing the window's current aspect ratio to the image's original aspect ratio.

function resizeBackground( evt ) {

// get window size and aspect ratio
var windowWidth = window.innerWidth,
    windowHeight = window.innerHeight;
    windowAspectRatio = windowHeight / windowWidth;

//compare window ratio to image ratio so you know which way the image should fill
if ( windowAspectRatio < imgAspectRatio ) {
    // we are fill width
    img.style.width = windowWidth + "px";
    // and applying the correct aspect to the height now
    img.style.height = (windowWidth * imgAspectRatio) + "px";
    // this can be margin if your element is not positioned relatively, absolutely or fixed
    // make sure image is always centered
    img.style.left = "0px";
    img.style.top = (windowHeight - (windowWidth * imgAspectRatio)) / 2 + "px";
} else { // same thing as above but filling height instead
    img.style.height = windowHeight + "px";
    img.style.width = (windowHeight / imgAspectRatio) + "px";
    img.style.left = (windowWidth - (windowHeight / imgAspectRatio)) / 2 + "px";
    img.style.top = "0px";
}

}

How can I read large text files in Python, line by line, without loading it into memory?

I demonstrated a parallel byte level random access approach here in this other question:

Getting number of lines in a text file without readlines

Some of the answers already provided are nice and concise. I like some of them. But it really depends what you want to do with the data that's in the file. In my case I just wanted to count lines, as fast as possible on big text files. My code can be modified to do other things too of course, like any code.

Error: No module named psycopg2.extensions

first install apt-get install python-setuptools

then try easy_install psycopg2

Conditional replacement of values in a data.frame

Since you are conditionally indexing df$est, you also need to conditionally index the replacement vector df$a:

index <- df$b == 0
df$est[index] <- (df$a[index] - 5)/2.533 

Of course, the variable index is just temporary, and I use it to make the code a bit more readible. You can write it in one step:

df$est[df$b == 0] <- (df$a[df$b == 0] - 5)/2.533 

For even better readibility, you can use within:

df <- within(df, est[b==0] <- (a[b==0]-5)/2.533)

The results, regardless of which method you choose:

df
          a b      est
1  11.77000 2 0.000000
2  10.90000 3 0.000000
3  10.32000 2 0.000000
4  10.96000 0 2.352941
5   9.90600 0 1.936834
6  10.70000 0 2.250296
7  11.43000 1 0.000000
8  11.41000 2 0.000000
9  10.48512 4 0.000000
10 11.19000 0 2.443743

As others have pointed out, an alternative solution in your example is to use ifelse.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

org.hibernate.MappingException: Could not determine type for: java.util.Set

Adding the @ElementCollection to the List field solved this issue:

@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;

How do I update a formula with Homebrew?

I think the correct way to do is

brew upgrade mongodb

It will upgrade the mongodb formula. If you want to upgrade all outdated formula, simply

brew upgrade

What does "publicPath" in Webpack do?

The webpack2 documentation explains this in a much cleaner way: https://webpack.js.org/guides/public-path/#use-cases

webpack has a highly useful configuration that let you specify the base path for all the assets on your application. It's called publicPath.

Using the AND and NOT Operator in Python

It's called and and or in Python.

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

After spending hours on this issue found solution here

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
    
@NgModule({
    imports: [
         FormsModule,
         ReactiveFormsModule      
    ]
})

When to use Task.Delay, when to use Thread.Sleep?

I want to add something. Actually, Task.Delay is a timer based wait mechanism. If you look at the source you would find a reference to a Timer class which is responsible for the delay. On the other hand Thread.Sleep actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always use Task.Delay() if you want something(continuation) happen after some delay.

PostgreSQL: How to change PostgreSQL user password?

You can and should have the users's password encrypted:

ALTER USER username WITH ENCRYPTED PASSWORD 'password';

ArrayList: how does the size increase?

  1. Arraylist default capacity is 10.

  2. [1,2,3,4,5.....10]

  3. if you want to increase the size of Arraylist in java, you can apply this

  4. formula-

  5. int newcapacity, current capacity;

  6. newcapacity =((current capacity*3/2)+1)

  7. arralist will be [1,2,3,4,5.....10,11] and arraylist capacity is 16.

How to compare 2 files fast using .NET?

Another improvement on large files with identical length, might be to not read the files sequentially, but rather compare more or less random blocks.

You can use multiple threads, starting on different positions in the file and comparing either forward or backwards.

This way you can detect changes at the middle/end of the file, faster than you would get there using a sequential approach.

Turn a simple socket into an SSL socket

There are several steps when using OpenSSL. You must have an SSL certificate made which can contain the certificate with the private key be sure to specify the exact location of the certificate (this example has it in the root). There are a lot of good tutorials out there.

Some includes:

#include <openssl/applink.c>
#include <openssl/bio.h>
#include <openssl/ssl.h>
#include <openssl/err.h>

You will need to initialize OpenSSL:

void InitializeSSL()
{
    SSL_load_error_strings();
    SSL_library_init();
    OpenSSL_add_all_algorithms();
}

void DestroySSL()
{
    ERR_free_strings();
    EVP_cleanup();
}

void ShutdownSSL()
{
    SSL_shutdown(cSSL);
    SSL_free(cSSL);
}

Now for the bulk of the functionality. You may want to add a while loop on connections.

int sockfd, newsockfd;
SSL_CTX *sslctx;
SSL *cSSL;

InitializeSSL();
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd< 0)
{
    //Log and Error
    return;
}
struct sockaddr_in saiServerAddress;
bzero((char *) &saiServerAddress, sizeof(saiServerAddress));
saiServerAddress.sin_family = AF_INET;
saiServerAddress.sin_addr.s_addr = serv_addr;
saiServerAddress.sin_port = htons(aPortNumber);

bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr));

listen(sockfd,5);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);

sslctx = SSL_CTX_new( SSLv23_server_method());
SSL_CTX_set_options(sslctx, SSL_OP_SINGLE_DH_USE);
int use_cert = SSL_CTX_use_certificate_file(sslctx, "/serverCertificate.pem" , SSL_FILETYPE_PEM);

int use_prv = SSL_CTX_use_PrivateKey_file(sslctx, "/serverCertificate.pem", SSL_FILETYPE_PEM);

cSSL = SSL_new(sslctx);
SSL_set_fd(cSSL, newsockfd );
//Here is the SSL Accept portion.  Now all reads and writes must use SSL
ssl_err = SSL_accept(cSSL);
if(ssl_err <= 0)
{
    //Error occurred, log and close down ssl
    ShutdownSSL();
}

You are then able read or write using:

SSL_read(cSSL, (char *)charBuffer, nBytesToRead);
SSL_write(cSSL, "Hi :3\n", 6);

Update The SSL_CTX_new should be called with the TLS method that best fits your needs in order to support the newer versions of security, instead of SSLv23_server_method(). See: OpenSSL SSL_CTX_new description

TLS_method(), TLS_server_method(), TLS_client_method(). These are the general-purpose version-flexible SSL/TLS methods. The actual protocol version used will be negotiated to the highest version mutually supported by the client and the server. The supported protocols are SSLv3, TLSv1, TLSv1.1, TLSv1.2 and TLSv1.3.

Javascript one line If...else...else if statement

I know this is an old thread, but thought I'd put my two cents in. Ternary operators are able to be nested in the following fashion:

var variable = conditionA ? valueA : (conditionB ? valueB: (conditionC ? valueC : valueD));

Example:

var answer = value === 'foo' ? 1 :
    (value === 'bar' ? 2 : 
        (value === 'foobar' ? 3 : 0));

Use 'import module' or 'from module import'?

I was answering a similar question post but the poster deleted it before i could post. Here is one example to illustrate the differences.

Python libraries may have one or more files (modules). For exmaples,

package1
  |-- __init__.py

or

package2
  |-- __init__.py
  |-- module1.py
  |-- module2.py

We can define python functions or classes inside any of the files based design requirements.

Let's define

  1. func1() in __init__.py under mylibrary1, and
  2. foo() in module2.py under mylibrary2.

We can access func1() using one of these methods

import package1

package1.func1()

or

import package1 as my

my.func1()

or

from package1 import func1

func1()

or

from package1 import *

func1()

We can use one of these methods to access foo():

import package2.module2

package2.module2.foo()

or

import package2.module2 as mod2

mod2.foo()

or

from package2 import module2

module2.foo()

or

from package2 import module2 as mod2

mod2.foo()

or

from package2.module2 import *

foo()

angularjs directive call function specified in attribute and pass an argument to it

Not knowing exactly what you want to do... but still here's a possible solution.

Create a scope with a '&'-property in the local scope. It "provides a way to execute an expression in the context of the parent scope" (see the directive documentation for details).

I also noticed that you used a shorthand linking function and shoved in object attributes in there. You can't do that. It is more clear (imho) to just return the directive-definition object. See my code below.

Here's a code sample and a fiddle.

<div ng-app="myApp">
<div ng-controller="myController">
    <div my-method='theMethodToBeCalled'>Click me</div>
</div>
</div>

<script>

   var app = angular.module('myApp',[]);

   app.directive("myMethod",function($parse) {
       var directiveDefinitionObject = {
         restrict: 'A',
         scope: { method:'&myMethod' },
         link: function(scope,element,attrs) {
            var expressionHandler = scope.method();
            var id = "123";

            $(element).click(function( e, rowid ) {
               expressionHandler(id);
            });
         }
       };
       return directiveDefinitionObject;
   });

   app.controller("myController",function($scope) {
      $scope.theMethodToBeCalled = function(id) { 
          alert(id); 
      };
   });

</script>

com.jcraft.jsch.JSchException: UnknownHostKey

Supply the public rsa key of the host :-

String knownHostPublicKey = "mywebsite.com ssh-rsa AAAAB3NzaC1.....XL4Jpmp/";

session.setKnownHosts(new ByteArrayInputStream(knownHostPublicKey.getBytes()));

How to SUM two fields within an SQL query

Try the following:

SELECT *, (FieldA + FieldB) AS Sum
FROM Table

When should a class be Comparable and/or Comparator?

here are few differences between Comparator and Comparable I found on web :

  1. If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.

  2. Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.

  3. If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Array.sort() method and object will be sorted based on there natural order defined by CompareTo method.

  4. Objects which implement Comparable in Java can be used as keys in a sorted map or elements in a sorted set for example TreeSet, without specifying any Comparator.

site:How to use Comparator and Comparable in Java? With example

Read more: How to use Comparator and Comparable in Java? With example

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.

How do I control how Emacs makes backup files?

If you've ever been saved by an Emacs backup file, you probably want more of them, not less of them. It is annoying that they go in the same directory as the file you're editing, but that is easy to change. You can make all backup files go into a directory by putting something like the following in your .emacs.

(setq backup-directory-alist `(("." . "~/.saves")))

There are a number of arcane details associated with how Emacs might create your backup files. Should it rename the original and write out the edited buffer? What if the original is linked? In general, the safest but slowest bet is to always make backups by copying.

(setq backup-by-copying t)

If that's too slow for some reason you might also have a look at backup-by-copying-when-linked.

Since your backups are all in their own place now, you might want more of them, rather than less of them. Have a look at the Emacs documentation for these variables (with C-h v).

(setq delete-old-versions t
  kept-new-versions 6
  kept-old-versions 2
  version-control t)

Finally, if you absolutely must have no backup files:

(setq make-backup-files nil)

It makes me sick to think of it though.

How can I remove a trailing newline?

An example in Python's documentation simply uses line.strip().

Perl's chomp function removes one linebreak sequence from the end of a string only if it's actually there.

Here is how I plan to do that in Python, if process is conceptually the function that I need in order to do something useful to each line from this file:

import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
    for line in f:
        if line[sep_pos:] == os.linesep:
            line = line[:sep_pos]
        process(line)

Android Color Picker

After some searches in the android references, the newcomer QuadFlask Color Picker seems to be a technically and aesthetically good choice. Also it has Transparency slider and supports HEX coded colors.

Take a look:
QuadFlask Color Picker

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

SeekBar and media player in android

Try this Code:

public class MainActivity extends AppCompatActivity {

MediaPlayer mplayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

            //You create MediaPlayer variable ==> set the path and start the audio.

    mplayer = MediaPlayer.create(this, R.raw.example);
    mplayer.start();

            //Find the seek bar by Id (which you have to create in layout)
            // Set seekBar max with length of audio
           // You need a Timer variable to set progress with position of audio

    final SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
    seekBar.setMax(mplayer.getDuration());

    new Timer().scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    seekBar.setProgress(mplayer.getCurrentPosition());
                }
            }, 0, 1000);


            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            // Update the progress depending on seek bar
                    mplayer.seekTo(progress);

                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {

                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }

How to cache Google map tiles for offline usage?

update:

I found the terms of use from Google Map:

Section 10.5

No caching or storage. You will not pre-fetch, cache, index, or store any Content to be used outside the Service, except that you may store limited amounts of Content solely for the purpose of improving the performance of your Maps API Implementation due to network latency (and not for the purpose of preventing Google from accurately tracking usage), and only if such storage: is temporary (and in no event more than 30 calendar days); is secure; does not manipulate or aggregate any part of the Content or Service; and does not modify attribution in any way.

It means we can cache for limited time actually

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

What does it mean when a PostgreSQL process is "idle in transaction"?

As mentioned here: Re: BUG #4243: Idle in transaction it is probably best to check your pg_locks table to see what is being locked and that might give you a better clue where the problem lies.

Display html text in uitextview

For Swift 4, Swift 4.2: and Swift 5

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]

let attributedString = try! NSAttributedString(data: htmlData!, options: options, documentAttributes: nil)

textView.attributedText = attributedString

For Swift 3:

let htmlString = """
    <html>
        <head>
            <style>
                body {
                    background-color : rgb(230, 230, 230);
                    font-family      : 'Arial';
                    text-decoration  : none;
                }
            </style>
        </head>
        <body>
            <h1>A title</h1>
            <p>A paragraph</p>
            <b>bold text</b>
        </body>
    </html>
    """

let htmlData = NSString(string: htmlString).data(using: String.Encoding.unicode.rawValue)

let attributedString = try! NSAttributedString(data: htmlData!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)

textView.attributedText = attributedString

Oracle Age calculation from Date of birth and Today

For business logic I usually find a decimal number (in years) is useful:

select months_between(TRUNC(sysdate),
                      to_date('15-Dec-2000','DD-MON-YYYY')
                     )/12
as age from dual;

       AGE
----------
9.48924731

How to get detailed list of connections to database in sql server 2005?

sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2

SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'

(Adapted from SQL Server: Filter output of sp_who2.)

In c# what does 'where T : class' mean?

It is a generic type constraint. In this case it means that the generic type T has to be a reference type (class, interface, delegate, or array type).

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Removing duplicate objects with Underscore for Javascript

with underscore i had to use String() in the iteratee function

function isUniq(item) {
    return String(item.user);
}
var myUniqArray = _.uniq(myArray, isUniq);

Can't ignore UserInterfaceState.xcuserstate

Git is probably already tracking the file.

From the gitignore docs:

To stop tracking a file that is currently tracked, use git rm --cached.

Use this, replacing [project] and [username] with your info:

git rm --cached [project].xcodeproj/project.xcworkspace/xcuserdata/[username].xcuserdatad/UserInterfaceState.xcuserstate
git commit -m "Removed file that shouldn't be tracked"

Alternatively you can use the -a option to git commit that will add all files that have been modified or deleted.

Once you've removed the file from git, it will respect your .gitignore.

ImportError: No module named MySQLdb

Or try this:

apt-get install python-mysqldb

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Python Anaconda - How to Safely Uninstall

To uninstall anaconda you have to:

1) Remove the entire anaconda install directory with:

rm -rf ~/anaconda2

2) And (OPTIONAL):

->Edit ~/.bash_profile to remove the anaconda directory from your PATH environment variable.

->Remove the following hidden file and folders that may have been created in the home directory:

rm -rf ~/.condarc ~/.conda ~/.continuum

source

How to send email to multiple address using System.Net.Mail

 string[] MultiEmails = email.Split(',');
 foreach (string ToEmail in MultiEmails)
 {
    message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
 }

HTML entity for the middle dot

There's actually seven variants of this:

    char   description          unicode   html       html entity    utf-8

    ·      Middle Dot           U+00B7    &#183;     &middot;       C2 B7
    ·      Greek Ano Teleia     U+0387    &#903;                    CE 87
    •      Bullet               U+2022    &#8226;    &bull;         E2 80 A2
    ‧      Hyphenation Point    U+2027    &#8321;                   E2 80 A7
    ∙      Bullet Operator      U+2219    &#8729;                   E2 88 99
    ●      Black Circle         U+25CF    &#9679;                   E2 97 8F
    ⬤     Black Large Circle   U+2B24    &#11044;                  E2 AC A4

Depending on your viewing application or font, the Bullet Operator may seem very similar to either the Middle Dot or the Bullet.

how to delete a specific row in codeigniter?

**multiple delete not working**

function delete_selection() 
{
        $id_array = array();
        $selection = $this->input->post("selection", TRUE);
        $id_array = explode("|", $selection);

        foreach ($id_array as $item):
            if ($item != ''):
                //DELETE ROW
                $this->db->where('entry_id', $item);
                $this->db->delete('helpline_entry');
            endif;
        endforeach;
    }

Remove trailing comma from comma-separated string

public static String removeExtraCommas(String entry) {
    if(entry==null)
        return null;

    String ret="";
    entry=entry.replaceAll("\\s","");
    String arr[]=entry.split(",");
    boolean start=true;
    for(String str:arr) {
        if(!"".equalsIgnoreCase(str)) {
            if(start) {
                ret=str;
                start=false;
            }
            else {
            ret=ret+","+str;
            }
        }
    }               
    return ret;

}

How does System.out.print() work?

The scenarios that you have mentioned are not of overloading, you are just concatenating different variables with a String.

System.out.print("Hello World");

System.out.print("My name is" + foo);

System.out.print("Sum of " + a + "and " + b + "is " + c); 

System.out.print("Total USD is " + usd);

in all of these cases, you are only calling print(String s) because when something is concatenated with a string it gets converted to a String by calling the toString() of that object, and primitives are directly concatenated. However if you want to know of different signatures then yes print() is overloaded for various arguments.

Check if page gets reloaded or refreshed in JavaScript

Store a cookie the first time someone visits the page. On refresh check if your cookie exists and if it does, alert.

function checkFirstVisit() {
  if(document.cookie.indexOf('mycookie')==-1) {
    // cookie doesn't exist, create it now
    document.cookie = 'mycookie=1';
  }
  else {
    // not first visit, so alert
    alert('You refreshed!');
  }
}

and in your body tag:

<body onload="checkFirstVisit()">

Use string in switch case in java

Java 8 supports string switchcase.

String type = "apple";

switch(type){
    case "apple":
       //statements
    break;
    default:
       //statements
    break; }

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Difference between application/x-javascript and text/javascript content types

text/javascript is obsolete, and application/x-javascript was experimental (hence the x- prefix) for a transitional period until application/javascript could be standardised.

You should use application/javascript. This is documented in the RFC.

As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/* and application/* MIME type groups had a consistent meaning where possible. (text/* MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).

Note that using application/javascript in the type attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript there or omit the attribute entirely (which is permitted in HTML 5).

This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript.

Why doesn't list have safe "get" method like dictionary?

Try this:

>>> i = 3
>>> a = [1, 2, 3, 4]
>>> next(iter(a[i:]), 'fail')
4
>>> next(iter(a[i + 1:]), 'fail')
'fail'

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

Including a css file in a blade template?

in your main layout put this in the head at the bottom of everything

@stack('styles')

and in your view put this

@push('styles')

    <link rel="stylesheet" href="{{ asset('css/app.css') }}">

@endpush

basically a placeholder so the links will appear on your main layout, and you can see custom css files on different pages

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

If you're using concatenate method then don't forget to trim the string if you're working with if else method.

Arrays vs Vectors: Introductory Similarities and Differences

arrays:

  • are a builtin language construct;
  • come almost unmodified from C89;
  • provide just a contiguous, indexable sequence of elements; no bells and whistles;
  • are of fixed size; you can't resize an array in C++ (unless it's an array of POD and it's allocated with malloc);
  • their size must be a compile-time constant unless they are allocated dynamically;
  • they take their storage space depending from the scope where you declare them;
  • if dynamically allocated, you must explicitly deallocate them;
  • if they are dynamically allocated, you just get a pointer, and you can't determine their size; otherwise, you can use sizeof (hence the common idiom sizeof(arr)/sizeof(*arr), that however fails silently when used inadvertently on a pointer);
  • automatically decay to a pointers in most situations; in particular, this happens when passing them to a function, which usually requires passing a separate parameter for their size;
  • can't be returned from a function;
  • can't be copied/assigned directly;
  • dynamical arrays of objects require a default constructor, since all their elements must be constructed first;

std::vector:

  • is a template class;
  • is a C++ only construct;
  • is implemented as a dynamic array;
  • grows and shrinks dynamically;
  • automatically manage their memory, which is freed on destruction;
  • can be passed to/returned from functions (by value);
  • can be copied/assigned (this performs a deep copy of all the stored elements);
  • doesn't decay to pointers, but you can explicitly get a pointer to their data (&vec[0] is guaranteed to work as expected);
  • always brings along with the internal dynamic array its size (how many elements are currently stored) and capacity (how many elements can be stored in the currently allocated block);
  • the internal dynamic array is not allocated inside the object itself (which just contains a few "bookkeeping" fields), but is allocated dynamically by the allocator specified in the relevant template parameter; the default one gets the memory from the freestore (the so-called heap), independently from how where the actual object is allocated;
  • for this reason, they may be less efficient than "regular" arrays for small, short-lived, local arrays;
  • when reallocating, the objects are copied (moved, in C++11);
  • does not require a default constructor for the objects being stored;
  • is better integrated with the rest of the so-called STL (it provides the begin()/end() methods, the usual STL typedefs, ...)

Also consider the "modern alternative" to arrays - std::array; I already described in another answer the difference between std::vector and std::array, you may want to have a look at it.

How to print a stack trace in Node.js?

you can use node-stack-trace module which is a power full module to track call stacks.

Using HTML data-attribute to set CSS background-image url

How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).

/*
  Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";

@each $i in $social {
  [data-social="#{$i}"] {
    background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
    background-size: cover; // Only seems to work if placed below background property
  }
}

Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.

Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

Install Windows Service created in Visual Studio

Yet another catch I ran into: ensure your Installer derived class (typically ProjectInstaller) is at the top of the namespace hierarchy, I tried to use a public class within another public class, but this results in the same old error:

No public installers with the RunInstallerAttribute.Yes attribute could be found

How do I get Fiddler to stop ignoring traffic to localhost?

Fiddler's website addresses this question directly.

There are several suggested workarounds, but the most straightforward is simply to use the machine name rather than "localhost" or "127.0.0.1":

http://machinename/mytestpage.aspx

Truncate Decimal number not Round Off

Forget Everything just check out this

double num = 2.22939393;
num  = Convert.ToDouble(num.ToString("#0.000"));

Correct way to quit a Qt program?

While searching this very question I discovered this example in the documentation.

QPushButton *quitButton = new QPushButton("Quit");
connect(quitButton, &QPushButton::clicked, &app, &QCoreApplication::quit, Qt::QueuedConnection);

Mutatis mutandis for your particular action of course.

Along with this note.

It's good practice to always connect signals to this slot using a QueuedConnection. If a signal connected (non-queued) to this slot is emitted before control enters the main event loop (such as before "int main" calls exec()), the slot has no effect and the application never exits. Using a queued connection ensures that the slot will not be invoked until after control enters the main event loop.

It's common to connect the QGuiApplication::lastWindowClosed() signal to quit()

How do I auto-hide placeholder text upon focus using css or jquery?

For a pure CSS based solution:

input:focus::-webkit-input-placeholder  {color:transparent;}
input:focus::-moz-placeholder   {color:transparent;}
input:-moz-placeholder   {color:transparent;}

Note: Not yet supported by all browser vendors.

Reference: Hide placeholder text on focus with CSS by Ilia Raiskin.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

the mysqli_queryexcepts 2 parameters , first variable is mysqli_connectequivalent variable , second one is the query you have provided

$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);

$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");

How to kill an application with all its activities?

which is stored in the SharesPreferences as long as the application needs it.

Why?

As soon as the user wants to exit, the password in the SharedPreferences should be wiped and of course all activities of the application should be closed (it makes no sense to run them without the known password - they would crash).

Even better: don't put the password in SharedPreferences. Hold onto it in a static data member. The data will naturally go away when all activities in the app are exited (e.g., BACK button) or otherwise destroyed (e.g., kicked out of RAM to make room for other activities sometime after the user pressed HOME).

If you want some sort of proactive "flush password", just set the static data member to null, and have your activities check that member and take appropriate action when it is null.

milliseconds to days

If you don't have another time interval bigger than days:

int days = (int) (milliseconds / (1000*60*60*24));

If you have weeks too:

int days = (int) ((milliseconds / (1000*60*60*24)) % 7);
int weeks = (int) (milliseconds / (1000*60*60*24*7));

It's probably best to avoid using months and years if possible, as they don't have a well-defined fixed length. Strictly speaking neither do days: daylight saving means that days can have a length that is not 24 hours.

Mongoose.js: Find user by username LIKE value

if I want to query all record at some condition,I can use this:

if (userId == 'admin')
  userId = {'$regex': '.*.*'};
User.where('status', 1).where('creator', userId);

How to sort a data frame by alphabetic order of a character variable in R?

Use order function:

set.seed(1)
DF <- data.frame(ID= sample(letters[1:26], 15, TRUE),
                 num = sample(1:100, 15, TRUE),
                 random = rnorm(15),
                 stringsAsFactors=FALSE)
DF[order(DF[,'ID']), ]
   ID num      random
10  b  27  0.61982575
12  e   2 -0.15579551
5   f  78  0.59390132
11  f  39 -0.05612874
1   g  50 -0.04493361
2   j  72 -0.01619026
14  j  87 -0.47815006
3   o 100  0.94383621
9   q  13 -1.98935170
8   r  66  0.07456498
13  r  39 -1.47075238
15  u  35  0.41794156
4   x  39  0.82122120
6   x  94  0.91897737
7   y  22  0.78213630

Another solution would be using orderByfunction from doBy package:

> library(doBy)
> orderBy(~ID, DF)

Pip install - Python 2.7 - Windows 7

For New versions

Older versions of python may not have pip installed and get-pip will throw errors. Please update your python (2.7.15 as of Aug 12, 2018).

All current versions have an option to install pip and add it to the path.

Steps:

  1. Open Powershell as admin. (win+x then a)
  2. Type python -m pip install <package>.

If python is not in PATH, it'll throw an error saying unrecognized cmd. To fix, simply add it to the path as mentioned below.

[OLD Answer]

Python 2.7 must be having pip pre-installed.

Try installing your package by:

  1. Open cmd as admin. (win+x then a)
  2. Go to scripts folder: C:\Python27\Scripts
  3. Type pip install "package name".

Note: Else reinstall python: https://www.python.org/downloads/

Also note: You must be in C:\Python27\Scripts in order to use pip command, Else add it to your path by typing: [Environment]::SetEnvironmentVariable("Path","$env:Path;C:\Python27\;C:\Python27\Scripts\", "User")

Change string color with NSAttributedString?

One liner for Swift:

NSAttributedString(string: "Red Text", attributes: [.foregroundColor: UIColor.red])

GIT_DISCOVERY_ACROSS_FILESYSTEM problem when working with terminal and MacFusion

Try a different protocol. git:// may have problems from your firewall, for example; try a git clone with https: instead.

How do you determine the size of a file in C?

POSIX

The POSIX standard has its own method to get file size.
Include the sys/stat.h header to use the function.

Synopsis

  • Get file statistics using stat(3).
  • Obtain the st_size property.

Examples

Note: It limits the size to 4GB. If not Fat32 filesystem then use the 64bit version!

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat info;
    stat(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat64 info;
    stat64(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}

ANSI C (standard)

The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!

Synopsis

  • Seek the file to the end using fseek(3).
  • Get the current position using ftell(3).

Example

#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* fp = fopen(argv[1]);
    int f_size;

    fseek(fp, 0, SEEK_END);
    f_size = ftell(fp);
    rewind(fp); // to back to start again

    printf("%s: size=%ld", (unsigned long)f_size);
}

If the file is stdin or a pipe. POSIX, ANSI C won't work.
It will going return 0 if the file is a pipe or stdin.

Opinion: You should use POSIX standard instead. Because, it has 64bit support.

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

you can use this

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost:3306/YOUR_DB_NAME";


   static final String USER = "root";
   static final String PASS = "YOUR_ROOT_PASSWORD"; 

  Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);

you have to give the right root password .

How to get textLabel of selected row in swift?

Swift 4

To get the label of the selected row:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
    print(cell.textLabel?.text)
}

To get the label of the deselected row:

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    let cell = tableView.cellForRow(at: indexPath) as! TableViewCell
    print(cell.textLabel?.text)
}

Android ClassNotFoundException: Didn't find class on path

If you are using Multidex on Android 4.4 and prior, your issue might be that your activity class is located in the second dex file and therefore not found by the android system.

To keep your activity class in the main dex file, see this page:

https://developer.android.com/studio/build/multidex.html#keep


To find which classes are located in a dex file use Android Studio.

Simply drag n drop your apk into Android Studio. You should be able to see your dex files in the apk explorer.

Then select the dex file to see what classes are inside.


another alternative is dexdump:

You can check the content of your dex files contained in your apk by using the command dexdump which can be found in

android-sdk/build-tools/27.0.3/dexdump

For windows users see this tool I made to ease the process

HTML / CSS table with GRIDLINES

<table border="1"></table>

should do the trick.

Palindrome check in Javascript

Thought I will share my solution using Array.prototype.filter(). filter() filters the array based on boolean values the function returns.

var inputArray=["","a","ab","aba","abab","ababa"]
var outputArray=inputArray.filter(function isPalindrome(x){
  if (x.length<2) return true;
  var y=x.split("").reverse().join("");
  return x==y;
})
console.log(outputArray);

Iterate keys in a C++ map

You could

  • create a custom iterator class, aggregating the std::map<K,V>::iterator
  • use std::transform of your map.begin() to map.end() with a boost::bind( &pair::second, _1 ) functor
  • just ignore the ->second member while iterating with a for loop.

What is time_t ultimately a typedef to?

Typically you will find these underlying implementation-specific typedefs for gcc in the bits or asm header directory. For me, it's /usr/include/x86_64-linux-gnu/bits/types.h.

You can just grep, or use a preprocessor invocation like that suggested by Quassnoi to see which specific header.

Regex match everything after question mark?

str.replace(/^.+?\"|^.|\".+/, '');

This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.

Even for me it is a bit confusing, but ill try to explain it. ^.+? (not anything OPTIONAL) till first " then | Or/stop (still researching what it really means) till/at ^. has selected nothing until before the 2nd " using (| stop/at). And select all that comes after with .+.

Changing user agent on urllib2.urlopen

Another solution in urllib2 and Python 2.7:

req = urllib2.Request('http://www.example.com/')
req.add_unredirected_header('User-Agent', 'Custom User-Agent')
urllib2.urlopen(req)

An example of how to use getopts in bash

Use getopt

Why getopt?

To parse elaborated command-line arguments to avoid confusion and clarify the options we are parsing so that reader of the commands can understand what's happening.

What is getopt?

getopt is used to break up (parse) options in command lines for easy parsing by shell procedures, and to check for legal options. It uses the GNU getopt(3) routines to do this.

getopt can have following types of options.

  1. No-value options
  2. key-value pair options

Note: In this document, during explaining syntax:

  • Anything inside [ ] is optional parameter in the syntax/examples.
  • is a place holder, which mean it should be substituted with an actual value.

HOW TO USE getopt?

Syntax: First Form

getopt optstring parameters

Examples:

# This is correct
getopt "hv:t::" "-v 123 -t123"  
getopt "hv:t::" "-v123 -t123"  # -v and 123 doesn't have whitespace

# -h takes no value.
getopt "hv:t::" "-h -v123"


# This is wrong. after -t can't have whitespace.
# Only optional params cannot have whitespace between key and value
getopt "hv:t::" "-v 123 -t 123"

# Multiple arguments that takes value.
getopt "h:v:t::g::" "-h abc -v 123 -t21"

# Multiple arguments without value
# All of these are correct
getopt "hvt" "-htv"
getopt "hvt" "-h -t -v"
getopt "hvt" "-tv -h"

Here h,v,t are the options and -h -v -t is how options should be given in command-line.

  1. 'h' is a no-value option.
  2. 'v:' implies that option -v has value and is a mandatory option. ':' means has a value.
  3. 't::' implies that option -t has value but is optional. '::' means optional.

In optional param, value cannot have whitespace separation with the option. So, in "-t123" example, -t is option 123 is value.

Syntax: Second Form

getopt [getopt_options] [--] [optstring] [parameters]

Here after getopt is split into five parts

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The short options, is taken immediately after -- is found. Just like the Form first syntax.
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.

Examples

getopt -l "name:,version::,verbose" -- "n:v::V" "--name=Karthik -version=5.2 -verbose"

Syntax: Third Form

getopt [getopt_options] [-o options] [--] [optstring] [parameters]

Here after getopt is split into five parts

  • The command itself i.e. getopt
  • The getopt_options, it describes how to parse the arguments. single dash long options, double dash options.
  • The short options i.e. -o or --options. Just like the Form first syntax but with option "-o" and before the "--" (double dash).
  • --, separates out the getopt_options from the options you want to parse and the allowed short options
  • The parameters, these are the options that you have passed into the program. The options you want to parse and get the actual values set on them.

Examples

getopt -l "name:,version::,verbose" -a -o "n:v::V" -- "-name=Karthik -version=5.2 -verbose"

GETOPT_OPTIONS

getopt_options changes the way command-line params are parsed.

Below are some of the getopt_options

Option: -l or --longoptions

Means getopt command should allow multi-character options to be recognised. Multiple options are separated by comma.

For example, --name=Karthik is a long option sent in command line. In getopt, usage of long options are like

getopt "name:,version" "--name=Karthik"

Since name: is specified, the option should contain a value

Option: -a or --alternative

Means getopt command should allow long option to have a single dash '-' rather than double dash '--'.

Example, instead of --name=Karthik you could use just -name=Karthik

getopt "name:,version" "-name=Karthik"

A complete script example with the code:

#!/bin/bash

# filename: commandLine.sh
# author: @theBuzzyCoder

showHelp() {
# `cat << EOF` This means that cat should stop reading when EOF is detected
cat << EOF  
Usage: ./installer -v <espo-version> [-hrV]
Install Pre-requisites for EspoCRM with docker in Development mode

-h, -help,          --help                  Display help

-v, -espo-version,  --espo-version          Set and Download specific version of EspoCRM

-r, -rebuild,       --rebuild               Rebuild php vendor directory using composer and compiled css using grunt

-V, -verbose,       --verbose               Run script in verbose mode. Will print out each step of execution.

EOF
# EOF is found above and hence cat command stops reading. This is equivalent to echo but much neater when printing out.
}


export version=0
export verbose=0
export rebuilt=0

# $@ is all command line parameters passed to the script.
# -o is for short options like -v
# -l is for long options with double dash like --version
# the comma separates different long options
# -a is for long options with single dash like -version
options=$(getopt -l "help,version:,verbose,rebuild,dryrun" -o "hv:Vrd" -a -- "$@")

# set --:
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters 
# are set to the arguments, even if some of them begin with a ‘-’.
eval set -- "$options"

while true
do
case $1 in
-h|--help) 
    showHelp
    exit 0
    ;;
-v|--version) 
    shift
    export version=$1
    ;;
-V|--verbose)
    export verbose=1
    set -xv  # Set xtrace and verbose mode.
    ;;
-r|--rebuild)
    export rebuild=1
    ;;
--)
    shift
    break;;
esac
shift
done

Running this script file:

# With short options grouped together and long option
# With double dash '--version'

bash commandLine.sh --version=1.0 -rV
# With short options grouped together and long option
# With single dash '-version'

bash commandLine.sh -version=1.0 -rV

# OR with short option that takes value, value separated by whitespace
# by key

bash commandLine.sh -v 1.0 -rV

# OR with short option that takes value, value without whitespace
# separation from key.

bash commandLine.sh -v1.0 -rV

# OR Separating individual short options

bash commandLine.sh -v1.0 -r -V

Find value in an array

Use:

myarray.index "valuetoFind"

That will return you the index of the element you want or nil if your array doesn't contain the value.

Entity Framework is Too Slow. What are my options?

From my experience, the problem not with EF, but with ORM approach itself.

In general all ORMs suffers from N+1 problem not optimized queries and etc. My best guess would be to track down queries that causes performance degradation and try to tune-up ORM tool, or rewrite that parts with SPROC.

Android Studio doesn't start, fails saying components not installed

I encountered the same problem attempting to setup Android Studio from work. Running as admin didn't solve my problem, and I don't have direct access to proxy / firewall settings. In the end I resolved the issue by using the Android SDK Manager and installing the proper packages. A few of the package names and error messages (from studio install failure) didn't match up directly but a quick Google search showed me the light.

Hope this helps!

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Hers's what I used to get the day names (0-6 means monday - sunday):

public static String getFullDayName(int day) {
    Calendar c = Calendar.getInstance();
    // date doesn't matter - it has to be a Monday
    // I new that first August 2011 is one ;-)
    c.set(2011, 7, 1, 0, 0, 0);
    c.add(Calendar.DAY_OF_MONTH, day);
    return String.format("%tA", c);
}

public static String getShortDayName(int day) {
    Calendar c = Calendar.getInstance();
    c.set(2011, 7, 1, 0, 0, 0);
    c.add(Calendar.DAY_OF_MONTH, day);
    return String.format("%ta", c);
}

Can we rely on String.isEmpty for checking null condition on a String in Java?

Use StringUtils.isEmpty instead, it will also check for null.

Examples are:

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

See more on official Documentation on String Utils.

JavaScript dictionary with names

An object technically is a dictionary.

var myMappings = {
    mykey1: 'myValue',
    mykey2: 'myValue'
};

var myVal = myMappings['myKey1'];

alert(myVal); // myValue

You can even loop through one.

for(var key in myMappings) {
    var myVal = myMappings[key];
    alert(myVal);
}

There is no reason whatsoever to reinvent the wheel. And of course, assignment goes like:

myMappings['mykey3'] = 'my value';

And ContainsKey:

if (myMappings.hasOwnProperty('myKey3')) {
    alert('key already exists!');
}

I suggest you follow this: http://javascriptissexy.com/how-to-learn-javascript-properly/

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

You can view this dump from the UNIX console.

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

E.g.:

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

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

Java double comparison epsilon

Yes. Java doubles will hold their precision better than your given epsilon of 0.00001.

Any rounding error that occurs due to the storage of floating point values will occur smaller than 0.00001. I regularly use 1E-6 or 0.000001 for a double epsilon in Java with no trouble.

On a related note, I like the format of epsilon = 1E-5; because I feel it is more readable (1E-5 in Java = 1 x 10^-5). 1E-6 is easy to distinguish from 1E-5 when reading code whereas 0.00001 and 0.000001 look so similar when glancing at code I think they are the same value.

DataGridView.Clear()

try:

datagrid.DataSource = null;
datagrid.DataBind();

Basically you will need to clear the datasource your binding to the grid.

Beginner Python: AttributeError: 'list' object has no attribute

You need to pass the values of the dict into the Bike constructor before using like that. Or, see the namedtuple -- seems more in line with what you're trying to do.

How to clear textarea on click?

The best solution what I know so far:

<textarea name="message" onblur="if (this.value == '') {this.value = 'text here';}"   onfocus="if (this.value == 'text here') {this.value = '';}">text here</textarea>

How to split a string to 2 strings in C

If you're open to changing the original string, you can simply replace the delimiter with \0. The original pointer will point to the first string and the pointer to the character after the delimiter will point to the second string. The good thing is you can use both pointers at the same time without allocating any new string buffers.

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I have tried your code and it works just fine. The file is being created without any problem, this is the code I used (it's your code, I just changed the datasource for testing):

    public ActionResult ExportToExcel()
    {
        var products = new System.Data.DataTable("teste");
        products.Columns.Add("col1", typeof(int));
        products.Columns.Add("col2", typeof(string));

        products.Rows.Add(1, "product 1");
        products.Rows.Add(2, "product 2");
        products.Rows.Add(3, "product 3");
        products.Rows.Add(4, "product 4");
        products.Rows.Add(5, "product 5");
        products.Rows.Add(6, "product 6");
        products.Rows.Add(7, "product 7");


        var grid = new GridView();
        grid.DataSource = products;
        grid.DataBind();

        Response.ClearContent();
        Response.Buffer = true;
        Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
        Response.ContentType = "application/ms-excel";

        Response.Charset = "";
        StringWriter sw = new StringWriter();
        HtmlTextWriter htw = new HtmlTextWriter(sw);

        grid.RenderControl(htw);

        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

        return View("MyView");
    }

How to drop all user tables?

To remove all objects in oracle :

1) Dynamic

DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE' 
AND OWNER='SCHEMA_NAME';
 CURSOR IY IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE 
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND  OWNER='SCHEMA_NAME';
 CURSOR IZ IS
 SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND  OWNER='SCHEMA_NAME';
BEGIN
 FOR X IN IX LOOP
   EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' SCHEMA_NAME.'||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
 END LOOP;
 FOR Y IN IY LOOP
   EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' SCHEMA_NAME.'||Y.OBJECT_NAME);
 END LOOP;
 FOR Z IN IZ LOOP
   EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' SCHEMA_NAME.'||Z.OBJECT_NAME||' FORCE ');
 END LOOP;
END;
/

2)Static

    SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
        union ALL
        select 'drop '||object_type||' '|| object_name || ';' from user_objects 
        where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
        union ALL
        SELECT 'drop '
        ||object_type
        ||' '
        || object_name
        || ' force;'
        FROM user_objects
        WHERE object_type IN ('TYPE');

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

If you need to retrieve more columns other than columns which are in group by then you can consider below query. Check it once whether it is performing well or not.

SELECT 
a.[CUSTOMER ID], 
a.[NAME], 
(select SUM(b.[AMOUNT]) from INV_DATA b
where b.[CUSTOMER ID] = a.[CUSTOMER ID]
GROUP BY b.[CUSTOMER ID]) AS [TOTAL AMOUNT]
FROM RES_DATA a

How do I declare an array variable in VBA?

The Array index only accepts a long value.

You declared iCounter as an integer. You should declare it as a long.

How to change Hash values?

If you know that the values are strings, you can call the replace method on them while in the cycle: this way you will change the value.

Altohugh this is limited to the case in which the values are strings and hence doesn't answer the question fully, I thought it can be useful to someone.

Limiting the number of characters in a string, and chopping off the rest

The solution may be java.lang.String.format("%" + maxlength + "s", string).trim(), like this:

int maxlength = 20;
String longString = "Any string you want which length is greather than 'maxlength'";
String shortString = "Anything short";
String resultForLong = java.lang.String.format("%" + maxlength + "s", longString).trim();
String resultForShort = java.lang.String.format("%" + maxlength + "s", shortString).trim();
System.out.println(resultForLong);
System.out.println(resultForShort);

ouput:

Any string you want w

Anything short

How do I calculate a trendline for a graph?

This is the way i calculated the slope: Source: http://classroom.synonym.com/calculate-trendline-2709.html

class Program
    {
        public double CalculateTrendlineSlope(List<Point> graph)
        {
            int n = graph.Count;
            double a = 0;
            double b = 0;
            double bx = 0;
            double by = 0;
            double c = 0;
            double d = 0;
            double slope = 0;

            foreach (Point point in graph)
            {
                a += point.x * point.y;
                bx = point.x;
                by = point.y;
                c += Math.Pow(point.x, 2);
                d += point.x;
            }
            a *= n;
            b = bx * by;
            c *= n;
            d = Math.Pow(d, 2);

            slope = (a - b) / (c - d);
            return slope;
        }
    }

    class Point
    {
        public double x;
        public double y;
    }

How to set the part of the text view is clickable

I made this helper method in case someone need start and end position from a String.

public static TextView createLink(TextView targetTextView, String completeString,
    String partToClick, ClickableSpan clickableAction) {

    SpannableString spannableString = new SpannableString(completeString);

    // make sure the String is exist, if it doesn't exist
    // it will throw IndexOutOfBoundException
    int startPosition = completeString.indexOf(partToClick);
    int endPosition = completeString.lastIndexOf(partToClick) + partToClick.length();

    spannableString.setSpan(clickableAction, startPosition, endPosition,
        Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

    targetTextView.setText(spannableString);
    targetTextView.setMovementMethod(LinkMovementMethod.getInstance());

    return targetTextView;
}

And here is how you use it

private void initSignUp() {
    String completeString = "New to Reddit? Sign up here.";
    String partToClick = "Sign up";
    ClickableTextUtil
        .createLink(signUpEditText, completeString, partToClick,
            new ClickableSpan() {
                @Override
                public void onClick(View widget) {
                    // your action
                    Toast.makeText(activity, "Start Sign up activity",
                        Toast.LENGTH_SHORT).show();
                }

                @Override
                public void updateDrawState(TextPaint ds) {
                    super.updateDrawState(ds);
                    // this is where you set link color, underline, typeface etc.
                    int linkColor = ContextCompat.getColor(activity, R.color.blumine);
                    ds.setColor(linkColor);
                    ds.setUnderlineText(false);
                }
            });
}

How to sort an array based on the length of each element?

I adapted @shareef's answer to make it concise. I use,

.sort(function(arg1, arg2) { return arg1.length - arg2.length })

How can I remove a style added with .css() function?

You can use:

 $("#eslimi").removeAttr("style").hide();

jQuery and TinyMCE: textarea value doesn't submit

tinyMCE.triggerSave(); seems to be the correct answer, as it will sync changes from the iFrame to your textarea.

To add to the other answers though - why do you need this? I had been using tinyMCE for awhile and hadn't encountered issues with form fields not coming through. After some research, it turned out to be their "auto patching" of form element submits, which is on by default - http://www.tinymce.com/wiki.php/Configuration3x:submit_patch

Basically, they redefine submit to call triggerSave beforehand, but only if submit hasn't already been redefined by something else:

if (!n.submit.nodeType && !n.submit.length) {
    t.formElement = n;
    n._mceOldSubmit = n.submit;
    n.submit = function() {
        // Save all instances
        tinymce.triggerSave();
        t.isNotDirty = 1;

        return t.formElement._mceOldSubmit(t.formElement);
    };
}

So, if something else in your code (or another 3rd party library) is messing with submit, their "auto patching" won't work and it becomes necessary to call triggerSave.

EDIT: And actually in the OP's case, submit isn't being called at all. Since it's ajax'd, this is bypassing the "auto patching" described above.

How to terminate a Python script

I'm a total novice but surely this is cleaner and more controlled

def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        return
    print 'You wont see this'

if __name__ == '__main__': 
    main()

...

Program terminated

than

import sys
def main():
    try:
        Answer = 1/0
        print  Answer
    except:
        print 'Program terminated'
        sys.exit()
    print 'You wont see this'

if __name__ == '__main__': 
    main()

...

Program terminated Traceback (most recent call last): File "Z:\Directory\testdieprogram.py", line 12, in main() File "Z:\Directory\testdieprogram.py", line 8, in main sys.exit() SystemExit

Edit

The point being that the program ends smoothly and peacefully, rather than "I'VE STOPPED !!!!"

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Download file from an ASP.NET Web API method using AngularJS

We also had to develop a solution which would even work with APIs requiring authentication (see this article)

Using AngularJS in a nutshell here is how we did it:

Step 1: Create a dedicated directive

// jQuery needed, uses Bootstrap classes, adjust the path of templateUrl
app.directive('pdfDownload', function() {
return {
    restrict: 'E',
    templateUrl: '/path/to/pdfDownload.tpl.html',
    scope: true,
    link: function(scope, element, attr) {
        var anchor = element.children()[0];

        // When the download starts, disable the link
        scope.$on('download-start', function() {
            $(anchor).attr('disabled', 'disabled');
        });

        // When the download finishes, attach the data to the link. Enable the link and change its appearance.
        scope.$on('downloaded', function(event, data) {
            $(anchor).attr({
                href: 'data:application/pdf;base64,' + data,
                download: attr.filename
            })
                .removeAttr('disabled')
                .text('Save')
                .removeClass('btn-primary')
                .addClass('btn-success');

            // Also overwrite the download pdf function to do nothing.
            scope.downloadPdf = function() {
            };
        });
    },
    controller: ['$scope', '$attrs', '$http', function($scope, $attrs, $http) {
        $scope.downloadPdf = function() {
            $scope.$emit('download-start');
            $http.get($attrs.url).then(function(response) {
                $scope.$emit('downloaded', response.data);
            });
        };
    }] 
});

Step 2: Create a template

<a href="" class="btn btn-primary" ng-click="downloadPdf()">Download</a>

Step 3: Use it

<pdf-download url="/some/path/to/a.pdf" filename="my-awesome-pdf"></pdf-download>

This will render a blue button. When clicked, a PDF will be downloaded (Caution: the backend has to deliver the PDF in Base64 encoding!) and put into the href. The button turns green and switches the text to Save. The user can click again and will be presented with a standard download file dialog for the file my-awesome.pdf.

Visual Studio 2017: Display method references

In Visual Studio Professional or Enterprise you can enable CodeLens by doing this:

Tools ? Options ? Text Editor ? All Languages ? CodeLens

This is not available in the Community Edition

How to install SimpleJson Package for Python

You can import json as simplejson like this:

import json as simplejson

and keep backward compatibility.

A Simple, 2d cross-platform graphics library for c or c++?

What about SDL?

Perhaps it's a bit too complex for your needs, but it's certainly cross-platform.

SFTP Libraries for .NET

For comprehensive SFTP support in .NET try edtFTPnet/PRO. It's been around a long time with support for many different SFTP servers.

We also sell an SFTP server for Windows, CompleteFTP, which is an inexpensive way to get support for SFTP on your Windows machine. Also has FTP and FTPS.

Check if SQL Connection is Open or Closed

you can also use this

if (SQLCON.State == ConnectionState.Closed)
{
     SQLCON.Open();
}

Char array declaration and initialization in C

That's because your first code snippet is not performing initialization, but assignment:

char myarray[4] = "abc";  // Initialization.

myarray = "abc";          // Assignment.

And arrays are not directly assignable in C.

The name myarray actually resolves to the address of its first element (&myarray[0]), which is not an lvalue, and as such cannot be the target of an assignment.

How to return value from an asynchronous callback function?

This is impossible as you cannot return from an asynchronous call inside a synchronous method.

In this case you need to pass a callback to foo that will receive the return value

function foo(address, fn){
  geocoder.geocode( { 'address': address}, function(results, status) {
     fn(results[0].geometry.location); 
  });
}

foo("address", function(location){
  alert(location); // this is where you get the return value
});

The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.

If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.

Generate unique random numbers between 1 and 100

This can handle generating upto 20 digit UNIQUE random number

JS

 var generatedNumbers = [];

    function generateRandomNumber(precision) { // input --> number precision in integer 
        if (precision <= 20) {
            var randomNum = Math.round(Math.random().toFixed(precision) * Math.pow(10, precision));
            if (generatedNumbers.indexOf(randomNum) > -1) {
                if (generatedNumbers.length == Math.pow(10, precision))
                    return "Generated all values with this precision";
                    return generateRandomNumber(precision);
            } else {
                generatedNumbers.push(randomNum);
                return randomNum;
            }
        } else
           return "Number Precision shoould not exceed 20";
    }
    generateRandomNumber(1);

enter image description here

jsFiddle

The provider is not compatible with the version of Oracle client

Recently I had to work on an older project where the solution and all contained projects were targeted to x32 platform. I kept on trying to copy Oracle.DataAccess.dll and all other suggested Oracle files on all the places, but hit the wall every time. Finally the bulb in the head lit up (after 8 hours :)), and asked to check for the installed ODAC assemblies and their platform. I had all the 64-bit (x64) ODAC clients installed already but not the 32 bit ones (x32). Installed the 32-bit ODAC and the problem disappeared.

How to check the version of installed ODAC: Look in folder C:\Windows\assembly. The "Processor Architecture" property will inform the platform of installed ODAC.

Eight hours is a long time for the bulb to light up. No wonder I always have to slog at work :).

JWT (JSON Web Token) library for Java

By referring to https://jwt.io/ you can find jwt implementations in many languages including java. Also the site provide some comparison between these implementation (the algorithms they support and ....).

For java these are mentioned libraries:

requestFeature() must be called before adding content

Change the Compile SDK version,Target SDK version to Build Tools version to 24.0.0 in build.gradle if u face issue in request Feature

How to recover stashed uncommitted changes

To make this simple, you have two options to reapply your stash:

  1. git stash pop - Restore back to the saved state, but it deletes the stash from the temporary storage.
  2. git stash apply - Restore back to the saved state and leaves the stash list for possible later reuse.

You can read in more detail about git stashes in this article.

How to open in default browser in C#

For those finding this question in dotnet core. I found a solution here

Code:

private void OpenUrl(string url)
{
    try
    {
        Process.Start(url);
    }
    catch
    {
        // hack because of this: https://github.com/dotnet/corefx/issues/10361
        if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
        {
            url = url.Replace("&", "^&");
            Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true });
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
        {
            Process.Start("xdg-open", url);
        }
        else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
        {
            Process.Start("open", url);
        }
        else
        {
            throw;
        }
    }
}

How to display Wordpress search results?

WordPress include tags, categories and taxonomies in search results

This code is taken from http://atiblog.com/custom-search-results/

Some functions here are taken from twentynineteen theme.Because it is made on this theme.

This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.

You need to modify your search.php of your theme to do so.

<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) ); 
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );

$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();

foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}

foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}

foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}

$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));

$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {

}

?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {

}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>

<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {

}
?>

Set initial value in datepicker with jquery?

You can set the value in the HTML and then init datepicker to start/highlight the actual date

<input name="datefrom" type="text" class="datepicker" value="20-1-2011">
<input name="dateto" type="text" class="datepicker" value="01-01-2012">
<input name="dateto2" type="text" class="datepicker" >


$(".datepicker").each(function() {    
    $(this).datepicker('setDate', $(this).val());
});

The above even works with danish date formats

http://jsfiddle.net/DDsBP/2/