Programs & Examples On #Bimap

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

How to fix System.NullReferenceException: Object reference not set to an instance of an object

I had the same problem but it only occurred on the published website on Godaddy. It was no problem in my local host.

The error came from an aspx.cs (code behind file) where I tried to assign a value to a label. It appeared that from within the code behind, that the label Text appears to be null. So all I did with change all my Label Text properties in the ASPX file from Text="" to Text=" ".

The problem disappeared. I don’t know why the error happens from the hosted version but not on my localhost and don’t have time to figure out why. But it works fine now.

Google Maps API warning: NoApiKeys

Google maps requires an API key for new projects since june 2016. For more information take a look at the Google Developers Blog. Also more information in german you'll find at this blog post from the clickstorm Blog.

How do I load the contents of a text file into a javascript variable?

If your input was structured as XML, you could use the importXML function. (More info here at quirksmode).

If it isn't XML, and there isn't an equivalent function for importing plain text, then you could open it in a hidden iframe and then read the contents from there.

Store an array in HashMap

If you want to store multiple values for a key (if I understand you correctly), you could try a MultiHashMap (available in various libraries, not only commons-collections).

System.MissingMethodException: Method not found?

I solved this problem by making a shelveset with my changes and running TFS Power Tools 'scorch' in my workspace (https://visualstudiogallery.msdn.microsoft.com/f017b10c-02b4-4d6d-9845-58a06545627f). Then I unshelved the changes and recompiled the project. This way you will cleanup any 'hanging-parties' that may be around in your workspace and will startup with a fresh one. This requires, of course, that you are using TFS.

TSQL How do you output PRINT in a user defined function?

I have tended in the past to work on my functions in two stages. The first stage would be to treat them as fairly normal SQL queries and make sure that I am getting the right results out of it. After I am confident that it is performing as desired, then I would convert it into a UDF.

AES Encrypt and Decrypt

CryptoSwift Example

Updated SWIFT 4.*

func aesEncrypt() throws -> String {
    let encrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).encrypt([UInt8](self.data(using: .utf8)!))
    return Data(encrypted).base64EncodedString()
}

func aesDecrypt() throws -> String {
    guard let data = Data(base64Encoded: self) else { return "" }
    let decrypted = try AES(key: KEY, iv: IV, padding: .pkcs7).decrypt([UInt8](data))
    return String(bytes: decrypted, encoding: .utf8) ?? self
}

Nullable property to entity field, Entity Framework through Code First

In Ef .net core there are two options that you can do; first with data annotations:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Or with fluent api:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired(false)//optinal case
            .IsRequired()//required case
            ;
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

There are more details here

You need to use a Theme.AppCompat theme (or descendant) with this activity

If you are using the application context, like this:

final AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());

change it to an activity context like this:

final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

Adding a color background and border radius to a Layout

You don't need the separate fill item. In fact, it's invalid. You just have to add a solid block to the shape. The subsequent stroke draws on top of the solid:

<shape 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:shape="rectangle">

    <corners android:radius="5dp" />
    <solid android:color="@android:color/white" />
    <stroke
        android:width="1dip"
        android:color="@color/bggrey" />
</shape>

You also don't need the layer-list if you only have one shape.

How to break a while loop from an if condition inside the while loop?

The break keyword does exactly that. Here is a contrived example:

public static void main(String[] args) {
  int i = 0;
  while (i++ < 10) {
    if (i == 5) break;
  }
  System.out.println(i); //prints 5
}

If you were actually using nested loops, you would be able to use labels.

$.focus() not working

In my case, and in case someone else runs into this, I load a form for view, user clicks "Edit" and ajax gets & returns values and updates the form.

Just after this, I tried all of these and none worked except:

setTimeout(function() { $('input[name="q"]').focus() }, 3000);

which I had to change to (due to ajax):

setTimeout(function() { $('input[name="q"]').focus() }, **500**);

and I finally just used $("#q") even though it was an input:

setTimeout(function () { $("#q").focus() }, 500);

How can I schedule a job to run a SQL query daily?

I made an animated GIF of the steps in the accepted answer. This is from MSSQL Server 2012

Schedule SQL Job

Adding Google Translate to a web site

to allow google translate to be mobile friendly get rid of the layout section, layout: google.translate.TranslateElement.InlineLayout.SIMPLE

<div id="google_translate_element">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en'}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

It works on my site and it is mobile friendly. https://livinghisword.org/articles/pages/whoiscernandisourworld.php

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

You must add it to entryComponents, as specified in the docs.

@NgModule({
  imports: [
    // ...
  ],
  entryComponents: [
    DialogInvokingComponent, 
    DialogResultExampleDialog
  ],
  declarations: [
    DialogInvokingComponent,   
    DialogResultExampleDialog
  ],
  // ...
})

Here is a full example for an app module file with a dialog defined as entryComponents.

jQuery multiple conditions within if statement

i == 'InvKey' && i == 'PostDate' will never be true, since i can never equal two different things at once.

You're probably trying to write

if (i !== 'InvKey' && i !== 'PostDate')) 

How do I reverse an int array in Java?

With Commons.Lang, you could simply use

ArrayUtils.reverse(int[] array)

Most of the time, it's quicker and more bug-safe to stick with easily available libraries already unit-tested and user-tested when they take care of your problem.

How to extract the nth word and count word occurrences in a MySQL string?

As others have said, mysql does not provide regex tools for extracting sub-strings. That's not to say you can't have them though if you're prepared to extend mysql with user-defined functions:

https://github.com/mysqludf/lib_mysqludf_preg

That may not be much help if you want to distribute your software, being an impediment to installing your software, but for an in-house solution it may be appropriate.

refresh both the External data source and pivot tables together within a time schedule

Auto Refresh Workbook for example every 5 sec. Apply to module

Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll

alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
    Application.OnTime alertTime, "Refresh"

End Sub

Apply to Workbook on Open

Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub

:)

How to import Maven dependency in Android Studio/IntelliJ?

I am using the springframework android artifact as an example

open build.gradle

Then add the following at the same level as apply plugin: 'android'

apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
   compile group: 'org.springframework.android', name: 'spring-android-rest-template', version: '1.0.1.RELEASE'
}

you can also use this notation for maven artifacts

compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

Your IDE should show the jar and its dependencies under 'External Libraries' if it doesn't show up try to restart the IDE (this happened to me quite a bit)

here is the example that you provided that works

buildscript { 
    repositories { 
        maven { 
            url 'repo1.maven.org/maven2'; 
        } 
    } 
    dependencies { 
        classpath 'com.android.tools.build:gradle:0.4' 
    } 
} 
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies { 
    compile files('libs/android-support-v4.jar') 
    compile group:'com.squareup.picasso', name:'picasso', version:'1.0.1' 
} 
android { 
    compileSdkVersion 17 
    buildToolsVersion "17.0.0" 
    defaultConfig { 
        minSdkVersion 14 
        targetSdkVersion 17 
    } 
} 

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

I had the same problem (i.e. indexing with multi-conditions, here it's finding data in a certain date range). The (a-b).any() or (a-b).all() seem not working, at least for me.

Alternatively I found another solution which works perfectly for my desired functionality (The truth value of an array with more than one element is ambigous when trying to index an array).

Instead of using suggested code above, simply using a numpy.logical_and(a,b) would work. Here you may want to rewrite the code as

selected  = r[numpy.logical_and(r["dt"] >= startdate, r["dt"] <= enddate)]

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

How to check if MySQL returns null/empty?

Use empty() and/or is_null()

http://www.php.net/empty http://www.php.net/is_null

Empty alone will achieve your current usage, is_null would just make more control possible if you wanted to distinguish between a field that is null and a field that is empty.

How can I force clients to refresh JavaScript files?

Athough it is framework specific, Django 1.4 has this functionailty which works in a similar fashion to the link to the 'greenfelt' site in the above answer

When is it appropriate to use UDP instead of TCP?

UDP when speed is necessary and the accuracy if the packets is not, and TCP when you need accuracy.

UDP is often harder in that you must write your program in such a way that it is not dependent on the accuracy of the packets.

How to sort an array of objects with jquery or javascript

data.sort(function(a,b) 
{
   return a.val - b.val;
});

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

I had the same issue "Cannot create a connection to data source...Login failed for user.." on Windows 8.1, SQL Server 2014 Developer Edition and Visual Studio 2013 Pro. All solutions offered above by other Stackoverflow Community members did not work for me.

So, I did the next steps (running all Windows applications as Administrator):

  1. VS2013 SSRS: I converted my Data Source to Shared Data Source (.rds) with Windows Authentication (Integrated Security) on the Right Pane "Solution Explorer".

  2. Original (non-shared) Data Source (on the Left Pane "Report Data") got "Don't Use Credentials".

  3. On the Project Properties, I set for "Deployment" "Overwrite DataSources" to "True" and redeployed the Project.

enter image description here

After that, I could run my report without further requirements to enter Credentials. All Shared DataSources were deployed in a separate Directory "DataSources".

enter image description here

enter image description here

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

Why should we typedef a struct so often in C?

From an old article by Dan Saks (http://www.ddj.com/cpp/184403396?pgno=3):


The C language rules for naming structs are a little eccentric, but they're pretty harmless. However, when extended to classes in C++, those same rules open little cracks for bugs to crawl through.

In C, the name s appearing in

struct s
    {
    ...
    };

is a tag. A tag name is not a type name. Given the definition above, declarations such as

s x;    /* error in C */
s *p;   /* error in C */

are errors in C. You must write them as

struct s x;     /* OK */
struct s *p;    /* OK */

The names of unions and enumerations are also tags rather than types.

In C, tags are distinct from all other names (for functions, types, variables, and enumeration constants). C compilers maintain tags in a symbol table that's conceptually if not physically separate from the table that holds all other names. Thus, it is possible for a C program to have both a tag and an another name with the same spelling in the same scope. For example,

struct s s;

is a valid declaration which declares variable s of type struct s. It may not be good practice, but C compilers must accept it. I have never seen a rationale for why C was designed this way. I have always thought it was a mistake, but there it is.

Many programmers (including yours truly) prefer to think of struct names as type names, so they define an alias for the tag using a typedef. For example, defining

struct s
    {
    ...
    };
typedef struct s S;

lets you use S in place of struct s, as in

S x;
S *p;

A program cannot use S as the name of both a type and a variable (or function or enumeration constant):

S S;    // error

This is good.

The tag name in a struct, union, or enum definition is optional. Many programmers fold the struct definition into the typedef and dispense with the tag altogether, as in:

typedef struct
    {
    ...
    } S;

The linked article also has a discussion about how the C++ behavior of not requireing a typedef can cause subtle name hiding problems. To prevent these problems, it's a good idea to typedef your classes and structs in C++, too, even though at first glance it appears to be unnecessary. In C++, with the typedef the name hiding become an error that the compiler tells you about rather than a hidden source of potential problems.

Best Way to View Generated Source of Webpage?

In the Web Developer Toolbar, have you tried the Tools -> Validate HTML or Tools -> Validate Local HTML options?

The Validate HTML option sends the url to the validator, which works well with publicly facing sites. The Validate Local HTML option sends the current page's HTML to the validator, which works well with pages behind a login, or those that aren't publicly accessible.

You may also want to try View Source Chart (also as FireFox add-on). An interesting note there:

Q. Why does View Source Chart change my XHTML tags to HTML tags?

A. It doesn't. The browser is making these changes, VSC merely displays what the browser has done with your code. Most common: self closing tags lose their closing slash (/). See this article on Rendered Source for more information (archive.org).

Input mask for numeric and decimal

Try imaskjs. It has Number, RegExp and other masks. Very simple to extend.

Display only date and no time

If the column type is DateTime in SQL then it will store a time where you pass one or not.

It'd be better to save the date properly:

model.ReturnDate = DateTime.Now;

and then format it when you need to display it:

@Html.Label(Model.ReturnDate.ToShortDateString())

Or if you're using EditorFor:

@Html.EditorFor(model => model.ReturnDate.ToShortDateString())

or

@Html.EditorFor(model => model.ReturnDate.ToString("MM/dd/yyyy"))

To add a property to your model add this code:

public string ReturnDateForDisplay
{
    get
    {
       return this.ReturnDate.ToString("d");
    }
}

Then in your PartialView:

@Html.EditorFor(model => model.ReturnDateForDisplay)

EDIT:

I just want to clarify for this answer that by my saying 'If you're using EditorFor', that means you need to have an EditorFor template for the type of value you're trying to represent.

Editor templates are a cool way of managing repetitive controls in MVC:

http://coding-in.net/asp-net-mvc-3-how-to-use-editortemplates/

You can use them for naive types like String as I've done above; but they're especially great for letting you template a set of input fields for a more complicated data type.

Pandas - How to flatten a hierarchical index in columns

A bit late maybe, but if you are not worried about duplicate column names:

df.columns = df.columns.tolist()

What is object slicing?

when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off (discard) form the base class object.

class Base { 
int x;
 };

class Derived : public Base { 
 int z; 
 };

 int main() 
{
Derived d;
Base b = d; // Object Slicing,  z of d is sliced off
}

Adding image inside table cell in HTML

Or... You could place the image in an anchor tag. Cause I had the same problem and it fixed it without issue. A lot of people use local paths before they publish their site and photos. Just make sure you go back and fix that in the final editing phase.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

How to use Oracle's LISTAGG function with a unique filter?

create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');
commit;

select group_id, 
       (select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
  select group_id, collect(distinct name) as coll_names 
    from demotable
    group by group_id 
)

GROUP_ID    NAMES
1   Alan,David,John
2   Charles,Julie

How do I assert an Iterable contains elements with a certain property?

As long as your List is a concrete class, you can simply call the contains() method as long as you have implemented your equals() method on MyItem.

// given 
// some input ... you to complete

// when
List<MyItems> results = service.getMyItems();

// then
assertTrue(results.contains(new MyItem("foo")));
assertTrue(results.contains(new MyItem("bar")));

Assumes you have implemented a constructor that accepts the values you want to assert on. I realise this isn't on a single line, but it's useful to know which value is missing rather than checking both at once.

Expand/collapse section in UITableView in iOS

Expanding on this answer written in Objective C, I wrote the following for those writing in Swift

The idea is to use sections within the table and set the number of rows in the section to 1 (collapsed) and 3(expanded) when the first row in that section is tapped

The table decides how many rows to draw based on an array of Boolean values

You'll need to create two rows in storyboard and give them the reuse identifiers 'CollapsingRow' and 'GroupHeading'

import UIKit

class CollapsingTVC:UITableViewController{

    var sectionVisibilityArray:[Bool]!// Array index corresponds to section in table

    override func viewDidLoad(){
        super.viewDidLoad()
        sectionVisibilityArray = [false,false,false]
    }

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
    }

    override func numberOfSections(in tableView: UITableView) -> Int{
        return sectionVisibilityArray.count
    }
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 0
    }

    // numberOfRowsInSection - Get count of entries
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        var rowsToShow:Int = 0
        if(sectionVisibilityArray[section]){
            rowsToShow = 3 // Or however many rows should be displayed in that section
        }else{
            rowsToShow = 1
        }
        return rowsToShow
    }// numberOfRowsInSection


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        if(indexPath.row == 0){
            if(sectionVisibilityArray[indexPath.section]){
                sectionVisibilityArray[indexPath.section] = false
            }else{
                sectionVisibilityArray[indexPath.section] = true
            }
            self.tableView.reloadSections([indexPath.section], with: .automatic)
        }
    }

    // cellForRowAtIndexPath - Get table cell corresponding to this IndexPath
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell:UITableViewCell

        if(indexPath.row == 0){
             cell = tableView.dequeueReusableCell(withIdentifier: "GroupHeading", for: indexPath as IndexPath)
        }else{
            cell = tableView.dequeueReusableCell(withIdentifier: "CollapsingRow", for: indexPath as IndexPath)
        }

        return cell

    }// cellForRowAtIndexPath

}

Convert dd-mm-yyyy string to date

In my case

new Date("20151102034013".replace(/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/, "$1-$2-$3T$4:$5:$6"))

Result: Mon Nov 02 2015 04:40:13 GMT+0100 (CET) then I use .getTime() to work with milliseconds

Cmake doesn't find Boost

You can also specify the version of Boost that you would like CMake to use by passing -DBOOST_INCLUDEDIR or -DBOOST_ROOT pointing to the location of correct version boost headers

Example:

cmake -DBOOST_ROOT=/opt/latestboost

This will also be useful when multiple boost versions are on the same system.

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

Your problem is that a running process within STS is using files located in your target directory while you execute a mvn clean command. Maven will be unable to delete these files (since other processes are still accessing them) and thus fail with that error.

Try to stop all processes (tests, servers, applications) from within STS before running Maven console commands. Look out: This behaviour might also appear if STS is cleaning up the projects and thus re-compiles the sources, and not running a process.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You should add the pipe to the interpolation and not to the ngFor

ul
  li(*ngFor='let movie of (movies)') ///////////removed here///////////////////
    | {{ movie.title | async }}

Reference docs

Can someone post a well formed crossdomain.xml sample?

This is what I've been using for development:

<?xml version="1.0" ?>
<cross-domain-policy>
<allow-access-from domain="*" />
</cross-domain-policy>

This is a very liberal approach, but is fine for my application.

As others have pointed out below, beware the risks of this.

What integer hash function are good that accepts an integer hash key?

I don't think we can say that a hash function is "good" without knowing your data in advance ! and without knowing what you're going to do with it.

There are better data structures than hash tables for unknown data sizes (I'm assuming you're doing the hashing for a hash table here ). I would personally use a hash table when I Know I have a "finite" number of elements that are needing stored in a limited amount of memory. I would try and do a quick statistical analysis on my data, see how it is distributed etc before I start thinking about my hash function.

collapse cell in jupyter notebook

You don't need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

enter image description here

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions

enter image description here

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

The Problem might be from the driver name for example instead of DRIVER={MySQL ODBC 5.3 Driver} try DRIVER={MySQL ODBC 5.3 Unicode Driver} you can see the name of the driver from administration tool

CSS background-image not working

Use this one to add background---

background-image: url('images-path');

You can also add repeat or no-repeat function in it!

background: url('images-path')   no-repeat 00;

How to convert Blob to File in JavaScript

This function converts a Blob into a File and it works great for me.

Vanilla JavaScript

function blobToFile(theBlob, fileName){
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

TypeScript (with proper typings)

public blobToFile = (theBlob: Blob, fileName:string): File => {
    var b: any = theBlob;
    //A Blob() is almost a File() - it's just missing the two properties below which we will add
    b.lastModifiedDate = new Date();
    b.name = fileName;

    //Cast to a File() type
    return <File>theBlob;
}

Usage

var myBlob = new Blob();

//do stuff here to give the blob some data...

var myFile = blobToFile(myBlob, "my-image.png");

Android: how do I check if activity is running?

An option without using any auxiliar variable is:

activity.getWindow().getDecorView().getRootView().isShown()

where activity is f.e.: this or getActivity().

The value returned by this expression changes in onStart() / onStop(), which are the events that start / stop showing the layout of the activity on the phone.

Count number of matches of a regex in Javascript

As mentioned in my earlier answer, you can use RegExp.exec() to iterate over all matches and count each occurrence; the advantage is limited to memory only, because on the whole it's about 20% slower than using String.match().

var re = /\s/g,
count = 0;

while (re.exec(text) !== null) {
    ++count;
}

return count;

Getting command-line password input in Python

Here is my code based off the code offered by @Ahmed ALaa

Features:

  • Works for passwords up to 64 characters
  • Accepts backspace input
  • Outputs * character (DEC: 42 ; HEX: 0x2A) instead of the input character

Demerits:

  • Works on Windows only

The function secure_password_input() returns the password as a string when called. It accepts a Password Prompt string, which will be displayed to the user to type the password

def secure_password_input(prompt=''):
    p_s = ''
    proxy_string = [' '] * 64
    while True:
        sys.stdout.write('\x0D' + prompt + ''.join(proxy_string))
        c = msvcrt.getch()
        if c == b'\r':
            break
        elif c == b'\x08':
            p_s = p_s[:-1]
            proxy_string[len(p_s)] = " "
        else:
            proxy_string[len(p_s)] = "*"
            p_s += c.decode()

    sys.stdout.write('\n')
    return p_s

What's the difference between an argument and a parameter?

Simple:

  • PARAMETER ? PLACEHOLDER (This means a placeholder belongs to the function naming and be used in the function body)
  • ARGUMENT ? ACTUAL VALUE (This means an actual value which is passed by the function calling)

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

Receiving JSON data back from HTTP request

I think the shortest way is:

var client = new HttpClient();
string reqUrl = $"http://myhost.mydomain.com/api/products/{ProdId}";
var prodResp = await client.GetAsync(reqUrl);
if (!prodResp.IsSuccessStatusCode){
    FailRequirement();
}
var prods = await prodResp.Content.ReadAsAsync<Products>();

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

Unable to find the requested .Net Framework Data Provider in Visual Studio 2010 Professional

I thought my issue was due to my machine.config per answers I found online but the culprit turned out to be in the project's web.config that was clearing out the DbProviderFactories.

<system.data>
  <DbProviderFactories>
    <clear />
       ...
  </DbProviderFactories>
</system.data>

jquery: animate scrollLeft

First off I should point out that css animations would probably work best if you are doing this a lot but I ended getting the desired effect by wrapping .scrollLeft inside .animate

$('.swipeRight').click(function()
{

    $('.swipeBox').animate( { scrollLeft: '+=460' }, 1000);
});

$('.swipeLeft').click(function()
{
    $('.swipeBox').animate( { scrollLeft: '-=460' }, 1000);
});

The second parameter is speed, and you can also add a third parameter if you are using smooth scrolling of some sort.

ExecuteNonQuery: Connection property has not been initialized.

just try this..

you need to open the connection using connection.open() on the SqlCommand.Connection object before executing ExecuteNonQuery()

pandas groupby sort descending order

You can do a sort_values() on the dataframe before you do the groupby. Pandas preserves the ordering in the groupby.

In [44]: d.head(10)
Out[44]:
              name transcript  exon
0  ENST00000456328          2     1
1  ENST00000450305          2     1
2  ENST00000450305          2     2
3  ENST00000450305          2     3
4  ENST00000456328          2     2
5  ENST00000450305          2     4
6  ENST00000450305          2     5
7  ENST00000456328          2     3
8  ENST00000450305          2     6
9  ENST00000488147          1    11

for _, a in d.head(10).sort_values(["transcript", "exon"]).groupby(["name", "transcript"]): print(a)
              name transcript  exon
1  ENST00000450305          2     1
2  ENST00000450305          2     2
3  ENST00000450305          2     3
5  ENST00000450305          2     4
6  ENST00000450305          2     5
8  ENST00000450305          2     6
              name transcript  exon
0  ENST00000456328          2     1
4  ENST00000456328          2     2
7  ENST00000456328          2     3
              name transcript  exon
9  ENST00000488147          1    11

creating Hashmap from a JSON String

This is simple operation no need to use any external library.

You can use this class instead :) (handles even lists , nested lists and json)

public class Utility {

    public static Map<String, Object> jsonToMap(Object json) throws JSONException {

        if(json instanceof JSONObject)
            return _jsonToMap_((JSONObject)json) ;

        else if (json instanceof String)
        {
            JSONObject jsonObject = new JSONObject((String)json) ;
            return _jsonToMap_(jsonObject) ;
        }
        return null ;
    }


   private static Map<String, Object> _jsonToMap_(JSONObject json) throws JSONException {
        Map<String, Object> retMap = new HashMap<String, Object>();

        if(json != JSONObject.NULL) {
            retMap = toMap(json);
        }
        return retMap;
    }


    private static Map<String, Object> toMap(JSONObject object) throws JSONException {
        Map<String, Object> map = new HashMap<String, Object>();

        Iterator<String> keysItr = object.keys();
        while(keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = object.get(key);

            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }


    public static List<Object> toList(JSONArray array) throws JSONException {
        List<Object> list = new ArrayList<Object>();
        for(int i = 0; i < array.length(); i++) {
            Object value = array.get(i);
            if(value instanceof JSONArray) {
                value = toList((JSONArray) value);
            }

            else if(value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            list.add(value);
        }
        return list;
    }
}

To convert your JSON string to hashmap use this :

HashMap<String, Object> hashMap = new HashMap<>(Utility.jsonToMap(response)) ;

What is the total amount of public IPv4 addresses?

Public IP Addresses

https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.

'1.0.0.0/8' to '191.0.0.0/8' are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:

import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
    '0.0.0.0/8',      '10.0.0.0/8',     '100.64.0.0/10', '127.0.0.0/8',
    '169.254.0.0/16', '172.16.0.0/12',  '192.0.0.0/24',  '192.0.2.0/24',
    '192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
    '203.0.113.0/24', '224.0.0.0/4',    '240.0.0.0/4',   '255.255.255.255/32'
)

IP Generator

Generates a JSON dump of IP Addresses and associated Geo information. Note that the valid public IP Address range is from '1.0.0.0/8' to '191.0.0.0/8' excluding the reserved Private IP Address ranges shown lower down in this readme.

docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip               ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip               ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip               ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0'   geo-ip               ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0'   geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip 

A little faster option for scanning all valid public addresses:

for i in $(seq 1 191); do \
    docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
    sleep 1; \ 
done

This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:

{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
 "continent": "North America", "continent_code": "NA",
 "state": "California", "country": "United States", "latitude": 37.418,
 "iso_code": "US", "state_code": "CA", "aso": "PubNub",
 "asn": "11404", "zip_code": "94107"}

Private and Reserved IP Range

The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses

MaxMind Geo IP

The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home

Insert ellipsis (...) into HTML tag if content too wide

The following CSS only solution for truncating text on a single line works with all browers listed at http://www.caniuse.com as of writing with the exception of Firefox 6.0. Note that JavaScript is totally unnecessary unless you need to support wrapping multiline text or earlier versions of Firefox.

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -o-text-overflow: ellipsis;
}

If you need support for earlier versions of Firefox check out my answer on this other question.

How to do case insensitive search in Vim

You can use in your vimrc those commands:

  • set ignorecase - All your searches will be case insensitive
  • set smartcase - Your search will be case sensitive if it contains an uppercase letter

You need to set ignorecase if you want to use what smartcase provides.

I wrote recently an article about Vim search commands (both built in command and the best plugins to search efficiently).

How to manually install an artifact in Maven 2?

If you ever get similar errors when using Windows PowerShell, you should try Windows' simple command-line. I didn't find out what caused this, but PowerShell seems to interpret some of Maven's parameters.

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

Export to csv in jQuery

I recently posted a free software library for this: "html5csv.js" -- GitHub

It is intended to help streamline the creation of small simulator apps in Javascript that might need to import or export csv files, manipulate, display, edit the data, perform various mathematical procedures like fitting, etc.

After loading "html5csv.js" the problem of scanning a table and creating a CSV is a one-liner:

CSV.begin('#PrintDiv').download('MyData.csv').go();

Here is a JSFiddle demo of your example with this code.

Internally, for Firefox/Chrome this is a data URL oriented solution, similar to that proposed by @italo, @lepe, and @adeneo (on another question). For IE

The CSV.begin() call sets up the system to read the data into an internal array. That fetch then occurs. Then the .download() generates a data URL link internally and clicks it with a link-clicker. This pushes a file to the end user.

According to caniuse IE10 doesn't support <a download=...>. So for IE my library calls navigator.msSaveBlob() internally, as suggested by @Manu Sharma

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

[ :Unexpected operator in shell programming

POSIX sh doesn't understand == for string equality, as that is a bash-ism. Use = instead.

The other people saying that brackets aren't supported by sh are wrong, btw.

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How do I deploy Node.js applications as a single executable file?

In addition to nexe, browserify can be used to bundle up all your dependencies as a single .js file. This does not bundle the actual node executable, just handles the javascript side. It too does not handle native modules. The command line options for pure node compilation would be browserify --output bundle.js --bare --dg false input.js.

Links not going back a directory?

You need to give a relative file path of <a href="../index.html">Home</a>

Alternately you can specify a link from the root of your site with <a href="/pages/en/index.html">Home</a>

.. and . have special meanings in file paths, .. means up one directory and . means current directory.

so <a href="index.html">Home</a> is the same as <a href="./index.html">Home</a>

How to open a website when a Button is clicked in Android application?

In your Java file write the following piece of code...

ImageView Button = (ImageView)findViewById(R.id.yourButtonsId);

Button.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_BROWSABLE);
        intent.setData(Uri.parse("http://www.yourURL.com"));
        startActivity(intent);
    }
});

Swift - Integer conversion to Hours/Minutes/Seconds

convert a number into time as a string

func convertToHMS(number: Int) -> String {
  let hour    = number / 3600;
  let minute  = (number % 3600) / 60;
  let second = (number % 3600) % 60 ;
  
  var h = String(hour);
  var m = String(minute);
  var s = String(second);
  
  if h.count == 1{
      h = "0\(hour)";
  }
  if m.count == 1{
      m = "0\(minute)";
  }
  if s.count == 1{
      s = "0\(second)";
  }
  
  return "\(h):\(m):\(s)"
}
print(convertToHMS(number:3900))

How can I get a Dialog style activity window to fill the screen?

This would be helpful for someone like me. Create custom dialog style:

<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

In AndroidManifest.xml file set theme for wanted activity:

<activity
        android:name=".CustomDialog"
        ...
        android:theme="@style/MyDialog"/>

That is all, no need to call methods programaticaly.

Can I apply multiple background colors with CSS3?

Yes its possible! and you can use as many colors and images as you desire, here is the right way:

_x000D_
_x000D_
body{_x000D_
/* Its, very important to set the background repeat to: no-repeat */_x000D_
background-repeat:no-repeat; _x000D_
_x000D_
background-image:  _x000D_
/* 1) An image              */ url(http://lorempixel.com/640/100/nature/John3-16/), _x000D_
/* 2) Gradient              */ linear-gradient(to right, RGB(0, 0, 0), RGB(255, 255, 255)), _x000D_
/* 3) Color(using gradient) */ linear-gradient(to right, RGB(110, 175, 233), RGB(110, 175, 233));_x000D_
_x000D_
background-position:_x000D_
/* 1) Image position        */ 0 0, _x000D_
/* 2) Gradient position     */ 0 100px,_x000D_
/* 3) Color position        */ 0 130px;_x000D_
_x000D_
background-size:  _x000D_
/* 1) Image size            */ 640px 100px,_x000D_
/* 2) Gradient size         */ 100% 30px, _x000D_
/* 3) Color size            */ 100% 30px;_x000D_
}
_x000D_
_x000D_
_x000D_

Quickly reading very large tables as dataframes

A minor additional points worth mentioning. If you have a very large file you can on the fly calculate the number of rows (if no header) using (where bedGraph is the name of your file in your working directory):

>numRow=as.integer(system(paste("wc -l", bedGraph, "| sed 's/[^0-9.]*\\([0-9.]*\\).*/\\1/'"), intern=T))

You can then use that either in read.csv , read.table ...

>system.time((BG=read.table(bedGraph, nrows=numRow, col.names=c('chr', 'start', 'end', 'score'),colClasses=c('character', rep('integer',3)))))
   user  system elapsed 
 25.877   0.887  26.752 
>object.size(BG)
203949432 bytes

Why do we have to override the equals() method in Java?

Object.equals() method checks only reference of object not primitive data type or Object value (Wrapper class object of primitive data, simple primitive data type (byte, short, int, long etc.)). So that we must override equals() method when we compare object based on primitive data type.

Open file dialog and select a file using WPF controls and C#

Something like that should be what you need

private void button1_Click(object sender, RoutedEventArgs e)
{
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();



    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".png";
    dlg.Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"; 


    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog();


    // Get the selected file name and display in a TextBox 
    if (result == true)
    {
        // Open document 
        string filename = dlg.FileName;
        textBox1.Text = filename;
    }
}

Rename computer and join to domain in one step with PowerShell

In one-step w/admin credentials:

Add-Computer -DomainName xxxx -ComputerName xxxx -NewName xxxx -Credential Domain\Admin -Restart

-DomainName = Your domain name (e.g. corp.local)

-ComputerName = Name of your local computer (e.g. The computer you are on. Use "Hostname" in PS to find out name).

-NewName = What you want to rename the computer (e.g. CORP-ANNE-TX)

-Credentials = Your admin credentials that give you authorization to perform this action (e.g. Domain\Admin = example Corp\JSmith. A dialog box will appear to put in your password)

In two-steps:

Step 1

Rename-Computer -NewName xxxx -Restart

Here you do not have to put -ComputerName as it assumes you are at the local computer. If doing this remotely; different story.

Step 2

Add-Computer -DomainName xxxx -Credential xxxx\xxxxx -Restart

xxxx\xxxx = Your domain and admin username (e.g. Corp\Jsmith)

Cloning an Object in Node.js

Check out underscore.js. It has both clone and extend and many other very useful functions.

This can be useful: Using the Underscore module with Node.js

How to run python script in webpage

In order for your code to show, you need several things:

Firstly, there needs to be a server that handles HTTP requests. At the moment you are just opening a file with Firefox on your local hard drive. A server like Apache or something similar is required.

Secondly, presuming that you now have a server that serves the files, you will also need something that interprets the code as Python code for the server. For Python users the go to solution is nowadays mod_wsgi. But for simpler cases you could stick with CGI (more info here), but if you want to produce web pages easily, you should go with a existing Python web framework like Django.

Setting this up can be quite the hassle, so be prepared.

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

Random Number Between 2 Double Numbers

What if one of the values is negative? Wouldn't a better idea be:

double NextDouble(double min, double max)
{
       if (min >= max)
            throw new ArgumentOutOfRangeException();    
       return random.NextDouble() * (Math.Abs(max-min)) + min;
}

Adding a Method to an Existing Object Instance

from types import MethodType

def method(self):
   print 'hi!'


setattr( targetObj, method.__name__, MethodType(method, targetObj, type(method)) )

With this, you can use the self pointer

Find size and free space of the filesystem containing a given file

For the first point, you can try using os.path.realpath to get a canonical path, check it against /etc/mtab (I'd actually suggest calling getmntent, but I can't find a normal way to access it) to find the longest match. (to be sure, you should probably stat both the file and the presumed mountpoint to verify that they are in fact on the same device)

For the second point, use os.statvfs to get block size and usage information.

(Disclaimer: I have tested none of this, most of what I know came from the coreutils sources)

How can I read a text file from the SD card in Android?

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

JavaScript closures vs. anonymous functions

I would like to share my example and an explanation about closures. I made a python example, and two figures to demonstrate stack states.

def maker(a, b, n):
    margin_top = 2
    padding = 4
    def message(msg):
        print('\n’ * margin_top, a * n, 
            ' ‘ * padding, msg, ' ‘ * padding, b * n)
    return message

f = maker('*', '#', 5)
g = maker('?', '?’, 3)
…
f('hello')
g(‘good bye!')

The output of this code would be as follows:

*****      hello      #####

???      good bye!    ???

Here are two figures to show stacks and the closure attached to the function object.

when the function is returned from maker

when the function is called later

When the function is called through a parameter or a nonlocal variable, the code needs local variable bindings such as margin_top, padding as well as a, b, n. In order to ensure the function code to work, the stack frame of the maker function which was gone away long ago should be accessible, which is backed up in the closure we can find along with the function message object.

Using BufferedReader to read Text File

or

public String getFileStream(final String inputFile) {
        String result = "";
        Scanner s = null;

        try {
            s = new Scanner(new BufferedReader(new FileReader(inputFile)));
            while (s.hasNext()) {
                result = result + s.nextLine();
            }
        } catch (final IOException ex) {
            ex.printStackTrace();
        } finally {
            if (s != null) {
                s.close();
            }
        }
        return result;
}

This gets first line as well.

Can you run GUI applications in a Docker container?

With docker data volumes it's very easy to expose xorg's unix domain socket inside the container.

For example, with a Dockerfile like this:

FROM debian
RUN apt-get update
RUN apt-get install -qqy x11-apps
ENV DISPLAY :0
CMD xeyes

You could do the following:

$ docker build -t xeyes - < Dockerfile
$ XSOCK=/tmp/.X11-unix/X0
$ docker run -v $XSOCK:$XSOCK xeyes

This of course is essentially the same as X-forwarding. It grants the container full access to the xserver on the host, so it's only recommended if you trust what's inside.

Note: If you are concerned about security, a better solution would be to confine the app with mandatory- or role-based-access control. Docker achieves pretty good isolation, but it was designed with a different purpose in mind. Use AppArmor, SELinux, or GrSecurity, which were designed to address your concern.

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

Have bash script answer interactive prompts

There is a special build-in util for this - 'yes'.

To answer all questions with the same answer, you can run

yes [answer] |./your_script

Or you can put it inside your script have specific answer to each question

Double precision - decimal places

IEEE 754 floating point is done in binary. There's no exact conversion from a given number of bits to a given number of decimal digits. 3 bits can hold values from 0 to 7, and 4 bits can hold values from 0 to 15. A value from 0 to 9 takes roughly 3.5 bits, but that's not exact either.

An IEEE 754 double precision number occupies 64 bits. Of this, 52 bits are dedicated to the significand (the rest is a sign bit and exponent). Since the significand is (usually) normalized, there's an implied 53rd bit.

Now, given 53 bits and roughly 3.5 bits per digit, simple division gives us 15.1429 digits of precision. But remember, that 3.5 bits per decimal digit is only an approximation, not a perfectly accurate answer.

Many (most?) debuggers actually look at the contents of the entire register. On an x86, that's actually an 80-bit number. The x86 floating point unit will normally be adjusted to carry out calculations to 64-bit precision -- but internally, it actually uses a couple of "guard bits", which basically means internally it does the calculation with a few extra bits of precision so it can round the last one correctly. When the debugger looks at the whole register, it'll usually find at least one extra digit that's reasonably accurate -- though since that digit won't have any guard bits, it may not be rounded correctly.

Find oldest/youngest datetime object in a list

Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

How to revert initial git commit?

I will throw in what worked for me in the end. I needed to remove the initial commit on a repository as quarantined data had been misplaced, the commit had already been pushed.

Make sure you are are currently on the right branch.

git checkout master

git update-ref -d HEAD

git commit -m "Initial commit

git push -u origin master

This was able to resolve the problem.

Important

This was on an internal repository which was not publicly accessible, if your repository was publicly accessible please assume anything you need to revert has already been pulled down by someone else.

Detect changes in the DOM

The following example was adapted from Mozilla Hacks' blog post and is using MutationObserver.

// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');

// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true };

// Callback function to execute when mutations are observed
var callback = function(mutationsList) {
    for(var mutation of mutationsList) {
        if (mutation.type == 'childList') {
            console.log('A child node has been added or removed.');
        }
        else if (mutation.type == 'attributes') {
            console.log('The ' + mutation.attributeName + ' attribute was modified.');
        }
    }
};

// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(targetNode, config);

// Later, you can stop observing
observer.disconnect();

Browser support: Chrome 18+, Firefox 14+, IE 11+, Safari 6+

warning about too many open figures

Here's a bit more detail to expand on Hooked's answer. When I first read that answer, I missed the instruction to call clf() instead of creating a new figure. clf() on its own doesn't help if you then go and create another figure.

Here's a trivial example that causes the warning:

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    for i in range(21):
        _fig, ax = plt.subplots()
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.clf()
    print('Done.')

main()

To avoid the warning, I have to pull the call to subplots() outside the loop. In order to keep seeing the rectangles, I need to switch clf() to cla(). That clears the axis without removing the axis itself.

from matplotlib import pyplot as plt, patches
import os


def main():
    path = 'figures'
    _fig, ax = plt.subplots()
    for i in range(21):
        x = range(3*i)
        y = [n*n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    print('Done.')

main()

If you're generating plots in batches, you might have to use both cla() and close(). I ran into a problem where a batch could have more than 20 plots without complaining, but it would complain after 20 batches. I fixed that by using cla() after each plot, and close() after each batch.

from matplotlib import pyplot as plt, patches
import os


def main():
    for i in range(21):
        print('Batch {}'.format(i))
        make_plots('figures')
    print('Done.')


def make_plots(path):
    fig, ax = plt.subplots()
    for i in range(21):
        x = range(3 * i)
        y = [n * n for n in x]
        ax.add_patch(patches.Rectangle(xy=(i, 1), width=i, height=10))
        plt.step(x, y, linewidth=2, where='mid')
        figname = 'fig_{}.png'.format(i)
        dest = os.path.join(path, figname)
        plt.savefig(dest)  # write image to file
        plt.cla()
    plt.close(fig)


main()

I measured the performance to see if it was worth reusing the figure within a batch, and this little sample program slowed from 41s to 49s (20% slower) when I just called close() after every plot.

Android emulator: could not get wglGetExtensionsStringARB error

First of all, use INTEL x86... this as CPU/ABI. Secondly, uncheck Snapshot if it is checked. Keep the Target upto Android 4.2.2

Regex pattern to match at least 1 number and 1 character in a string

If you need the digit to be at the end of any word, this worked for me:

/\b([a-zA-Z]+[0-9]+)\b/g
  • \b word boundary
  • [a-zA-Z] any letter
  • [0-9] any number
  • "+" unlimited search (show all results)

Definitive way to trigger keypress events with jQuery

In case you need to take into account the current cursor and text selection...

This wasn't working for me for an AngularJS app on Chrome. As Nadia points out in the original comments, the character is never visible in the input field (at least, that was my experience). In addition, the previous solutions don't take into account the current text selection in the input field. I had to use a wonderful library jquery-selection.

I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    

Laravel update model with unique validation rule for attribute

A simple example for roles update


// model/User.php
class User extends Eloquent
{

    public static function rolesUpdate($id)
    {
        return array(
            'username'              => 'required|alpha_dash|unique:users,username,' . $id,
            'email'                 => 'required|email|unique:users,email,'. $id,
            'password'              => 'between:4,11',
        );
    }
}       

.

// controllers/UsersControllers.php
class UsersController extends Controller
{

    public function update($id)
    {
        $user = User::find($id);
        $validation = Validator::make($input, User::rolesUpdate($user->id));

        if ($validation->passes())
        {
            $user->update($input);

            return Redirect::route('admin.user.show', $id);
        }

        return Redirect::route('admin.user.edit', $id)->withInput()->withErrors($validation);
    }

}

How to update values using pymongo?

in python the operators should be in quotes: db.ProductData.update({'fromAddress':'http://localhost:7000/'}, {"$set": {'fromAddress': 'http://localhost:5000/'}},{"multi": True})

How to create a global variable?

Global variables that are defined outside of any method or closure can be scope restricted by using the private keyword.

import UIKit

// MARK: Local Constants

private let changeSegueId = "MasterToChange"
private let bookSegueId   = "MasterToBook"

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

How to Customize a Progress Bar In Android

If you want to do this in code, here is a sample:

pd = new ProgressDialog(MainActivity.this);
pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pd.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
pd.getWindow().setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);
TextView tv = new TextView(this);
tv.setTextColor(Color.WHITE);
tv.setTextSize(20);
tv.setText("Waiting...");
pd.setCustomTitle(tv);
pd.setIndeterminate(true);
pd.show();

Using TextView gives you an option to change color, size, and font of your text. Otherwise you can just call setMessage(), as usual.

Cannot bulk load. Operating system error code 5 (Access is denied.)

I don't think reinstalling SQL Server is going to fix this, it's just going to kill some time.

  1. Confirm that your user account has read privileges to the folder in question.
  2. Use a tool like Process Monitor to see what user is actually trying to access the file.
  3. My guess is that it is not Michael-PC\Michael that is trying to access the file, but rather the SQL Server service account. If this is the case, then you have at least three options (but probably others):

    a. Set the SQL Server service to run as you.
    b. Grant the SQL Server service account explicit access to that folder.
    c. Put the files somewhere more logical where SQL Server has access, or can be made to have access (e.g. C:\bulk\).

I suggest these things assuming that this is a contained, local workstation. There are definitely more serious security concerns around local filesystem access from SQL Server when we're talking about a production machine, of course this can still be largely mitigated by using c. above - and only giving the service account access to the folders you want it to be able to touch.

How do I connect to this localhost from another computer on the same network?

That's definitely possible. We'll take a general case with Apache here.

Let's say you're a big Symfony2 fan and you would like to access your symfony website at http://symfony.local/ from 4 different computers (the main one hosting your website, as well as a Mac, a Windows and a Linux distro connected (wireless or not) to the main computer.

General Sketch:

enter image description here


1 Set up a virtual host:

You first need to set up a virtual host in your apache httpd-vhosts.conf file. On XAMP, you can find this file here: C:\xampp\apache\conf\extra\httpd-vhosts.conf. On MAMP, you can find this file here: Applications/MAMP/conf/apache/extra/httpd-vhosts.conf. This step prepares the Web server on your computer for handling symfony.local requests. You need to provide the name of the Virtual Host as well as the root/main folder of your website. To do this, add the following line at the end of that file. You need to change the DocumentRoot to wherever your main folder is. Here I have taken /Applications/MAMP/htdocs/Symfony/ as the root of my website.

<VirtualHost *:80>
    DocumentRoot "/Applications/MAMP/htdocs/Symfony/"
    ServerName symfony.local
</VirtualHost>

2 Configure your hosts file:

For the client (your browser in that case) to understand what symfony.local really means, you need to edit the hosts file on your computer. Everytime you type an URL in your browser, your computer tries to understand what it means! symfony.local doesn't mean anything for a computer. So it will try to resolve the name symfony.local to an IP address. It will do this by first looking into the hosts file on your computer to see if he can match an IP address to what you typed in the address bar. If it can't, then it will ask DNS servers. The trick here is to append the following to your hosts file.

  • On MAC, this file is in /private/etc/hosts;
  • On LINUX, this file is in /etc/hosts;
  • On WINDOWS, this file is in \Windows\system32\private\etc\hosts;
  • On WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts;
  • On WINDOWS 10, this file is in \Windows\system32\drivers\etc\hosts;

Hosts file

##
# Host Database
# localhost is used to configure the loopback interface
##
#...
127.0.0.1           symfony.local

From now on, everytime you type symfony.local on this computer, your computer will use the loopback interface to connect to symfony.local. It will understand that you want to work on localhost (127.0.0.1).

3 Access symfony.local from an other computer:

We finally arrive to your main question which is:

How can I now access my website through an other computer?

Well this is now easy! We just need to tell the other computers how they could find symfony.local! How do we do this?

3a Get the IP address of the computer hosting the website:

We first need to know the IP address on the computer that hosts the website (the one we've been working on since the very beginning). In the terminal, on MAC and LINUX type ifconfig |grep inet, on WINDOWS type ipconfig. Let's assume the IP address of this computer is 192.168.1.5.

3b Edit the hosts file on the computer you are trying to access the website from.:

Again, on MAC, this file is in /private/etc/hosts; on LINUX, in /etc/hosts; and on WINDOWS, in \Windows\system32\private\etc\hosts (if you're using WINDOWS 7, this file is in \Windows\system32\drivers\etc\hosts).. The trick is now to use the IP address of the computer we are trying to access/talk to:

##
# Host Database
# localhost is used to configure the loopback interface
##
#...
192.168.1.5         symfony.local

4 Finally enjoy the results in your browser

You can now go into your browser and type http://symfony.local to beautifully see your website on different computers! Note that you can apply the same strategy if you are a OSX user to test your website on Internet Explorer via Virtual Box (if you don't want to use a Windows computer). This is beautifully explained in Crafting Your Windows / IE Test Environment on OSX.


You can also access your localhost from mobile devices

You might wonder how to access your localhost website from a mobile device. In some cases, you won't be able to modify the hosts file (iPhone, iPad...) on your device (jailbreaking excluded).

Well, the solution then is to install a proxy server on the machine hosting the website and connect to that proxy from your iphone. It's actually very well explained in the following posts and is not that long to set up:

On a Mac, I would recommend: Testing a Mac OS X web site using a local hostname on a mobile device: Using SquidMan as a proxy. It's a 100% free solution. Some people can also use Charles as a proxy server but it's 50$.

On Linux, you can adapt the Mac OS way above by using Squid as a proxy server.

On Windows, you can do that using Fiddler. The solution is described in the following post: Monitoring iPhone traffic with Fiddler


Edit 23/11/2017: Hey I don't want to modify my Hosts file

@Dre. Any possible way to access the website from another computer by not editing the host file manually? let's say I have 100 computers wanted to access the website

This is an interesting question, and as it is related to the OP question, let me help.

You would have to do a change on your network so that every machine knows where your website is hosted. Most everyday routers don't do that so you would have to run your own DNS Server on your network.

Let's pretend you have a router (192.168.1.1). This router has a DHCP server and allocates IP addresses to 100 machines on the network.

Now, let's say you have, same as above, on the same network, a machine at 192.168.1.5 which has your website. We will call that machine pompei.

$ echo $HOSTNAME
pompei

Same as before, that machine pompei at 192.168.1.5 runs an HTTP Server which serves your website symfony.local.

For every machine to know that symfony.local is hosted on pompei we will now need a custom DNS Server on the network which knows where symfony.local is hosted. Devices on the network will then be able to resolve domain names served by pompei internally.

3 simple steps.

Step 1: DNS Server

Set-up a DNS Server on your network. Let's have it on pompei for convenience and use something like dnsmasq.

Dnsmasq provides Domain Name System (DNS) forwarder, ....

We want pompei to run DNSmasq to handle DNS requests Hey, pompei, where is symfony.local and respond Hey, sure think, it is on 192.168.1.5 but don't take my word for it.

Go ahead install dnsmasq, dnsmasq configuration file is typically in /etc/dnsmasq.conf depending on your environment.

I personally use no-resolv and google servers server=8.8.8.8 server=8.8.8.4.

*Note:* ALWAYS restart DNSmasq if modifying /etc/hosts file as no changes will take effect otherwise.

Step 2: Firewall

To work, pompei needs to allow incoming and outgoing 'domain' packets, which are going from and to port 53. Of course! These are DNS packets and if pompei does not allow them, there is no way for your DNS server to be reached at all. Go ahead and open that port 53. On linux, you would classically use iptables for this.

Sharing what I came up with but you will very likely have to dive into your firewall and understand everything well.

#
# Allow outbound DNS port 53
#
 iptables -A INPUT -p tcp --dport 53 -j ACCEPT
 iptables -A INPUT -p udp --dport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --dport 53 -j ACCEPT

 iptables -A INPUT -p udp --sport 53 -j ACCEPT
 iptables -A INPUT -p tcp --sport 53 -j ACCEPT

 iptables -A OUTPUT -p tcp --sport 53 -j ACCEPT
 iptables -A OUTPUT -p udp --sport 53 -j ACCEPT

Step 3: Router

Tell your router that your dns server is on 192.168.1.5 now. Most of the time, you can just login into your router and change this manually very easily.

That's it, When you are on a machine and ask for symfony.local, it will ask your DNS Server where symfony.local is hosted, and as soon as it has received its answer from the DNS server, will then send the proper HTTP request to pompei on 192.168.1.5.

I let you play with this and enjoy the ride. These 2 steps are the main guidelines, so you will have to debug and spend a few hours if this is the first time you do it. Let's say this is a bit more advanced networking, there are primary DNS Server, secondary DNS Servers, etc.. Good luck!

WebDriver: check if an element exists?

String link = driver.findElement(By.linkText(linkText)).getAttribute("href")

This will give you the link the element is pointing to.

Add line break within tooltips

This css will help you.

    .tooltip {
      word-break: break-all;
    }

or if you want in one line

    .tooltip-inner {
      max-width: 100%;
    }

How can I convert a comma-separated string to an array?

Here is a function that will convert a string to an array, even if there is only one item in the list (no separator character):

function listToAray(fullString, separator) {
  var fullArray = [];

  if (fullString !== undefined) {
    if (fullString.indexOf(separator) == -1) {
      fullAray.push(fullString);
    } else {
      fullArray = fullString.split(separator);
    }
  }

  return fullArray;
}

Use it like this:

var myString = 'alpha,bravo,charlie,delta';
var myArray = listToArray(myString, ',');
myArray[2]; // charlie

var yourString = 'echo';
var yourArray = listToArray(yourString, ',');
yourArray[0]; // echo

I created this function because split throws out an error if there isn't any separator character in the string (only one item).

How to find and return a duplicate value in array

If you are comparing two different arrays (instead of one against itself) a very fast way is to use the intersect operator & provided by Ruby's Array class.

# Given
a = ['a', 'b', 'c', 'd']
b = ['e', 'f', 'c', 'd']

# Then this...
a & b # => ['c', 'd']

How do you parse and process HTML/XML in PHP?

One general approach I haven't seen mentioned here is to run HTML through Tidy, which can be set to spit out guaranteed-valid XHTML. Then you can use any old XML library on it.

But to your specific problem, you should take a look at this project: http://fivefilters.org/content-only/ -- it's a modified version of the Readability algorithm, which is designed to extract just the textual content (not headers and footers) from a page.

How to shift a block of code left/right by one space in VSCode?

Have a look at File > Preferences > Keyboard Shortcuts (or Ctrl+K Ctrl+S)

Search for cursorColumnSelectDown or cursorColumnSelectUp which will give you the relevent keyboard shortcut. For me it is Shift+Alt+Down/Up Arrow

Nginx - Customizing 404 page

You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.

To redirect to a simple 404 not found page for a specific location:

location /my_blog {
    error_page    404 /blog_article_not_found.html;
}

A site wide 404 page:

server {
    listen 80;
    error_page  404  /website_page_not_found.html;
    ...

You can append standard error codes together to have a single page for several types of errors:

location /my_blog {
    error_page 500 502 503 504 /server_error.html
}

To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:

upstream server2 {
    server 10.0.0.1:80;
}
server {
    location /my_blog {
        error_page    404 @try_server2;
    }
    location @try_server2 {
        proxy_pass http://server2;
    }

The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.

jQuery .search() to any string

if (str.toLowerCase().indexOf("yes") >= 0)

Or,

if (/yes/i.test(str))

Force "git push" to overwrite remote files

Works for me:

git push --set-upstream origin master -f

Mocking a function to raise an Exception to test an except block

Your mock is raising the exception just fine, but the error.resp.status value is missing. Rather than use return_value, just tell Mock that status is an attribute:

barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')

Additional keyword arguments to Mock() are set as attributes on the resulting object.

I put your foo and bar definitions in a my_tests module, added in the HttpError class so I could use it too, and your test then can be ran to success:

>>> from my_tests import foo, HttpError
>>> import mock
>>> with mock.patch('my_tests.bar') as barMock:
...     barMock.side_effect = HttpError(mock.Mock(status=404), 'not found')
...     result = my_test.foo()
... 
404 - 
>>> result is None
True

You can even see the print '404 - %s' % error.message line run, but I think you wanted to use error.content there instead; that's the attribute HttpError() sets from the second argument, at any rate.

How to suspend/resume a process in Windows?

PsSuspend, as mentioned by Vadzim, even suspends/resumes a process by its name, not only by pid.

I use both PsSuspend and PsList (another tool from the PsTools suite) in a simple toggle script for the OneDrive process: if I need more bandwidth, I suspend the OneDrive sync, afterwards I resume the process by issuing the same mini script:

PsList -d onedrive|find/i "suspend" && PsSuspend -r onedrive || PsSuspend onedrive

PsSuspend command line utility from SysInternals suite. It suspends / resumes a process by its id.

How to get TimeZone from android mobile?

Simplest Solution With Simple Date Format: SimpleDateFormat("ZZZZZ"):

 Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"),
                Locale.getDefault());
        Date currentLocalTime = calendar.getTime();

        DateFormat date = new SimpleDateFormat("ZZZZZ",Locale.getDefault());
        String localTime = date.format(currentLocalTime);
        System.out.println(localTime+ "  TimeZone   " );

==> Output is : +05:30

Replace whitespace with a comma in a text file in Linux

This worked for me.

sed -e 's/\s\+/,/g' input.txt >> output.csv

support FragmentPagerAdapter holds reference to old fragments

Just so you know...

Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.

I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).

The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.

I don't have a clean workaround. I used something like this:

  public void onSaveInstanceState(Bundle outState) {
    IFragmentListener listener = (IFragmentListener)getActivity();
    if (listener!= null)
    {
        if (!listener.isStillInTheAdapter(this.getAdapterItem()))
        {
            return; // return empty state.
        }

    }
    super.onSaveInstanceState(outState);

    // normal saving of state for flips and 
    // paging out of the activity follows
    ....
  }

An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

I'm getting favicon.ico error

You can provide your own image and reference it in the head, for example:

<link rel="shortcut icon" href="images/favicon.ico">

How to wait for async method to complete?

Avoid async void. Have your methods return Task instead of void. Then you can await them.

Like this:

private async Task RequestToSendOutputReport(List<byte[]> byteArrays)
{
    foreach (byte[] b in byteArrays)
    {
        while (condition)
        {
            // we'll typically execute this code many times until the condition is no longer met
            Task t = SendOutputReportViaInterruptTransfer();
            await t;
        }

        // read some data from device; we need to wait for this to return
        await RequestToGetInputReport();
    }
}

private async Task RequestToGetInputReport()
{
    // lots of code prior to this
    int bytesRead = await GetInputReportViaInterruptTransfer();
}

In Git, how do I figure out what my current revision is?

There are many ways git log -1 is the easiest and most common, I think

Apply pandas function to column to create multiple new columns?

Have posted the same answer in two other similar questions. The way I prefer to do this is to wrap up the return values of the function in a series:

def f(x):
    return pd.Series([x**2, x**3])

And then use apply as follows to create separate columns:

df[['x**2','x**3']] = df.apply(lambda row: f(row['x']), axis=1)

Is there a simple way to increment a datetime object one month in Python?

Question: Is there a simple way to do this in the current release of Python?

Answer: There is no simple (direct) way to do this in the current release of Python.

Reference: Please refer to docs.python.org/2/library/datetime.html, section 8.1.2. timedelta Objects. As we may understand from that, we cannot increment month directly since it is not a uniform time unit.

Plus: If you want first day -> first day and last day -> last day mapping you should handle that separately for different months.

Docker expose all ports or range of ports from 7000 to 8000

Since Docker 1.5 you can now expose a range of ports to other linked containers using:

The Dockerfile EXPOSE command:

EXPOSE 7000-8000

or The Docker run command:

docker run --expose=7000-8000

Or instead you can publish a range of ports to the host machine via Docker run command:

docker run -p 7000-8000:7000-8000

Reading file from Workspace in Jenkins with Groovy script

Based on your comments, you would be better off with Text-finder plugin.

It allows to search file(s), as well as console, for a regular expression and then set the build either unstable or failed if found.

As for the Groovy, you can use the following to access ${WORKSPACE} environment variable:
def workspace = manager.build.getEnvVars()["WORKSPACE"]

C# code to validate email address

What about this?

bool IsValidEmail(string email)
{
    try {
        var addr = new System.Net.Mail.MailAddress(email);
        return addr.Address == email;
    }
    catch {
        return false;
    }
}

Per Stuart's comment, this compares the final address with the original string instead of always returning true. MailAddress tries to parse a string with spaces into "Display Name" and "Address" portions, so the original version was returning false positives.


To clarify, the question is asking whether a particular string is a valid representation of an e-mail address, not whether an e-mail address is a valid destination to send a message. For that, the only real way is to send a message to confirm.

Note that e-mail addresses are more forgiving than you might first assume. These are all perfectly valid forms:

  • cog@wheel
  • "cogwheel the orange"@example.com
  • 123@$.xyz

For most use cases, a false "invalid" is much worse for your users and future proofing than a false "valid". Here's an article that used to be the accepted answer to this question (that answer has since been deleted). It has a lot more detail and some other ideas of how to solve the problem.

Providing sanity checks is still a good idea for user experience. Assuming the e-mail address is valid, you could look for known top-level domains, check the domain for an MX record, check for spelling errors from common domain names (gmail.cmo), etc. Then present a warning giving the user a chance to say "yes, my mail server really does allow as an email address."


As for using exception handling for business logic, I agree that is a thing to be avoided. But this is one of those cases where the convenience and clarity may outweigh the dogma.

Besides, if you do anything else with the e-mail address, it's probably going to involve turning it to a MailAddress. Even if you don't use this exact function, you will probably want to use the same pattern. You can also check for specific kinds of failure by catching different exceptions: null, empty, or invalid format.


--- Further reading ---

Documentation for System.Net.Mail.MailAddress

Explanation of what makes up a valid email address

Using $_POST to get select option value from HTML


-- html file --

<select name='city[]'> 
                <option name='Kabul' value="Kabul" > Kabul </option>
                <option name='Herat' value='Herat' selected="selected">             Herat </option>
                <option name='Mazar' value='Mazar'>Mazar </option>
</select>

-- php file --

$city = (isset($_POST['city']) ? $_POST['city']: null);
print("city is: ".$city[0]);

Passing a varchar full of comma delimited values to a SQL Server IN function

Error 493: The column 'i' that was returned from the nodes() method cannot be 
   used directly. It can only be used with one of the four XML data type 
   methods, exist(), nodes(), query(), and value(), or in IS NULL and IS NOT 
   NULL checks.

The above errorr was fixed in SQL Server 2014 by using following snippet

Declare @Ids varchar(50)
Set @Ids = '1,2,3,5,4,6,7,98,234'

DECLARE @XML XML
SET @XML = CAST('<i>' + REPLACE(@Ids, ',', '</i><i>') + '</i>' AS XML)

SELECT SomeTable.* 
FROM
    SomeTable 
    cross apply @XML.nodes('i') x(i) 
        where SomeTable .Id = x.i.value('.', 'VARCHAR(MAX)')

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

What's the fastest way to loop through an array in JavaScript?

I have tried some other ways to iterate a huge array and found out that halving the array length and then iterating both halves in a single loop is faster. This performance difference can be seen while processing huge arrays.

var firstHalfLen =0;
var secondHalfLen = 0;
var count2=0;
var searchterm = "face";
var halfLen = arrayLength/2;
if(arrayLength%2==halfLen)
{
   firstHalfLen = Math.ceil(halfLen);
   secondHalfLen=Math.floor(halfLen);
}
else
{
   firstHalfLen=halfLen;
   secondHalfLen=halfLen;
}
for(var firstHalfCOunter=0,secondHalfCounter = arrayLength-secondHalfLen;
    firstHalfCOunter < firstHalfLen;
    firstHalfCOunter++)
{
  if(mainArray[firstHalfCOunter].search(new RegExp(searchterm, "i"))> -1)
  {
    count2+=1;
  }
  if(secondHalfCounter < arrayLength)
  {
    if(mainArray[secondHalfCounter].search(new RegExp(searchterm, "i"))> -1)
    {
        count2+=1;
    }
    secondHalfCounter++; 
  }
}

Some performance comparison (using timer.js) between the cached length for-loop VS the above method.

http://jsfiddle.net/tejzpr/bbLgzxgo/

Add column in dataframe from list

Just assign the list directly:

df['new_col'] = mylist

Alternative
Convert the list to a series or array and then assign:

se = pd.Series(mylist)
df['new_col'] = se.values

or

df['new_col'] = np.array(mylist)

How to correctly catch change/focusOut event on text input in React.js?

Its late, yet it's worth your time nothing that, there are some differences in browser level implementation of focusin and focusout events and react synthetic onFocus and onBlur. focusin and focusout actually bubble, while onFocus and onBlur dont. So there is no exact same implementation for focusin and focusout as of now for react. Anyway most cases will be covered in onFocus and onBlur.

How can I sort a List alphabetically?

Solution with Collections.sort

If you are forced to use that List, or if your program has a structure like

  • Create List
  • Add some country names
  • sort them once
  • never change that list again

then Thilos answer will be the best way to do it. If you combine it with the advice from Tom Hawtin - tackline, you get:

java.util.Collections.sort(listOfCountryNames, Collator.getInstance());

Solution with a TreeSet

If you are free to decide, and if your application might get more complex, then you might change your code to use a TreeSet instead. This kind of collection sorts your entries just when they are inserted. No need to call sort().

Collection<String> countryNames = 
    new TreeSet<String>(Collator.getInstance());
countryNames.add("UK");
countryNames.add("Germany");
countryNames.add("Australia");
// Tada... sorted.

Side note on why I prefer the TreeSet

This has some subtle, but important advantages:

  • It's simply shorter. Only one line shorter, though.
  • Never worry about is this list really sorted right now becaude a TreeSet is always sorted, no matter what you do.
  • You cannot have duplicate entries. Depending on your situation this may be a pro or a con. If you need duplicates, stick to your List.
  • An experienced programmer looks at TreeSet<String> countyNames and instantly knows: this is a sorted collection of Strings without duplicates, and I can be sure that this is true at every moment. So much information in a short declaration.
  • Real performance win in some cases. If you use a List, and insert values very often, and the list may be read between those insertions, then you have to sort the list after every insertion. The set does the same, but does it much faster.

Using the right collection for the right task is a key to write short and bug free code. It's not as demonstrative in this case, because you just save one line. But I've stopped counting how often I see someone using a List when they want to ensure there are no duplictes, and then build that functionality themselves. Or even worse, using two Lists when you really need a Map.

Don't get me wrong: Using Collections.sort is not an error or a flaw. But there are many cases when the TreeSet is much cleaner.

Laravel blade check empty foreach

Using following code, one can first check variable is set or not using @isset of laravel directive and then check that array is blank or not using @unless of laravel directive

@if(@isset($names))
    @unless($names)
        Array has no value
    @else
        Array has value

        @foreach($names as $name)
            {{$name}}
        @endforeach

    @endunless
@else
    Not defined
@endif

How to document Python code using Doxygen

Sphinx is mainly a tool for formatting docs written independently from the source code, as I understand it.

For generating API docs from Python docstrings, the leading tools are pdoc and pydoctor. Here's pydoctor's generated API docs for Twisted and Bazaar.

Of course, if you just want to have a look at the docstrings while you're working on stuff, there's the "pydoc" command line tool and as well as the help() function available in the interactive interpreter.

SQL 'like' vs '=' performance

You should also keep in mind that when using like, some sql flavors will ignore indexes, and that will kill performance. This is especially true if you don't use the "starts with" pattern like your example.

You should really look at the execution plan for the query and see what it's doing, guess as little as possible.

This being said, the "starts with" pattern can and is optimized in sql server. It will use the table index. EF 4.0 switched to like for StartsWith for this very reason.

File Upload using AngularJS

The code will helps to insert file

<body ng-app = "myApp">
<form ng-controller="insert_Ctrl"  method="post" action=""  name="myForm" enctype="multipart/form-data" novalidate>
    <div>
        <p><input type="file" ng-model="myFile" class="form-control"  onchange="angular.element(this).scope().uploadedFile(this)">
            <span style="color:red" ng-show="(myForm.myFile.$error.required&&myForm.myFile.$touched)">Select Picture</span>
        </p>
    </div>
    <div>
        <input type="button" name="submit"  ng-click="uploadFile()" class="btn-primary" ng-disabled="myForm.myFile.$invalid" value="insert">
    </div>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> 
<script src="insert.js"></script>
</body>

insert.js

var app = angular.module('myApp',[]);
app.service('uploadFile', ['$http','$window', function ($http,$window) {
    this.uploadFiletoServer = function(file,uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(data){
            alert("insert successfull");
            $window.location.href = ' ';//your window location
        })
        .error(function(){
            alert("Error");
        });
    }
}]);
app.controller('insert_Ctrl',  ['$scope', 'uploadFile', function($scope, uploadFile){
    $scope.uploadFile = function() {
        $scope.myFile = $scope.files[0];
        var file = $scope.myFile;
        var url = "save_data.php";
        uploadFile.uploadFiletoServer(file,url);
    };
    $scope.uploadedFile = function(element) {
        var reader = new FileReader();
        reader.onload = function(event) {
            $scope.$apply(function($scope) {
                $scope.files = element.files;
                $scope.src = event.target.result  
            });
        }
        reader.readAsDataURL(element.files[0]);
    }
}]);

save_data.php

<?php
    require "dbconnection.php";
    $ext = pathinfo($_FILES['file']['name'],PATHINFO_EXTENSION);
    $image = time().'.'.$ext;
    move_uploaded_file($_FILES["file"]["tmp_name"],"upload/".$image);
    $query="insert into test_table values ('null','$image')";
    mysqli_query($con,$query);
?>

Batch file to run a command in cmd within a directory

Chain arbitrary commands using & like this:

command1 & command2 & command3 & ...

Thus, in your particular case, put this line in a batch file on your desktop:

START cmd.exe /k "cd C:\activiti-5.9\setup & ant demo.start"

You can also use && to chain commands, albeit this will perform error checking and the execution chain will break if one of the commands fails. The behaviour is detailed here.

Edit: Intrigued by @James K's comment "You CAN chain the commands, but they will have no effect", I tested some more and to my surprise discovered, that the program I was starting in my original test - firefox.exe - while not existing in a directory in the PATH environment variable, is actually executable anywhere on my system (which really made me wonder - see bottom of answer for explanation). So in fact executing...

START cmd.exe /k "cd C:\progra~1\mozill~1 && firefox"

...didn't prove the solution was working. So I chose another program (nLite) after making sure that it was not executable anywhere on my system:

START cmd.exe /k "cd C:\progra~1\nlite && nlite"

And that works just as my original answer already suggested. A Windows version is not given in the question, but I'm using Windows XP, btw.


If anybody is interested why firefox.exe, while not being in PATH, is executable anywhere on my system - and very probably on yours as well - this is due to a registry key where applications can be registered to be available everywhere. See this SU answer for details.

how to configure lombok in eclipse luna

Step 1: Goto https://projectlombok.org/download and click on 1.18.2

Step 2: Place your jar file in java installation path in my case it is C:\Program Files\Java\jdk-10.0.1\lib

step 3: Open your Eclipse IDE folder where you have in your PC.

Step 4: Add the place where I added then open your IDE it will open without any errors.

-startup
plugins/org.eclipse.equinox.launcher_1.5.0.v20180512-1130.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.700.v20180518-1200
-product
org.eclipse.epp.package.jee.product
-showsplash
org.eclipse.epp.package.common
--launcher.defaultAction
openFile
--launcher.defaultAction
openFile
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8
-javaagent:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
-Xbootclasspath/a:C:\Program Files\Java\jdk-10.0.1\lib\lombok.jar
[email protected]/eclipse-workspace
-XX:+UseG1GC
-XX:+UseStringDeduplication
--add-modules=ALL-SYSTEM
-Dosgi.requiredJavaVersion=1.8
-Dosgi.dataAreaRequiresExplicitInit=true
-Xms256m
-Xmx1024m
--add-modules=ALL-SYSTEM

Microsoft.Office.Core Reference Missing

You can add reference of Microsoft.Office.Core from COM components tab in the add reference window by adding reference of Microsoft Office 12.0 Object Library. The screen shot will shows what component you need.

enter image description here

How to start mongodb shell?

You need to find the bin folder and then open a command prompt on that folder Then just type mongo.exe and press enter to start the shell

Or you can supply the full path to mongo.exe from any folder to start the shell:

c:\MongoDB\bin\mongo.exe

Then if you have multiple databases, you can do enter command >use <database_name> to use that db

Let me know if it helps or have issues

ASP.NET Web Api: The requested resource does not support http method 'GET'

I got this error when running a query without SSL.

Simply changing the URL scheme of my request from HTTP to HTTPS fixed it.

How to flatten only some dimensions of a numpy array

A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.

e.g. to flatten all but the last two dimensions:

arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)

EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:

arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)

How to loop through an array containing objects and access their properties

for (var j = 0; j < myArray.length; j++){
  console.log(myArray[j].x);
}

Check if string is neither empty nor space in shell script

To check if a string is empty or contains only whitespace you could use:

shopt -s extglob  # more powerful pattern matching

if [ -n "${str##+([[:space:]])}" ]; then
    echo '$str is not null or space'
fi

See Shell Parameter Expansion and Pattern Matching in the Bash Manual.

Add timer to a Windows Forms application

Something like this in your form main. Double click the form in the visual editor to create the form load event.

 Timer Clock=new Timer();
 Clock.Interval=2700000; // not sure if this length of time will work 
 Clock.Start();
 Clock.Tick+=new EventHandler(Timer_Tick);

Then add an event handler to do something when the timer fires.

  public void Timer_Tick(object sender,EventArgs eArgs)
  {
    if(sender==Clock)
    {
      // do something here      
    }
  }

Changing the default icon in a Windows Forms application

Add your icon as a Resource (Project > yourprojectname Properties > Resources > Pick "Icons from dropdown > Add Resource (or choose Add Existing File from dropdown if you already have the .ico)

Then:

this.Icon = Properties.Resources.youriconname;

What is JNDI? What is its basic use? When is it used?

I will use one example to explain how JNDI can be used to configure database without any application developer knowing username and password of the database.

1) We have configured the data source in JBoss server's standalone-full.xml. Additionally, we can configure pool details also.

 <datasource jta="false" jndi-name="java:/DEV.DS" pool-name="DEV" enabled="true" use-ccm="false">
                <connection-url>jdbc:oracle:thin:@<IP>:1521:DEV</connection-url>
                <driver-class>oracle.jdbc.OracleDriver</driver-class>
                <driver>oracle</driver>
                <security>
                    <user-name>usname</user-name>
                    <password>pass</password>
                    </security>
                    <security>

 <security-domain>encryptedSecurityDomain</security-domain>
                    </security>

                <validation>
                    <validate-on-match>false</validate-on-match>
                    <background-validation>false</background-validation>
                    <background-validation-millis>1</background-validation-millis>
                </validation>
                <statement>
                    <prepared-statement-cache-size>0</prepared-statement-cache-size>
                    <share-prepared-statements>false</share-prepared-statements>
                    <pool>
                        <min-pool-size>5</min-pool-size>
                        <max-pool-size>10</max-pool-size>
                    </pool>
                </statement>
            </datasource>

enter image description here

Now, this jndi-name and its associated datasource object will be available for our application.application.

2) We can retrieve this datasource object using JndiDataSourceLookup class.

enter image description here

Spring will instantiate the datasource bean, after we provide the jndi-name.

Now, we can change the pool size, user name or password as per our environment or requirement, but it will not impact the application.

Note : encryptedSecurityDomain, we need to configure it separately in JBoss server like

<security-domain name="encryptedSecurityDomain" cache-type="default">
                    <authentication>
                        <login-module code="org.picketbox.datasource.security.SecureIdentityLoginModule" flag="required">
                            <module-option name="username" value="<usernamefordb>"/>
                            <module-option name="password" value="894c8a6aegc8d028ce169c596d67afd0"/>
                        </login-module>
                    </authentication>
                </security-domain>

This is one of the use cases. Hope it clarifies.

jQuery animate margin top

You had MarginTop instead of marginTop

http://jsfiddle.net/kX7b6/1/

It is also very buggy if you leave mid animation, here is update:

http://jsfiddle.net/kX7b6/3/

Note I changed it to mouseenter and mouseleave because I don't think the intention was to cancel the animation when you hover over the red or green area.

Clear Application's Data Programmatically

I'm just putting the tutorial from the link ihrupin posted here in this post.

package com.hrupin.cleaner;

import java.io.File;

import android.app.Application;
import android.util.Log;

public class MyApplication extends Application {

    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance() {
        return instance;
    }

    public void clearApplicationData() {
        File cacheDirectory = getCacheDir();
        File applicationDirectory = new File(cacheDirectory.getParent());
        if (applicationDirectory.exists()) {
            String[] fileNames = applicationDirectory.list();
            for (String fileName : fileNames) {
                if (!fileName.equals("lib")) {
                    deleteFile(new File(applicationDirectory, fileName));
                }
            }
        }
    }

    public static boolean deleteFile(File file) {
        boolean deletedAll = true;
        if (file != null) {
            if (file.isDirectory()) {
                String[] children = file.list();
                for (int i = 0; i < children.length; i++) {
                    deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
                }
            } else {
                deletedAll = file.delete();
            }
        }

        return deletedAll;
    }
}

So if you want a button to do this you need to call MyApplication.getInstance(). clearApplicationData() from within an onClickListener

Update: Your SharedPreferences instance might hold onto your data and recreate the preferences file after you delete it. So your going to want to get your SharedPreferences object and

prefs.edit().clear().commit();

Update:

You need to add android:name="your.package.MyApplication" to the application tag inside AndroidManifest.xml if you had not done so. Else, MyApplication.getInstance() returns null, resulting a NullPointerException.

Undo working copy modifications of one file in Git?

I restore my files using the SHA id, What i do is git checkout <sha hash id> <file name>

Create a new workspace in Eclipse

In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.

Then close eclipse and reopen.

Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.

Or File->Switch Workspace->Other...

How can foreign key constraints be temporarily disabled using T-SQL?

Answer marked '905' looks good but does not work.

Following worked for me. Any Primary Key, Unique Key, or Default constraints CAN NOT be disabled. In fact, if 'sp_helpconstraint '' shows 'n/a' in status_enabled - Means it can NOT be enabled/disabled.

-- To generate script to DISABLE

select 'ALTER TABLE ' + object_name(id) + ' NOCHECK CONSTRAINT [' + object_name(constid) + ']'
from sys.sysconstraints 
where status & 0x4813 = 0x813 order by object_name(id)

-- To generate script to ENABLE

select 'ALTER TABLE ' + object_name(id) + ' CHECK CONSTRAINT [' + object_name(constid) + ']'
from sys.sysconstraints 
where status & 0x4813 = 0x813 order by object_name(id)

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

PHP Warning: Invalid argument supplied for foreach()

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}

Horizontal line using HTML/CSS

Or change it to height: 0.1em; orso, minimal size of anything displayable is 1px.

The 0.05 em you are using means, get the current font size in pixels of this elements and give me 5% of it. Which for 12 pixels returns 0.6 pixels which is too little to display. if you would turn up the font size of the div to atleast 20pixels it would display fine. I suppose Chrome doesnt round up sizes to be atleast 1pixel where other browsers do.

Curl Command to Repeat URL Request

You could use URL sequence substitution with a dummy query string (if you want to use CURL and save a few keystrokes):

curl http://www.myurl.com/?[1-20]

If you have other query strings in your URL, assign the sequence to a throwaway variable:

curl http://www.myurl.com/?myVar=111&fakeVar=[1-20]

Check out the URL section on the man page: https://curl.haxx.se/docs/manpage.html

jQuery UI Dialog Box - does not open after being closed

on the last line, don't use $(this).remove() use $(this).hide() instead.

EDIT: To clarify,on the close click event you're removing the #terms div from the DOM which is why its not coming back. You just need to hide it instead.

Difference between HashMap, LinkedHashMap and TreeMap

Just some more input from my own experience with maps, on when I would use each one:

  • HashMap - Most useful when looking for a best-performance (fast) implementation.
  • TreeMap (SortedMap interface) - Most useful when I'm concerned with being able to sort or iterate over the keys in a particular order that I define.
  • LinkedHashMap - Combines advantages of guaranteed ordering from TreeMap without the increased cost of maintaining the TreeMap. (It is almost as fast as the HashMap). In particular, the LinkedHashMap also provides a great starting point for creating a Cache object by overriding the removeEldestEntry() method. This lets you create a Cache object that can expire data using some criteria that you define.

jQueryUI modal dialog does not show close button (x)

In the upper right corner of the dialog, mouse over where the button should be, and see rather or not you get some effect (the button hover). Try clicking it and seeing if it closes. If it does close, then you're just missing your image sprites that came with your package download.

How to properly upgrade node using nvm

Bash alias for updating current active version:

alias nodeupdate='nvm install $(nvm current | sed -rn "s/v([[:digit:]]+).*/\1/p") --reinstall-packages-from=$(nvm current)'

The part sed -rn "s/v([[:digit:]]+).*/\1/p" transforms output from nvm current so that only a major version of node is returned, i.e.: v13.5.0 -> 13.

What is the newline character in the C language: \r or \n?

What is the newline character in the C language: \r or \n?

The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

  1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

  2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

  3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
    Note: File I/O in binary mode makes no translation.

The '\r' in source code is the carriage return char.

(*1) A lone 13 and/or 10 may also translate into \n.

Ruby on Rails: Clear a cached page

Check for a static version of your page in /public and delete it if it's there. When Rails 3.x caches pages, it leaves a static version in your public folder and loads that when users hit your site. This will remain even after you clear your cache.

Java get month string from integer

Take an array containing months name.

String[] str = {"January",      
   "February",
   "March",        
   "April",        
   "May",          
   "June",         
   "July",         
   "August",       
   "September",    
   "October",      
   "November",     
   "December"};

Then where you wanna take month use like follow:

if(i<str.length)
    monthString = str[i-1];
else
    monthString = "Invalid month";

JSON.parse unexpected token s

You're asking it to parse the JSON text something (not "something"). That's invalid JSON, strings must be in double quotes.

If you want an equivalent to your first example:

var s = '"something"';
var result = JSON.parse(s);

Is there a way to add/remove several classes in one single instruction with classList?

A better way to add the multiple classes separated by spaces in a string is using the Spread_syntax with the split:

element.classList.add(...classesStr.split(" "));

Ruby on Rails - Import Data from a CSV file

It is better to wrap the database related process inside a transaction block. Code snippet blow is a full process of seeding a set of languages to Language model,

require 'csv'

namespace :lan do
  desc 'Seed initial languages data with language & code'
  task init_data: :environment do
    puts '>>> Initializing Languages Data Table'
    ActiveRecord::Base.transaction do
      csv_path = File.expand_path('languages.csv', File.dirname(__FILE__))
      csv_str = File.read(csv_path)
      csv = CSV.new(csv_str).to_a
      csv.each do |lan_set|
        lan_code = lan_set[0]
        lan_str = lan_set[1]
        Language.create!(language: lan_str, code: lan_code)
        print '.'
      end
    end
    puts ''
    puts '>>> Languages Database Table Initialization Completed'
  end
end

Snippet below is a partial of languages.csv file,

aa,Afar
ab,Abkhazian
af,Afrikaans
ak,Akan
am,Amharic
ar,Arabic
as,Assamese
ay,Aymara
az,Azerbaijani
ba,Bashkir
...

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

All of above do not work for me.

What I found was click the Details button. enter image description here

Then following the Multiple contexts with the same path error running web service in Eclipse using Tomcat

Removed the duplicated line then I got an another error.

The server cannot be started because one or more of the ports are invalid. Open the server editor and correct the invalid ports.

Following Can't start tomcatv9.0 in Eclipse

Then it works.

Convert UTC/GMT time to local time

I know this is an older question, but I ran into a similar situation, and I wanted to share what I had found for future searchers, possibly including myself :).

DateTime.Parse() can be tricky -- see here for example.

If the DateTime is coming from a Web service or some other source with a known format, you might want to consider something like

DateTime.ParseExact(dateString, 
                   "MM/dd/yyyy HH:mm:ss", 
                   CultureInfo.InvariantCulture, 
                   DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal)

or, even better,

DateTime.TryParseExact(...)

The AssumeUniversal flag tells the parser that the date/time is already UTC; the combination of AssumeUniversal and AdjustToUniversal tells it not to convert the result to "local" time, which it will try to do by default. (I personally try to deal exclusively with UTC in the business / application / service layer(s) anyway. But bypassing the conversion to local time also speeds things up -- by 50% or more in my tests, see below.)

Here's what we were doing before:

DateTime.Parse(dateString, new CultureInfo("en-US"))

We had profiled the app and found that the DateTime.Parse represented a significant percentage of CPU usage. (Incidentally, the CultureInfo constructor was not a significant contributor to CPU usage.)

So I set up a console app to parse a date/time string 10000 times in a variety of ways. Bottom line:
Parse() 10 sec
ParseExact() (converting to local) 20-45 ms
ParseExact() (not converting to local) 10-15 ms
... and yes, the results for Parse() are in seconds, whereas the others are in milliseconds.

How to use a jQuery plugin inside Vue

Step 1 We place ourselves with the terminal in the folder of our project and install JQuery through npm or yarn.

npm install jquery --save

Step 2 Within our file where we want to use JQuery, for example app.js (resources/js/app.js), in the script section we include the following code.

// We import JQuery
const $ = require('jquery');
// We declare it globally
window.$ = $;

// You can use it now
$('body').css('background-color', 'orange');

// Here you can add the code for different plugins

Git push error pre-receive hook declined

ihave followed the instruction of heroku logs img https://devcenter.heroku.com/articles/buildpacks#detection-failure ( use cmd: heroku logs -> show your error) then do the cmd: "heroku buildpacks:clear". finally, it worked for me!

Which command in VBA can count the number of characters in a string variable?

Do you mean counting the number of characters in a string? That's very simple

Dim strWord As String
Dim lngNumberOfCharacters as Long

strWord = "habit"
lngNumberOfCharacters = Len(strWord)
Debug.Print lngNumberOfCharacters

mysql: get record count between two date-time

select * from yourtable where created < now() and created > '2011-04-25 04:00:00'

How to change theme for AlertDialog

I have written an article in my blog on how to configure the layout of an AlertDialog with XML style files. The main problem is that you need different style definitions for different layout parameters. Here is a boilerplate based on the AlertDialog style of Holo Light Platform version 19 for a style file that should cover a bunch of the standard layout aspects like text sizes and background colors.

<style name="AppBaseTheme" parent="android:Theme.Holo.Light">
    ...
    <item name="android:alertDialogTheme">@style/MyAlertDialogTheme</item>
    <item name="android:alertDialogStyle">@style/MyAlertDialogStyle</item>
    ...
</style>

<style name="MyBorderlessButton">
    <!-- Set background drawable and text size of the buttons here -->
    <item name="android:background">...</item>
    <item name="android:textSize">...</item>
</style>

<style name="MyButtonBar">
    <!-- Define a background for the button bar and a divider between the buttons here -->
    <item name="android:divider">....</item>
    <item name="android:dividerPadding">...</item>
    <item name="android:showDividers">...</item>
    <item name="android:background">...</item>
</style>

<style name="MyAlertDialogTitle">
    <item name="android:maxLines">1</item>
    <item name="android:scrollHorizontally">true</item>
</style>

<style name="MyAlertTextAppearance">
    <!-- Set text size and color of title and message here -->
    <item name="android:textSize"> ... </item>
    <item name="android:textColor">...</item>
</style>

<style name="MyAlertDialogTheme">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowTitleStyle">@style/MyAlertDialogTitle</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowMinWidthMajor">@android:dimen/dialog_min_width_major</item>
    <item name="android:windowMinWidthMinor">@android:dimen/dialog_min_width_minor</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:textAppearanceMedium">@style/MyAlertTextAppearance</item>
    <!-- If you don't want your own button bar style use
            @android:style/Holo.Light.ButtonBar.AlertDialog
            and
            ?android:attr/borderlessButtonStyle
         instead of @style/MyButtonBar and @style/MyBorderlessButton -->
    <item name="android:buttonBarStyle">@style/MyButtonBar</item>
    <item name="android:buttonBarButtonStyle">@style/MyBorderlessButton</item>
</style>

<style name="MyAlertDialogStyle">
    <!-- Define background colors of title, message, buttons, etc. here -->
    <item name="android:fullDark">...</item>
    <item name="android:topDark">...</item>
    <item name="android:centerDark">...</item>
    <item name="android:bottomDark">...</item>
    <item name="android:fullBright">...</item>
    <item name="android:topBright">...</item>
    <item name="android:centerBright">...</item>
    <item name="android:bottomBright">...</item>
    <item name="android:bottomMedium">...</item>
    <item name="android:centerMedium">...</item>
</style>

Is it possible to use if...else... statement in React render function?

Not exactly like that, but there are workarounds. There's a section in React's docs about conditional rendering that you should take a look. Here's an example of what you could do using inline if-else.

render() {
  const isLoggedIn = this.state.isLoggedIn;
  return (
    <div>
      {isLoggedIn ? (
        <LogoutButton onClick={this.handleLogoutClick} />
      ) : (
        <LoginButton onClick={this.handleLoginClick} />
      )}
    </div>
  );
}

You can also deal with it inside the render function, but before returning the jsx.

if (isLoggedIn) {
  button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
  button = <LoginButton onClick={this.handleLoginClick} />;
}

return (
  <div>
    <Greeting isLoggedIn={isLoggedIn} />
    {button}
  </div>
);

It's also worth mentioning what ZekeDroid brought up in the comments. If you're just checking for a condition and don't want to render a particular piece of code that doesn't comply, you can use the && operator.

  return (
    <div>
      <h1>Hello!</h1>
      {unreadMessages.length > 0 &&
        <h2>
          You have {unreadMessages.length} unread messages.
        </h2>
      }
    </div>
  );

visual c++: #include files from other projects in the same solution

You need to set the path to the headers in the project properties so the compiler looks there when trying to find the header file(s). I can't remember the exact location, but look though the Project properties and you should see it.

What is a regular expression for a MAC Address?

I don't think that the main RegEx is correct as it also classifies

'3D-F2-C9:A6-B3:4F' 

as a valid MAC Address, even though it is not correct. The correct one would be:

((([a-zA-z0-9]{2}[-:]){5}([a-zA-z0-9]{2}))|(([a-zA-z0-9]{2}:){5}([a-zA-z0-9]{2})))

So that every time you can choose ':' or '-' for the whole MAC address.

Server is already running in Rails

gem install shutup

then go in the current folder of your rails project and run

shutup # this will kill the Rails process currently running

You can use the command 'shutup' every time you want

DICLAIMER: I am the creator of this gem

NOTE: if you are using rvm install the gem globally

rvm @global do gem install shutup

Bootstrap: adding gaps between divs

Starting from Bootstrap v4 you can simply add the following to your div class attribute: mt-2 (margin top 2)

<div class="mt-2 col-md-12">
        This will have a two-point top margin!
</div>

More examples are given in the docs: Bootstrap v4 docs

Does functional programming replace GoF design patterns?

Is there any truth to the claim that functional programming eliminates the need for OOP design patterns?

Functional programming is not the same as object-oriented programming. Object-oriented design patterns don't apply to functional programming. Instead, you have functional programming design patterns.

For functional programming, you won't read the OO design pattern books; you'll read other books on FP design patterns.

language agnostic

Not totally. Only language-agnostic with respect to OO languages. The design patterns don't apply to procedural languages at all. They barely make sense in a relational database design context. They don't apply when designing a spreadsheet.

a typical OOP design pattern and its functional equivalent?

The above shouldn't exist. That's like asking for a piece of procedural code rewritten as OO code. Ummm... If I translate the original Fortran (or C) into Java, I haven't done anything more than translate it. If I totally rewrite it into an OO paradigm, it will no longer look anything like the original Fortran or C -- it will be unrecognizable.

There's no simple mapping from OO design to functional design. They're very different ways of looking at the problem.

Functional programming (like all styles of programming) has design patterns. Relational databases have design patterns, OO has design patterns, and procedural programming has design patterns. Everything has design patterns, even the architecture of buildings.

Design patterns -- as a concept -- are a timeless way of building, irrespective of technology or problem domain. However, specific design patterns apply to specific problem domains and technologies.

Everyone who thinks about what they're doing will uncover design patterns.

Hide "NFC Tag type not supported" error on Samsung Galaxy devices

Before Android 4.4

What you are trying to do is simply not possible from an app (at least not on a non-rooted/non-modified device). The message "NFC tag type not supported" is displayed by the Android system (or more specifically the NFC system service) before and instead of dispatching the tag to your app. This means that the NFC system service filters MIFARE Classic tags and never notifies any app about them. Consequently, your app can't detect MIFARE Classic tags or circumvent that popup message.

On a rooted device, you may be able to bypass the message using either

  1. Xposed to modify the behavior of the NFC service, or
  2. the CSC (Consumer Software Customization) feature configuration files on the system partition (see /system/csc/. The NFC system service disables the popup and dispatches MIFARE Classic tags to apps if the CSC feature <CscFeature_NFC_EnableSecurityPromptPopup> is set to any value but "mifareclassic" or "all". For instance, you could use:

    <CscFeature_NFC_EnableSecurityPromptPopup>NONE</CscFeature_NFC_EnableSecurityPromptPopup>
    

    You could add this entry to, for instance, the file "/system/csc/others.xml" (within the section <FeatureSet> ... </FeatureSet> that already exists in that file).

Since, you asked for the Galaxy S6 (the question that you linked) as well: I have tested this method on the S4 when it came out. I have not verified if this still works in the latest firmware or on other devices (e.g. the S6).

Since Android 4.4

This is pure guessing, but according to this (link no longer available), it seems that some apps (e.g. NXP TagInfo) are capable of detecting MIFARE Classic tags on affected Samsung devices since Android 4.4. This might mean that foreground apps are capable of bypassing that popup using the reader-mode API (see NfcAdapter.enableReaderMode) possibly in combination with NfcAdapter.FLAG_READER_SKIP_NDEF_CHECK.

Using jquery to get element's position relative to viewport

Here are two functions to get the page height and the scroll amounts (x,y) without the use of the (bloated) dimensions plugin:

// getPageScroll() by quirksmode.com
function getPageScroll() {
    var xScroll, yScroll;
    if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
    } else if (document.documentElement && document.documentElement.scrollTop) {
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
    } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
    }
    return new Array(xScroll,yScroll)
}

// Adapted from getPageSize() by quirksmode.com
function getPageHeight() {
    var windowHeight
    if (self.innerHeight) { // all except Explorer
      windowHeight = self.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
      windowHeight = document.documentElement.clientHeight;
    } else if (document.body) { // other Explorers
      windowHeight = document.body.clientHeight;
    }
    return windowHeight
}

What's the difference between VARCHAR and CHAR?

CHAR Vs VARCHAR

CHAR is used for Fixed Length Size Variable
VARCHAR is used for Variable Length Size Variable.

E.g.

Create table temp
(City CHAR(10),
Street VARCHAR(10));

Insert into temp
values('Pune','Oxford');

select length(city), length(street) from temp;

Output will be

length(City)          Length(street)
10                    6

Conclusion: To use storage space efficiently must use VARCHAR Instead CHAR if variable length is variable

How can I find matching values in two arrays?

use lodash

GLOBAL.utils = require('lodash')
var arr1 = ['first' , 'second'];
var arr2 = ['second '];

var result = utils.difference(arr1 , arr2);
console.log ( "result :" + result );

Real time data graphing on a line chart with html5

I would suggest Smoothie Charts.

It's very simple to use, easily and widely configurable, and does a great job of streaming real time data.

There's a builder that lets you explore the options and generate code.

Disclaimer: I am a contributor to the library.

Check if a key exists inside a json object

you can do like this:

if("merchant_id" in thisSession){ /** will return true if exist */
 console.log('Exist!');
}

or

if(thisSession["merchant_id"]){ /** will return its value if exist */
 console.log('Exist!');
}

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

how to get the host url using javascript from the current page

Depending on your needs, you can use one of the window.location properties. In your question you are asking about the host, which may be retrieved using window.location.hostname (e.g. www.example.com). In your example you are showing something what is called origin, which may be retrieved using window.location.origin (e.g. http://www.example.com).

var path = window.location.origin + "/";

//result = "http://localhost:60470/"

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Select from table by knowing only date without time (ORACLE)

You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000