Programs & Examples On #Bizspark

BizSpark is a Microsoft initiative to get purchasable software into the hands of startup companies for free.

How can I format bytes a cell in Excel as KB, MB, GB etc?

I don't know of a way to make it show you binary gigabytes (multiples of 1024*1024*1024) but you can make it show you decimal gigabytes using a format like:

0.00,,,"Gb"

orderBy multiple fields in Angular

Make sure that the sorting is not to complicated for the end user. I always thought sorting on group and sub group is a little bit complicated to understand. If its a technical end user it might be OK.

How to redirect to previous page in Ruby On Rails?

This is how we do it in our application

def store_location
  session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end

def redirect_back_or_default(default)
  redirect_to(session[:return_to] || default)
end

This way you only store last GET request in :return_to session param, so all forms, even when multiple time POSTed would work with :return_to.

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

Tip #2

Can't you use the classical 2> redirection operator.

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) 2> $NULL
if(!$?){
   'foo'
}

I don't like errors so I avoid them at all costs.

Str_replace for multiple items

Like this:

str_replace(array(':', '\\', '/', '*'), ' ', $string);

Or, in modern PHP (anything from 5.4 onwards), the slighty less wordy:

str_replace([':', '\\', '/', '*'], ' ', $string);

"No cached version... available for offline mode."

Just happened to me after upgrading to Android Studio 3.1. The Offline Work checkbox was unchecked, so no luck there.

I went to Settings > Build, Execution, Deployment > Compiler and the Command-line Options textfield contained --offline, so I just deleted that and everything worked.

setting screenshot

How to Read from a Text File, Character by Character in C++

    //Variables
    char END_OF_FILE = '#';
    char singleCharacter;

    //Get a character from the input file
    inFile.get(singleCharacter);

    //Read the file until it reaches #
    //When read pointer reads the # it will exit loop
    //This requires that you have a # sign as last character in your text file

    while (singleCharacter != END_OF_FILE)
    {
         cout << singleCharacter;
         inFile.get(singleCharacter);
    }

   //If you need to store each character, declare a variable and store it
   //in the while loop.

Regex remove all special characters except numbers?

to remove symbol use tag [ ]

step:1

[]

step 2:place what symbol u want to remove eg:@ like [@]

[@]

step 3:

var name = name.replace(/[@]/g, "");

thats it

_x000D_
_x000D_
var name="ggggggg@fffff"
var result = name.replace(/[@]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

Extra Tips

To remove space (give one space into square bracket like []=>[ ])

[@ ]

It Remove Everything (using except)

[^place u dont want to remove]

eg:i remove everyting except alphabet (small and caps)

[^a-zA-Z ]

_x000D_
_x000D_
var name="ggggg33333@#$%^&**I(((**gg@fffff"
var result = name.replace(/[^a-zA-Z]/g, "");
console .log(result)
_x000D_
_x000D_
_x000D_

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

codeigniter model error: Undefined property

function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 

Verify host key with pysftp

Do not set cnopts.hostkeys = None (as the second most upvoted answer shows), unless you do not care about security. You lose a protection against Man-in-the-middle attacks by doing so.


Use CnOpts.hostkeys (returns HostKeys) to manage trusted host keys.

cnopts = pysftp.CnOpts(knownhosts='known_hosts')

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

where the known_hosts contains a server public key(s)] in a format like:

example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

If you do not want to use an external file, you can also use

from base64 import decodebytes
# ...

keydata = b"""AAAAB3NzaC1yc2EAAAADAQAB..."""
key = paramiko.RSAKey(data=decodebytes(keydata))
cnopts = pysftp.CnOpts()
cnopts.hostkeys.add('example.com', 'ssh-rsa', key)

with pysftp.Connection(host, username, password, cnopts=cnopts) as sftp:

Though as of pysftp 0.2.9, this approach will issue a warning, what seems like a bug:
"Failed to load HostKeys" warning while connecting to SFTP server with pysftp


An easy way to retrieve the host key in the needed format is using OpenSSH ssh-keyscan:

$ ssh-keyscan example.com
# example.com SSH-2.0-OpenSSH_5.3
example.com ssh-rsa AAAAB3NzaC1yc2EAAAADAQAB...

(due to a bug in pysftp, this does not work, if the server uses non-standard port – the entry starts with [example.com]:port + beware of redirecting ssh-keyscan to a file in PowerShell)

You can also make the application do the same automatically:
Use Paramiko AutoAddPolicy with pysftp
(It will automatically add host keys of new hosts to known_hosts, but for known host keys, it will not accept a changed key)


Though for an absolute security, you should not retrieve the host key remotely, as you cannot be sure, if you are not being attacked already.

See my article Where do I get SSH host key fingerprint to authorize the server?
It's for my WinSCP SFTP client, but most information there is valid in general.


If you need to verify the host key using its fingerprint only, see Python - pysftp / paramiko - Verify host key using its fingerprint.

Disable Scrolling on Body

This post was helpful, but just wanted to share a slight alternative that may help others:

Setting max-height instead of height also does the trick. In my case, I'm disabling scrolling based on a class toggle. Setting .someContainer {height: 100%; overflow: hidden;} when the container's height is smaller than that of the viewport would stretch the container, which wouldn't be what you'd want. Setting max-height accounts for this, but if the container's height is greater than the viewport's when the content changes, still disables scrolling.

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

jquery to change style attribute of a div class

In order to change the attribute of the class conditionally,

var css_val = $(".handle").css('left');
if(css_val == '336px')
{
  $(".handle").css('left','300px');
}

If id is given as following,

<a id="handle" class="handle" href="#" style="left: 336px;"></a>

Here is an alternative solution:

var css_val = $("#handle").css('left');
if(css_val == '336px')
{
  $("#handle").css('left','300px');
}

How do I set a cookie on HttpClient's HttpRequestMessage

I had a similar problem and for my AspNetCore 3.1 application the other answers to this question were not working. I found that configuring a named HttpClient in my Startup.cs and using header propagation of the Cookie header worked perfectly. It also avoids all the concerns about proper disposition of your handler and client. Note if propagation of the request cookies is not what you need (sorry Op) you can set your own cookies when configuring the client factory.

Configure Services with IServiceCollection

services.AddHttpClient("MyNamedClient").AddHeaderPropagation();
services.AddHeaderPropagation(options =>
{
    options.Headers.Add("Cookie");
});

Configure with IApplicationBuilder

builder.UseHeaderPropagation();
  • Inject the IHttpClientFactory into your controller or middleware.
  • Create your client using var client = clientFactory.CreateClient("MyNamedClient");

package R does not exist

Delete import android.R; from all the files.. once clean the the project and build the project.... It will generate

How do I get a TextBox to only accept numeric input in WPF?

Use:

Private Sub DetailTextBox_PreviewTextInput( _
  ByVal sender As Object, _
  ByVal e As System.Windows.Input.TextCompositionEventArgs) _
  Handles DetailTextBox.PreviewTextInput

    If _IsANumber Then
        If Not Char.IsNumber(e.Text) Then
            e.Handled = True
        End If
    End If
End Sub

How do you get the list of targets in a makefile?

@nobar's answer helpfully shows how to use tab completion to list a makefile's targets.

  • This works great for platforms that provide this functionality by default (e.g., Debian, Fedora).

  • On other platforms (e.g., Ubuntu) you must explicitly load this functionality, as implied by @hek2mgl's answer:

    • . /etc/bash_completion installs several tab-completion functions, including the one for make
    • Alternatively, to install only tab completion for make:
      • . /usr/share/bash-completion/completions/make
  • For platforms that don't offer this functionality at all, such as OSX, you can source the following commands (adapated from here) to implement it:
_complete_make() { COMPREPLY=($(compgen -W "$(make -pRrq : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($1 !~ "^[#.]") {print $1}}' | egrep -v '^[^[:alnum:]]' | sort | xargs)" -- "${COMP_WORDS[$COMP_CWORD]}")); }
complete -F _complete_make make
  • Note: This is not as sophisticated as the tab-completion functionality that comes with Linux distributions: most notably, it invariably targets the makefile in the current directory, even if the command line targets a different makefile with -f <file>.

What's wrong with using == to compare floats in Java?

I think there is a lot of confusion around floats (and doubles), it is good to clear it up.

  1. There is nothing inherently wrong in using floats as IDs in standard-compliant JVM [*]. If you simply set the float ID to x, do nothing with it (i.e. no arithmetics) and later test for y == x, you'll be fine. Also there is nothing wrong in using them as keys in a HashMap. What you cannot do is assume equalities like x == (x - y) + y, etc. This being said, people usually use integer types as IDs, and you can observe that most people here are put off by this code, so for practical reasons, it is better to adhere to conventions. Note that there are as many different double values as there are long values, so you gain nothing by using double. Also, generating "next available ID" can be tricky with doubles and requires some knowledge of the floating-point arithmetic. Not worth the trouble.

  2. On the other hand, relying on numerical equality of the results of two mathematically equivalent computations is risky. This is because of the rounding errors and loss of precision when converting from decimal to binary representation. This has been discussed to death on SO.

[*] When I said "standard-compliant JVM" I wanted to exclude certain brain-damaged JVM implementations. See this.

How to format DateTime columns in DataGridView?

If it is a windows form Datagrid, you could use the below code to format the datetime for a column

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy HH:mm:ss";

EDIT :

Apart from this, if you need the datetime in AM/PM format, you could use the below code

dataGrid.Columns[2].DefaultCellStyle.Format = "MM/dd/yyyy hh:mm:ss tt";

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

R doesn't have these operations because (most) objects in R are immutable. They do not change. Typically, when it looks like you're modifying an object, you're actually modifying a copy.

Reading rows from a CSV file in Python

One can do it using pandas library.

Example:

import numpy as np
import pandas as pd

file = r"C:\Users\unknown\Documents\Example.csv"
df1 = pd.read_csv(file)
df1.head()

How to find and replace string?

like some say boost::replace_all

here a dummy example:

    #include <boost/algorithm/string/replace.hpp>

    std::string path("file.gz");
    boost::replace_all(path, ".gz", ".zip");

Limit Decimal Places in Android EditText

More elegant way would be using a regular expression ( regex ) as follows:

public class DecimalDigitsInputFilter implements InputFilter {

Pattern mPattern;

public DecimalDigitsInputFilter(int digitsBeforeZero,int digitsAfterZero) {
    mPattern=Pattern.compile("[0-9]{0," + (digitsBeforeZero-1) + "}+((\\.[0-9]{0," + (digitsAfterZero-1) + "})?)||(\\.)?");
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

        Matcher matcher=mPattern.matcher(dest);       
        if(!matcher.matches())
            return "";
        return null;
    }

}

To use it do:

editText.setFilters(new InputFilter[] {new DecimalDigitsInputFilter(5,2)});

On npm install: Unhandled rejection Error: EACCES: permission denied

sudo npm install -g @angular/cli

use this. it worked for me

Preventing twitter bootstrap carousel from auto sliding on page load

add this to your coursel div :

data-interval="false"

How to map a composite key with JPA and Hibernate?

You need to use @EmbeddedId:

@Entity
class Time {
    @EmbeddedId
    TimeId id;

    String src;
    String dst;
    Integer distance;
    Integer price;
}

@Embeddable
class TimeId implements Serializable {
    Integer levelStation;
    Integer confPathID;
}

PHP: Possible to automatically get all POSTed data?

You can use $_REQUEST as well as $_POST to reach everything such as Post, Get and Cookie data.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

download jre1.7.0_45 and then extract it into the Eclipse folder and rename folder of jre1.7.0_45 to jre and Eclipse will run

Selenium and xpath: finding a div with a class/id and verifying text inside

To account for leading and trailing whitespace, you probably want to use normalize-space()

//div[contains(@class, 'Caption') and normalize-space(.)='Model saved']

and

//div[@id='alertLabel' and normalize-space(.)='Save to server successful']

Note that //div[contains(@class, 'Caption') and normalize-space(.//text())='Model saved'] also works.

How to remove a file from the index in git?

This should unstage a <file> for you (without removing or otherwise modifying the file):

git reset <file>

How to display Toast in Android?

enter image description here

Must read: Android Toast Example

Syntax

Toast.makeText(context, text, duration);

You can use getApplicationContext() or getActivity() or MainActivity.this(if Activity Name is MainActivity)

Toast.makeText(getApplicationContext(),"Hi I am toast",Toast.LENGTH_LONG).show();

or

Toast.makeText(MainActivity.this,"Hi I am Toast", Toast.LENGTH_LONG).show();

The easiest way to transform collection to array?

For example, you have collection ArrayList with elements Student class:

List stuList = new ArrayList();
Student s1 = new Student("Raju");
Student s2 = new Student("Harish");
stuList.add(s1);
stuList.add(s2);
//now you can convert this collection stuList to Array like this
Object[] stuArr = stuList.toArray();           // <----- toArray() function will convert collection to array

Uncaught TypeError: undefined is not a function while using jQuery UI

For my situation, it was a naming conflict problem. Adding $J solves it.

//Old code:
function () {
    var extractionDialog;

    extractionDialog = $j("#extractWindowDialog").dialog({
        autoOpen: false,
        appendTo: "form",
        height: "100",
        width: "250",
        modal: true
    });

    $("extractBomInfoBtn").button().on("click", function () {
        extractionDialog.dialog("open");
    }

And the following is new code.

 $j(function () {
    var extractionDialog;

    extractionDialog = $j("#extractWindowDialog").dialog({
        autoOpen: false,
        appendTo: "form",
        height: "100",
        width: "250",
        modal: true
    });

    $j("extractBomInfoBtn").button().on("click", function () {
        extractionDialog.dialog("open");
    });
});

Hope it could help someone.

Load json from local file with http.get() in angular 2

MY OWN SOLUTION

I created a new component called test in this folder:

enter image description here

I also created a mock called test.json in the assests folder created by angular cli (important):

enter image description here

This mock looks like this:

[
        {
            "id": 1,
            "name": "Item 1"
        },
        {
            "id": 2,
            "name": "Item 2"
        },
        {
            "id": 3,
            "name": "Item 3"
        }
]

In the controller of my component test import follow rxjs like this

import 'rxjs/add/operator/map'

This is important, because you have to map your response from the http get call, so you get a json and can loop it in your ngFor. Here is my code how I load the mock data. I used http get and called my path to the mock with this path this.http.get("/assets/mock/test/test.json"). After this i map the response and subscribe it. Then I assign it to my variable items and loop it with ngFor in my template. I also export the type. Here is my whole controller code:

import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'

export type Item = { id: number, name: string };

@Component({
  selector: "test",
  templateUrl: "./test.component.html",
  styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
  items: Array<Item>;

  constructor(private http: Http) {}

  ngOnInit() {
    this.http
      .get("/assets/mock/test/test.json")
      .map(data => data.json() as Array<Item>)
      .subscribe(data => {
        this.items = data;
        console.log(data);
      });
  }
}

And my loop in it's template:

<div *ngFor="let item of items">
  {{item.name}}
</div>

It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json. Notice that you have also to import the HTTP and Response in your controller. The same in you app.module.ts (main) like this:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';


import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';


@NgModule({
  declarations: [
    AppComponent,
    TestComponent
  ],
  imports: [
    BrowserModule,
    HttpModule,
    JsonpModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Synchronizing a local Git repository with a remote one

Sounds like you want a mirror of the remote repository:

git clone --mirror url://to/remote.git local.git

That command creates a bare repository. If you don't want a bare repository, things get more complicated.

Convert or extract TTC font to TTF - how to?

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

The steps are:

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

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

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

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

Addenda

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

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

Linux command-line call not returning what it should from os.system?

For your requirement, Popen function of subprocess python module is the answer. For example,

import subprocess
..
process = subprocess.Popen("ps -p 2993 -o time --no-headers", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()
print stdout

Batch files: How to read a file?

Well theres a lot of different ways but if you only want to DISPLAY the text and not STORE it anywhere then you just use: findstr /v "randomtextthatnoonewilluse" filename.txt

MVC DateTime binding with incorrect date format

public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    var str = controllerContext.HttpContext.Request.QueryString[bindingContext.ModelName];
    if (string.IsNullOrEmpty(str)) return null;
    var date = DateTime.ParseExact(str, "dd.MM.yyyy", null);
    return date;
}

Setting Java heap space under Maven 2 on Windows

It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

Default VM Arguments = -Xms128m -Xmx1024m

Xcode Objective-C | iOS: delay function / NSTimer help?

sleep doesn't work because the display can only be updated after your main thread returns to the system. NSTimer is the way to go. To do this, you need to implement methods which will be called by the timer to change the buttons. An example:

- (void)button_circleBusy:(id)sender {
    firstButton.enabled = NO;
    // 60 milliseconds is .06 seconds
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToSecondButton:) userInfo:nil repeats:NO];
}
- (void)goToSecondButton:(id)sender {
    firstButton.enabled = YES;
    secondButton.enabled = NO;
    [NSTimer scheduledTimerWithTimeInterval:.06 target:self selector:@selector(goToThirdButton:) userInfo:nil repeats:NO];
}
...

How to convert a file to utf-8 in Python?

This worked for me in a small test:

sourceEncoding = "iso-8859-1"
targetEncoding = "utf-8"
source = open("source")
target = open("target", "w")

target.write(unicode(source.read(), sourceEncoding).encode(targetEncoding))

How to change a DIV padding without affecting the width/height ?

Declare this in your CSS and you should be good:

* { 
    -moz-box-sizing: border-box; 
    -webkit-box-sizing: border-box; 
     box-sizing: border-box; 
}

This solution can be implemented without using additional wrappers.

This will force the browser to calculate the width according to the "outer"-width of the div, it means the padding will be subtracted from the width.

Generate a Hash from string in Javascript

Thanks to the example by mar10, I found a way to get the same results in C# AND Javascript for an FNV-1a. If unicode chars are present, the upper portion is discarded for the sake of performance. Don't know why it would be helpful to maintain those when hashing, as am only hashing url paths for now.

C# Version

private static readonly UInt32 FNV_OFFSET_32 = 0x811c9dc5;   // 2166136261
private static readonly UInt32 FNV_PRIME_32 = 0x1000193;     // 16777619

// Unsigned 32bit integer FNV-1a
public static UInt32 HashFnv32u(this string s)
{
    // byte[] arr = Encoding.UTF8.GetBytes(s);      // 8 bit expanded unicode array
    char[] arr = s.ToCharArray();                   // 16 bit unicode is native .net 

    UInt32 hash = FNV_OFFSET_32;
    for (var i = 0; i < s.Length; i++)
    {
        // Strips unicode bits, only the lower 8 bits of the values are used
        hash = hash ^ unchecked((byte)(arr[i] & 0xFF));
        hash = hash * FNV_PRIME_32;
    }
    return hash;
}

// Signed hash for storing in SQL Server
public static Int32 HashFnv32s(this string s)
{
    return unchecked((int)s.HashFnv32u());
}

JavaScript Version

var utils = utils || {};

utils.FNV_OFFSET_32 = 0x811c9dc5;

utils.hashFnv32a = function (input) {
    var hval = utils.FNV_OFFSET_32;

    // Strips unicode bits, only the lower 8 bits of the values are used
    for (var i = 0; i < input.length; i++) {
        hval = hval ^ (input.charCodeAt(i) & 0xFF);
        hval += (hval << 1) + (hval << 4) + (hval << 7) + (hval << 8) + (hval << 24);
    }

    return hval >>> 0;
}

utils.toHex = function (val) {
    return ("0000000" + (val >>> 0).toString(16)).substr(-8);
}

iPhone UITextField - Change placeholder text color

iOS 6 and later offers attributedPlaceholder on UITextField. iOS 3.2 and later offers setAttributes:range: on NSMutableAttributedString.

You can do the following:

NSMutableAttributedString *ms = [[NSMutableAttributedString alloc] initWithString:self.yourInput.placeholder];
UIFont *placeholderFont = self.yourInput.font;
NSRange fullRange = NSMakeRange(0, ms.length);
NSDictionary *newProps = @{NSForegroundColorAttributeName:[UIColor yourColor], NSFontAttributeName:placeholderFont};
[ms setAttributes:newProps range:fullRange];
self.yourInput.attributedPlaceholder = ms;

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Go to apache-tomcat\conf folder add these lines in

tomcat-users.xml file

<role rolename="manager-gui"/>
<user username="admin" password="admin" roles="manager-gui"/>

and restart server

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

How do you explicitly set a new property on `window` in TypeScript?

I don't need to do this very often, the only case I have had was when using Redux Devtools with middleware.

I simply did:

const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

Or you could do:

let myWindow = window as any;

and then myWindow.myProp = 'my value';

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

Get GPS location from the web browser

Use this, and you will find all informations at http://www.w3schools.com/html/html5_geolocation.asp

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script>

CodeIgniter Active Record - Get number of returned rows

$sql = "SELECT count(id) as value FROM your_table WHERE your_field = ?";
$your_count = $this->db->query($sql, array($your_field))->row(0)->value;
echo $your_count;

How can I change default dialog button text color in android 5

There are two ways to change the dialog button color.

Basic Way

If you just want to change in an activity, write the below two lines after alertDialog.show();

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

Recommended

I'll recommend adding a theme for AlertDialog in styles.xml so you don't have to write the same code again and again in each activity/dialog call. You can just create a style and apply that theme on the dialog box. So whenever you want to change the color of AlertDialog box, just change color in styles.xml and all the dialog boxes will be updated in the whole application.

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorPrimary</item>
</style>

And apply the theme in AlertDialog.Builder

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

How do I implement a callback in PHP?

With PHP 5.3, you can now do this:

function doIt($callback) { $callback(); }

doIt(function() {
    // this will be done
});

Finally a nice way to do it. A great addition to PHP, because callbacks are awesome.

java.net.MalformedURLException: no protocol

The documentation could help you : http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilder.html

The method DocumentBuilder.parse(String) takes a URI and tries to open it. If you want to directly give the content, you have to give it an InputStream or Reader, for example a StringReader. ... Welcome to the Java standard levels of indirections !

Basically :

DocumentBuilder db = ...;
String xml = ...;
db.parse(new InputSource(new StringReader(xml)));

Note that if you read your XML from a file, you can directly give the File object to DocumentBuilder.parse() .

As a side note, this is a pattern you will encounter a lot in Java. Usually, most API work with Streams more than with Strings. Using Streams means that potentially not all the content has to be loaded in memory at the same time, which can be a great idea !

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

How to disable the back button in the browser using JavaScript

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

Getting selected value of a combobox

Try this:

int selectedIndex = comboBox1.SelectedIndex;
comboBox1.SelectedItem.ToString();
int selectedValue = (int)comboBox1.Items[selectedIndex];

How to group by week in MySQL?

Just ad this in the select :

DATE_FORMAT($yourDate, \'%X %V\') as week

And

group_by(week);

How to convert a negative number to positive?

simply multiplying by -1 works in both ways ...

>>> -10 * -1
10
>>> 10 * -1
-10

Oracle - Insert New Row with Auto Incremental ID

To get an auto increment number you need to use a sequence in Oracle. (See here and here).

CREATE SEQUENCE my_seq;

SELECT my_seq.NEXTVAL FROM DUAL; -- to get the next value

-- use in a trigger for your table demo
CREATE OR REPLACE TRIGGER demo_increment 
BEFORE INSERT ON demo
FOR EACH ROW

BEGIN
  SELECT my_seq.NEXTVAL
  INTO   :new.id
  FROM   dual;
END;
/

Creating an instance of class

Lines 1,2,3,4 will call the default constructor. They are different in the essence as 1,2 are dynamically created object and 3,4 are statically created objects.

In Line 7, you create an object inside the argument call. So its an error.

And Lines 5 and 6 are invitation for memory leak.

Excel function to make SQL-like queries on worksheet data?

You can use Get External Data (dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh 
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

Change a branch name in a Git repo

Assuming you're currently on the branch you want to rename:

git branch -m newname

This is documented in the manual for git-branch, which you can view using

man git-branch

or

git help branch

Specifically, the command is

git branch (-m | -M) [<oldbranch>] <newbranch>

where the parameters are:

   <oldbranch>
       The name of an existing branch to rename.

   <newbranch>
       The new name for an existing branch. The same restrictions as for <branchname> apply.

<oldbranch> is optional, if you want to rename the current branch.

How to test if a string is JSON or not?

You can try the following one because it also validates number, null, string but the above-marked answer is not working correctly it's just a fix of the above function:

function isJson(str) {
  try {
      const obj = JSON.parse(str);
      if (obj && typeof obj === `object`) {
        return true;
      }
    } catch (err) {
      return false;
    }
   return false;
}

What is the best way to get the first letter from a string in Java, returned as a string of length 1?

String whole = "something";
String first = whole.substring(0, 1);
System.out.println(first);

How to vertically align text in input type="text"?

An alternative is to use line-height: http://jsfiddle.net/DjT37/

.bigbox{
    height:40px;
    line-height:40px;
    padding:0 5px;
}

This tends to be more consistent when you want a specific height as you don't need to calculate padding based on font-size and desired height, etc.

HTML Table different number of columns in different rows

If you need different column width, do this:

<tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
</tr>
<tr>
    <td colspan="9">
        <table>
            <tr>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
        </table>
    </td>
</tr>

Trigger a button click with JavaScript on the Enter key in a text box

One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

<form onsubmit="Search();" action="javascript:void(0);">
    <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
    <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>

Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

Git will not init/sync/update new submodules

I had the same problem today and figured out that because I typed git submodule init then I had those line in my .git/config:

[submodule]
   active = .

I removed that and typed:

git submodule update --init --remote

And everything was back to normal, my submodule updated in its subdirectory as usual.

Javamail Could not convert socket to TLS GMail

above application.properties worked amazing for me:

spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.ssl.trust=smtp.gmail.com

If Radio Button is selected, perform validation on Checkboxes

You need to use == or === for comparison. = assigns a new value.

Besides that, using == is pointless when dealing with booleans only. Just use if(foo) instead of if(foo == true).

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

Unique random string generation

I don't think that they really are random, but my guess is those are some hashes.

Whenever I need some random identifier, I usually use a GUID and convert it to its "naked" representation:

Guid.NewGuid().ToString("n");

center aligning a fixed position div

From the post above, I think the best way is

  1. Have a fixed div with width: 100%
  2. Inside the div, make a new static div with margin-left: auto and margin-right: auto, or for table make it align="center".
  3. Tadaaaah, you have centered your fixed div now

Hope this will help.

Concrete Javascript Regex for Accented Characters (Diacritics)

What about this?

^([a-zA-Z]|[à-ú]|[À-Ú])+$

It will match every word with accented characters or not.

How to add RSA key to authorized_keys file?

There is already a command in the ssh suite to do this automatically for you. I.e log into a remote host and add the public key to that computers authorized_keys file.

ssh-copy-id -i /path/to/key/file [email protected]

If the key you are installing is ~/.ssh/id_rsa then you can even drop the -i flag completely.

Much better than manually doing it!

How to synchronize or lock upon variables in Java?

If on another occasion you're synchronising a Collection rather than a String, perhaps you're be iterating over the collection and are worried about it mutating, Java 5 offers:

How to resize a custom view programmatically?

With Kotlin and using dp unit:

myView.updateLayoutParams {
    val pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200f, context.resources.displayMetrics)
    height = pixels.toInt()
}

Pad left or right with string.format (not padleft or padright) with arbitrary string

You could encapsulate the string in a struct that implements IFormattable

public struct PaddedString : IFormattable
{
   private string value;
   public PaddedString(string value) { this.value = value; }

   public string ToString(string format, IFormatProvider formatProvider)
   { 
      //... use the format to pad value
   }

   public static explicit operator PaddedString(string value)
   {
     return new PaddedString(value);
   }
}

Then use this like that :

 string.Format("->{0:x20}<-", (PaddedString)"Hello");

result:

"->xxxxxxxxxxxxxxxHello<-"

Break string into list of characters in Python

So to add the string hello to a list as individual characters, try this:

newlist = []
newlist[:0] = 'hello'
print (newlist)

  ['h','e','l','l','o']

However, it is easier to do this:

splitlist = list(newlist)
print (splitlist)

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

I had this error when trying to use the dreadful Business Objects 4 for .Net SDK.

They ship five BusinessObjects*.dll files, but all of them are 64-bit.

To get my webpage to load, I needed to click on Tools\Options, then change this setting in VS2013:

enter image description here

Xcode 6: Keyboard does not show up in simulator

It would be difficult to say if there's any issue with your code without checking it out, however this happens to me quite a lot in (Version 6.0 (6A216f)). I usually have to reset the simulator's Content and Settings and/or restart xCode to get it working again. Try those and see if that solves the problem.

React Native fetch() Network Request Failed

By running the mock-server on 0.0.0.0
Note: This works on Expo when you are running another server using json-server.


Another approach is to run the mock server on 0.0.0.0 instead of localhost or 127.0.0.1.

This makes the mock server accessible on the LAN and because Expo requires the development machine and the mobile running the Expo app to be on the same network the mock server becomes accessible too.

This can be achieved with the following command when using json-server

json-server --host 0.0.0.0 --port 8000 ./db.json --watch

Visit this link for more information.

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

how to read certain columns from Excel using Pandas - Python

parse_cols is deprecated, use usecols instead

that is:

df = pd.read_excel(file_loc, index_col=None, na_values=['NA'], usecols = "A,C:AA")

How do I access refs of a child component in the parent component

First access the children with: this.props.children, each child will then have its ref as a property on it.

Zero-pad digits in string

There's also str_pad

<?php
$input = "Alien";
echo str_pad($input, 10);                      // produces "Alien     "
echo str_pad($input, 10, "-=", STR_PAD_LEFT);  // produces "-=-=-Alien"
echo str_pad($input, 10, "_", STR_PAD_BOTH);   // produces "__Alien___"
echo str_pad($input, 6 , "___");               // produces "Alien_"
?>

CSS hide scroll bar, but have element scrollable

You can make use of the SlimScroll plugin to make a div scrollable even if it is set to overflow: hidden;(i.e. scrollbar hidden).

You can also control touch scroll as well as the scroll speed using this plugin.

Hope this helps :)

Can you have multiple $(document).ready(function(){ ... }); sections?

Yes you can.

Multiple document ready sections are particularly useful if you have other modules haging off the same page that use it. With the old window.onload=func declaration, every time you specified a function to be called, it replaced the old.

Now all functions specified are queued/stacked (can someone confirm?) regardless of which document ready section they are specified in.

'^M' character at end of lines

Fix line endings in vi by running the following:

:set fileformat=unix

:w

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

How to convert entire dataframe to numeric while preserving decimals?

Using dplyr (a bit like sapply..)

df2 <- mutate_all(df1, function(x) as.numeric(as.character(x)))

which gives:

glimpse(df2)
Observations: 4
Variables: 2
$ a <dbl> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

from your df1 which was:

glimpse(df1)
Observations: 4
Variables: 2
$ a <fctr> 0.01, 0.02, 0.03, 0.04
$ b <dbl> 2, 4, 5, 7

Changing Placeholder Text Color with Swift

Swift 4 :

txtControl.attributedPlaceholder = NSAttributedString(string: "Placeholder String...",attributes: [NSAttributedStringKey.foregroundColor: UIColor.gray])

Objective-C :

UIColor *color = [UIColor grayColor];
txtControl.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"Placeholder String..." attributes:@{NSForegroundColorAttributeName: color}];

View's SELECT contains a subquery in the FROM clause

As per documentation:

MySQL Docs

  • The SELECT statement cannot contain a subquery in the FROM clause.

Your workaround would be to create a view for each of your subqueries.

Then access those views from within your view view_credit_status

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

What is the default boolean value in C#?

Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

Only the following variables are automatically initialized to their default values:

  • Static variables
  • Instance variables of class and struct instances
  • Array elements

The default values are as follows (assigned in default constructor of a class):

  • The default value of a variable of reference type is null.
  • For integer types, the default value is 0
  • For char, the default value is `\u0000'
  • For float, the default value is 0.0f
  • For double, the default value is 0.0d
  • For decimal, the default value is 0.0m
  • For bool, the default value is false
  • For an enum type, the default value is 0
  • For a struct type, the default value is obtained by setting all value type fields to their default values

As far as later parts of your question are conerned:

  • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
  • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.

Creating and returning Observable from Angular 2 Service

In the service.ts file -

a. import 'of' from observable/of
b. create a json list
c. return json object using Observable.of()
Ex. -

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';

@Injectable()
export class ClientListService {
    private clientList;

    constructor() {
        this.clientList = [
            {name: 'abc', address: 'Railpar'},
            {name: 'def', address: 'Railpar 2'},
            {name: 'ghi', address: 'Panagarh'},
            {name: 'jkl', address: 'Panagarh 2'},
        ];
    }

    getClientList () {
        return Observable.of(this.clientList);
    }
};

In the component where we are calling the get function of the service -

this.clientListService.getClientList().subscribe(res => this.clientList = res);

How do I calculate the date in JavaScript three months prior to today?

_x000D_
_x000D_
var d = new Date("2013/01/01");_x000D_
console.log(d.toLocaleDateString());_x000D_
d.setMonth(d.getMonth() + 18);_x000D_
console.log(d.toLocaleDateString());
_x000D_
_x000D_
_x000D_

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

What's the difference between Invoke() and BeginInvoke()

Just to give a short, working example to see an effect of their difference

new Thread(foo).Start();

private void foo()
{
  this.Dispatcher.BeginInvoke(DispatcherPriority.Normal,
    (ThreadStart)delegate()
    {
        myTextBox.Text = "bing";
        Thread.Sleep(TimeSpan.FromSeconds(3));
    });
  MessageBox.Show("done");
}

If use BeginInvoke, MessageBox pops simultaneous to the text update. If use Invoke, MessageBox pops after the 3 second sleep. Hence, showing the effect of an asynchronous (BeginInvoke) and a synchronous (Invoke) call.

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

Can I override and overload static methods in Java?

I design a code of static method overriding.I think It is override easily.Please clear me how its unable to override static members.Here is my code-

class Class1 {
    public static int Method1(){
          System.out.println("true");
          return 0;
    }
}
class Class2 extends Class1 {
    public static int Method1(){
   System.out.println("false");
          return 1;
    }

}
public class Mai {
    public static void main(String[] args){
           Class2 c=new Class2();
          //Must explicitly chose Method1 from Class1 or Class2
          //Class1.Method1();
          c.Method1();
    }
}

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

How can I calculate an md5 checksum of a directory?

find /path/to/dir/ -type f -name "*.py" -exec md5sum {} + | awk '{print $1}' | sort | md5sum

The find command lists all the files that end in .py. The md5sum is computed for each .py file. awk is used to pick off the md5sums (ignoring the filenames, which may not be unique). The md5sums are sorted. The md5sum of this sorted list is then returned.

I've tested this by copying a test directory:

rsync -a ~/pybin/ ~/pybin2/

I renamed some of the files in ~/pybin2.

The find...md5sum command returns the same output for both directories.

2bcf49a4d19ef9abd284311108d626f1  -

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

Big-O summary for Java Collections Framework implementations?

The book Java Generics and Collections has this information (pages: 188, 211, 222, 240).

List implementations:

                      get  add  contains next remove(0) iterator.remove
ArrayList             O(1) O(1) O(n)     O(1) O(n)      O(n)
LinkedList            O(n) O(1) O(n)     O(1) O(1)      O(1)
CopyOnWrite-ArrayList O(1) O(n) O(n)     O(1) O(n)      O(n)

Set implementations:

                      add      contains next     notes
HashSet               O(1)     O(1)     O(h/n)   h is the table capacity
LinkedHashSet         O(1)     O(1)     O(1) 
CopyOnWriteArraySet   O(n)     O(n)     O(1) 
EnumSet               O(1)     O(1)     O(1) 
TreeSet               O(log n) O(log n) O(log n)
ConcurrentSkipListSet O(log n) O(log n) O(1)

Map implementations:

                      get      containsKey next     Notes
HashMap               O(1)     O(1)        O(h/n)   h is the table capacity
LinkedHashMap         O(1)     O(1)        O(1) 
IdentityHashMap       O(1)     O(1)        O(h/n)   h is the table capacity 
EnumMap               O(1)     O(1)        O(1) 
TreeMap               O(log n) O(log n)    O(log n) 
ConcurrentHashMap     O(1)     O(1)        O(h/n)   h is the table capacity 
ConcurrentSkipListMap O(log n) O(log n)    O(1)

Queue implementations:

                      offer    peek poll     size
PriorityQueue         O(log n) O(1) O(log n) O(1)
ConcurrentLinkedQueue O(1)     O(1) O(1)     O(n)
ArrayBlockingQueue    O(1)     O(1) O(1)     O(1)
LinkedBlockingQueue   O(1)     O(1) O(1)     O(1)
PriorityBlockingQueue O(log n) O(1) O(log n) O(1)
DelayQueue            O(log n) O(1) O(log n) O(1)
LinkedList            O(1)     O(1) O(1)     O(1)
ArrayDeque            O(1)     O(1) O(1)     O(1)
LinkedBlockingDeque   O(1)     O(1) O(1)     O(1)

The bottom of the javadoc for the java.util package contains some good links:

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Sending Email in Android using JavaMail API without using the default/built-in app

Those who are getting ClassDefNotFoundError try to move that Three jar files to lib folder of your Project,it worked for me!!

Python 2.6: Class inside a Class?

class Second:
    def __init__(self, data):
        self.data = data

class First:
    def SecondClass(self, data):
        return Second(data)

FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data

How return error message in spring mvc @Controller

return new ResponseEntity<>(GenericResponseBean.newGenericError("Error during the calling the service", -1L), HttpStatus.EXPECTATION_FAILED);

Read text from response

This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse

Relevant bits below:

HttpWebResponse webresponse;

webresponse = (HttpWebResponse)webrequest.GetResponse();

Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);

string Response = loResponseStream.ReadToEnd();

loResponseStream.Close();
webresponse.Close();

return Response;

getting error while updating Composer

Problem :

Problem 1
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - laravel/framework v5.8.38 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
    - Installation request for laravel/framework (locked at v5.8.38, required as 5.8.*) -> satisfiable by laravel/framework[v5.8.38].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\xampp\php\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Solution :

if you using xampp just remove ' ; ' from

;extension=mbstring

in php.ini , save it, done!

Getting Current time to display in Label. VB.net

try

total.Text = DateTime.Now.ToString()

or

Dim theDate As DateTime = System.DateTime.Now
total.Text = theDate.ToString()

You declare Start as an Integer, while you are trying to put a DateTime in it, which is not possible.

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

What are all the uses of an underscore in Scala?

There is one usage I can see everyone here seems to have forgotten to list...

Rather than doing this:

List("foo", "bar", "baz").map(n => n.toUpperCase())

You could can simply do this:

List("foo", "bar", "baz").map(_.toUpperCase())

Virtual/pure virtual explained

Virtual methods CAN be overridden by deriving classes, but need an implementation in the base class (the one that will be overridden)

Pure virtual methods have no implementation the base class. They need to be defined by derived classes. (So technically overridden is not the right term, because there's nothing to override).

Virtual corresponds to the default java behaviour, when the derived class overrides a method of the base class.

Pure Virtual methods correspond to the behaviour of abstract methods within abstract classes. And a class that only contains pure virtual methods and constants would be the cpp-pendant to an Interface.

How do I get a PHP class constructor to call its parent's parent's constructor?

Beautiful solution using Reflection.

<?php
class Grandpa 
{
    public function __construct()
    {
        echo "Grandpa's constructor called\n";
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        echo "Papa's constructor called\n";

        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        echo "Kiddo's constructor called\n";

        $reflectionMethod = new ReflectionMethod(get_parent_class(get_parent_class($this)), '__construct');
        $reflectionMethod->invoke($this);
    }
}

$kiddo = new Kiddo();
$papa = new Papa();

Returning binary file from controller in ASP.NET Web API

You can try the following code snippet

httpResponseMessage.Content.Headers.Add("Content-Type", "application/octet-stream");

Hope it will work for you.

Where to find free public Web Services?

https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.

How to find Port number of IP address?

If it is a normal then the port number is always 80 and may be written as http://www.somewhere.com:80 Though you don't need to specify it as :80 is the default of every web browser.

If the site chose to use something else then they are intending to hide from anything not sent by a "friendly" or linked to. Those ones usually show with https and their port number is unknown and decided by their admin.

If you choose to runn a port scanner trying every number nn from say 10000 to 30000 in https://something.somewhere.com:nn Then your isp or their antivirus will probably notice and disconnect you.

Changing capitalization of filenames in Git

Starting Git 2.0.1 (June 25th, 2014), a git mv will just work on a case insensitive OS.

See commit baa37bf by David Turner (dturner-tw).

mv: allow renaming to fix case on case insensitive filesystems

"git mv hello.txt Hello.txt" on a case insensitive filesystem always triggers "destination already exists" error, because these two names refer to the same path from the filesystem's point of view and requires the user to give "--force" when correcting the case of the path recorded in the index and in the next commit.

Detect this case and allow it without requiring "--force".

git mv hello.txt Hello.txt just works (no --force required anymore).


The other alternative is:

git config --global core.ignorecase false

And rename the file directly; git add and commit.

Documentation for using JavaScript code inside a PDF file

Look for books by Ted Padova. Over the years, he has written a series of books called The Acrobat PDF {5,6,7,8,9...} Bible. They contain chapter(s) on JavaScript in PDF files. They are not as comprehensive as the reference documentation listed here, but in the books there are some realistic use-cases discussed in context.

There was also a talk on hacking PDF files by a computer scientist, given at a conference in 2010. The link on the talk's announcement-page to the slides is dead, but Google is your friend-. The talk is not exclusively on JavaScript, though. YouTube video - JavaScript starts at 06:00.

Installing Numpy on 64bit Windows 7 with Python 2.7.3

It is not improbable, that programmers looking for python on windows, also use the Python Tools for Visual Studio. In this case it is easy to install additional packages, by taking advantage of the included "Python Environment" Window. "Overview" is selected within the window as default. You can select "Pip" there.

Then you can install numpy without additional work by entering numpy into the seach window. The coresponding "install numpy" instruction is already suggested.

Nevertheless I had 2 easy to solve Problems in the beginning:

  • "error: Unable to find vcvarsall.bat": This problem has been solved here. Although I did not find it at that time and instead installed the C++ Compiler for Python.
  • Then the installation continued but failed because of an additional inner exception. Installing .NET 3.5 solved this.

Finally the installation was done. It took some time (5 minutes), so don't cancel the process to early.

net::ERR_INSECURE_RESPONSE in Chrome

A missing intermediate certificate might be the problem.

You may want to check your https://hostname with curl, openssl or a website like https://www.digicert.com/help/.

No idea why Chrome (possibly) sometimes has problems validating these certs.

How to use if - else structure in a batch file?

Your syntax is incorrect. You can't use ELSE IF. It appears that you don't really need it anyway. Simply use multiple IF statements:

IF %F%==1 IF %C%==1 (
    ::copying the file c to d
    copy "%sourceFile%" "%destinationFile%"
    )

IF %F%==1 IF %C%==0 (
    ::moving the file c to d
    move "%sourceFile%" "%destinationFile%"
    )

IF %F%==0 IF %C%==1 (
    ::copying a directory c from d, /s:  bos olanlar hariç, /e:bos olanlar dahil
    xcopy "%sourceCopyDirectory%" "%destinationCopyDirectory%" /s/e
    )

IF %F%==0 IF %C%==0 (
    ::moving a directory
    xcopy /E "%sourceMoveDirectory%" "%destinationMoveDirectory%"
    rd /s /q "%sourceMoveDirectory%"
    )

Great batch file reference: http://ss64.com/nt/if.html

SELECT query with CASE condition and SUM()

Use an "Or"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where (CPaymentType='Check' Or CPaymentType='Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

or an "IN"

Select SUM(CAmount) as PaymentAmount 
from TableOrderPayment 
where CPaymentType IN ('Check', 'Cash')
   and CDate <= case CPaymentType When 'Check' Then SYSDATETIME() else CDate End
   and CStatus='" & "Active" & "'"

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

Your project contains error(s), please fix it before running it

Is there a way to ignore existing errors in project. Something similar what eclipse allows in case of java projects.

In my case the errors exist in jni directory. The errors are shown even though ndk-buid succeeds. So all i want to do is to ignore the errors reported by eclipse.

If the errors are indeed errors then i should get unresolved symbols during ndk-build.

I have ensured standard android includes are there in include path.

Also my project is of type android/c/c++.

I have two builders associated with the project 1. statndard android builder 2. custom ndk builder that ive explicitly created.

CSS Animation onClick

You can achieve this by binding an onclick listener and then adding the animate class like this:

$('#button').onClick(function(){
    $('#target_element').addClass('animate_class_name');
});

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

How do I insert an image in an activity with android studio?

When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.

How to find the last field using 'cut'

You could try something like this:

echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev

Explanation

  • rev reverses "maps.google.com" to be moc.elgoog.spam
  • cut uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
  • lastly, we reverse it again to get com

python: create list of tuples from lists

You're looking for the zip builtin function. From the docs:

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]

PHP: If internet explorer 6, 7, 8 , or 9

if (isset($_SERVER['HTTP_USER_AGENT']) && preg_match("/(?i)msie|trident|edge/",$_SERVER['HTTP_USER_AGENT'])) {
// eh, IE found
}

how to apply click event listener to image in android

ImageView img = (ImageView) findViewById(R.id.myImageId);
img.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
       // your code here
    }
});

The requested operation cannot be performed on a file with a user-mapped section open

Happened to me after I have changed the project target CPU from 'Any CPU' to 'X64' and then back to 'Any CPU'.
Solved it by deleting the Obj folder (for beginners: don`t worry about deleting the obj folder, it will be recreated again in the next compile).

Retrieve the commit log for a specific line in a file?

This will call git blame for every meaningful revision to show line $LINE of file $FILE:

git log --format=format:%H $FILE | xargs -L 1 git blame $FILE -L $LINE,$LINE

As usual, the blame shows the revision number in the beginning of each line. You can append

| sort | uniq -c

to get aggregated results, something like a list of commits that changed this line. (Not quite, if code only has been moved around, this might show the same commit ID twice for different contents of the line. For a more detailed analysis you'd have to do a lagged comparison of the git blame results for adjacent commits. Anyone?)

Create a git patch from the uncommitted changes in the current working directory

git diff and git apply will work for text files, but won't work for binary files.

You can easily create a full binary patch, but you will have to create a temporary commit. Once you've made your temporary commit(s), you can create the patch with:

git format-patch <options...>

After you've made the patch, run this command:

git reset --mixed <SHA of commit *before* your working-changes commit(s)>

This will roll back your temporary commit(s). The final result leaves your working copy (intentionally) dirty with the same changes you originally had.

On the receiving side, you can use the same trick to apply the changes to the working copy, without having the commit history. Simply apply the patch(es), and git reset --mixed <SHA of commit *before* the patches>.

Note that you might have to be well-synced for this whole option to work. I've seen some errors when applying patches when the person making them hadn't pulled down as many changes as I had. There are probably ways to get it to work, but I haven't looked far into it.


Here's how to create the same patches in Tortoise Git (not that I recommend using that tool):

  1. Commit your working changes
  2. Right click the branch root directory and click Tortoise Git -> Create Patch Serial
    1. Choose whichever range makes sense (Since: FETCH_HEAD will work if you're well-synced)
    2. Create the patch(es)
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before your temporary commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

And how to apply them:

  1. Right click the branch root directory and click Tortoise Git -> Apply Patch Serial
  2. Select the correct patch(es) and apply them
  3. Right click the branch root directory and click Tortise Git -> Show Log
  4. Right click the commit before the patch's commit(s), and click reset "<branch>" to this...
  5. Select the Mixed option

Which UUID version to use?

Postgres documentation describes the differences between UUIDs. A couple of them:

V3:

uuid_generate_v3(namespace uuid, name text) - This function generates a version 3 UUID in the given namespace using the specified input name.

V4:

uuid_generate_v4 - This function generates a version 4 UUID, which is derived entirely from random numbers.

Make Font Awesome icons in a circle?

Font Awesome icons are inserted as a :before. Therefore you can style either your i or a like so:

.i {
   background: #fff;
   border-radius: 50%;
   display: inline-block;
   height: 20px;   
   width: 20px;
}

<a href="#"><i class="fa fa-facebook fa-lg"></i></a>

How to use a variable for a key in a JavaScript object literal?

2020 update/example...

A more complex example, using brackets and literals...something you may have to do for example with vue/axios. Wrap the literal in the brackets, so

[ ` ... ` ]

{
    [`filter[${query.key}]`]: query.value,  // 'filter[foo]' : 'bar'
}

What do pty and tty mean?

If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system

Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).

Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .

For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.

Extract value of attribute node via XPath

//Parent/Children[@  Attribute='value']/@Attribute

This is the case which can be used where element is having 2 attribute and we can get the one attribute with the help of another one.

ConnectivityManager getNetworkInfo(int) deprecated

Something like this:

public boolean hasConnection(final Context context){
    ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNW = cm.getActiveNetworkInfo();
    if (activeNW != null && activeNW.isConnected())
    {
        return true;
    }
    return false;
}

And in the main program body:

if(hasConnection(this)) {
    Toast.makeText(this, "Active networks OK ", Toast.LENGTH_LONG).show();
    getAccountData(token, tel);
}
else  Toast.makeText(this, "No active networks... ", Toast.LENGTH_LONG).show();

Angular2 Material Dialog css, dialog size

You can inspect the dialog element with dev tools and see what classes are applied on mdDialog.

For example, .md-dialog-container is the main classe of the MDDialog and has padding: 24px

you can create a custom CSS to overwrite whatever you want

.md-dialog-container {
      background-color: #000;
      width: 250px;
      height: 250px
}

In my opinion this is not a good option and probably goes against Material guide but since it doesn't have all features it has in it's previous version, you should do what you think is best for you.

jQuery UI Sortable Position

As per the official documentation of the jquery sortable UI: http://api.jqueryui.com/sortable/#method-toArray

In update event. use:

var sortedIDs = $( ".selector" ).sortable( "toArray" );

and if you alert or console this var (sortedIDs). You'll get your sequence. Please choose as the "Right Answer" if it is a right one.

How to split a string literal across multiple lines in C / Objective-C?

An alternative is to use any tool for removing line breaks. Write your string using any text editor, once you finished, paste your text here and copy it again in xcode.

Is it possible to append Series to rows of DataFrame without making a list first?

Try using this command. See the example given below:

Before image

df.loc[len(df)] = ['Product 9',99,9.99,8.88,1.11]

df

After Image

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

How to save an HTML5 Canvas as an image on a server?

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

<?php
  $encodedData = str_replace(' ','+',$encodedData);
  $decocedData = base64_decode($encodedData);
?>

http://php.net/manual/ro/function.base64-decode.php

What's the difference between session.persist() and session.save() in Hibernate?

It completely answered on basis of "generator" type in ID while storing any entity. If value for generator is "assigned" which means you are supplying the ID. Then it makes no diff in hibernate for save or persist. You can go with any method you want. If value is not "assigned" and you are using save() then you will get ID as return from the save() operation.

Another check is if you are performing the operation outside transaction limit or not. Because persist() belongs to JPA while save() for hibernate. So using persist() outside transaction boundaries will not allow to do so and throw exception related to persistant. while with save() no such restriction and one can go with DB transaction through save() outside the transaction limit.

Array to String PHP?

$data = array("asdcasdc","35353","asdca353sdc","sadcasdc","sadcasdc","asdcsdcsad");

$string_array = json_encode($data);

now you can insert this $string_array value into Database

Selecting text in an element (akin to highlighting with your mouse)

Here's a version with no browser sniffing and no reliance on jQuery:

function selectElementText(el, win) {
    win = win || window;
    var doc = win.document, sel, range;
    if (win.getSelection && doc.createRange) {
        sel = win.getSelection();
        range = doc.createRange();
        range.selectNodeContents(el);
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (doc.body.createTextRange) {
        range = doc.body.createTextRange();
        range.moveToElementText(el);
        range.select();
    }
}

selectElementText(document.getElementById("someElement"));
selectElementText(elementInIframe, iframe.contentWindow);

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

Another option is to use

$_SERVER['REQUEST_METHOD'] == 'POST'

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

To get specific part of a string in c#

If you want to get the strings separated by the , you can use

string b = a.Split(',')[0];

Should a RESTful 'PUT' operation return something

I used RESTful API in my services, and here is my opinion: First we must get to a common view: PUT is used to update an resource not create or get.

I defined resources with: Stateless resource and Stateful resource:

  • Stateless resources For these resources, just return the HttpCode with empty body, it's enough.

  • Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.

But, for a service or system, keep it simple, clearly, easy to use and maintain is the most important thing.

JFrame.dispose() vs System.exit()

JFrame.dispose() affects only to this frame (release all of the native screen resources used by this component, its subcomponents, and all children). System.exit() affects to entire JVM.

If you want to close all JFrame or all Window (since Frames extend Windows) to terminate the application in an ordered mode, you can do some like this:

Arrays.asList(Window.getWindows()).forEach(e -> e.dispose()); // or JFrame.getFrames()

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128)

You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.

If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.

If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Then you can do some Chinese json output in utf-8 format, such as:

name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)

You will get an utf-8 encoded string, rather than \u escaped json string.

To verify your default encoding:

print sys.getdefaultencoding()

You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.

Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.

How can I get the current date and time in the terminal and set a custom command in the terminal for it?

The command is date

To customise the output there are a myriad of options available, see date --help for a list.

For example, date '+%A %W %Y %X' gives Tuesday 34 2013 08:04:22 which is the name of the day of the week, the week number, the year and the time.

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

How do I check to see if a value is an integer in MySQL?

To check if a value is Int in Mysql, we can use the following query. This query will give the rows with Int values

SELECT col1 FROM table WHERE concat('',col * 1) = col;

PHP unable to load php_curl.dll extension

libeay32.dll and ssleay32.dll have to be path-accessible for php_curl.dll loading to succeed.

But copying them into Apache's ServerRoot, Apache's \bin\, Window's \System32\, or even worse into the Windows main directory is a bad hack and may not even work with newer PHP versions.

The right way to do it is to add the PHP path to the Windows Path variable.

  1. In Control Panel -> System click on Advanced System Settings or press WIN+R and type SystemPropertiesAdvanced
  2. Click the button Environment Variables.
  3. Under System Variables you will find the Path variable. Edit it and prepend C:\PHP; to it - or whatever the path to your PHP folder is.
    (Hint: If your PHP folder contains spaces like C:\Program Files\PHP you may need to use the short filename form here, i.e. C:\Progra~1\PHP.)
  4. Then fully stop Apache and start it again (a simple restart might not be enough).

Update 2017-05:
I changed the instructions above to prepend the Path variable with the PHP path instead of appending to it. This makes sure that the DLLs in the PHP path are used and not any other (outdated) versions in other paths of the system.

Update 2018-04:
If you have already chosen the wrong way and copied any of the PHP DLLs to Apache or Windows paths, then I strongly recommend that you remove them again! If you don't, you might get into trouble when you later try to update PHP. If a new PHP version brings new versions of these DLLs, but your old DLLs still linger around in system or webserver paths, these old DLLs might be found first. This will most certainly prevent the PHP interpreter from starting. Such errors can be very hard to understand and resolve. So better clean up now and remove any of the mentioned DLLs from Windows and Apache paths, if you copied them there.
(Thanks to @EdmundTam and @WasimA. for pointing out this problem in the comments!)

Update 2019-10:
Tip: To find all copies of these DLLs and check whether you might have placed them in the wrong folders, you can use the following commands in a Windows Command Prompt window:

dir c:\libeay32.dll /s
dir c:\ssleay32.dll /s

Be warned that these commands may take some time to complete as they search through the entire directory structure of your system drive C:.

Update 2020-08:
If your PHP folder contains spaces (i.e. C:\Program Files\PHP) you may need to use the short filename form in the Path variable at step 3 (i.e. C:\Progra~1\PHP). Thanks to @onee for this tip!

assignment operator overloading in c++

The second is pretty standard. You often prefer to return a reference from an assignment operator so that statements like a = b = c; resolve as expected. I can't think of any cases where I would want to return a copy from assignment.

One thing to note is that if you aren't needing a deep copy it's sometimes considered best to use the implicit copy constructor and assignment operator generated by the compiler than roll your own. Really up to you though ...

Edit:

Here's some basic calls:

SimpleCircle x; // default constructor
SimpleCircle y(x); // copy constructor
x = y; // assignment operator

Now say we had the first version of your assignment operator:

SimpleCircle SimpleCircle::operator=(const SimpleCircle & rhs)
{
     if(this == &rhs)
        return *this; // calls copy constructor SimpleCircle(*this)
     itsRadius = rhs.getRadius(); // copy member
     return *this; // calls copy constructor
}

It calls the copy constructor and passes a reference to this in order to construct the copy to be returned. Now in the second example we avoid the copy by just returning a reference to this

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    if(this == &rhs)
       return *this; // return reference to this (no copy)
    itsRadius = rhs.getRadius(); // copy member
    return *this; // return reference to this (no copy)
}

Beautiful way to remove GET-variables with PHP?

How about a function to rewrite the query string by looping through the $_GET array

! Rough outline of a suitable function

function query_string_exclude($exclude, $subject = $_GET, $array_prefix=''){
   $query_params = array;
   foreach($subject as $key=>$var){
      if(!in_array($key,$exclude)){
         if(is_array($var)){ //recursive call into sub array
            $query_params[]  = query_string_exclude($exclude, $var, $array_prefix.'['.$key.']');
         }else{
            $query_params[] = (!empty($array_prefix)?$array_prefix.'['.$key.']':$key).'='.$var;
         }
      }
   }

   return implode('&',$query_params);
}

Something like this would be good to keep handy for pagination links etc.

<a href="?p=3&<?= query_string_exclude(array('p')) ?>" title="Click for page 3">Page 3</a>

How can I increment a date by one day in Java?

In Java 8 simple way to do is:

Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))

javascript password generator

This method gives the options to change size and charset of your password.

function generatePassword(length=8, charset="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
    return new Array(length)
      .fill(null)
      .map(()=> charset.charAt(Math.floor(Math.random() * charset.length)))
      .join('');
}

console.log(generatePassword()); // 02kdFjzX
console.log(generatePassword(4)); // o8L5
console.log(generatePassword(16)); // jpPd7S09txv9b02p
console.log(generatePassword(16, "abcd1234")); // 4c4d323a31c134dd

How to get POSTed JSON in Flask?

First of all, the .json attribute is a property that delegates to the request.get_json() method, which documents why you see None here.

You need to set the request content type to application/json for the .json property and .get_json() method (with no arguments) to work as either will produce None otherwise. See the Flask Request documentation:

This will contain the parsed JSON data if the mimetype indicates JSON (application/json, see is_json()), otherwise it will be None.

You can tell request.get_json() to skip the content type requirement by passing it the force=True keyword argument.

Note that if an exception is raised at this point (possibly resulting in a 400 Bad Request response), your JSON data is invalid. It is in some way malformed; you may want to check it with a JSON validator.

Using .otf fonts on web browsers

You can implement your OTF font using @font-face like:

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWeb.otf") format("opentype");
}

@font-face {
    font-family: GraublauWeb;
    font-weight: bold;
    src: url("path/GraublauWebBold.otf") format("opentype");
}

// Edit: OTF now works in most browsers, see comments

However if you want to support a wide variety of browsers i would recommend you to switch to WOFF and TTF font types. WOFF type is implemented by every major desktop browser, while the TTF type is a fallback for older Safari, Android and iOS browsers. If your font is a free font, you could convert your font using for example a transfonter.

@font-face {
    font-family: GraublauWeb;
    src: url("path/GraublauWebBold.woff") format("woff"), url("path/GraublauWebBold.ttf")  format("truetype");
}

If you want to support nearly every browser that is still out there (not necessary anymore IMHO), you should add some more font-types like:

@font-face {
    font-family: GraublauWeb;
    src: url("webfont.eot"); /* IE9 Compat Modes */
    src: url("webfont.eot?#iefix") format("embedded-opentype"), /* IE6-IE8 */
         url("webfont.woff") format("woff"), /* Modern Browsers */
         url("webfont.ttf")  format("truetype"), /* Safari, Android, iOS */
         url("webfont.svg#svgFontName") format("svg"); /* Legacy iOS */
}

You can read more about why all these types are implemented and their hacks here. To get a detailed view of which file-types are supported by which browsers, see:

@font-face Browser Support

EOT Browser Support

WOFF Browser Support

TTF Browser Support

SVG-Fonts Browser Support

hope this helps

Python class returning value

You are describing a function, not a class.

def Myclass():
    return []

How do you attach and detach from Docker's process?

If you only need the docker process to go in the background you can use

Ctrl + Z

Be aware that it is not a real detach and it comes with a performance penalty. (You can return it to foreground with the bg command).

Another option is to just close your terminal, if you don't need it any longer.

Flutter command not found

after follow installation guide, download and extract, just try this command, you can change file depending on where you extract SDK, in my case it was home and works fine..

export PATH="$PATH":"$HOME/flutter/bin"

then try:

flutter --version

if works don't forget to complete remain installation steps.

Side-by-side plots with ggplot2

In my experience gridExtra:grid.arrange works perfectly, if you are trying to generate plots in a loop.

Short Code Snippet:

gridExtra::grid.arrange(plot1, plot2, ncol = 2)

** Updating this comment to show how to use grid.arrange() within a for loop to generate plots for different factors of a categorical variable.

for (bin_i in levels(athlete_clean$BMI_cat)) {

plot_BMI <- athlete_clean %>% filter(BMI_cat == bin_i) %>% group_by(BMI_cat,Team) %>% summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Participating Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

plot_BMI_Medal <- athlete_clean %>% 
          filter(!is.na(Medal), BMI_cat == bin_i) %>% 
          group_by(BMI_cat,Team) %>% 
          summarize(count_BMI_team = n()) %>% 
          mutate(percentage_cbmiT = round(count_BMI_team/sum(count_BMI_team) * 100,2)) %>% 
          arrange(-count_BMI_team) %>% top_n(10,count_BMI_team) %>% 
          ggplot(aes(x = reorder(Team,count_BMI_team), y = count_BMI_team, fill = Team)) +
            geom_bar(stat = "identity") +
            theme_bw() +
            # facet_wrap(~Medal) +
            labs(title = paste("Top 10 Winning Teams with \n",bin_i," BMI",sep=""), y = "Number of Athletes", 
                 x = paste("Teams - ",bin_i," BMI Category", sep="")) +
            geom_text(aes(label = paste(percentage_cbmiT,"%",sep = "")), 
                      size = 3, check_overlap = T,  position = position_stack(vjust = 0.7) ) +
            theme(axis.text.x = element_text(angle = 00, vjust = 0.5), plot.title = element_text(hjust = 0.5), legend.position = "none") +
            coord_flip()

gridExtra::grid.arrange(plot_BMI, plot_BMI_Medal, ncol = 2)

}

One of the Sample Plots from the above for loop is included below. The above loop will produce multiple plots for all levels of BMI category.

Sample Image

If you wish to see a more comprehensive use of grid.arrange() within for loops, check out https://rpubs.com/Mayank7j_2020/olympic_data_2000_2016

How to put a text beside the image?

If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:

CSS

.linkWithImageIcon{

    Display:inline-block;
}
.MyLink{
  Background:#FF3300;
  width:200px;
  height:70px;
  vertical-align:top;
  display:inline-block; font-weight:bold;
} 

.MyLinkText{
  /*---The margin depends on how the image size is ---*/
  display:inline-block; margin-top:5px;
}

HTML

<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>

enter image description here

if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design

What's the difference setting Embed Interop Types true and false in Visual Studio?

I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

Please follow this guide: https://gist.github.com/feczo/7282a6e00181fde4281b with pictures.

In short:

Using Puttygen, click 'Generate' move the mouse around as instructed and wait

  • Enter your desired username

  • Enter your password

  • Save the private key

Copy the entire content of the 'Public key for pasting into OpenSSH authorized_keys file' window. Make sure to copy every single character from the beginning to the very end!

Go to the Create instances page in the Google Cloud Platform Console and in the advanced options link paste the contents of your public key.

Note the IP address of the instance once it is complete. Open putty, from the left hand menu go to Connection / SSH / Auth and define the key file location which was saved.

From the left hand menu go to Connection / Data and define the same username

  • Enter the IP address of your instance
  • name the connection below saved Sessions as 'GCE' click on 'Save'
  • double click the 'GCE' entry you just created
  • accept the identy of the host

Now login with the password you specified earlier and run sudo su - and you are all set.

Jenkins pipeline if else not working

It requires a bit of rearranging, but when does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3 stage is now two different stages. One that runs on the master branch and one that runs on anything else.

stage ('Test 3: Master') {
    when { branch 'master' }
    steps { 
        echo 'I only execute on the master branch.' 
    }
}

stage ('Test 3: Dev') {
    when { not { branch 'master' } }
    steps {
        echo 'I execute on non-master branches.'
    }
}

PHP CURL DELETE request

To call GET,POST,DELETE,PUT All kind of request, i have created one common function

function CallAPI($method, $api, $data) {
    $url = "http://localhost:82/slimdemo/RESTAPI/" . $api;
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    switch ($method) {
        case "GET":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "GET");
            break;
        case "POST":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "PUT");
            break;
        case "DELETE":
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "DELETE"); 
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));
            break;
    }
    $response = curl_exec($curl);
    $data = json_decode($response);

    /* Check for 404 (file not found). */
    $httpCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    // Check the HTTP Status code
    switch ($httpCode) {
        case 200:
            $error_status = "200: Success";
            return ($data);
            break;
        case 404:
            $error_status = "404: API Not found";
            break;
        case 500:
            $error_status = "500: servers replied with an error.";
            break;
        case 502:
            $error_status = "502: servers may be down or being upgraded. Hopefully they'll be OK soon!";
            break;
        case 503:
            $error_status = "503: service unavailable. Hopefully they'll be OK soon!";
            break;
        default:
            $error_status = "Undocumented error: " . $httpCode . " : " . curl_error($curl);
            break;
    }
    curl_close($curl);
    echo $error_status;
    die;
}

CALL Delete Method

$data = array('id'=>$_GET['did']);
$result = CallAPI('DELETE', "DeleteCategory", $data);

CALL Post Method

$data = array('title'=>$_POST['txtcategory'],'description'=>$_POST['txtdesc']);
$result = CallAPI('POST', "InsertCategory", $data);

CALL Get Method

$data = array('id'=>$_GET['eid']);
$result = CallAPI('GET', "GetCategoryById", $data);

CALL Put Method

$data = array('id'=>$_REQUEST['eid'],m'title'=>$_REQUEST['txtcategory'],'description'=>$_REQUEST['txtdesc']);
$result = CallAPI('POST', "UpdateCategory", $data);

Check whether there is an Internet connection available on Flutter app

I've created a package that (I think) deals reliably with this issue.

The package on pub.dev

The package on GitHub

Discussion is very welcome. You can use the issues tracker on GitHub.


I no longer think this below is a reliable method:


Wanna add something to @Oren's answer: you should really add one more catch, which will catch all other exceptions (just to be safe), OR just remove the exception type altogether and use a catch, that deals with all of the exceptions:

Case 1:

try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} on PlatformException catch(_) { // May be thrown on Airplane mode
  hasConnection = false;
} on TimeoutException catch(_) {
  hasConnection = false;
} catch (_) {
  hasConnection = false;
}

or even simpler...

Case 2:


try {
  await Firestore.instance
    .runTransaction((Transaction tx) {})
    .timeout(Duration(seconds: 5));
  hasConnection = true;
} catch (_) {
  hasConnection = false;
}

Why do I get "'property cannot be assigned" when sending an SMTP email?

Just need to try this:

string smtpAddress = "smtp.gmail.com";
int portNumber = 587;
bool enableSSL = true;
string emailFrom = "companyemail";
string password = "password";
string emailTo = "Your email";
string subject = "Hello!";
string body = "Hello, Mr.";
MailMessage mail = new MailMessage();
mail.From = new MailAddress(emailFrom);
mail.To.Add(emailTo);
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient(smtpAddress, portNumber))
{
   smtp.Credentials = new NetworkCredential(emailFrom, password);
   smtp.EnableSsl = enableSSL;
   smtp.Send(mail);
}

How do I add a placeholder on a CharField in Django?

class FormClass(forms.ModelForm):
    class Meta:
        model = Book
        fields = '__all__'
        widgets = {
            'field_name': forms.TextInput(attrs={'placeholder': 'Type placeholder text here..'}),
        }

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Python iterating through object attributes

Iterate over an objects attributes in python:

class C:
    a = 5
    b = [1,2,3]
    def foobar():
        b = "hi"    

for attr, value in C.__dict__.iteritems():
    print "Attribute: " + str(attr or "")
    print "Value: " + str(value or "")

Prints:

python test.py
Attribute: a
Value: 5
Attribute: foobar
Value: <function foobar at 0x7fe74f8bfc08>
Attribute: __module__
Value: __main__
Attribute: b
Value: [1, 2, 3]
Attribute: __doc__
Value:

get next sequence value from database using hibernate

I found the solution:

public class DefaultPostgresKeyServer
{
    private Session session;
    private Iterator<BigInteger> iter;
    private long batchSize;

    public DefaultPostgresKeyServer (Session sess, long batchFetchSize)
    {
        this.session=sess;
        batchSize = batchFetchSize;
        iter = Collections.<BigInteger>emptyList().iterator();
    }

        @SuppressWarnings("unchecked")
        public Long getNextKey()
        {
            if ( ! iter.hasNext() )
            {
                Query query = session.createSQLQuery( "SELECT nextval( 'mySchema.mySequence' ) FROM generate_series( 1, " + batchSize + " )" );

                iter = (Iterator<BigInteger>) query.list().iterator();
            }
            return iter.next().longValue() ;
        }

}

Android Completely transparent Status Bar?

Simple and crisp and works with almost all use cases (for API level 16 and above):

  1. Use the following tag in your app theme to make the status bar transparent:

    <item name="android:statusBarColor">@android:color/transparent</item>

  2. And then use this code in your activity's onCreate method.

    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    

That's all you need to do ;)

You can learn more from the developer documentation. I'd also recommend reading this blog post.

KOTLIN CODE:

    val decorView = window.decorView
    decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

Check my another answer here

Check if object value exists within a Javascript array of objects and if not add a new object to array

It's rather trivial to check for existing username:

var arr = [{ id: 1, username: 'fred' }, 
  { id: 2, username: 'bill'}, 
  { id: 3, username: 'ted' }];

function userExists(username) {
  return arr.some(function(el) {
    return el.username === username;
  }); 
}

console.log(userExists('fred')); // true
console.log(userExists('bred')); // false

But it's not so obvious what to do when you have to add a new user to this array. The easiest way out - just pushing a new element with id equal to array.length + 1:

function addUser(username) {
  if (userExists(username)) {
    return false; 
  }
  arr.push({ id: arr.length + 1, username: username });
  return true;
}

addUser('fred'); // false
addUser('bred'); // true, user `bred` added

It will guarantee the IDs uniqueness, but will make this array look a bit strange if some elements will be taken off its end.

How to remove duplicate white spaces in string using Java?

Like this:

yourString = yourString.replaceAll("\\s+", " ");

For example

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

outputs

lorem ipsum dolor sit.

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.


Source: Java: Removing duplicate white spaces in strings

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

Replace whole line containing a string using Sed

In my makefile I use this:

@sed -i '/.*Revision:.*/c\'"`svn info -R main.cpp | awk '/^Rev/'`"'' README.md

PS: DO NOT forget that the -i changes actually the text in the file... so if the pattern you defined as "Revision" will change, you will also change the pattern to replace.

Example output:

Abc-Project written by John Doe

Revision: 1190

So if you set the pattern "Revision: 1190" it's obviously not the same as you defined them as "Revision:" only...

T-SQL Cast versus Convert

CONVERT is SQL Server specific, CAST is ANSI.

CONVERT is more flexible in that you can format dates etc. Other than that, they are pretty much the same. If you don't care about the extended features, use CAST.

EDIT:

As noted by @beruic and @C-F in the comments below, there is possible loss of precision when an implicit conversion is used (that is one where you use neither CAST nor CONVERT). For further information, see CAST and CONVERT and in particular this graphic: SQL Server Data Type Conversion Chart. With this extra information, the original advice still remains the same. Use CAST where possible.

How to Generate a random number of fixed length using JavaScript?

_x000D_
_x000D_
  var number = Math.floor(Math.random() * 9000000000) + 1000000000;_x000D_
    console.log(number);
_x000D_
_x000D_
_x000D_

This can be simplest way and reliable one.

What is the correct way to declare a boolean variable in Java?

As stated by Levon, this is not mandatory as stated in the docs: http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

This is probably either an habit from other languages that don't guarantee primitive data types default values.

Python: Continuing to next iteration in outer loop

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

How do I compare version numbers in Python?

... and getting back to easy ... for simple scripts you can use:

import sys
needs = (3, 9) # or whatever
pvi = sys.version_info.major, sys.version_info.minor    

later in your code

try:
    assert pvi >= needs
except:
    print("will fail!")
    # etc.

Unicode via CSS :before

The escaped hex reference of &#xf066; is \f066.

content: "\f066";

Getting the difference between two sets

Java 8

We can make use of removeIf which takes a predicate to write a utility method as:

// computes the difference without modifying the sets
public static <T> Set<T> differenceJava8(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeIf(setTwo::contains);
     return result;
}

And in case we are still at some prior version then we can use removeAll as:

public static <T> Set<T> difference(final Set<T> setOne, final Set<T> setTwo) {
     Set<T> result = new HashSet<T>(setOne);
     result.removeAll(setTwo);
     return result;
}

How to enable Logger.debug() in Log4j

This is happening due to the fact that the logging level of your logger is set to 'error' - therefore you will only see error messages or above this level in terms of severity so this is why you also see the 'fatal' message.

If you set the logging level to 'debug' on your logger in your log4j.xml you should see all messages.

Have a look at the log4j introduction for explaination.