Programs & Examples On #Scrolledwindow

How do I make a JAR from a .java file?

Perhaps the most beginner-friendly way to compile a JAR from your Java code is to use an IDE (integrated development environment; essentially just user-friendly software for development) like Netbeans or Eclipse.

  • Install and set-up an IDE. Here is the latest version of Eclipse.
  • Create a project in your IDE and put your Java files inside of the project folder.
  • Select the project in the IDE and export the project as a JAR. Double check that the appropriate java files are selected when exporting.

You can always do this all very easily with the command line. Make sure that you are in the same directory as the files targeted before executing a command such as this:

javac YourApp.java
jar -cf YourJar.jar YourApp.class

...changing "YourApp" and "YourJar" to the proper names of your files, respectively.

How to disable Home and other system buttons in Android?

Refreshing an old topic. I was able to achieve that my activity does not fold when the home button (physical or virtual) is pressed. Here is my code for activity onCreate() method:

super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alarm_screen);
        context = getApplicationContext();
        int windowType;
        if (Build.VERSION.SDK_INT>=26) windowType = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        else windowType = WindowManager.LayoutParams.TYPE_TOAST;
        final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
                windowType,
                WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                        | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_FULLSCREEN,
                PixelFormat.TRANSLUCENT
        );
        wm = (WindowManager) getApplicationContext()
                .getSystemService(Context.WINDOW_SERVICE);

        mTopView = (ViewGroup) getLayoutInflater().inflate(R.layout.activity_alarm_screen, null);
        getWindow().setAttributes(params);
        //Set up your views here
        testView = mTopView.findViewById(R.id.test);
        wm.addView(mTopView, params);

On API 26 and abovem you need to get screen overlay permission from the user. Tested on Android 7 and 8.

How to set the env variable for PHP?

It depends on your OS, but if you are on Windows XP, you need to go to Systems Properties, then Advanced, then Environment Variables, and include the php binary path to the %PATH% variable.

Locate it by browsing your WAMP directory. It's called php.exe

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

Modifying location.hash without page scrolling

Adding this here because the more relevant questions have all been marked as duplicates pointing here…

My situation is simpler:

  • user clicks the link (a[href='#something'])
  • click handler does: e.preventDefault()
  • smoothscroll function: $("html,body").stop(true,true).animate({ "scrollTop": linkoffset.top }, scrollspeed, "swing" );
  • then window.location = link;

This way, the scroll occurs, and there's no jump when the location is updated.

Permission denied when launch python script via bash

Do “chmod +x script”

Now try executing

What's the difference between an Angular component and module

Angular Component

A component is one of the basic building blocks of an Angular app. An app can have more than one component. In a normal app, a component contains an HTML view page class file, a class file that controls the behaviour of the HTML page and the CSS/scss file to style your HTML view. A component can be created using @Component decorator that is part of @angular/core module.

import { Component } from '@angular/core';

and to create a component

@Component({selector: 'greet', template: 'Hello {{name}}!'})
class Greet {
  name: string = 'World';
}

To create a component or angular app here is the tutorial

Angular Module

An angular module is set of angular basic building blocks like component, directives, services etc. An app can have more than one module.

A module can be created using @NgModule decorator.

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

Error Handler - Exit Sub vs. End Sub

Your ProcExit label is your place where you release all the resources whether an error happened or not. For instance:

Public Sub SubA()
  On Error Goto ProcError

  Connection.Open
  Open File for Writing
  SomePreciousResource.GrabIt

ProcExit:  
  Connection.Close
  Connection = Nothing
  Close File
  SomePreciousResource.Release

  Exit Sub

ProcError:  
  MsgBox Err.Description  
  Resume ProcExit
End Sub

Is there a good jQuery Drag-and-drop file upload plugin?

http://blueimp.github.com/jQuery-File-Upload/ = great solution

According to their docs, the following browsers support drag & drop:

  • Firefox 4+
  • Safari 5+
  • Google Chrome
  • Microsoft Internet Explorer 10.0+

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

R memory management / cannot allocate vector of size n Mb

The simplest way to sidestep this limitation is to switch to 64 bit R.

Access a JavaScript variable from PHP

_GET accesses query string variables, test is not a querystring variable (PHP does not process the JS in any way). You need to rethink. You could make a php variable $test, and do something like:

<?php
$test = "tester";
?>
<script type="text/javascript" charset="utf-8">
    var test = "<?php echo $test?>";
</script>

<?php
    echo $test;
?>

Of course, I don't know why you want this, so I'm not sure the best solution.

EDIT: As others have noted, if the JavaScript variable is really generated on the client, you will need AJAX or a form to send it to the server.

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

What is the difference between Select and Project Operations

Project will effects Columns in the table while Select effects the Rows. on other hand Project is use to select the columns with specefic properties rather than Select the all of columns data

Difference between DataFrame, Dataset, and RDD in Spark

Because DataFrame is weakly typed and developers aren't getting the benefits of the type system. For example, lets say you want to read something from SQL and run some aggregation on it:

val people = sqlContext.read.parquet("...")
val department = sqlContext.read.parquet("...")

people.filter("age > 30")
  .join(department, people("deptId") === department("id"))
  .groupBy(department("name"), "gender")
  .agg(avg(people("salary")), max(people("age")))

When you say people("deptId"), you're not getting back an Int, or a Long, you're getting back a Column object which you need to operate on. In languages with a rich type systems such as Scala, you end up losing all the type safety which increases the number of run-time errors for things that could be discovered at compile time.

On the contrary, DataSet[T] is typed. when you do:

val people: People = val people = sqlContext.read.parquet("...").as[People]

You're actually getting back a People object, where deptId is an actual integral type and not a column type, thus taking advantage of the type system.

As of Spark 2.0, the DataFrame and DataSet APIs will be unified, where DataFrame will be a type alias for DataSet[Row].

Python read next()

next() does not work in your case because you first call readlines() which basically sets the file iterator to point to the end of file.

Since you are reading in all the lines anyway you can refer to the next line using an index:

filne = "in"
with open(filne, 'r+') as f:
    lines = f.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        print line
        if line[:5] == "anim ":
            ne = lines[i + 1] # you may want to check that i < len(lines)
            print ' ne ',ne,'\n'
            break

How to decode encrypted wordpress admin password?

just edit wp_user table with your phpmyadmin, and choose MD5 on Function field then input your new password, save it (go button). enter image description here

Android Layout Weight

It doesn't work because you are using fill_parent as the width. The weight is used to distribute the remaining empty space or take away space when the total sum is larger than the LinearLayout. Set your widths to 0dip instead and it will work.

Resizing an image in an HTML5 canvas

The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

This function downsample to half at a time until reaching the desired size:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )
           return;

        tmp.src = dst.src;
     }

  }
  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

Credits to this post

How do I get the HTML code of a web page in PHP?

You may want to check out the YQL libraries from Yahoo: http://developer.yahoo.com/yql

The task at hand is as simple as

select * from html where url = 'http://stackoverflow.com/questions/ask'

You can try this out in the console at: http://developer.yahoo.com/yql/console (requires login)

Also see Chris Heilmanns screencast for some nice ideas what more you can do: http://developer.yahoo.net/blogs/theater/archives/2009/04/screencast_collating_distributed_information.html

How to get response status code from jQuery.ajax?

I see the status field on the jqXhr object, here is a fiddle with it working:

http://jsfiddle.net/magicaj/55HQq/3/

$.ajax({
    //...        
    success: function(data, textStatus, xhr) {
        console.log(xhr.status);
    },
    complete: function(xhr, textStatus) {
        console.log(xhr.status);
    } 
});

python ignore certificate validation urllib2

According to @Enno Gröper 's post, I've tried the SSLContext constructor and it works well on my machine. code as below:

import ssl
ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
urllib2.urlopen("https://your-test-server.local", context=ctx)

if you need opener, just added this context like:

opener = urllib2.build_opener(urllib2.HTTPSHandler(context=ctx))

NOTE: all above test environment is python 2.7.12. I use PROTOCOL_SSLv23 here since the doc says so, other protocol might also works but depends on your machine and remote server, please check the doc for detail.

How do I determine scrollHeight?

Correct ways in jQuery are -

  • $('#test').prop('scrollHeight') OR
  • $('#test')[0].scrollHeight OR
  • $('#test').get(0).scrollHeight

How to make an inline element appear on new line, or block element not occupy the whole line?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.feature_wrapper span {
    float: left;
    clear: left;
    display:inline
}

EDIT: now browsers have better support you can make use of the do inline-block.

.feature_wrapper span {
    display:inline-block;
    *display:inline; *zoom:1;
}

Depending on the text-align this will appear as through its inline while also acting like a block element.

Homebrew refusing to link OpenSSL

export https_proxy=http://127.0.0.1:1087 http_proxy=http://127.0.0.1:1087 all_proxy=socks5://127.0.0.1:1080

works for me

and I think it can solve all the problems like Failed to connect to raw.githubusercontent.com port 443: Connection refused

Property 'map' does not exist on type 'Observable<Response>'

In the latest Angular 7.*.*, you can try this simply as:

import { Observable, of } from "rxjs";
import { map, catchError } from "rxjs/operators";

And then you can use these methods as follows:

   private getHtml(): Observable<any> {
    return this.http.get("../../assets/test-data/preview.html").pipe(
      map((res: any) => res.json()),
      catchError(<T>(error: any, result?: T) => {
        console.log(error);
        return of(result as T);
      })
    );
  }

Check this demo for more details.

How to dynamically add a class to manual class names?

const ClassToggleFC= () =>{
  
  const [isClass, setClass] = useState(false);

  const toggle =() => {
       setClass( prevState => !prevState)
  }
  
  return(
      <>
        <h1 className={ isClass ? "heading" : ""}> Hiii There </h1>
       <button onClick={toggle}>Toggle</button>
      </>
   )

}

I simply created a Function Component. Inside I take a state and set initial value is false..

I have a button for toggling state..

Whenever we change state rerender component and if state value (isClass) is false h1's className should be "" and if state value (isClass) is true h1's className is "heading"

Pythonic way to check if a list is sorted or not

A solution using assignment expressions (added in Python 3.8):

def is_sorted(seq):
    seq_iter = iter(seq)
    cur = next(seq_iter, None)
    return all((prev := cur) <= (cur := nxt) for nxt in seq_iter)

z = list(range(10))
print(z)
print(is_sorted(z))

import random
random.shuffle(z)
print(z)
print(is_sorted(z))

z = []
print(z)
print(is_sorted(z))

Gives:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
True
[1, 7, 5, 9, 4, 0, 8, 3, 2, 6]
False
[]
True

Column count doesn't match value count at row 1

You should also look at new triggers.

MySQL doesn't show the table name in the error, so you're really left in a lurch. Here's a working example:

use test;
create table blah (id int primary key AUTO_INCREMENT, data varchar(100));
create table audit_blah (audit_id int primary key AUTO_INCREMENT, action enum('INSERT','UPDATE','DELETE'), id int, data varchar(100) null);
insert into audit_blah(action, id, data) values ('INSERT', 1, 'a');
select * from blah;
select * from audit_blah;
truncate table audit_blah;

delimiter //
/* I've commented out "id" below, so the insert fails with an ambiguous error: */
create trigger ai_blah after insert on blah for each row 
begin 
  insert into audit_blah (action, /*id,*/ data) values ('INSERT', /*NEW.id,*/ NEW.data);
end;//

/* This insert is valid, but you'll get an exception from the trigger: */
insert into blah (data) values ('data1');

How do I position an image at the bottom of div?

< img style="vertical-align: bottom" src="blah.png" >

Works for me. Inside a parallax div as well.

Using ALTER to drop a column if it exists in MySQL

I just built a reusable procedure that can help making DROP COLUMN idempotent:

-- column_exists:

DROP FUNCTION IF EXISTS column_exists;

DELIMITER $$
CREATE FUNCTION column_exists(
  tname VARCHAR(64),
  cname VARCHAR(64)
)
  RETURNS BOOLEAN
  READS SQL DATA
  BEGIN
    RETURN 0 < (SELECT COUNT(*)
                FROM `INFORMATION_SCHEMA`.`COLUMNS`
                WHERE `TABLE_SCHEMA` = SCHEMA()
                      AND `TABLE_NAME` = tname
                      AND `COLUMN_NAME` = cname);
  END $$
DELIMITER ;

-- drop_column_if_exists:

DROP PROCEDURE IF EXISTS drop_column_if_exists;

DELIMITER $$
CREATE PROCEDURE drop_column_if_exists(
  tname VARCHAR(64),
  cname VARCHAR(64)
)
  BEGIN
    IF column_exists(tname, cname)
    THEN
      SET @drop_column_if_exists = CONCAT('ALTER TABLE `', tname, '` DROP COLUMN `', cname, '`');
      PREPARE drop_query FROM @drop_column_if_exists;
      EXECUTE drop_query;
    END IF;
  END $$
DELIMITER ;

Usage:

CALL drop_column_if_exists('my_table', 'my_column');

Example:

SELECT column_exists('my_table', 'my_column');       -- 1
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column');       -- 0
CALL drop_column_if_exists('my_table', 'my_column'); -- success
SELECT column_exists('my_table', 'my_column');       -- 0

Shortcut to open file in Vim

I recently fell in love with fuzzyfinder.vim ... :-)

:FuzzyFinderFile will let you open files by typing partial names or patterns.

Add and remove attribute with jquery

It's because you've removed the id which is how you're finding the element. This line of code is trying to add id="page_navigation1" to an element with the id named page_navigation1, but it doesn't exist (because you deleted the attribute):

$("#page_navigation1").attr("id","page_navigation1");

Demo: jsFiddle

If you want to add and remove a class that makes your <div> red use:

$( '#page_navigation1' ).addClass( 'red-class' );

And:

$( '#page_navigation1' ).removeClass( 'red-class' );

Where red-class is:

.red-class {
    background-color: red;
}

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

How to edit default dark theme for Visual Studio Code?

As others have stated, you'll need to override the editor.tokenColorCustomizations or the workbench.colorCustomizations setting in the settings.json file. Here you can choose a base theme, like Abyss, and only override the things you want to change. You can either override very few things like the function, string colors etc. very easily.

E.g. for workbench.colorCustomizations

"workbench.colorCustomizations": {
    "[Default Dark+]": {
        "editor.background": "#130e293f",
    }
}

E.g. for editor.tokenColorCustomizations:

"editor.tokenColorCustomizations": {
    "[Abyss]": {
        "functions": "#FF0000",
        "strings": "#FF0000"
    }
}
// Don't do this, looks horrible.

However, deep customisations like change the colour of the var keyword will require you to provide the override values under the textMateRules key.

E.g. below:

"editor.tokenColorCustomizations": {
    "[Abyss]": {
        "textMateRules": [
            {
                "scope": "keyword.operator",
                "settings": {
                    "foreground": "#FFFFFF"
                }
            },
            {
                "scope": "keyword.var",
                "settings": {
                    "foreground": "#2871bb",
                    "fontStyle": "bold"
                }
            }
        ]
    }
}

You can also override globally across themes:

"editor.tokenColorCustomizations": {
    "textMateRules": [
        {
            "scope": [
                //following will be in italics (=Pacifico)
                "comment",
                "entity.name.type.class", //class names
                "keyword", //import, export, return…
                //"support.class.builtin.js", //String, Number, Boolean…, this, super
                "storage.modifier", //static keyword
                "storage.type.class.js", //class keyword
                "storage.type.function.js", // function keyword
                "storage.type.js", // Variable declarations
                "keyword.control.import.js", // Imports
                "keyword.control.from.js", // From-Keyword
                //"entity.name.type.js", // new … Expression
                "keyword.control.flow.js", // await
                "keyword.control.conditional.js", // if
                "keyword.control.loop.js", // for
                "keyword.operator.new.js", // new
            ],
            "settings": {
                "fontStyle": "italic"
            }
        }
    ]
}

More details here: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide

Pycharm does not show plot

I was facing above error when i am trying to plot histogram and below points worked for me.

OS : Mac Catalina 10.15.5

Pycharm Version : Community version 2019.2.3

Python version : 3.7

  1. I changed import statement as below (from - to)

from :

import matplotlib.pylab as plt

to:

import matplotlib.pyplot as plt

  1. and plot statement to below (changed my command form pyplot to plt)

from:

plt.pyplot.hist(df["horsepower"])

# set x/y labels and plot title
plt.pyplot.xlabel("horsepower")
plt.pyplot.ylabel("count")
plt.pyplot.title("horsepower bins") 

to :

plt.hist(df["horsepower"])

# set x/y labels and plot title
plt.xlabel("horsepower")
plt.ylabel("count")
plt.title("horsepower bins")
  1. use plt.show to display histogram

plt.show()

Fastest way to update 120 Million records

What I'd try first is
to drop all constraints, indexes, triggers and full text indexes first before you update.

If above wasn't performant enough, my next move would be
to create a CSV file with 12 million records and bulk import it using bcp.

Lastly, I'd create a new heap table (meaning table with no primary key) with no indexes on a different filegroup, populate it with -1. Partition the old table, and add the new partition using "switch".

What does the "yield" keyword do?

There is another yield use and meaning (since Python 3.3):

yield from <expr>

From PEP 380 -- Syntax for Delegating to a Subgenerator:

A syntax is proposed for a generator to delegate part of its operations to another generator. This allows a section of code containing 'yield' to be factored out and placed in another generator. Additionally, the subgenerator is allowed to return with a value, and the value is made available to the delegating generator.

The new syntax also opens up some opportunities for optimisation when one generator re-yields values produced by another.

Moreover this will introduce (since Python 3.5):

async def new_coroutine(data):
   ...
   await blocking_action()

to avoid coroutines being confused with a regular generator (today yield is used in both).

How to print out all the elements of a List in Java?

The objects in the list must have toString implemented for them to print something meaningful to screen.

Here's a quick test to see the differences:

public class Test {

    public class T1 {
        public Integer x;
    }

    public class T2 {
        public Integer x;

        @Override
        public String toString() {
            return x.toString();
        }
    }

    public void run() {
        T1 t1 = new T1();
        t1.x = 5;
        System.out.println(t1);

        T2 t2 = new T2();
        t2.x = 5;
        System.out.println(t2);

    }

    public static void main(String[] args) {        
        new Test().run();
    }
}

And when this executes, the results printed to screen are:

t1 = Test$T1@19821f
t2 = 5

Since T1 does not override the toString method, its instance t1 prints out as something that isn't very useful. On the other hand, T2 overrides toString, so we control what it prints when it is used in I/O, and we see something a little better on screen.

Difference between Visual Basic 6.0 and VBA

VB is not a language. VB is a program that hosts VBA, just as Office hosts VBA. VB is a set of App objects, just like Word and Excel have, and a forms package, just like in Office.

So you can only write VBA code in VB.

PS this info is on the INFO tab on the VB question page for VB.

From VBA Info

VBA 6, was shipped in 1998 and includes a myriad of licensed hosts, among them: Office 2000 - 2010, AutoCAD, PI Processbook, and the stand-alone Visual Basic 6.0

Add an element to an array in Swift

You could use

Myarray.insert("Data #\(index)", atIndex: index)

Check if a temporary table exists and delete if it exists before creating a temporary table

pmac72 is using GO to break down the query into batches and using an ALTER.

You appear to be running the same batch but running it twice after changing it: DROP... CREATE... edit... DROP... CREATE..

Perhaps post your exact code so we can see what is going on.

Hibernate show real SQL

Can I see (...) the real SQL

If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).

Alternatively you can enable logging of the following categories (using a log4j.properties file here):

log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE

The first is equivalent to hibernate.show_sql=true, the second prints the bound parameters among other things.

Reference

How to display with n decimal places in Matlab

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

How to render a DateTime object in a Twig template

you can render in following way

{{ post.published_at|date("m/d/Y") }}

For more details can visit http://twig.sensiolabs.org/doc/filters/date.html

Using Mockito to test abstract classes

The following suggestion let's you test abstract classes without creating a "real" subclass - the Mock is the subclass.

use Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS), then mock any abstract methods that are invoked.

Example:

public abstract class My {
  public Result methodUnderTest() { ... }
  protected abstract void methodIDontCareAbout();
}

public class MyTest {
    @Test
    public void shouldFailOnNullIdentifiers() {
        My my = Mockito.mock(My.class, Mockito.CALLS_REAL_METHODS);
        Assert.assertSomething(my.methodUnderTest());
    }
}

Note: The beauty of this solution is that you do not have to implement the abstract methods, as long as they are never invoked.

In my honest opinion, this is neater than using a spy, since a spy requires an instance, which means you have to create an instantiatable subclass of your abstract class.

Run Java Code Online

there is also http://ideone.com/ (supports many languages)

How to read GET data from a URL using JavaScript?

You can do like this

function parseURLParams(url) {
        var queryStart = url.indexOf("?") + 1,
            queryEnd   = url.indexOf("#") + 1 || url.length + 1,
            query = url.slice(queryStart, queryEnd - 1),
            pairs = query.replace(/\+/g, " ").split("&"),
            parms = {}, i, n, v, nv;

        if (query === url || query === "") return;

        for (i = 0; i < pairs.length; i++) {
            nv = pairs[i].split("=", 2);
            n = decodeURIComponent(nv[0]);
            v = decodeURIComponent(nv[1]);

            if (!parms.hasOwnProperty(n)) parms[n] = [];
            parms[n].push(nv.length === 2 ? v : null);
        }
        return parms;
    }

    //enter code here


    var urlString = "http://www.examle.com/bar?a=a+a&b%20b=b&c=1&c=2&d#hash";

    urlParams = parseURLParams(urlString);
    console.log(urlParams)

Git pull a certain branch from GitHub

for pulling the branch from GitHub you can use

git checkout --track origin/the-branch-name

Make sure that the branch name is exactly the same.

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

Changing element style attribute dynamically using JavaScript

I would recommend using a function, which accepts the element id and an object containing the CSS properties, to handle this. This way you write multiple styles at once and use standard CSS property syntax.

//function to handle multiple styles
function setStyle(elId, propertyObject) {
    var el = document.getElementById(elId);
    for (var property in propertyObject) {
        el.style[property] = propertyObject[property];
    }
}

setStyle('xyz', {'padding-top': '10px'});

Better still you could store the styles in a variable, which will make for much easier property management e.g.

var xyzStyles = {'padding-top':'10px'}
setStyle('xyz', xyzStyles);

Hope that helps

How to generate a random number between a and b in Ruby?

Just note the difference between the range operators:

3..10  # includes 10
3...10 # doesn't include 10

Array definition in XML?

The second way isn't valid XML; did you mean <numbers>[3,2,1]</numbers>?

If so, then the first one is preferred because all you need to get the array elements is some XML manipulation. On the second one you first need to get the value of the <numbers> element via XML manipulation, then somehow parse the [3,2,1] text using something else.

Or if you really want some compact format, you can consider using JSON (which "natively" supports arrays). But that depends on your application requirements.

jQuery UI Slider (setting programmatically)

Finally below works for me

$("#priceSlider").slider('option',{min: 5, max: 20,value:[6,19]}); $("#priceSlider").slider("refresh");

How to avoid soft keyboard pushing up my layout?

To solve this simply add android:windowSoftInputMode="stateVisible|adjustPan to that activity in android manifest file. for example

<activity 
    android:name="com.comapny.applicationname.activityname"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="stateVisible|adjustPan"/>

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

Setting the User-Agent header for a WebClient request

This worked for me:

var message = new HttpRequestMessage(method, url);
message.Headers.TryAddWithoutValidation("user-agent", "<user agent header value>");
var client = new HttpClient();
var response = await client.SendAsync(message);

Here you can find the documentation for TryAddWithoutValidation

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

how to include glyphicons in bootstrap 3

I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

Bootstrap requires a specific file structure to work. I see from your code you have this:

<link href="bootstrap.css" rel="stylesheet" media="screen">

Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

But first, let me recommend you setup your folder structure like so:

/css      <-- Bootstrap.css here
/fonts    <-- Bootstrap fonts here
/img
/js       <-- Bootstrap JavaScript here
index.html

If you notice, this is also how Bootstrap structures its files in its download ZIP.

You then include your Bootstrap file like so:

<link href="css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="./css/bootstrap.css" rel="stylesheet" media="screen">
or
<link href="/css/bootstrap.css" rel="stylesheet" media="screen">

Depending on your server structure or what you're going for.

The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

So, why do this?

Bootstrap.css has this specific line for Glyphfonts:

@font-face {
    font-family: 'Glyphicons Halflings';
    src: url('../fonts/glyphicons-halflings-regular.eot');
    src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}

What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

/fonts
Bootstrap.css
index.html

The CSS file is going one level deeper than looking for a /fonts folder.

So, let's say the actual location of these files are:

C:\www\fonts
C:\www\Boostrap.css
C:\www\index.html

The CSS file would technically be looking for a folder at:

C:\fonts

but your folder is actually in:

C:\www\fonts

So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

When you get that fixed, your HTML should simply be:

<span class="glyphicon glyphicon-comment"></span>

Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

How to create a .jar file or export JAR in IntelliJ IDEA (like Eclipse Java archive export)?

You didn't specify your IDEA version. Before 9.0 use Build | Build Jars, in IDEA 9.0 use Project Structure | Artifacts.

Monitor network activity in Android Phones

TCPDUMP is one of my favourite tools for analyzing network, but if you find difficult to cross-compile tcpdump for android, I'd recomend you to use some applications from the market.

These are the applications I was talking about:

  • Shark: Is small version of wireshark for Android phones). This program will create a *.pcap and you can read the file on PC with wireshark.
  • Shark Reader : This program allows you to read the *.pcap directly in your Android phone.

Shark app works with rooted devices, so if you want to install it, be sure that you have your device already rooted.

Good luck ;)

Javascript search inside a JSON object

Use PaulGuo's jSQL, a SQL like database using javascript. For example:

var db = new jSQL();
db.create('dbname', testListData).use('dbname');
var data = db.select('*').where(function(o) {
    return o.name == 'Jacking';
}).listAll();

DateTime fields from SQL Server display incorrectly in Excel

Try the following: Paste "2004-06-01 00:00:00.000" into Excel.

Now try paste "2004-06-01 00:00:00" into Excel.

Excel doesn't seem to be able to handle milliseconds when pasting...

select the TOP N rows from a table

you can also check this link

SELECT * FROM master_question WHERE 1 ORDER BY question_id ASC LIMIT 20

for more detail click here

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

Assigning the return value of new by reference is deprecated

just remove new in the $obj_md =& new MDB2();

How to do a HTTP HEAD request from the windows command line?

I'd download PuTTY and run a telnet session on port 80 to the webserver you want

HEAD /resource HTTP/1.1
Host: www.example.com

You could alternatively download Perl and try LWP's HEAD command. Or write your own script.

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

How to compare two maps by their values

All of these are returning equals. They arent actually doing a comparison, which is useful for sort. This will behave more like a comparator:

private static final Comparator stringFallbackComparator = new Comparator() {
    public int compare(Object o1, Object o2) {
        if (!(o1 instanceof Comparable))
            o1 = o1.toString();
        if (!(o2 instanceof Comparable))
            o2 = o2.toString();
        return ((Comparable)o1).compareTo(o2);
    }
};

public int compare(Map m1, Map m2) {
    TreeSet s1 = new TreeSet(stringFallbackComparator); s1.addAll(m1.keySet());
    TreeSet s2 = new TreeSet(stringFallbackComparator); s2.addAll(m2.keySet());
    Iterator i1 = s1.iterator();
    Iterator i2 = s2.iterator();
    int i;
    while (i1.hasNext() && i2.hasNext())
    {
        Object k1 = i1.next();
        Object k2 = i2.next();
        if (0!=(i=stringFallbackComparator.compare(k1, k2)))
            return i;
        if (0!=(i=stringFallbackComparator.compare(m1.get(k1), m2.get(k2))))
            return i;
    }
    if (i1.hasNext())
        return 1;
    if (i2.hasNext())
        return -1;
    return 0;
}

How to generate random number in Bash?

Maybe I am a bit too late, but what about using jot to generate a random number within a range in Bash?

jot -r -p 3 1 0 1

This generates a random (-r) number with 3 decimal places precision (-p). In this particular case, you'll get one number between 0 and 1 (1 0 1). You can also print sequential data. The source of the random number, according to the manual, is:

Random numbers are obtained through arc4random(3) when no seed is specified, and through random(3) when a seed is given.

Return value in SQL Server stored procedure

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
DECLARE @AA INT
SET @AA=(SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress)

IF @AA> 0
    BEGIN
        SET @UserId = 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

How to use auto-layout to move other views when a view is hidden?

It is possible, but you'll have to do a little extra work. There are a couple conceptual things to get out of the way first:

  • Hidden views, even though they don't draw, still participate in Auto Layout and usually retain their frames, leaving other related views in their places.
  • When removing a view from its superview, all related constraints are also removed from that view hierarchy.

In your case, this likely means:

  • If you set your left view to be hidden, the labels stay in place, since that left view is still taking up space (even though it's not visible).
  • If you remove your left view, your labels will probably be left ambiguously constrained, since you no longer have constraints for your labels' left edges.

What you need to do is judiciously over-constrain your labels. Leave your existing constraints (10pts space to the other view) alone, but add another constraint: make your labels' left edges 10pts away from their superview's left edge with a non-required priority (the default high priority will probably work well).

Then, when you want them to move left, remove the left view altogether. The mandatory 10pt constraint to the left view will disappear along with the view it relates to, and you'll be left with just a high-priority constraint that the labels be 10pts away from their superview. On the next layout pass, this should cause them to expand left until they fill the width of the superview but for your spacing around the edges.

One important caveat: if you ever want your left view back in the picture, not only do you have to add it back into the view hierarchy, but you also have to reestablish all its constraints at the same time. This means you need a way to put your 10pt spacing constraint between the view and its labels back whenever that view is shown again.

Fetch: reject promise and catch the error if status is not OK?

Thanks for the help everyone, rejecting the promise in .catch() solved my issue:

export function fetchVehicle(id) {
    return dispatch => {
        return dispatch({
            type: 'FETCH_VEHICLE',
            payload: fetch(`http://swapi.co/api/vehicles/${id}/`)
                .then(status)
                .then(res => res.json())    
                .catch(error => {
                    return Promise.reject()
                })
            });
    };
}


function status(res) {
    if (!res.ok) {
        throw new Error(res.statusText);
    }
    return res;
}

How should I tackle --secure-file-priv in MySQL?

I had this problem on windows 10. "--secure-file-priv in MySQL" To solve this I did the following.

  1. In windows search (bottom left) I typed "powershell".
  2. Right clicked on powershell and ran as admin.
  3. Navigated to the server bin file. (C:\Program Files\MySQL\MySQL Server 5.6\bin);
  4. Typed ./mysqld
  5. Hit "enter"

The server started up as expected.

How to refresh an IFrame using Javascript?

Got this from here

var f = document.getElementById('iframe1');
f.src = f.src;

SVN commit command

First add the new files:

svn add fileName

Then commit all new and modified files

svn ci <files_separated_by_space> -m "Commit message|ReviewID:XXXX"

If non source files are to be committed then

svn ci <files> -m "Commit msg|ReviewID:NON-SOURCE"

Best font for coding

Funny, I was just researching this yesterday!

I personally use Monaco 10 or 11 for the Mac, but a good cross platform font would have to be Droid Sans Mono: http://damieng.com/blog/2007/11/14/droid-sans-mono-great-coding-font Or DejaVu sans mono is another great one (goes under a lot of different names, will be Menlo on SNow leopard and is really just a repackaged Prima/Vera) check it out here: Prima/Vera... Check it out here: http://dejavu-fonts.org/wiki/index.php?title=Download

How do I properly compare strings in C?

Whenever you are trying to compare the strings, compare them with respect to each character. For this you can use built in string function called strcmp(input1,input2); and you should use the header file called #include<string.h>

Try this code:

#include<stdio.h> 
#include<stdlib.h> 
#include<string.h>  

int main() 
{ 
    char s[]="STACKOVERFLOW";
    char s1[200];
    printf("Enter the string to be checked\n");//enter the input string
    scanf("%s",s1);
    if(strcmp(s,s1)==0)//compare both the strings  
    {
        printf("Both the Strings match\n"); 
    } 
    else
    {
        printf("Entered String does not match\n");  
    } 
    system("pause");  
} 

How to parse a CSV in a Bash script?

First prototype using plain old grep and cut:

grep "${VALUE}" inputfile.csv | cut -d, -f"${INDEX}"

If that's fast enough and gives the proper output, you're done.

Interfaces vs. abstract classes

The advantages of an abstract class are:

  • Ability to specify default implementations of methods
  • Added invariant checking to functions
  • Have slightly more control in how the "interface" methods are called
  • Ability to provide behavior related or unrelated to the interface for "free"

Interfaces are merely data passing contracts and do not have these features. However, they are typically more flexible as a type can only be derived from one class, but can implement any number of interfaces.

Should I use <i> tag for icons instead of <span>?

I thought this looked pretty bad - because I was working on a Joomla template recently and I kept getting the template failing W3C because it was using the <i> tag and that had deprecated, as it's original use was to italicize something, which is now done through CSS not HTML any more.

It does make really bad practice because when I saw it I went through the template and changed all the <i> tags to <span style="font-style:italic"> instead and then wondered why the entire template looked strange.

This is the main reason it is a bad idea to use the <i> tag in this way - you never know who is going to look at your work afterwards and "assume" that what you were really trying to do is italicize the text rather than display an icon. I've just put some icons in a website and I did it with the following code

<img class="icon" src="electricity.jpg" alt="Electricity" title="Electricity">

that way I've got all my icons in one class so any changes I make affects all the icons (say I wanted them larger or smaller, or rounded borders, etc), the alt text gives screen readers the chance to tell the person what the icon is rather than possibly getting just "text in italics, end of italics" (I don't exactly know how screen readers read screens but I guess it's something like that), and the title also gives the user a chance to mouse over the image and get a tooltip telling them what the icon is in case they can't figure it out. Much better than using <i> - and also it passes W3C standard.

How can I find all *.js file in directory recursively in Linux?

Use find on the command line:

find /my/directory -name '*.js'

Illegal mix of collations MySQL Error

You should set both your table encoding and connection encoding to UTF-8:

ALTER TABLE keywords CHARACTER SET UTF8; -- run once

and

SET NAMES 'UTF8';
SET CHARACTER SET 'UTF8';

How to build a JSON array from mysql database

Is something like this what you want to do?

$return_arr = array();

$fetch = mysql_query("SELECT * FROM table"); 

while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
    $row_array['id'] = $row['id'];
    $row_array['col1'] = $row['col1'];
    $row_array['col2'] = $row['col2'];

    array_push($return_arr,$row_array);
}

echo json_encode($return_arr);

It returns a json string in this format:

[{"id":"1","col1":"col1_value","col2":"col2_value"},{"id":"2","col1":"col1_value","col2":"col2_value"}]

OR something like this:

$year = date('Y');
$month = date('m');

$json_array = array(

//Each array below must be pulled from database
    //1st record
    array(
    'id' => 111,
    'title' => "Event1",
    'start' => "$year-$month-10",
    'url' => "http://yahoo.com/"
),

     //2nd record
     array(
    'id' => 222,
    'title' => "Event2",
    'start' => "$year-$month-20",
    'end' => "$year-$month-22",
    'url' => "http://yahoo.com/"
)

);

echo json_encode($json_array);

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

HTTPS secures the transmission of the message over the network and provides some assurance to the client about the identity of the server. This is what's important to your bank or online stock broker. Their interest in authenticating the client is not in the identity of the computer, but in your identity. So card numbers, user names, passwords etc. are used to authenticate you. Some precautions are then usually taken to ensure that submissions haven't been tampered with, but on the whole whatever happens over in the session is regarded as having been initiated by you.

WS-Security offers confidentiality and integrity protection from the creation of the message to it's consumption. So instead of ensuring that the content of the communications can only be read by the right server it ensures that it can only be read by the right process on the server. Instead of assuming that all the communications in the securely initiated session are from the authenticated user each one has to be signed.

There's an amusing explanation involving naked motorcyclists here:

https://docs.microsoft.com/archive/blogs/vbertocci/end-to-end-security-or-why-you-shouldnt-drive-your-motorcycle-naked

So WS-Security offers more protection than HTTPS would, and SOAP offers a richer API than REST. My opinion is that unless you really need the additional features or protection you should skip the overhead of SOAP and WS-Security. I know it's a bit of a cop-out but the decisions about how much protection is actually justified (not just what would be cool to build) need to be made by those who know the problem intimately.

Check number of arguments passed to a Bash script

Check out this bash cheatsheet, it can help alot.

To check the length of arguments passed in, you use "$#"

To use the array of arguments passed in, you use "$@"

An example of checking the length, and iterating would be:

myFunc() {
  if [[ "$#" -gt 0 ]]; then
    for arg in "$@"; do
      echo $arg
    done
  fi
}

myFunc "$@"

This articled helped me, but was missing a few things for me and my situation. Hopefully this helps someone.

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Code Sign error: The identity 'iPhone Developer' doesn't match any valid certificate/private key pair in the default keychain

if your certificate is not valid, it will have a red "x" and state the reason why. Generally the reason is "This certificate has expired" or "This certificate was signed by an unknown authority.

to solve this you need to do the following step.

  1. If your certificate has expired, renew it at the iPhone Portal, download it, and double-click it to add it to your Keychain.
  2. If it's "signed by an unknown authority", download the "Apple Worldwide Developer Relations" certificate from the Certificates section of the iPhone Developer portal and double-click it to add it to your Keychain.
  3. If your certificate was revoked, delete the certificate from your Keychain, then follow the "Obtaining your iPhone Development Certificate" or "Obtaining your iPhone Distribution Certificate" section in the iPhone Developer Program Portal User Guide to generate a new certificate.
  4. Make sure you create a backup of your private key. The steps for doing this are described in the iPhone Developer Program Portal User Guide, under "Saving your Private Key and Transferring to other Systems".
  5. If you have the iPhone Developer (or iPhone Distribution) certificate and its associated private key, the Apple WWDR Intermediate certificate is installed, and your certificate is valid, confirm that Online Certificate Status Protocol (OCSP) and Certificate Revocation List (CRL) are set to "Off" in Keychain Access > Preferences > Certificates.
  6. if you still getting problem then contact support apple community.

Node.js: Gzip compression?

1- Install compression

npm install compression

2- Use it

var express     = require('express')
var compression = require('compression')

var app = express()
app.use(compression())

compression on Github

var.replace is not a function

You should probably do some validations before you actually execute your function :

function trim(str) {
    if(typeof str !== 'string') {
        throw new Error('only string parameter supported!');
    }

    return str.replace(/^\s+|\s+$/g,'');
}

How to place two forms on the same page?

Hope this will help you. Assumed that login form has: username and password inputs.

if(isset($_POST['username']) && trim($_POST['username']) != "" && isset($_POST['password']) && trim($_POST['password']) != ""){
//login
} else {
//register
}

Thymeleaf: Concatenation - Could not parse as expression

But from what I see you have quite a simple error in syntax

<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>

the correct syntax would look like

<p th:text="${bean.field + '!' + bean.field}">Static content</p>

As a matter of fact, the syntax th:text="'static part' + ${bean.field}" is equal to th:text="${'static part' + bean.field}".

Try it out. Even though this is probably kind of useless now after 6 months.

Using IF..ELSE in UPDATE (SQL server 2005 and/or ACCESS 2007)

Yes you can use CASE

UPDATE table 
SET columnB = CASE fieldA 
        WHEN columnA=1 THEN 'x' 
        WHEN columnA=2 THEN 'y' 
        ELSE 'z' 
      END 
WHERE columnC = 1

Reset textbox value in javascript

First, select the element. You can usually use the ID like this:

$("#searchField"); // select element by using "#someid"

Then, to set the value, use .val("something") as in:

$("#searchField").val("something"); // set the value

Note that you should only run this code when the element is available. The usual way to do this is:

$(document).ready(function() { // execute when everything is loaded
    $("#searchField").val("something"); // set the value
});

How to restart a node.js server

In this case you are restarting your node.js server often because it's in active development and you are making changes all the time. There is a great hot reload script that will handle this for you by watching all your .js files and restarting your node.js server if any of those files have changed. Just the ticket for rapid development and test.

The script and explanation on how to use it are at here at Draco Blue.

When to use throws in a Java method declaration?

This is not an answer, but a comment, but I could not write a comment with a formatted code, so here is the comment.

Lets say there is

public static void main(String[] args) {
  try {
    // do nothing or throw a RuntimeException
    throw new RuntimeException("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

The output is

test
Exception in thread "main" java.lang.RuntimeException: test
    at MyClass.main(MyClass.java:10)

That method does not declare any "throws" Exceptions, but throws them! The trick is that the thrown exceptions are RuntimeExceptions (unchecked) that are not needed to be declared on the method. It is a bit misleading for the reader of the method, since all she sees is a "throw e;" statement but no declaration of the throws exception

Now, if we have

public static void main(String[] args) throws Exception {
  try {
    throw new Exception("test");
  } catch (Exception e) {
    System.out.println(e.getMessage());
    throw e;
  }
}

We MUST declare the "throws" exceptions in the method otherwise we get a compiler error.

How can I clone a private GitLab repository?

It looks like there's not a straightforward solution for HTTPS-based cloning regarding GitLab. Therefore if you want a SSH-based cloning, you should take account these three forthcoming steps:

  • Create properly an SSH key using your email used to sign up. I would use the default filename to key for Windows. Don't forget to introduce a password!

    $ ssh-keygen -t rsa -C "[email protected]" -b 4096
    
    Generating public/private rsa key pair.
    Enter file in which to save the key ($PWD/.ssh/id_rsa): [\n]
    Enter passphrase (empty for no passphrase):[your password]
    Enter same passphrase again: [your password]
    Your identification has been saved in $PWD/.ssh/id_rsa.
    Your public key has been saved in $PWD/.ssh/id_rsa.pub.
    
  • Copy and paste all content from the recently id_rsa.pub generated into Setting>SSH keys>Key from your GitLab profile.

  • Get locally connected:

    $ ssh -i $PWD/.ssh/id_rsa [email protected]
    
    Enter passphrase for key "$PWD/.ssh/id_rsa": [your password]
    PTY allocation request failed on channel 0
    Welcome to GitLab, you!
    Connection to gitlab.com closed.
    

Finally, clone any private or internal GitLab repository!

$ git clone https://git.metabarcoding.org/obitools/ROBIBarcodes.git

Cloning into 'ROBIBarcodes'...
remote: Counting objects: 69, done.
remote: Compressing objects: 100% (65/65), done.
remote: Total 69 (delta 14), reused 0 (delta 0)
Unpacking objects: 100% (69/69), done.

How to get the top 10 values in postgresql?

For this you can use limit

select *
from scores
order by score desc
limit 10

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


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

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

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

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

SQL Fiddle

PHP using Gettext inside <<<EOF string

As far as I can see in the manual, it is not possible to call functions inside HEREDOC strings. A cumbersome way would be to prepare the words beforehand:

<?php

    $world = _("World");

    $str = <<<EOF
    <p>Hello</p>
    <p>$world</p>
EOF;
    echo $str;
?>

a workaround idea that comes to mind is building a class with a magic getter method.

You would declare a class like this:

class Translator
{
 public function __get($name) {
  return _($name); // Does the gettext lookup
  }
 }

Initialize an object of the class at some point:

  $translate = new Translator();

You can then use the following syntax to do a gettext lookup inside a HEREDOC block:

    $str = <<<EOF
    <p>Hello</p>
    <p>{$translate->World}</p>
EOF;
    echo $str;
?>

$translate->World will automatically be translated to the gettext lookup thanks to the magic getter method.

To use this method for words with spaces or special characters (e.g. a gettext entry named Hello World!!!!!!, you will have to use the following notation:

 $translate->{"Hello World!!!!!!"}

This is all untested but should work.

Update: As @mario found out, it is possible to call functions from HEREDOC strings after all. I think using getters like this is a sleek solution, but using a direct function call may be easier. See the comments on how to do this.

How to recompile with -fPIC

Have a look at this page.

you can try globally adding the flag using: export CXXFLAGS="$CXXFLAGS -fPIC"

Best practices for API versioning?

Versioning your REST API is analogous to the versioning of any other API. Minor changes can be done in place, major changes might require a whole new API. The easiest for you is to start from scratch every time, which is when putting the version in the URL makes most sense. If you want to make life easier for the client you try to maintain backwards compatibility, which you can do with deprecation (permanent redirect), resources in several versions etc. This is more fiddly and requires more effort. But it's also what REST encourages in "Cool URIs don't change".

In the end it's just like any other API design. Weigh effort against client convenience. Consider adopting semantic versioning for your API, which makes it clear for your clients how backwards compatible your new version is.

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]

Upgrade MySql driver to Connector/Python 8.0.17 or greater than 8.0.17, Those who are using greater than MySQL 5.5 version

Algorithm to randomly generate an aesthetically-pleasing color palette

I would use a color wheel and given a random position you could add the golden angle (137,5 degrees)

http://en.wikipedia.org/wiki/Golden_angle

in order to get different colours each time that do not overlap.

Adjusting the brightness for the color wheel you could get also different bright/dark color combinations.

I've found this blog post that explains really well the problem and the solution using the golden ratio.

http://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/

UPDATE: I've just found this other approach:

It's called RYB(red, yellow, blue) method and it's described in this paper:

http://threekings.tk/mirror/ryb_TR.pdf

as "Paint Inspired Color Compositing".

The algorithm generates the colors and each new color is chosen to maximize its euclidian distance to the previously selected ones.

Here you can find a a good implementation in javascript:

http://afriggeri.github.com/RYB/

UPDATE 2:

The Sciences Po Medialb have just released a tool called "I want Hue" that generate color palettes for data scientists. Using different color spaces and generating the palettes by using k-means clustering or force vectors ( repulsion graphs) The results from those methods are very good, they show the theory and an implementation in their web page.

http://tools.medialab.sciences-po.fr/iwanthue/index.php

What is the difference between active and passive FTP?

I recently run into this question in my work place so I think I should say something more here. I will use image to explain how the FTP works as an additional source for previous answer.

Active mode:

active mode


Passive mode:

enter image description here


In an active mode configuration, the server will attempt to connect to a random client-side port. So chances are, that port wouldn't be one of those predefined ports. As a result, an attempt to connect to it will be blocked by the firewall and no connection will be established.

enter image description here


A passive configuration will not have this problem since the client will be the one initiating the connection. Of course, it's possible for the server side to have a firewall too. However, since the server is expected to receive a greater number of connection requests compared to a client, then it would be but logical for the server admin to adapt to the situation and open up a selection of ports to satisfy passive mode configurations.

So it would be best for you to configure server to support passive mode FTP. However, passive mode would make your system vulnerable to attacks because clients are supposed to connect to random server ports. Thus, to support this mode, not only should your server have to have multiple ports available, your firewall should also allow connections to all those ports to pass through!

To mitigate the risks, a good solution would be to specify a range of ports on your server and then to allow only that range of ports on your firewall.

For more information, please read the official document.

Jquery Smooth Scroll To DIV - Using ID value from Link

You can do this:

$('.searchbychar').click(function () {
    var divID = '#' + this.id;
    $('html, body').animate({
        scrollTop: $(divID).offset().top
    }, 2000);
});

F.Y.I.

  • You need to prefix a class name with a . (dot) like in your first line of code.
  • $( 'searchbychar' ).click(function() {
  • Also, your code $('.searchbychar').attr('id') will return a string ID not a jQuery object. Hence, you can not apply .offset() method to it.

Extract the maximum value within each group in a dataframe

There are many possibilities to do this in R. Here are some of them:

df <- read.table(header = TRUE, text = 'Gene   Value
A      12
A      10
B      3
B      5
B      6
C      1
D      3
D      4')

# aggregate
aggregate(df$Value, by = list(df$Gene), max)
aggregate(Value ~ Gene, data = df, max)

# tapply
tapply(df$Value, df$Gene, max)

# split + lapply
lapply(split(df, df$Gene), function(y) max(y$Value))

# plyr
require(plyr)
ddply(df, .(Gene), summarise, Value = max(Value))

# dplyr
require(dplyr)
df %>% group_by(Gene) %>% summarise(Value = max(Value))

# data.table
require(data.table)
dt <- data.table(df)
dt[ , max(Value), by = Gene]

# doBy
require(doBy)
summaryBy(Value~Gene, data = df, FUN = max)

# sqldf
require(sqldf)
sqldf("select Gene, max(Value) as Value from df group by Gene", drv = 'SQLite')

# ave
df[as.logical(ave(df$Value, df$Gene, FUN = function(x) x == max(x))),]

Apply function to each element of a list

Or, alternatively, you can take a list comprehension approach:

>>> mylis = ['this is test', 'another test']
>>> [item.upper() for item in mylis]
['THIS IS TEST', 'ANOTHER TEST']

Read data from a text file using Java

Simple code for reading file in JAVA:

import java.io.*;

class ReadData
{
    public static void main(String args[])
    {
        FileReader fr = new FileReader(new File("<put your file path here>"));
        while(true)
        {
            int n=fr.read();
            if(n>-1)
            {
                char ch=(char)fr.read();
                System.out.print(ch);
            }
        }
    }
}

How can I select rows with most recent timestamp for each key value?

There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM (
    SELECT sensorID,timestamp,sensorField1,sensorField2
        , ROW_NUMBER() OVER(
            PARTITION BY sensorID
            ORDER BY timestamp
        ) AS rn
    FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;

I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.

count number of characters in nvarchar column

Use the LEN function:

Returns the number of characters of the specified string expression, excluding trailing blanks.

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Comma separated results in SQL

For Sql Server 2017 and later you can use the new STRING_AGG function

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.

SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv 
FROM Person.Person;

Here is the result set.

John,N/A,Mike,Peter,N/A,N/A,Alice,Bob

Perhaps a more common use case is to group together and then aggregate, just like you would with SUM, COUNT or AVG.

SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags 
FROM dbo.Article AS a       
LEFT JOIN dbo.ArticleTag AS t 
    ON a.ArticleId = t.ArticleId 
GROUP BY a.articleId, title;

Drop all duplicate rows across multiple columns in Python Pandas

If you want result to be stored in another dataset:

df.drop_duplicates(keep=False)

or

df.drop_duplicates(keep=False, inplace=False)

If same dataset needs to be updated:

df.drop_duplicates(keep=False, inplace=True)

Above examples will remove all duplicates and keep one, similar to DISTINCT * in SQL

Cannot ping AWS EC2 instance

If you setup the rules as "Custom ICMP" rule and "echo reply" with anywhere it will work like a champ. The "echo request" is the wrong rule for answering pings.

How to print instances of a class using print()?

A prettier version of response by @user394430

class Element:
    def __init__(self, name, symbol, number):
        self.name = name
        self.symbol = symbol
        self.number = number

    def __str__(self):
        return  str(self.__class__) + '\n'+ '\n'.join(('{} = {}'.format(item, self.__dict__[item]) for item in self.__dict__))

elem = Element('my_name', 'some_symbol', 3)
print(elem)

Produces visually nice list of the names and values.

<class '__main__.Element'>
name = my_name
symbol = some_symbol
number = 3

An even fancier version (thanks Ruud) sorts the items:

def __str__(self):
    return  str(self.__class__) + '\n' + '\n'.join((str(item) + ' = ' + str(self.__dict__[item]) for item in sorted(self.__dict__)))

How do I create a WPF Rounded Corner container?

I just had to do this myself, so I thought I would post another answer here.

Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.

The xaml:

<Border
    Width="200"
    Height="25"
    CornerRadius="11"
    Background="#FF919194"
>
    <Border.Clip>
        <RectangleGeometry
            RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
            RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
        >
            <RectangleGeometry.Rect>
                <MultiBinding
                    Converter="{StaticResource widthAndHeightToRectConverter}"
                >
                    <Binding
                        Path="ActualWidth"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                    <Binding
                        Path="ActualHeight"
                        RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
                    />
                </MultiBinding>
            </RectangleGeometry.Rect>
        </RectangleGeometry>
    </Border.Clip>

    <Rectangle
        Width="100"
        Height="100"
        Fill="Blue"
        HorizontalAlignment="Left"
        VerticalAlignment="Center"
    />
</Border>

The code for the converter:

public class WidthAndHeightToRectConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        double width = (double)values[0];
        double height = (double)values[1];
        return new Rect(0, 0, width, height);
    }
    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

How to extract multiple JSON objects from one file?

So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.

The basic idea is to signal the reader to split on the carriage character "\n" (or "\r\n" for Windows). Python can do this with the file.readline() function.

import json
def json_reader(filename):
    with open(filename) as f:
        for line in f:
            yield json.loads(line)

However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.

def json_writer(file, json_objects):
    with open(file, "w") as f:
        for jsonobj in json_objects:
            jsonstr = json.dumps(jsonobj)
            f.write(jsonstr + "\n")

You could also do the same operation with file.writelines() and a list comprehension:

...
    json_strs = [json.dumps(j) + "\n" for j in json_objects]
    f.writelines(json_strs)
...

And if you wanted to append the data instead of writing a new file just change open(file, "w") to open(file, "a").

In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.

On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write

lst = list(json_reader(file))

Addressing localhost from a VirtualBox virtual machine

I found that 10.0.2.2:<port> works, but only if Promiscuous Mode is set correctly. After installing my VM, I went to Settings > Network > Adapter 1.

NAT is set by default, and the Promiscuous Mode dropdown is disabled. I switched from NAT to Bridged Adapter, which enabled the Promiscuous Mode dropdown, and then changed the value from "Deny" to "Allow VMs". I then switched back to NAT, which disabled Promiscuous Mode again, but retained the new value.

After only this change, I was able to launch my VM and see my host machines localhost:<port> on my VM at 10.0.2.2:<port>.

SQL Server add auto increment primary key to existing table

When we add and identity column in an existing table it will automatically populate no need to populate it manually.

PHP compare two arrays and get the matched values not the difference

I think the better answer for this questions is

array_diff() 

because it Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays.

Whereas

array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved.

Selenium WebDriver: I want to overwrite value in field instead of appending to it with sendKeys using Java

Use this one, it is trusted solution and works well for all browsers:

protected void clearInput(WebElement webElement) {
    // isIE() - just checks is it IE or not - use your own implementation
    if (isIE() && "file".equals(webElement.getAttribute("type"))) {
        // workaround
        // if IE and input's type is file - do not try to clear it.
        // If you send:
        // - empty string - it will find file by empty path
        // - backspace char - it will process like a non-visible char
        // In both cases it will throw a bug.
        // 
        // Just replace it with new value when it is need to.
    } else {
        // if you have no StringUtils in project, check value still empty yet
        while (!StringUtils.isEmpty(webElement.getAttribute("value"))) {
            // "\u0008" - is backspace char
            webElement.sendKeys("\u0008");
        }
    }
}

If input has type="file" - do not clear it for IE. It will try to find file by empty path and will throw a bug.

More details you could find on my blog

Get everything after the dash in a string in JavaScript

Everyone else has posted some perfectly reasonable answers. I took a different direction. Without using split, substring, or indexOf. Works great on i.e. and firefox. Probably works on Netscape too.

Just a loop and two ifs.

function getAfterDash(str) {
    var dashed = false;
    var result = "";
    for (var i = 0, len = str.length; i < len; i++) {
        if (dashed) {
            result = result + str[i];
        }
        if (str[i] === '-') {
            dashed = true;
        }
    }
    return result;
};

console.log(getAfterDash("adfjkl-o812347"));

My solution is performant and handles edge cases.


The point of the above code was to procrastinate work, please don't actually use it.

How to use XPath in Python?

PyXML works well.

You didn't say what platform you're using, however if you're on Ubuntu you can get it with sudo apt-get install python-xml. I'm sure other Linux distros have it as well.

If you're on a Mac, xpath is already installed but not immediately accessible. You can set PY_USE_XMLPLUS in your environment or do it the Python way before you import xml.xpath:

if sys.platform.startswith('darwin'):
    os.environ['PY_USE_XMLPLUS'] = '1'

In the worst case you may have to build it yourself. This package is no longer maintained but still builds fine and works with modern 2.x Pythons. Basic docs are here.

What is the difference between JVM, JDK, JRE & OpenJDK?

JVM is the Java Virtual Machine – it actually runs Java ByteCode.

JRE is the Java Runtime Environment – it contains a JVM, among other things, and is what you need to run a Java program.

JDK is the Java Development Kit – it is the JRE, but with javac (which is what you need to compile Java source code) and other programming tools added.

OpenJDK is a specific JDK implementation.

Wireshark localhost traffic capture

For Windows,

You cannot capture packets for Local Loopback in Wireshark however, you can use a very tiny but useful program called RawCap;

RawCap

Run RawCap on command prompt and select the Loopback Pseudo-Interface (127.0.0.1) then just write the name of the packet capture file (.pcap)

A simple demo is as below;

C:\Users\Levent\Desktop\rawcap>rawcap
Interfaces:
 0.     169.254.125.51  Local Area Connection* 12       Wireless80211
 1.     192.168.2.254   Wi-Fi   Wireless80211
 2.     169.254.214.165 Ethernet        Ethernet
 3.     192.168.56.1    VirtualBox Host-Only Network    Ethernet
 4.     127.0.0.1       Loopback Pseudo-Interface 1     Loopback
Select interface to sniff [default '0']: 4
Output path or filename [default 'dumpfile.pcap']: test.pcap
Sniffing IP : 127.0.0.1
File        : test.pcap
Packets     : 48^C

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

Debug message "Resource interpreted as other but transferred with MIME type application/javascript"

I don't think it is a bug, Try adding the MIME type to your .htaccess file For instance, put or add the following content to your .htaccess file (which should be in the same place of your .js or above folders)

#JavaScript
AddType application/x-javascript .js

This solved my tree "Resource interpreted as other but transfered ... " warnings. Everytime you have that kind of warning it means you don't have enough info in your .htaccess file.

BTW1: Since you are modifying .htaccess file, make sure you restart your server.

BTW2: I also could clear same warnings for GIF files in Safari 4 with this:

#GIF
AddType image/gif .gif

BTW3: For other file types: see w3schools list or htaccess-guide

Inheriting from a template class in c++

class Rectangle : public Area<int> {
};

Add placeholder text inside UITextView in Swift?

Swift 4, 4.2 and 5

[![@IBOutlet var detailTextView: UITextView!

override func viewDidLoad() {
        super.viewDidLoad()
        detailTextView.delegate = self
}

extension ContactUsViewController : UITextViewDelegate {

    public func textViewDidBeginEditing(_ textView: UITextView) {
        if textView.text == "Write your message here..." {
            detailTextView.text = ""
            detailTextView.textColor = UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.86)

        }
        textView.becomeFirstResponder()
    }

    public func textViewDidEndEditing(_ textView: UITextView) {

        if textView.text == "" {
            detailTextView.text = "Write your message here..."
            detailTextView.textColor = UIColor.init(red: 0/255, green: 0/255, blue: 0/255, alpha: 0.30)
        }
        textView.resignFirstResponder()
    }
[![}][1]][1]

Remove Select arrow on IE

In IE9, it is possible with purely a hack as advised by @Spudley. Since you've customized height and width of the div and select, you need to change div:before css to match yours.

In case if it is IE10 then using below css3 it is possible

select::-ms-expand {
    display: none;
}

However if you're interested in jQuery plugin, try Chosen.js or you can create your own in js.

Understanding slice notation

In Python 2.7

Slicing in Python

[a:b:c]

len = length of string, tuple or list

c -- default is +1. The sign of c indicates forward or backward, absolute value of c indicates steps. Default is forward with step size 1. Positive means forward, negative means backward.

a --  When c is positive or blank, default is 0. When c is negative, default is -1.

b --  When c is positive or blank, default is len. When c is negative, default is -(len+1).

Understanding index assignment is very important.

In forward direction, starts at 0 and ends at len-1

In backward direction, starts at -1 and ends at -len

When you say [a:b:c], you are saying depending on the sign of c (forward or backward), start at a and end at b (excluding element at bth index). Use the indexing rule above and remember you will only find elements in this range:

-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1

But this range continues in both directions infinitely:

...,-len -2 ,-len-1,-len, -len+1, -len+2, ..., 0, 1, 2,3,4 , len -1, len, len +1, len+2 , ....

For example:

             0    1    2   3    4   5   6   7   8   9   10   11
             a    s    t   r    i   n   g
    -9  -8  -7   -6   -5  -4   -3  -2  -1

If your choice of a, b, and c allows overlap with the range above as you traverse using rules for a,b,c above you will either get a list with elements (touched during traversal) or you will get an empty list.

One last thing: if a and b are equal, then also you get an empty list:

>>> l1
[2, 3, 4]

>>> l1[:]
[2, 3, 4]

>>> l1[::-1] # a default is -1 , b default is -(len+1)
[4, 3, 2]

>>> l1[:-4:-1] # a default is -1
[4, 3, 2]

>>> l1[:-3:-1] # a default is -1
[4, 3]

>>> l1[::] # c default is +1, so a default is 0, b default is len
[2, 3, 4]

>>> l1[::-1] # c is -1 , so a default is -1 and b default is -(len+1)
[4, 3, 2]


>>> l1[-100:-200:-1] # Interesting
[]

>>> l1[-1:-200:-1] # Interesting
[4, 3, 2]


>>> l1[-1:-1:1]
[]


>>> l1[-1:5:1] # Interesting
[4]


>>> l1[1:-7:1]
[]

>>> l1[1:-7:-1] # Interesting
[3, 2]

>>> l1[:-2:-2] # a default is -1, stop(b) at -2 , step(c) by 2 in reverse direction
[4]

Transpose list of lists

more_itertools.unzip() is easy to read, and it also works with generators.

import more_itertools
l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

or equivalently

import more_itertools
l = more_itertools.chunked(range(1,10), 3)
r = more_itertools.unzip(l) # a tuple of generators.
r = list(map(list, r))      # a list of lists

Angularjs ng-model doesn't work inside ng-if

Yes, ng-hide (or ng-show) directive won't create child scope.

Here is my practice:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular.min.js"></script>

<script>
    function main($scope) {
        $scope.testa = false;
        $scope.testb = false;
        $scope.testc = false;
        $scope.testd = false;
    }
</script>

<div ng-app >
    <div ng-controller="main">

        Test A: {{testa}}<br />
        Test B: {{testb}}<br />
        Test C: {{testc}}<br />
        Test D: {{testd}}<br />

        <div>
            testa (without ng-if): <input type="checkbox" ng-model="testa" />
        </div>
        <div ng-if="!testa">
            testb (with ng-if): <input type="checkbox" ng-model="$parent.testb" />
        </div>
        <div ng-show="!testa">
            testc (with ng-show): <input type="checkbox" ng-model="testc" />
        </div>
        <div ng-hide="testa">
            testd (with ng-hide): <input type="checkbox" ng-model="testd" />
        </div>

    </div>
</div>

http://jsfiddle.net/bn64Lrzu/

Running interactive commands in Paramiko

I'm not familiar with paramiko, but this may work:

ssh_stdin.write('input value')
ssh_stdin.flush()

For information on stdin:

http://docs.python.org/library/sys.html?highlight=stdin#sys.stdin

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

Ant is using wrong java version

By default the Ant will considered the JRE as the workspace JRE version. You need to change according to your required version by following the below.

In Eclipse:

  • Right click on your build.xml click "Run As", click on "External Tool Configurations..." Select tab JRE.

  • Select the JRE you are using.

  • Re-run the task, it should be fine now.

SQL Server Installation - What is the Installation Media Folder?

For the SQL Server 2017 (Developer Edition) installation, I did the following:

  1. Open SQL Server Installation Center
  2. Click on Installation
  3. Click on New SQL Server stand-alone installation or add features to an existing installation
  4. Browse to C:\SQLServer2017Media\Developer_ENU and click OK

C# - Making a Process.Start wait until the process has start-up

Are you sure the Start method returns before the child process starts? I was always under the impression that Start starts the child process synchronously.

If you want to wait until your child process finishes some sort of initialization then you need inter-process communication - see Interprocess communication for Windows in C# (.NET 2.0).

Move a view up only when the keyboard covers an input field

I use SwiftLint, which had a few issues with the formatting of the accepted answer. Specifically:

no space before the colon, no force casting, prefer UIEdgeInset(top: etc... instead of UIEdgeInsetMake.

so here are those updates for Swift 3

func registerForKeyboardNotifications() {
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func deregisterFromKeyboardNotifications() {
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWasShown(notification: NSNotification) {
    //Need to calculate keyboard exact size due to Apple suggestions
    scrollView?.isScrollEnabled = true
    var info = notification.userInfo!
    if let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)

        scrollView?.contentInset = contentInsets
        scrollView?.scrollIndicatorInsets = contentInsets

        var aRect: CGRect = self.view.frame
        aRect.size.height -= keyboardSize.height
        if let activeField = self.activeField {
            if !aRect.contains(activeField.frame.origin) {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }
}

func keyboardWillBeHidden(notification: NSNotification) {
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    if let keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size {
        let contentInsets: UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize.height, right: 0.0)
        scrollView?.contentInset = contentInsets
        scrollView?.scrollIndicatorInsets = contentInsets
    }

    view.endEditing(true)
    scrollView?.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField) {
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField) {
    activeField = nil
}

Foreign key constraints: When to use ON UPDATE and ON DELETE

Addition to @MarkR answer - one thing to note would be that many PHP frameworks with ORMs would not recognize or use advanced DB setup (foreign keys, cascading delete, unique constraints), and this may result in unexpected behaviour.

For example if you delete a record using ORM, and your DELETE CASCADE will delete records in related tables, ORM's attempt to delete these related records (often automatic) will result in error.

Why is processing a sorted array faster than processing an unsorted array?

Besides the fact that the branch prediction may slow you down, a sorted array has another advantage:

You can have a stop condition instead of just checking the value, this way you only loop over the relevant data, and ignore the rest.
The branch prediction will miss only once.

 // sort backwards (higher values first), may be in some other part of the code
 std::sort(data, data + arraySize, std::greater<int>());

 for (unsigned c = 0; c < arraySize; ++c) {
       if (data[c] < 128) {
              break;
       }
       sum += data[c];               
 }

Is there a way to get the source code from an APK file?

The simplest way is using Apk OneClick Decompiler. That is a tool package to decompile & disassemble APKs (android packages).

FEATURES

  • All features are integrated into the right-click menu of Windows.
  • Decompile APK classes to Java source codes.
  • Disassemble APK to smali code and decode its resources.
  • Install APK to phone by right-click.
  • Recompile APK after editing smali code and/or resources. During recompile:
  • Optimize png images
  • Sign apks
  • Zipalign

REQUIREMENTS

Java Runtime Environment (JRE) must be installed.

You can download it from this link Apk OneClick Decompiler

Enjoy that.

How do you set autocommit in an SQL Server session?

With SQLServer 2005 Express, what I found was that even with autocommit off, insertions into a Db table were committed without my actually issuing a commit command from the Management Studio session. The only difference was, when autocommit was off, I could roll back all the insertions; with *autocommit on, I could not.* Actually, I was wrong. With autocommit mode off, I see the changes only in the QA (Query Analyzer) window from which the commands were issued. If I popped a new QA (Query Analyzer) window, I do not see the changes made by the first window (session), i.e. they are NOT committed! I had to issue explicit commit or rollback commands to make changes visible to other sessions(QA windows) -- my bad! Things are working correctly.

how do I get the bullet points of a <ul> to center with the text?

ul {
  padding-left: 0;
  list-style-position: inside;
}

Explanation: The first property padding-left: 0 clears the default padding/spacing for the ul element while list-style-position: inside makes the dots/bullets of li aligned like a normal text.

So this code

<p>The ul element</p>
<ul>
asdfas
  <li>Coffee</li>
  <li>Tea</li>
  <li>Milk</li>
</ul>

without any CSS will give us this:
enter image description here
but if we add in the CSS give at the top, that will give us this:
enter image description here

Change the color of cells in one column when they don't match cells in another column

you could try this:

I have these two columns (column "A" and column "B"). I want to color them when the values between cells in the same row mismatch.

Follow these steps:

  1. Select the elements in column "A" (excluding A1);

  2. Click on "Conditional formatting -> New Rule -> Use a formula to determine which cells to format";

  3. Insert the following formula: =IF(A2<>B2;1;0);

  4. Select the format options and click "OK";

  5. Select the elements in column "B" (excluding B1) and repeat the steps from 2 to 4.

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

You don't have to, but some people like to explicitly initialize all variables (I do too). Especially those who program in a variety of languages, it's just easier to have the rule of always initializing your variables rather than deciding case-by-case/language-by-language.

For instance Java has default values for Boolean, int etc .. C on the other hand doesn't automatically give initial values, whatever happens to be in memory is what you end up with unless you assign a value explicitly yourself.

In your case above, as you discovered, the code works just as well without the initialization, esp since the variable is set in the next line which makes it appear particularly redundant. Sometimes you can combine both of those lines (declaration and initialization - as shown in some of the other posts) and get the best of both approaches, i.e., initialize the your variable with the result of the email1.equals (email2); operation.

What do the makefile symbols $@ and $< mean?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.
For example:

hello.o: hello.c hello.h
         gcc -c $< -o $@

Here, hello.o is the output file. This is what $@ expands to. The first dependency is hello.c. That's what $< expands to.

The -c flag generates the .o file; see man gcc for a more detailed explanation. The -o specifies the output file to create.

For further details, you can read this article about Linux Makefiles.

Also, you can check the GNU make manuals. It will make it easier to make Makefiles and to debug them.

If you run this command, it will output the makefile database:

make -p 

How to crop a CvMat in OpenCV?

I know this question is already solved.. but there is a very easy way to crop. you can just do it in one line-

Mat cropedImage = fullImage(Rect(X,Y,Width,Height));

How can I get javascript to read from a .json file?

Assuming you mean "file on a local filesystem" when you say .json file.

You'll need to save the json data formatted as jsonp, and use a file:// url to access it.

Your HTML will look like this:

<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
  function updateMe(){
    var x = 0;
    var activity=jsonstr;
    foreach (i in activity) {
        date = document.getElementById(i.date).innerHTML = activity.date;
        event = document.getElementById(i.event).innerHTML = activity.event;
    }
  }
</script>

And the file c:\data\activity.jsonp contains the following line:

jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];

Remove characters except digits from string using Python?

Use re.sub, like so:

>>> import re
>>> re.sub('\D', '', 'aas30dsa20')
'3020'

\D matches any non-digit character so, the code above, is essentially replacing every non-digit character for the empty string.

Or you can use filter, like so (in Python 2):

>>> filter(str.isdigit, 'aas30dsa20')
'3020'

Since in Python 3, filter returns an iterator instead of a list, you can use the following instead:

>>> ''.join(filter(str.isdigit, 'aas30dsa20'))
'3020'

How to set focus on an input field after rendering?

After trying a lot of options above with no success I've found that It was as I was disabling and then enabling the input which caused the focus to be lost.

I had a prop sendingAnswer which would disable the Input while I was polling the backend.

<Input
  autoFocus={question}
  placeholder={
    gettingQuestion ? 'Loading...' : 'Type your answer here...'
  }
  value={answer}
  onChange={event => dispatch(updateAnswer(event.target.value))}
  type="text"
  autocomplete="off"
  name="answer"
  // disabled={sendingAnswer} <-- Causing focus to be lost.
/>

Once I removed the disabled prop everything started working again.

Why do we use arrays instead of other data structures?

Not all programs do the same thing or run on the same hardware.

This is usually the answer why various language features exist. Arrays are a core computer science concept. Replacing arrays with lists/matrices/vectors/whatever advanced data structure would severely impact performance, and be downright impracticable in a number of systems. There are any number of cases where using one of these "advanced" data collection objects should be used because of the program in question.

In business programming (which most of us do), we can target hardware that is relatively powerful. Using a List in C# or Vector in Java is the right choice to make in these situations because these structures allow the developer to accomplish the goals faster, which in turn allows this type of software to be more featured.

When writing embedded software or an operating system an array may often be the better choice. While an array offers less functionality, it takes up less RAM, and the compiler can optimize code more efficiently for look-ups into arrays.

I am sure I am leaving out a number of the benefits for these cases, but I hope you get the point.

How add spaces between Slick carousel item

Just fix css:

/* the slides */
.slick-slider {
    overflow: hidden;
}
/* the parent */
.slick-list {
    margin: 0 -9px;
}
/* item */  
.item{
    padding: 0 9px;
}

jQuery datepicker years shown

Perfect for date of birth fields (and what I use) is similar to what Shog9 said, although I'm going to give a more specific DOB example:

$(".datePickerDOB").datepicker({ 
    yearRange: "-122:-18", //18 years or older up to 122yo (oldest person ever, can be sensibly set to something much smaller in most cases)
    maxDate: "-18Y", //Will only allow the selection of dates more than 18 years ago, useful if you need to restrict this
    minDate: "-122Y"
});

Hope future googlers find this useful :).

Copy rows from one Datatable to another DataTable?

I've created an easy way to do this issue

 DataTable newTable = oldtable.Clone();    
 for (int i = 0; i < oldtable.Rows.Count; i++)
 {
   DataRow drNew = newTable.NewRow();    
   drNew.ItemArray = oldtable.Rows[i].ItemArray;    
   newTable.Rows.Add(drNew);   
 } 

TypeScript function overloading

You can declare an overloaded function by declaring the function as having a type which has multiple invocation signatures:

interface IFoo
{
    bar: {
        (s: string): number;
        (n: number): string;
    }
}

Then the following:

var foo1: IFoo = ...;

var n: number = foo1.bar('baz');     // OK
var s: string = foo1.bar(123);       // OK
var a: number[] = foo1.bar([1,2,3]); // ERROR

The actual definition of the function must be singular and perform the appropriate dispatching internally on its arguments.

For example, using a class (which could implement IFoo, but doesn't have to):

class Foo
{
    public bar(s: string): number;
    public bar(n: number): string;
    public bar(arg: any): any 
    {
        if (typeof(arg) === 'number')
            return arg.toString();
        if (typeof(arg) === 'string')
            return arg.length;
    }
}

What's interesting here is that the any form is hidden by the more specifically typed overrides.

var foo2: new Foo();

var n: number = foo2.bar('baz');     // OK
var s: string = foo2.bar(123);       // OK
var a: number[] = foo2.bar([1,2,3]); // ERROR

Maximum number of records in a MySQL database table

In InnoDB, with a limit on table size of 64 terabytes and a MySQL row-size limit of 65,535 there can be 1,073,741,824 rows. That would be minimum number of records utilizing maximum row-size limit. However, more records can be added if the row size is smaller .

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Upload file to FTP using C#

This works for me,this method will SFTP a file to a location within your network. It uses SSH.NET.2013.4.7 library.One can just download it for free.

    //Secure FTP
    public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)

    {
        ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));

        var temp = destination.Split('/');
        string destinationFileName = temp[temp.Count() - 1];
        string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);


        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))
            {
                cmd.Execute();
            }
            sshclient.Disconnect();
        }


        using (var sftp = new SftpClient(ConnNfo))
        {
            sftp.Connect();
            sftp.ChangeDirectory(parentDirectory);
            using (var uplfileStream = System.IO.File.OpenRead(source))
            {
                sftp.UploadFile(uplfileStream, destinationFileName, true);
            }
            sftp.Disconnect();
        }
    }

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

I had a git conflict left in my workspace.xml i.e.

<<<<———————HEAD

which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
        here_is_another_long_identifier != and_finally_another_long_name):
    # ... your code here ...
    pass

Relative div height

Basically, the problem lies in block12. for the block1/2 to take up the total height of the block12, it must have a defined height. This stack overflow post explains that in really good detail.

So setting a defined height for block12 will allow you to set a proper height. I have created an example on JSfiddle that will show you the the blocks can be floated next to one another if the block12 div is set to a standard height through out the page.

Here is an example including a header and block3 div with some content in for examples.

#header{
   position:absolute;
   top:0;
   left:0;
   width:100%;
   height:20%;
    }

    #block12{
    position:absolute;
    top:20%;
    width:100%;
    left:0;
    height:40%;
    }
    #block1,#block2{
    float:left;
    overflow-y: scroll;
    text-align:center;
    color:red;
    width:50%;
    height:100%;

    }
 #clear{clear:both;}
 #block3{
    position:absolute;
    bottom:0;
    color:blue;
    height:40%;

    }

Java command not found on Linux

You can add one of the Java path to PATH variable using the following command.

export PATH=$PATH:/usr/java/jre1.6.0_24/bin/

You can add this line to .bashrc file in your home directory. Adding this to .bashrc will ensure everytime you open bash it will be PATH variable is updated.

How to fix "Headers already sent" error in PHP

Generally this error arise when we send header after echoing or printing. If this error arise on a specific page then make sure that page is not echoing anything before calling to start_session().

Example of Unpredictable Error:

 <?php //a white-space before <?php also send for output and arise error
session_start();
session_regenerate_id();

//your page content

One more example:

<?php
includes 'functions.php';
?> <!-- This new line will also arise error -->
<?php
session_start();
session_regenerate_id();

//your page content

Conclusion: Do not output any character before calling session_start() or header() functions not even a white-space or new-line

Get the latest date from grouped MySQL data

try this:

SELECT model, date
FROM doc
WHERE date = (SELECT MAX(date)
FROM doc GROUP BY model LIMIT 0, 1)
GROUP BY model

DynamoDB vs MongoDB NoSQL

I have worked on both and kind of fan of both.

But you need to understand when to use what and for what purpose.

I don't think It's a great idea to move all your database to DynamoDB, reason being querying is difficult except on primary and secondary keys, Indexing is limited and scanning in DynamoDB is painful.

I would go for a hybrid sort of DB, where extensive query-able data should be there is MongoDB, with all it's feature you would never feel constrained to provide enhancements or modifications.

DynamoDB is lightning fast (faster than MongoDB) so DynamoDB is often used as an alternative to sessions in scalable applications. DynamoDB best practices also suggests that if there are plenty of data which are less being used, move it to other table.

So suppose you have a articles or feeds. People are more likely to look for last week stuff or this month's stuff. chances are really rare for people to visit two year old data. For these purposes DynamoDB prefers to have data stored by month or years in different tables.

DynamoDB is seemlessly scalable, something you will have to do manually in MongoDB. however you would lose on performance of DynamoDB, if you don't understand about throughput partition and how scaling works behind the scene.

DynamoDB should be used where speed is critical, MongoDB on the other hand has too many hands and features, something DynamoDB lacks.

for example, you can have a replica set of MongoDB in such a way that one of the replica holds data instance of 8(or whatever) hours old. Really useful, if you messed up something big time in your DB and want to get the data as it is before.

That's my opinion though.

What is an NP-complete in computer science?

NP Problem :-

  1. NP problem are such problem that can be solved in non-deterministic polynomial time.
  2. Non deterministic algorithm operate in two stage.
  3. Non deterministic guessing stage && Non deterministic verification stage.

Type of Np Problem

  1. NP complete
  2. NP Hard

NP Complete problem :-

1 Decision Problem A is called NP complete if it has following two properties:-

  1. It belong to class NP.
  2. Every other problem in NP can be transformed to P in polynomial time.

Some Ex :-

  • Knapsack problem
  • sub set sum problem
  • Vertex covering problem

How to return a value from try, catch, and finally?

To return a value when using try/catch you can use a temporary variable, e.g.

public static double add(String[] values) {
    double sum = 0.0;
    try {
        int length = values.length;
        double arrayValues[] = new double[length];
        for(int i = 0; i < length; i++) {
            arrayValues[i] = Double.parseDouble(values[i]);
            sum += arrayValues[i];
        }
    } catch(NumberFormatException e) {
        e.printStackTrace();
    } catch(RangeException e) {
        throw e;
    } finally {
        System.out.println("Thank you for using the program!");
    }
    return sum;
}

Else you need to have a return in every execution path (try block or catch block) that has no throw.

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

Yarn: How to upgrade yarn version using terminal?

For macOS users, if you installed yarn via brew, you can upgrade it using the below command:

brew upgrade yarn

On Linux, just run the below command at the terminal:

$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash

On Windows, upgrade with Chocolatey

choco upgrade yarn

Credits: Added answers with the help of the below answers

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Get Client Machine Name in PHP

Not in PHP.
phpinfo(32) contains everything PHP able to know about particular client, and there is no [windows] computer name

How to Flatten a Multidimensional Array?

Flattens two dimensional arrays only:

$arr = [1, 2, [3, 4]];
$arr = array_reduce($arr, function ($a, $b) {
     return array_merge($a, (array) $b);
}, []);

// Result: [1, 2, 3, 4]

How to delete an element from an array in C#

Removing from an array itself is not simple, as you then have to deal with resizing. This is one of the great advantages of using something like a List<int> instead. It provides Remove/RemoveAt in 2.0, and lots of LINQ extensions for 3.0.

If you can, refactor to use a List<> or similar.

Extract first and last row of a dataframe in pandas

The accepted answer duplicates the first row if the frame only contains a single row. If that's a concern

df[0::len(df)-1 if len(df) > 1 else 1]

works even for single row-dataframes.

Example: For the following dataframe this will not create a duplicate:

df = pd.DataFrame({'a': [1], 'b':['a']})
df2 = df[0::len(df)-1 if len(df) > 1  else 1]

print df2

   a  b
0  1  a

whereas this does:

df3 = df.iloc[[0, -1]]

print df3 

   a  b
0  1  a
0  1  a

because the single row is the first AND last row at the same time.

What is a practical, real world example of the Linked List?

In operating systems ... one may use a linked list to keep track of what processes are running and what processes are sleeping ... a process that is running and wants to sleep ... gets removed from the LinkedList that keeps track of running processes and once the sleep time is over adds it back to the active process LinkedList

Maybe newer OS are using some funky data structures ... linked lists can be used there

Removing viewcontrollers from navigation stack

// removing the viewcontrollers by class names from stack and then dismissing the current view.

 self.navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
      if vc.isKind(of: ViewController.self) || vc.isKind(of: ViewController2.self) 
       {
        return true
        } 
     else 
        {
         return false
         }
        })
self.navigationController?.popViewController(animated: false)
self.dismiss(animated: true, completion: nil)

How to access the elements of a 2D array?

a[1][1] does work as expected. Do you mean a11 as the first element of the first row? Cause that would be a[0][0].

Updating .class file in jar

An alternative is not to replace the .class file in the jar file. Instead put it into a new jar file and ensure that it appears earlier on your classpath than the original jar file.

Not sure I would recommend this for production software but for development it is quick and easy.

Printing *s as triangles in Java?

This is the least complex program, which takes only 1 for loop to print the triangle. This works only for the center triangle, but small tweaking would make it work for other's as well -

import java.io.DataInputStream;

public class Triangle {
    public static void main(String a[]) throws Exception{
        DataInputStream in = new DataInputStream(System.in);

        int n = Integer.parseInt(in.readLine());
        String b = new String(new char[n]).replaceAll("\0", " ");
        String s = "*";
        for(int i=1; i<=n; i++){
            System.out.print(b);
            System.out.println(s);
            s += "**";
            b = b.substring(0, n-i);
            System.out.println();
        }
    }
}

AngularJS resource promise

/*link*/
$q.when(scope.regions).then(function(result) {
    console.log(result);
});
var Regions = $resource('mocks/regions.json');
$scope.regions = Regions.query().$promise.then(function(response) {
    return response;
});

Using HTTPS with REST in Java

Something to keep in mind is that this error isn't only due to self signed certs. The new Entrust CA certs fail with the same error, and the right thing to do is to update the server with the appropriate root certs, not to disable this important security feature.

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

List myArrayList  = Collections.synchronizedList(new ArrayList());

//add your elements  
 myArrayList.add();
 myArrayList.add();
 myArrayList.add();

synchronized(myArrayList) {
    Iterator i = myArrayList.iterator(); 
     while (i.hasNext()){
         Object  object = i.next();
     }
 }

What does -> mean in Python function definitions?

In the following code:

def f(x) -> int:
    return int(x)

the -> int just tells that f() returns an integer (but it doesn't force the function to return an integer). It is called a return annotation, and can be accessed as f.__annotations__['return'].

Python also supports parameter annotations:

def f(x: float) -> int:
    return int(x)

: float tells people who read the program (and some third-party libraries/programs, e. g. pylint) that x should be a float. It is accessed as f.__annotations__['x'], and doesn't have any meaning by itself. See the documentation for more information:

https://docs.python.org/3/reference/compound_stmts.html#function-definitions https://www.python.org/dev/peps/pep-3107/

jQuery: Get height of hidden element in jQuery

If you've already displayed the element on the page previously, you can simply take the height directly from the DOM element (reachable in jQuery with .get(0)), since it is set even when the element is hidden:

$('.hidden-element').get(0).height;

same for the width:

$('.hidden-element').get(0).width;

(thanks to Skeets O'Reilly for correction)

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You want to use URI templates. Look carefully at the README of this project: URLEncoder.encode() does NOT work for URIs.

Let us take your original URL:

http://site-test.test.com/Meetings/IC/DownloadDocument?meetingId=c21c905c-8359-4bd6-b864-844709e05754&itemId=a4b724d1-282e-4b36-9d16-d619a807ba67&file=\s604132shvw140\Test-Documents\c21c905c-8359-4bd6-b864-844709e05754_attachments\7e89c3cb-ce53-4a04-a9ee-1a584e157987\myDoc.pdf

and convert it to a URI template with two variables (on multiple lines for clarity):

http://site-test.test.com/Meetings/IC/DownloadDocument
    ?meetingId={meetingID}&itemId={itemID}&file={file}

Now let us build a variable map with these three variables using the library mentioned in the link:

final VariableMap = VariableMap.newBuilder()
    .addScalarValue("meetingID", "c21c905c-8359-4bd6-b864-844709e05754")
    .addScalarValue("itemID", "a4b724d1-282e-4b36-9d16-d619a807ba67e")
    .addScalarValue("file", "\\\\s604132shvw140\\Test-Documents"
        + "\\c21c905c-8359-4bd6-b864-844709e05754_attachments"
        + "\\7e89c3cb-ce53-4a04-a9ee-1a584e157987\\myDoc.pdf")
    .build();

final URITemplate template
    = new URITemplate("http://site-test.test.com/Meetings/IC/DownloadDocument"
        + "meetingId={meetingID}&itemId={itemID}&file={file}");

// Generate URL as a String
final String theURL = template.expand(vars);

This is GUARANTEED to return a fully functional URL!

Programmatically create a UIView with color gradient

I have implemented this in my code.

UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.view.frame.size.width, 31.0f)];
view1.backgroundColor = [UIColor clearColor];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view1.bounds;
UIColor *topColor = [UIColor colorWithRed:132.0/255.0 green:222.0/255.0 blue:109.0/255.0 alpha:1.0];
UIColor *bottomColor = [UIColor colorWithRed:31.0/255.0 green:150.0/255.0 blue:99.0/255.0 alpha:1.0];
gradient.colors = [NSArray arrayWithObjects:(id)[topColor CGColor], (id)[bottomColor CGColor], nil];


[view1.layer insertSublayer:gradient atIndex:0];

Now I can see a gradient on my view.

Loop over html table and get checked checkboxes (JQuery)

Use this instead:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked') //...
});

Let me explain you what the selector does: input[type="checkbox"] means that this will match each <input /> with type attribute type equals to checkbox After that: :checked will match all checked checkboxes.

You can loop over these checkboxes with:

$('#save').click(function () {
    $('#mytable').find('input[type="checkbox"]:checked').each(function () {
       //this is the current checkbox
    });
});

Here is demo in JSFiddle.


And here is a demo which solves exactly your problem http://jsfiddle.net/DuE8K/1/.

$('#save').click(function () {
    $('#mytable').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked') &&
            row.find('textarea').val().length <= 0) {
            alert('You must fill the text area!');
        }
    });
});

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

What does it mean when an HTTP request returns status code 0?

In addition to Lee's answer, you may find more information about the real cause by switching to synchronous requests, as you'll get also an exception :

function request(url) {
    var request = new XMLHttpRequest();
    try {
        request.open('GET', url, false);
        request.send(null);
    } catch (e) {
        console.log(url + ': ' + e);
    }
}

For example :

NetworkError: A network error occurred.

S3 - Access-Control-Allow-Origin Header

I fixed it writing the following:

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <MaxAgeSeconds>3000</MaxAgeSeconds>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

Why <AllowedHeader>*</AllowedHeader> is working and <AllowedHeader>Authorization</AllowedHeader> not?

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Just import following package,

import org.hibernate.cfg.Configuration;

Detecting when the 'back' button is pressed on a navbar

I've playing (or fighting) with this problem for two days. IMO the best approach is just to create an extension class and a protocol, like this:

@protocol UINavigationControllerBackButtonDelegate <NSObject>
/**
 * Indicates that the back button was pressed.
 * If this message is implemented the pop logic must be manually handled.
 */
- (void)backButtonPressed;
@end

@interface UINavigationController(BackButtonHandler)
@end

@implementation UINavigationController(BackButtonHandler)
- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item
{
    UIViewController *topViewController = self.topViewController;
    BOOL wasBackButtonClicked = topViewController.navigationItem == item;
    SEL backButtonPressedSel = @selector(backButtonPressed);
    if (wasBackButtonClicked && [topViewController respondsToSelector:backButtonPressedSel]) {
        [topViewController performSelector:backButtonPressedSel];
        return NO;
    }
    else {
        [self popViewControllerAnimated:YES];
        return YES;
    }
}
@end

This works because UINavigationController will receive a call to navigationBar:shouldPopItem: every time a view controller is popped. There we detect if back was pressed or not (any other button). The only thing you have to do is implement the protocol in the view controller where back is pressed.

Remember to manually pop the view controller inside backButtonPressedSel, if everything is ok.

If you already have subclassed UINavigationViewController and implemented navigationBar:shouldPopItem: don't worry, this won't interfere with it.

You may also be interested in disable the back gesture.

if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
    self.navigationController.interactivePopGestureRecognizer.enabled = NO;
}