Programs & Examples On #Mirc

Windows based IRC (Internet Relay Chat) client. Featuring easy to use interface and powerfull scripting language.

Java 8 Iterable.forEach() vs foreach loop

The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

Have look at below snippet,

  • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

    class MyConsumer implements Consumer<Integer>{
    
        @Override
        public void accept(Integer o) {
            System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
        }
    }
    
    public class ForEachConsumer {
    
        public static void main(String[] args) {
    
            // Creating simple ArrayList.
            ArrayList<Integer> aList = new ArrayList<>();
            for(int i=1;i<=10;i++) aList.add(i);
    
            //Calling forEach with customized Iterator.
            MyConsumer consumer = new MyConsumer();
            aList.forEach(consumer);
    
    
            // Using Lambda Expression for Consumer. (Functional Interface) 
            Consumer<Integer> lambda = (Integer o) ->{
                System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
            };
            aList.forEach(lambda);
    
            // Using Anonymous Inner Class.
            aList.forEach(new Consumer<Integer>(){
                @Override
                public void accept(Integer o) {
                    System.out.println("Calling with Anonymous Inner Class "+o);
                }
            });
        }
    }
    

What is the worst programming language you ever worked with?

CSS

For basic styling its OK, and selectors are pretty cool, but there's something a little bit sadistic about the box model, floats and clearing.

Hacking the language to make it do fundamental things, such as move one box below another, is all in a days work.

Here we are living in the future and just getting basic design elements to work, like rounded corners or drop shadows, is an exercise in futility.

The concept of 'reusability' pretty much ends with Ctrl-C Ctrl-V. Even a seasoned CSS writer will rarely touch someone else's stylesheet - meaning that basic layouts are routinely rewritten again and again all around the world.

Of course it shouldn't take all the flack - any hope it had of offering something truly useful to the world was cruelly dashed upon the rocks by the de facto 'platform' for the language - Internet Explorer.

How to delete Project from Google Developers Console

As of this writing, it was necessary to:

  1. Select 'Manage all projects' from the dropdown list at the top of the Console page
  2. Click the delete button (trashcan icon) for the specific project on the project listing page

Django MEDIA_URL and MEDIA_ROOT

Adding to Micah Carrick answer for django 1.8:

if settings.DEBUG:
  urlpatterns.append(url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {'document_root': settings.MEDIA_ROOT}))

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

Notepad++ Regular expression find and delete a line

Combining the best from all the answers

enter image description here

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

Is there an auto increment in sqlite?

As of today — June 2018


Here is what official SQLite documentation has to say on the subject (bold & italic are mine):

  1. The AUTOINCREMENT keyword imposes extra CPU, memory, disk space, and disk I/O overhead and should be avoided if not strictly needed. It is usually not needed.

  2. In SQLite, a column with type INTEGER PRIMARY KEY is an alias for the ROWID (except in WITHOUT ROWID tables) which is always a 64-bit signed integer.

  3. On an INSERT, if the ROWID or INTEGER PRIMARY KEY column is not explicitly given a value, then it will be filled automatically with an unused integer, usually one more than the largest ROWID currently in use. This is true regardless of whether or not the AUTOINCREMENT keyword is used.

  4. If the AUTOINCREMENT keyword appears after INTEGER PRIMARY KEY, that changes the automatic ROWID assignment algorithm to prevent the reuse of ROWIDs over the lifetime of the database. In other words, the purpose of AUTOINCREMENT is to prevent the reuse of ROWIDs from previously deleted rows.

Calculating the SUM of (Quantity*Price) from 2 different tables

Use:

  SELECT oi.orderid,
         SUM(oi.quantity * p.price) AS grand_total,
    FROM ORDERITEM oi
    JOIN PRODUCT p ON p.id = oi.productid
   WHERE oi.orderid = @OrderId
GROUP BY oi.orderid

Mind that if either oi.quantity or p.price is null, the SUM will return NULL.

Get original URL referer with PHP?

Using Cookie as a repository of reference page is much better in most cases, as cookies will keep referrer until the browser is closed (and will keep it even if browser tab is closed), so in case if user left the page open, let's say before weekends, and returned to it after a couple of days, your session will probably be expired, but cookies are still will be there.

Put that code at the begin of a page (before any html output, as cookies will be properly set only before any echo/print):

if(!isset($_COOKIE['origin_ref']))
{
    setcookie('origin_ref', $_SERVER['HTTP_REFERER']);
}

Then you can access it later:

$var = $_COOKIE['origin_ref'];

And to addition to what @pcp suggested about escaping $_SERVER['HTTP_REFERER'], when using cookie, you may also want to escape $_COOKIE['origin_ref'] on each request.

Angular window resize event

On Angular2 (2.1.0) I use ngZone to capture the screen change event.

Take a look on the example:

import { Component, NgZone } from '@angular/core';//import ngZone library
...
//capture screen changed inside constructor
constructor(private ngZone: NgZone) {
    window.onresize = (e) =>
    {
        ngZone.run(() => {
            console.log(window.innerWidth);
            console.log(window.innerHeight);
        });
    };
}

I hope this help!

How can I "reset" an Arduino board?

  1. Unplug Tx from the microcontroller
  2. Insert USB cable
  3. Wait until full load
  4. Connect Rx with hardware
  5. Compile empty sketch in prosses and unconnect tx (don't worry about the error)
  6. Connect Rx with hardware
  7. Compile empty sketch
  8. Power off and connect Tx

How to set entire application in portrait mode only?

Use:

android:screenOrientation="portrait" 

Just write this line in your application's manifest file in each activity which you want to show in portrait mode only.

how do you pass images (bitmaps) between android activities using bundles?

As suggested by @EboMike I saved the bitmap in a file named myImage in the internal storage of my application not accessible my other apps. Here's the code of that part:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

Bitmap bitmap = BitmapFactory.decodeStream(context
                    .openFileInput("myImage"));//here context can be anything like getActivity() for fragment, this or MainActivity.this

Note A lot of checking for null and scaling bitmap's is ommited.

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

How can I define colors as variables in CSS?

Sure can, sort of, thanks to the wonderful world of multiple classes, can do this:

.red {color:red}
.blackBack {background-color: black}

but I often end up combining them anyway like this:

.highlight {color:red, background-color: black}

I know the semantic police will be all over you, but it works.

Update Item to Revision vs Revert to Revision

To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:

BASE

The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.

Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.

Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.

Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.

what is difference between success and .done() method of $.ajax

success only fires if the AJAX call is successful, i.e. ultimately returns a HTTP 200 status. error fires if it fails and complete when the request finishes, regardless of success.

In jQuery 1.8 on the jqXHR object (returned by $.ajax) success was replaced with done, error with fail and complete with always.

However you should still be able to initialise the AJAX request with the old syntax. So these do similar things:

// set success action before making the request
$.ajax({
  url: '...',
  success: function(){
    alert('AJAX successful');
  }
});

// set success action just after starting the request
var jqxhr = $.ajax( "..." )
  .done(function() { alert("success"); });

This change is for compatibility with jQuery 1.5's deferred object. Deferred (and now Promise, which has full native browser support in Chrome and FX) allow you to chain asynchronous actions:

$.ajax("parent").
    done(function(p) { return $.ajax("child/" + p.id); }).
    done(someOtherDeferredFunction).
    done(function(c) { alert("success: " + c.name); });

This chain of functions is easier to maintain than a nested pyramid of callbacks you get with success.

However, please note that done is now deprecated in favour of the Promise syntax that uses then instead:

$.ajax("parent").
    then(function(p) { return $.ajax("child/" + p.id); }).
    then(someOtherDeferredFunction).
    then(function(c) { alert("success: " + c.name); }).
    catch(function(err) { alert("error: " + err.message); });

This is worth adopting because async and await extend promises improved syntax (and error handling):

try {
    var p = await $.ajax("parent");
    var x = await $.ajax("child/" + p.id);
    var c = await someOtherDeferredFunction(x);
    alert("success: " + c.name);
}
catch(err) { 
    alert("error: " + err.message); 
}

Set Locale programmatically

For those who tried everything but not not working. Please check that if you set darkmode with AppCompatDelegate.setDefaultNightMode and the system is not dark, then Configuration.setLocale will not work above Andorid 7.0.

Add this code in your every activity to solve this issue:

override fun applyOverrideConfiguration(overrideConfiguration: Configuration?) {
  if (overrideConfiguration != null) {
    val uiMode = overrideConfiguration.uiMode
    overrideConfiguration.setTo(baseContext.resources.configuration)
    overrideConfiguration.uiMode = uiMode
  }
  super.applyOverrideConfiguration(overrideConfiguration)
}

How do I undo a checkout in git?

Try this first:

git checkout master

(If you're on a different branch than master, use the branch name there instead.)

If that doesn't work, try...

For a single file:

git checkout HEAD /path/to/file

For the entire repository working copy:

git reset --hard HEAD

And if that doesn't work, then you can look in the reflog to find your old head SHA and reset to that:

git reflog
git reset --hard <sha from reflog>

HEAD is a name that always points to the latest commit in your current branch.

How to add column if not exists on PostgreSQL?

In my case, for how it was created reason it is a bit difficult for our migration scripts to cut across different schemas.

To work around this we used an exception that just caught and ignored the error. This also had the nice side effect of being a lot easier to look at.

However, be wary that the other solutions have their own advantages that probably outweigh this solution:

DO $$
BEGIN
  BEGIN
    ALTER TABLE IF EXISTS bobby_tables RENAME COLUMN "dckx" TO "xkcd";
  EXCEPTION
    WHEN undefined_column THEN RAISE NOTICE 'Column was already renamed';
  END;
END $$;

Android Eclipse - Could not find *.apk

Clean the project and it will do. Sometimes it happens unknowingly but keep trying to solve using diff methods.

CSS3 Transparency + Gradient

I just came across this more recent example . To simplify and use the most recent examples, giving the css a selector class of 'grad',(I've included backwards compatibility)

.grad {
    background-color: #F07575; /* fallback color if gradients are not supported */
    background-image: -webkit-linear-gradient(top left, red, rgba(255,0,0,0));/* For Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */
    background-image: -moz-linear-gradient(top left, red, rgba(255,0,0,0));/* For Firefox (3.6 to 15) */
    background-image: -o-linear-gradient(top left, red, rgba(255,0,0,0));/* For old Opera (11.1 to 12.0) */
    background-image: linear-gradient(to bottom right, red, rgba(255,0,0,0)); /* Standard syntax; must be last */
}

from https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient

set pythonpath before import statements

This will add a path to your Python process / instance (i.e. the running executable). The path will not be modified for any other Python processes. Another running Python program will not have its path modified, and if you exit your program and run again the path will not include what you added before. What are you are doing is generally correct.

set.py:

import sys
sys.path.append("/tmp/TEST")

loop.py

import sys
import time
while True:
  print sys.path
  time.sleep(1)

run: python loop.py &

This will run loop.py, connected to your STDOUT, and it will continue to run in the background. You can then run python set.py. Each has a different set of environment variables. Observe that the output from loop.py does not change because set.py does not change loop.py's environment.

A note on importing

Python imports are dynamic, like the rest of the language. There is no static linking going on. The import is an executable line, just like sys.path.append....

Python/Json:Expecting property name enclosed in double quotes

This:

{
    'http://example.org/about': {
        'http://purl.org/dc/terms/title': [
            {'type': 'literal', 'value': "Anna's Homepage"}
        ]
     }
}

is not JSON.
This:

{
     "http://example.org/about": {
         "http://purl.org/dc/terms/title": [
             {"type": "literal", "value": "Anna's Homepage"}
          ]
      }
}

is JSON.

EDIT:
Some commenters suggested that the above is not enough.
JSON specification - RFC7159 states that a string begins and ends with quotation mark. That is ".
Single quoute ' has no semantic meaning in JSON and is allowed only inside a string.

How to set up a Web API controller for multipart/form-data

Here's another answer for the ASP.Net Core solution to this problem...

On the Angular side, I took this code example...

https://stackblitz.com/edit/angular-drag-n-drop-directive

... and modified it to call an HTTP Post endpoint:

  prepareFilesList(files: Array<any>) {

    const formData = new FormData();
    for (var i = 0; i < files.length; i++) { 
      formData.append("file[]", files[i]);
    }

    let URL = "https://localhost:44353/api/Users";
    this.http.post(URL, formData).subscribe(
      data => { console.log(data); },
      error => { console.log(error); }
    );

With this in place, here's the code I needed in the ASP.Net Core WebAPI controller:

[HttpPost]
public ActionResult Post()
{
  try
  {
    var files = Request.Form.Files;

    foreach (IFormFile file in files)
    {
        if (file.Length == 0)
            continue;
        
        string tempFilename = Path.Combine(Path.GetTempPath(), file.FileName);
        System.Diagnostics.Trace.WriteLine($"Saved file to: {tempFilename}");

        using (var fileStream = new FileStream(tempFilename, FileMode.Create))
        {
            file.CopyTo(fileStream);
        }
    }
    return new OkObjectResult("Yes");
  }
  catch (Exception ex)
  {
    return new BadRequestObjectResult(ex.Message);
  }
}

Shockingly simple, but I had to piece together examples from several (almost-correct) sources to get this to work properly.

JavaScript load a page on button click

Don't abuse form elements where <a> elements will suffice.

<style>
    /* or put this in your stylesheet */

    .button {
        display: inline-block;
        padding: 3px 5px;
        border: 1px solid #000;
        background: #eee;
    }

</style>

<!-- instead of abusing a button or input element -->
<a href="url" class="button">text</a>

How can I check which version of Angular I'm using?

There are multiple ways:

  1. You may verify it from your package.json file
  2. You use the following command:

ng --version

The command above will result in the following output:

Angular CLI: 7.0.3

Node: 9.4.0

OS: darwin x64

Angular: 7.0.1

... animations, common, compiler, compiler-cli, core, forms

... http, language-service, platform-browser

... platform-browser-dynamic, router

Package Version


@angular-devkit/architect 0.10.3

@angular-devkit/build-angular 0.10.3

@angular-devkit/build-optimizer 0.10.3

@angular-devkit/build-webpack 0.10.3

@angular-devkit/core 7.0.3

@angular-devkit/schematics 7.0.3

@angular/cli 7.0.3

@ngtools/webpack 7.0.3

@schematics/angular 7.0.3

@schematics/update 0.10.3

rxjs 6.3.3

typescript 3.1.4

webpack 4.19.1

So, the version of Angular, Angular CLI, Node and many other packages can be verified from here.

Declaration of Methods should be Compatible with Parent Methods in PHP

if you wanna keep OOP form without turning any error off, you can also:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}

How do I add one month to current date in Java?

This method returns the current date plus 1 month.

public Date  addOneMonth()  {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH, 1);
        return cal.getTime();
}`

Get the length of a String

You can get the length simply by writing an extension:

extension String {
    // MARK: Use if it's Swift 2
    func stringLength(str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 3
    func stringLength(_ str: String) -> Int {
        return str.characters.count
    }

    // MARK: Use if it's Swift 4
    func stringLength(_ str: String) -> Int {
        return str.count
    }
}

Reading CSV files using C#

Don't reinvent the wheel. Take advantage of what's already in .NET BCL.

  • add a reference to the Microsoft.VisualBasic (yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)
  • use the Microsoft.VisualBasic.FileIO.TextFieldParser class to parse CSV file

Here is the sample code:

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData) 
    {
        //Processing row
        string[] fields = parser.ReadFields();
        foreach (string field in fields) 
        {
            //TODO: Process field
        }
    }
}

It works great for me in my C# projects.

Here are some more links/informations:

What is 0x10 in decimal?

0x means the number is hexadecimal, or base 16.

0x10 is 16.

Setting a property by reflection with a string value

Using Convert.ChangeType and getting the type to convert from the PropertyInfo.PropertyType.

propertyInfo.SetValue( ship,
                       Convert.ChangeType( value, propertyInfo.PropertyType ),
                       null );

What is the default database path for MongoDB?

I have version 2.0.7 installed on Ubuntu and it defaulted to /var/lib/mongodb/ and that is also what was placed into my /etc/mongodb.conf file.

Closing a file after File.Create

File.Create returns a FileStream object that you can call Close() on.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

Write to file, but overwrite it if it exists

In Bash, if you have set noclobber a la set -o noclobber, then you use the syntax >|

For example:

echo "some text" >| existing_file

This also works if the file doesn't exist yet


  • Check if noclobber is set with: set -o | grep noclobber

  • For a more detailed explanation on this special type of operator, see this post

  • For a more exhaustive list of redirection operators, refer to this post

How do I set GIT_SSL_NO_VERIFY for specific repos only?

On Linux, if you call this inside the git repository folder:

git config http.sslVerify false

this will add sslVerify = false in the [http] section of the config file in the .git folder, which can also be the solution, if you want to add this manually with nano .git/config:

...
[http]
  sslVerify = false

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Good to see someone's chimed in about Lucene - because I've no idea about that.

Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.

  • Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
  • Indexing speed is super-fast, because it talks directly to the database. Any slowness will come from complex SQL queries and un-indexed foreign keys and other such problems. I've never noticed any slowness in searching either.
  • I'm a Rails guy, so I've no idea how easy it is to implement with Django. There is a Python API that comes with the Sphinx source though.
  • The search service daemon (searchd) is pretty low on memory usage - and you can set limits on how much memory the indexer process uses too.
  • Scalability is where my knowledge is more sketchy - but it's easy enough to copy index files to multiple machines and run several searchd daemons. The general impression I get from others though is that it's pretty damn good under high load, so scaling it out across multiple machines isn't something that needs to be dealt with.
  • There's no support for 'did-you-mean', etc - although these can be done with other tools easily enough. Sphinx does stem words though using dictionaries, so 'driving' and 'drive' (for example) would be considered the same in searches.
  • Sphinx doesn't allow partial index updates for field data though. The common approach to this is to maintain a delta index with all the recent changes, and re-index this after every change (and those new results appear within a second or two). Because of the small amount of data, this can take a matter of seconds. You will still need to re-index the main dataset regularly though (although how regularly depends on the volatility of your data - every day? every hour?). The fast indexing speeds keep this all pretty painless though.

I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.

I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.

I cannot start SQL Server browser

Make sure that you run the SQL Server Configuration Manager snap-in as Administrator if UAC is enabled. Then right click the service and then click properties, change the start mode to enabled, then start it.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

FYI, another way this exception can occur is if:

  • Your transaction isolation is READ_COMMITTED
  • Transaction #1 queries for an entity, then deletes that entity
  • A simultaneous transaction #2 does the same thing

Then this can happen: TX #1 successfully commits before TX #2, then when TX #2 tries to delete the entity (again) it's not there any more - even though it was found by a query earlier in that same transaction. Note this anomaly is allowed with READ_COMMITTED isolation.

In my case the resulting exception looked like this:

HHH000315: Exception executing batch [org.hibernate.StaleStateException:
  Batch update returned unexpected row count from update [0]; actual row
  count: 0; expected: 1; statement executed: delete from Foobar where id=?],
  SQL: delete from Foobar where id=?

In ASP.NET, when should I use Session.Clear() rather than Session.Abandon()?

Session.Abandon() destroys the session and the Session_OnEnd event is triggered.

Session.Clear() just removes all values (content) from the Object. The session with the same key is still alive.

So, if you use Session.Abandon(), you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.

Use Session.Clear(), if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.

Get current working directory in a Qt application

Thank you RedX and Kaz for your answers. I don't get why by me it gives the path of the exe. I found an other way to do it :

QString pwd("");
char * PWD;
PWD = getenv ("PWD");
pwd.append(PWD);
cout << "Working directory : " << pwd << flush;

It is less elegant than a single line... but it works for me.

Difference between two dates in Python

Try this:

data=pd.read_csv('C:\Users\Desktop\Data Exploration.csv')
data.head(5)
first=data['1st Gift']
last=data['Last Gift']
maxi=data['Largest Gift']
l_1=np.mean(first)-3*np.std(first)
u_1=np.mean(first)+3*np.std(first)


m=np.abs(data['1st Gift']-np.mean(data['1st Gift']))>3*np.std(data['1st Gift'])
pd.value_counts(m)
l=first[m]
data.loc[:,'1st Gift'][m==True]=np.mean(data['1st Gift'])+3*np.std(data['1st Gift'])
data['1st Gift'].head()




m=np.abs(data['Last Gift']-np.mean(data['Last Gift']))>3*np.std(data['Last Gift'])
pd.value_counts(m)
l=last[m]
data.loc[:,'Last Gift'][m==True]=np.mean(data['Last Gift'])+3*np.std(data['Last Gift'])
data['Last Gift'].head()

Inheritance and init method in Python

Since you don't call Num.__init__ , the field "n1" never gets created. Call it and then it will be there.

Can lambda functions be templated?

Have a look at Boost.Phoenix for polymorphic lambdas: http://www.boost.org/doc/libs/1_44_0/libs/spirit/phoenix/doc/html/index.html Does not require C++0x, by the way :)

Choosing a jQuery datagrid plugin?

A good plugin that I have used before is DataTables.

How to install PyQt4 on Windows using pip?

You can't use pip. You have to download from the Riverbank website and run the installer for your version of python. If there is no install for your version, you will have to install Python for one of the available installers, or build from source (which is rather involved). Other answers and comments have the links.

How to enable php7 module in apache?

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

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

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

And then to:

gksu gedit /etc/apache2/apache2.conf

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

That make a deal with all problems

Maciej

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

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

DIV table colspan: how?

you can simply use two table divs, for instance:

_x000D_
_x000D_
<div style="display:table; width:450px; margin:0 auto; margin-top:30px; ">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:50%">element1</div>_x000D_
    <div style="width:50%">element2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div style="display:table; width:450px; margin:0 auto;">_x000D_
  <div style="display:table-row">_x000D_
    <div style="width:100%">element1</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

works great!

How to Correctly handle Weak Self in Swift Blocks with Arguments

If self could be nil in the closure use [weak self].

If self will never be nil in the closure use [unowned self].

If it's crashing when you use [unowned self] I would guess that self is nil at some point in that closure, which is why you had to go with [weak self] instead.

I really liked the whole section from the manual on using strong, weak, and unowned in closures:

https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html

Note: I used the term closure instead of block which is the newer Swift term:

Difference between block (Objective C) and closure (Swift) in ios

Calling ASP.NET MVC Action Methods from JavaScript

If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.

<div class="cart">
      @Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>

That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on

100% width background image with an 'auto' height

Just use a two color background image:

<div style="width:100%; background:url('images/bkgmid.png');
       background-size: cover;">
content
</div>

how to open Jupyter notebook in chrome on windows

  • Run the jupyter notebook --generate-config command on the anaconda prompt.
  • Then edit the jupyter_notebook_config.py file.

Find the c.NotebookApp.Browser like this:

c.NotebookApp.browser = 'c:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'

Works on mine.

How to create a file in memory for user to download, but not through server?

As mentioned before, filesaver is a great package to work with files on the client side. But, it is not do well with large files. StreamSaver.js is an alternative solution (which is pointed in FileServer.js) that can handle large files:

const fileStream = streamSaver.createWriteStream('filename.txt', size);
const writer = fileStream.getWriter();
for(var i = 0; i < 100; i++){
    var uint8array = new TextEncoder("utf-8").encode("Plain Text");
    writer.write(uint8array);
}
writer.close()

How to correctly use "section" tag in HTML5?

In the W3 wiki page about structuring HTML5, it says:

<section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.

And then displays an image that I cleaned up:

enter image description here

It's also important to know how to use the <article> tag (from the same W3 link above):

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up.

In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article>
      <!-- first blog post -->
    </article>

    <article>
      <!-- second blog post  -->
    </article>

    <article>
      <!-- third blog post -->
    </article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction">
  </section>

  <section id="content">
  </section>

  <section id="summary">
  </section>
</article>

Error: «Could not load type MvcApplication»

If you changed a namespace make sure to right click and refactor.

CSS scrollbar style cross browser

Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:

::-webkit-scrollbar
{
  width: 12px;  /* for vertical scrollbars */
  height: 12px; /* for horizontal scrollbars */
}

::-webkit-scrollbar-track
{
  background: rgba(0, 0, 0, 0.1);
}

::-webkit-scrollbar-thumb
{
  background: rgba(0, 0, 0, 0.5);
}

This answer is a fantastic source of additional information.

IDEA: javac: source release 1.7 requires target release 1.7

I've found required options ('target bytecode version') in settings > compiler > java compiler in my case (intelij idea 12.1.3)

Invalid Host Header when ngrok tries to connect to React dev server

If you use webpack devServer the simplest way is to set disableHostCheck, check webpack doc like this

devServer: {
    contentBase: path.join(__dirname, './dist'),
    compress: true,
    host: 'localhost',
    // host: '0.0.0.0',
    port: 8080,
    disableHostCheck: true //for ngrok
},

How to insert current_timestamp into Postgres via python

If you use psycopg2 (and possibly some other client library), you can simply pass a Python datetime object as a parameter to a SQL-query:

from datetime import datetime, timezone

dt = datetime.now(timezone.utc)
cur.execute('INSERT INTO mytable (mycol) VALUES (%s)', (dt,))

(This assumes that the timestamp with time zone type is used on the database side.)

More Python types that can be adapted into SQL (and returned as Python objects when a query is executed) are listed here.

How to send authorization header with axios

Instead of calling axios.get function Use:

axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })

What is the difference between field, variable, attribute, and property in Java POJOs?

  • variable - named storage address. Every variable has a type which defines a memory size, attributes and behaviours. There are for types of Java variables: class variable, instance variable, local variable, method parameter
//pattern
<Java_type> <name> ;

//for example
int myInt;
String myString;
CustomClass myCustomClass;
  • field - member variable or data member. It is a variable inside a class(class variable or instance variable)

  • attribute - in some articles you can find that attribute it is an object representation of class variable. Object operates by attributes which define a set of characteristics.

CustomClass myCustomClass = new CustomClass();
myCustomClass.myAttribute = "poor fantasy"; //`myAttribute` is an attribute of `myCustomClass` object with a "poor fantasy" value
  • property - field + bounded getter/setter. It has a field syntax but uses methods under the hood. Java does not support it in pure form. Take a look at Objective-C, Swift, Kotlin

For example Kotlin sample:

//field - Backing Field
class Person {
    var name: String = "default name"
        get() = field
        set(value) { field = value }
}

//using
val person = Person()
person.name = "Alex"    // setter is used
println(person.name)    // getter is used

[Swift variable, property...]

How do you write multiline strings in Go?

You can put content with `` around it, like

var hi = `I am here,
hello,
`

How do I horizontally center an absolute positioned element inside a 100% width div?

Its easy, just wrap it in a relative box like so:

<div class="relative">
 <div class="absolute">LOGO</div>
</div>

The relative box has a margin: 0 Auto; and, important, a width...

How to scale a UIImageView proportionally?

This works fine for me Swift 2.x:

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true;

Only allow specific characters in textbox

Intercept the KeyPressed event is in my opinion a good solid solution. Pay attention to trigger code characters (e.KeyChar lower then 32) if you use a RegExp.

But in this way is still possible to inject characters out of range whenever the user paste text from the clipboard. Unfortunately I did not found correct clipboard events to fix this.

So a waterproof solution is to intercept TextBox.TextChanged. Here is sometimes the original out of range character visible, for a short time. I recommend to implement both.

using System.Text.RegularExpressions;

private void Form1_Shown(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}


string pattern = @"[^0-9^+^\-^/^*^(^)]";

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if(e.KeyChar >= 32 && Regex.Match(e.KeyChar.ToString(), pattern).Success) { e.Handled = true; }
}

private void textBox1_TextChanged(object sender, EventArgs e)
{
    filterTextBoxContent(textBox1);
}

private bool filterTextBoxContent(TextBox textBox)
{
    string text = textBox.Text;

    MatchCollection matches = Regex.Matches(text, pattern);
    bool matched = false;

    int selectionStart = textBox.SelectionStart;
    int selectionLength = textBox.SelectionLength;

    int leftShift = 0;
    foreach (Match match in matches)
    {
        if (match.Success && match.Captures.Count > 0)
        {
            matched = true;
            Capture capture = match.Captures[0];

            int captureLength = capture.Length;
            int captureStart = capture.Index - leftShift;
            int captureEnd = captureStart + captureLength;

            int selectionEnd = selectionStart + selectionLength;

            text = text.Substring(0, captureStart) + text.Substring(captureEnd, text.Length - captureEnd);

            textBox.Text = text;

            int boundSelectionStart = selectionStart < captureStart ? -1 : (selectionStart < captureEnd ? 0 : 1);
            int boundSelectionEnd = selectionEnd < captureStart ? -1 : (selectionEnd < captureEnd ? 0 : 1);

            if (boundSelectionStart == -1)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionLength -= selectionEnd - captureStart;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionLength -= captureLength;
                }
            }
            else if (boundSelectionStart == 0)
            {
                if (boundSelectionEnd == 0)
                {
                    selectionStart = captureStart;
                    selectionLength = 0;
                }
                else if (boundSelectionEnd == 1)
                {
                    selectionStart = captureStart;
                    selectionLength -= captureEnd - selectionStart;
                }
            }
            else if (boundSelectionStart == 1)
            {
                selectionStart -= captureLength;
            }

            leftShift++;
        }
    }

    textBox.SelectionStart = selectionStart;
    textBox.SelectionLength = selectionLength;

    return matched;
}

How do I use brew installed Python as the default Python?

Quick fix:

  1. Open /etc/paths
  2. Change the order of the lines (highest priority on top)

In my case /etc/paths looks like:

/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin

If you want to know more about paths in OSX I found this article quite useful:

http://muttsnutts.github.com/blog/2011/09/12/manage-path-on-mac-os-x-lion/

Refreshing page on click of a button

This question actually is not JSP related, it is HTTP related. you can just do:

window.location = window.location;

In jQuery, how do I select an element by its name attribute?

The following code is used to get the selected radio button value by name

jQuery("input:radio[name=theme]:checked").val();

Thanks Adnan

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

Find all files in a folder

You can try with Directory.GetFiles and fix your pattern

 string[] files = Directory.GetFiles(@"c:\", "*.txt");

 foreach (string file in files)
 {
    File.Copy(file, "....");
 }

 Or Move

 foreach (string file in files)
 {
    File.Move(file, "....");
 }     

http://msdn.microsoft.com/en-us/library/wz42302f

Select Top and Last rows in a table (SQL server)

To get the bottom 1000 you will want to order it by a column in descending order, and still take the top 1000.

SELECT TOP 1000 *
FROM [SomeTable]
ORDER BY MySortColumn DESC

If you care for it to be in the same order as before you can use a common table expression for that:

;WITH CTE AS (
    SELECT TOP 1000 *
    FROM [SomeTable]
    ORDER BY MySortColumn DESC
)

SELECT * 
FROM CTE
ORDER BY MySortColumn

Git credential helper - update password

Working solution for Windows:

Control Panel > User Accounts > Credential Manager > Generic Credentials

enter image description here

What does character set and collation mean exactly?

I suggest to use utf8mb4_unicode_ci, which is based on the Unicode standard for sorting and comparison, which sorts accurately in a very wide range of languages.

Is there a minlength validation attribute in HTML5?

I notice that sometimes in Chrome when autofill is on and the fields are field by the autofill browser build in method, it bypasses the minlength validation rules, so in this case you will have to disable autofill by the following attribute:

autocomplete="off"

<input autocomplete="new-password" name="password" id="password" type="password" placeholder="Password" maxlength="12" minlength="6" required />

What Does This Mean in PHP -> or =>

The double arrow operator, =>, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.

$myArray = array(
    0 => 'Big',
    1 => 'Small',
    2 => 'Up',
    3 => 'Down'
);

The object operator, ->, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.

// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();

Open a URL in a new tab (and not a new window)

There are lots of answer copies suggesting using "_blank" as the target, however I found this didn't work. As Prakash notes, it is up to the browser. However, you can make certain suggestions to the browser, such as to whether the window should have a location bar.

If you suggest enough "tab-like things" you might get a tab, as per Nico's answer to this more specific question for chrome:

window.open('http://www.stackoverflow.com', '_blank', 'toolbar=yes, location=yes, status=yes, menubar=yes, scrollbars=yes');

Disclaimer: This is not a panacea. It is still up to the user and browser. Now at least you've specified one more preference for what you'd like your window to look like.

Enter key press in C#

private void Ctrl_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Enter)
    {
        this.SelectNextControl((Control)sender, true, true, true, true);
    }
}

Select all required textboxes; type in new Events name Ctrl_KeyUp.

See YouTube by BTNT TV: https://www.bing.com/videos/searchq=c%23+how+to+move+to+next+textbox+after+enterkey&view=detail&mid=999E8CAFC15140E867C0999E8CAFC15140E867C0&FORM=VIRE

Disable vertical sync for glxgears

I found a solution that works in the intel card and in the nvidia card using Bumblebee.

> export vblank_mode=0
glxgears
...
optirun glxgears
...
export vblank_mode=1

Passing Parameters JavaFX FXML

javafx.scene.Node class has a pair of methods setUserData(Object) and Object getUserData()

Which you could use to add your info to the Node.

So, you can call page.setUserData(info);

And controller can check, if info is set. Also, you could use ObjectProperty for back-forward data transfering, if needed.

Observe a documentation here: http://docs.oracle.com/javafx/2/api/javafx/fxml/doc-files/introduction_to_fxml.html Before the phrase "In the first version, the handleButtonAction() is tagged with @FXML to allow markup defined in the controller's document to invoke it. In the second example, the button field is annotated to allow the loader to set its value. The initialize() method is similarly annotated."

So, you need to associate a controller with a node, and set a user data to the node.

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

How to suppress warnings globally in an R Script

Have a look at ?options and use warn:

options( warn = -1 )

Javascript array search and remove string?

use array.splice

/*array.splice(index , howMany[, element1[, ...[, elementN]]])

array.splice(index) // SpiderMonkey/Firefox extension*/

array.splice(1,1)

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

mysqli or PDO - what are the pros and cons?

PDO will make it a lot easier to scale if your site/web app gets really being as you can daily set up Master and slave connections to distribute the load across the database, plus PHP is heading towards moving to PDO as a standard.

PDO Info

Scaling a Web Application

Convert SQL Server result set into string

The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...

ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286

original query...

SELECT StudentId FROM Student WHERE condition = xyz

original result set...

StudentId
1236
7656
8990

new query w/ concat...

SELECT group_concat(concat_ws(',', StudentId) separator '; ') 
FROM Student 
WHERE condition = xyz

concat string result set...

StudentId
1236; 7656; 8990

note: change the 'separator' to whatever you would like

GLHF!

How to check the extension of a filename in a bash script?

You just can't be sure on a Unix system, that a .txt file truly is a text file. Your best bet is to use "file". Maybe try using:

file -ib "$file"

Then you can use a list of MIME types to match against or parse the first part of the MIME where you get stuff like "text", "application", etc.

Using comma as list separator with AngularJS

If you are using ng-show to limit the values, the {{$last ? '' : ', '}} won`t work since it will still take into consideration all the values.Example

<div ng-repeat="x in records" ng-show="x.email == 1">{{x}}{{$last ? '' : ', '}}</div>

var myApp = angular.module("myApp", []);
myApp.controller("myCtrl", function($scope) {
  $scope.records = [
    {"email": "1"},
    {"email": "1"},
    {"email": "2"},
    {"email": "3"}
  ]
});

Results in adding a comma after the "last" value,since with ng-show it still takes into consideration all 4 values

{"email":"1"},
{"email":"1"},

One solution is to add a filter directly into ng-repeat

<div ng-repeat="x in records | filter: { email : '1' } ">{{x}}{{$last ? '' : ', '}}</div>

Results

{"email":"1"},
{"email":"1"}

Why don't self-closing script elements work?

That's because SCRIPT TAG is not a VOID ELEMENT.

In an HTML Document - VOID ELEMENTS do not need a "closing tag" at all!

In xhtml, everything is Generic, therefore they all need termination e.g. a "closing tag"; Including br, a simple line-break, as <br></br> or its shorthand <br />.

However, a Script Element is never a void or a parametric Element, because script tag before anything else, is a Browser Instruction, not a Data Description declaration.

Principally, a Semantic Termination Instruction e.g., a "closing tag" is only needed for processing instructions who's semantics cannot be terminated by a succeeding tag. For instance:

<H1> semantics cannot be terminated by a following <P> because it doesn't carry enough of its own semantics to override and therefore terminate the previous H1 instruction set. Although it will be able to break the stream into a new paragraph line, it is not "strong enough" to override the present font size & style line-height pouring down the stream, i.e leaking from H1 (because P doesn't have it).

This is how and why the "/" (termination) signalling has been invented.

A generic no-description termination Tag like < />, would have sufficed for any single fall off the encountered cascade, e.g.: <H1>Title< /> but that's not always the case, because we also want to be capable of "nesting", multiple intermediary tagging of the Stream: split into torrents before wrapping / falling onto another cascade. As a consequence a generic terminator such as < /> would not be able to determine the target of a property to terminate. For example: <b>bold <i>bold-italic < /> italic </>normal. Would undoubtedly fail to get our intention right and would most probably interpret it as bold bold-itallic bold normal.

This is how the notion of a wrapper ie., container was born. (These notions are so similar that it is impossible to discern and sometimes the same element may have both. <H1> is both wrapper and container at the same time. Whereas <B> only a semantic wrapper). We'll need a plain, no semantics container. And of course the invention of a DIV Element came by.

The DIV element is actually a 2BR-Container. Of course the coming of CSS made the whole situation weirder than it would otherwise have been and caused a great confusion with many great consequences - indirectly!

Because with CSS you could easily override the native pre&after BR behavior of a newly invented DIV, it is often referred to, as a "do nothing container". Which is, naturally wrong! DIVs are block elements and will natively break the line of the stream both before and after the end signalling. Soon the WEB started suffering from page DIV-itis. Most of them still are.

The coming of CSS with its capability to fully override and completely redefine the native behavior of any HTML Tag, somehow managed to confuse and blur the whole meaning of HTML existence...

Suddenly all HTML tags appeared as if obsolete, they were defaced, stripped of all their original meaning, identity and purpose. Somehow you'd gain the impression that they're no longer needed. Saying: A single container-wrapper tag would suffice for all the data presentation. Just add the required attributes. Why not have meaningful tags instead; Invent tag names as you go and let the CSS bother with the rest.

This is how xhtml was born and of course the great blunt, paid so dearly by new comers and a distorted vision of what is what, and what's the damn purpose of it all. W3C went from World Wide Web to What Went Wrong, Comrades?!!

The purpose of HTML is to stream meaningful data to the human recipient.

To deliver Information.

The formal part is there to only assist the clarity of information delivery. xhtml doesn't give the slightest consideration to the information. - To it, the information is absolutely irrelevant.

The most important thing in the matter is to know and be able to understand that xhtml is not just a version of some extended HTML, xhtml is a completely different beast; grounds up; and therefore it is wise to keep them separate.

How do you get the width and height of a multi-dimensional array?

You use Array.GetLength with the index of the dimension you wish to retrieve.

Normalize columns of pandas data frame

Detailed Example of Normalization Methods

  • Pandas normalization (unbiased)
  • Sklearn normalization (biased)
  • Does biased-vs-unbiased affect Machine Learning?
  • Mix-max scaling

References: Wikipedia: Unbiased Estimation of Standard Deviation

Example Data

import pandas as pd
df = pd.DataFrame({
               'A':[1,2,3],
               'B':[100,300,500],
               'C':list('abc')
             })
print(df)
   A    B  C
0  1  100  a
1  2  300  b
2  3  500  c

Normalization using pandas (Gives unbiased estimates)

When normalizing we simply subtract the mean and divide by standard deviation.

df.iloc[:,0:-1] = df.iloc[:,0:-1].apply(lambda x: (x-x.mean())/ x.std(), axis=0)
print(df)
     A    B  C
0 -1.0 -1.0  a
1  0.0  0.0  b
2  1.0  1.0  c

Normalization using sklearn (Gives biased estimates, different from pandas)

If you do the same thing with sklearn you will get DIFFERENT output!

import pandas as pd

from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()


df = pd.DataFrame({
               'A':[1,2,3],
               'B':[100,300,500],
               'C':list('abc')
             })
df.iloc[:,0:-1] = scaler.fit_transform(df.iloc[:,0:-1].to_numpy())
print(df)
          A         B  C
0 -1.224745 -1.224745  a
1  0.000000  0.000000  b
2  1.224745  1.224745  c

Does Biased estimates of sklearn makes Machine Learning Less Powerful?

NO.

The official documentation of sklearn.preprocessing.scale states that using biased estimator is UNLIKELY to affect the performance of machine learning algorithms and we can safely use them.

From official documentation:

We use a biased estimator for the standard deviation, equivalent to numpy.std(x, ddof=0). Note that the choice of ddof is unlikely to affect model performance.

What about MinMax Scaling?

There is no Standard Deviation calculation in MinMax scaling. So the result is same in both pandas and scikit-learn.

import pandas as pd
df = pd.DataFrame({
               'A':[1,2,3],
               'B':[100,300,500],
             })
(df - df.min()) / (df.max() - df.min())
     A    B
0  0.0  0.0
1  0.5  0.5
2  1.0  1.0


# Using sklearn
from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler() 
arr_scaled = scaler.fit_transform(df) 

print(arr_scaled)
[[0.  0. ]
 [0.5 0.5]
 [1.  1. ]]

df_scaled = pd.DataFrame(arr_scaled, columns=df.columns,index=df.index)
print(df_scaled)
     A    B
0  0.0  0.0
1  0.5  0.5
2  1.0  1.0

How can I remove file extension from a website address?

You have different choices. One on them is creating a folder named "profile" and rename your "profile.php" to "default.php" and put it into "profile" folder. and you can give orders to this page in this way:

Old page: http://something.com/profile.php?id=a&abc=1

New page: http://something.com/profile/?id=a&abc=1

If you are not satisfied leave a comment for complicated methods.

How to open the second form?

On any click event (or other one):

Form2 frm2 = new Form2();
frm2.Show();

How can I get onclick event on webview in android?

This works for me

webView.setOnTouchListener(new View.OnTouchListener() {
                            @Override
                            public boolean onTouch(View v, MotionEvent event) {
                                // Do what you want
                                return false;
                            }
                        });

POI setting Cell Background to a Custom Color

Slot free in NPOI excel indexedcolors from 57+

            Color selColor;

        var wb = new HSSFWorkbook();

        var sheet = wb.CreateSheet("NPOI");
        var style = wb.CreateCellStyle();
        var font = wb.CreateFont();
        var palette = wb.GetCustomPalette();

        short indexColor = 57; 
        palette.SetColorAtIndex(indexColor, (byte)selColor.R, (byte)selColor.G, (byte)selColor.B);

        font.Color = palette.GetColor(indexColor).Indexed;

C++ Dynamic Shared Library on Linux

Basically, you should include the class' header file in the code where you want to use the class in the shared library. Then, when you link, use the '-l' flag to link your code with the shared library. Of course, this requires the .so to be where the OS can find it. See 3.5. Installing and Using a Shared Library

Using dlsym is for when you don't know at compile time which library you want to use. That doesn't sound like it's the case here. Maybe the confusion is that Windows calls the dynamically loaded libraries whether you do the linking at compile or run-time (with analogous methods)? If so, then you can think of dlsym as the equivalent of LoadLibrary.

If you really do need to dynamically load the libraries (i.e., they're plug-ins), then this FAQ should help.

JQuery Number Formatting

http://locutus.io/php/strings/number_format/

module.exports = function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-enter code hereline camelcase
  //  discuss at: http://locutus.io/php/number_format/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // improved by: davook
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Theriault (https://github.com/Theriault)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Michael White (http://getsprink.com)
  // bugfixed by: Benjamin Lupton
  // bugfixed by: Allan Jensen (http://www.winternet.no)
  // bugfixed by: Howard Yeend
  // bugfixed by: Diogo Resende
  // bugfixed by: Rival
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  //  revised by: Luke Smith (http://lucassmith.name)
  //    input by: Kheang Hok Chin (http://www.distantia.ca/)
  //    input by: Jay Klehr
  //    input by: Amir Habibi (http://www.residence-mixte.com/)
  //    input by: Amirouche
  //   example 1: number_format(1234.56)
  //   returns 1: '1,235'
  //   example 2: number_format(1234.56, 2, ',', ' ')
  //   returns 2: '1 234,56'
  //   example 3: number_format(1234.5678, 2, '.', '')
  //   returns 3: '1234.57'
  //   example 4: number_format(67, 2, ',', '.')
  //   returns 4: '67,00'
  //   example 5: number_format(1000)
  //   returns 5: '1,000'
  //   example 6: number_format(67.311, 2)
  //   returns 6: '67.31'
  //   example 7: number_format(1000.55, 1)
  //   returns 7: '1,000.6'
  //   example 8: number_format(67000, 5, ',', '.')
  //   returns 8: '67.000,00000'
  //   example 9: number_format(0.9, 0)
  //   returns 9: '1'
  //  example 10: number_format('1.20', 2)
  //  returns 10: '1.20'
  //  example 11: number_format('1.20', 4)
  //  returns 11: '1.2000'
  //  example 12: number_format('1.2000', 3)
  //  returns 12: '1.200'
  //  example 13: number_format('1 000,50', 2, '.', ' ')
  //  returns 13: '100 050.00'
  //  example 14: number_format(1e-8, 8, '.', '')
  //  returns 14: '0.00000001'

  number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''

  var toFixedFix = function (n, prec) {
    if (('' + n).indexOf('e') === -1) {
      return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
    } else {
      var arr = ('' + n).split('e')
      var sig = ''
      if (+arr[1] + prec > 0) {
        sig = '+'
      }
      return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
    }
  }

  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }

  return s.join(dec)
}

gdb: "No symbol table is loaded"

I have the same problem and I followed this Post, it solved my problem.

Follow the following 2 steps:

  1. Make sure the optimization level is -O0
  2. Add -ggdb flag when compiling your program

Good luck!

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

I had the same problem and i solved it by including jquery-3.1.1.min before including any js and it worked like a charm. Hope it helps.

How to fill 100% of remaining height?

I know this is an old question, but nowadays there is a super easy form to do that, which is CCS Grid, so let me put the divs as example:

<div id="full">
  <div id="header">Contents of 1</div>
  <div id="someid">Contents of 2</div>
</div>

then the CSS code:

.full{
  width:/*the width you need*/;
  height:/*the height you need*/;
  display:grid;
  grid-template-rows: minmax(100px,auto) 1fr;
 }

And that's it, the second row, scilicet, the someide, will take the rest of the height because of the property 1fr, and the first div will have a min of 100px and a max of whatever it requires.

I must say CSS has advanced a lot to make easier programmers lives.

How to have multiple conditions for one if statement in python

Darian Moody has a nice solution to this challenge in his blog post:

a = 1
b = 2
c = True

rules = [a == 1,
         b == 2,
         c == True]

if all(rules):
    print("Success!")

The all() method returns True when all elements in the given iterable are true. If not, it returns False.

You can read a little more about it in the python docs here and more information and examples here.

(I also answered the similar question with this info here - How to have multiple conditions for one if statement in python)

R - Concatenate two dataframes?

you can use the function

bind_rows(a,b)

from the dplyr library

HTTPS using Jersey Client

Construct your client as such

HostnameVerifier hostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier();
ClientConfig config = new DefaultClientConfig();
SSLContext ctx = SSLContext.getInstance("SSL");
ctx.init(null, myTrustManager, null);
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, ctx));
Client client = Client.create(config);

Ripped from this blog post with more details: http://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with

For information on setting up your certs, see this nicely answered SO question: Using HTTPS with REST in Java

CMD what does /im (taskkill)?

See the doc : it will close all running tasks using the executable file something.exe, more or less like linux' killall

Only numbers. Input number in React

The most effective and simple solution I found:

<input
    type="number"
    name="phone"
    placeholder="Phone number"
    onKeyDown={e => /[\+\-\.\,]$/.test(e.key) && e.preventDefault()}
/>

Getting all types that implement an interface

I got exceptions in the linq-code so I do it this way (without a complicated extension):

private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
{
    IList<Type> implementingTypes = new List<Type>();

    // find all types
    foreach (var interfaceType in interfaces)
        foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
            try
            {
                foreach (var currentType in currentAsm.GetTypes())
                    if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
                        implementingTypes.Add(currentType);
            }
            catch { }

    return implementingTypes;
}

Post-increment and pre-increment within a 'for' loop produce same output

The third statement in the for construct is only executed, but its evaluated value is discarded and not taken care of.
When the evaluated value is discarded, pre and post increment are equal.
They only differ if their value is taken.

How to unzip a file using the command line?

7-Zip, it's open source, free and supports a wide range of formats.

7z.exe x myarchive.zip

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

I was getting this error even though I already had (actually because I already had) Schema::defaultStringLength(191); in my AppServiceProvider.php file.

The reason is because I was trying to set a string value in one of my migrations to a value higher than 191:

Schema::create('order_items', function (Blueprint $table) {
    $table->primary(['order_id', 'product_id', 'attributes']);
    $table->unsignedBigInteger('order_id');
    $table->unsignedBigInteger('product_id');
    $table->string('attributes', 1000); // This line right here
    $table->timestamps();
});

Removing the 1000 or setting it to 191 solved my issue.

"echo -n" prints "-n"

To achieve this there are basically two methods which I frequently use:

1. Using the cursor escape character (\c) with echo -e

Example :

for i in {0..10..2}; do
  echo -e "$i \c"              
done
# 0 2 4 6 8 10
  • -e flag enables the Escape characters in the string.
  • \c brings the Cursor back to the current line.

OR

2. Using the printf command

Example:

for ((i = 0; i < 5; ++i)); do
  printf "$i "
done
# 0 1 2 3 4

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How to check if a string contains a specific text

you can use this code

$a = '';

if(!empty($a))
  echo 'text';

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

Uploading multiple files using formData()

Here is the Vanilla JavaScript solution for this issue -

First, we'll use Array.prototype.forEach() method, as

document.querySelectorAll('input[type=file]') returns an array like object.

Then we'll use the Function.prototype.call() method to assign each element in the array-like object to the this value in the .forEach method.

HTML

<form id="myForm">

    <input type="file" name="myFile" id="myFile_1">
    <input type="file" name="myFile" id="myFile_2">
    <input type="file" name="myFile" id="myFile_3">

    <button type="button" onclick="saveData()">Save</button>

</form>

JavaScript

 function saveData(){
     var data = new FormData(document.getElementById("myForm"));
     var inputs = document.querySelectorAll('input[type=file]');

     Array.prototype.forEach.call(inputs[0].files, function(index){
        data.append('files', index);
     });
     console.log(data.getAll("myFile"));
}

You can view the working example of the same HERE

Mockito - difference between doReturn() and when()

The two syntaxes for stubbing are roughly equivalent. However, you can always use doReturn/when for stubbing; but there are cases where you can't use when/thenReturn. Stubbing void methods is one such. Others include use with Mockito spies, and stubbing the same method more than once.

One thing that when/thenReturn gives you, that doReturn/when doesn't, is type-checking of the value that you're returning, at compile time. However, I believe this is of almost no value - if you've got the type wrong, you'll find out as soon as you run your test.

I strongly recommend only using doReturn/when. There is no point in learning two syntaxes when one will do.

You may wish to refer to my answer at Forming Mockito "grammars" - a more detailed answer to a very closely related question.

PHPUnit assert that an exception was thrown?

The PHPUnit expectException method is very inconvenient because it allows to test only one exception per a test method.

I've made this helper function to assert that some function throws an exception:

/**
 * Asserts that the given callback throws the given exception.
 *
 * @param string $expectClass The name of the expected exception class
 * @param callable $callback A callback which should throw the exception
 */
protected function assertException(string $expectClass, callable $callback)
{
    try {
        $callback();
    } catch (\Throwable $exception) {
        $this->assertInstanceOf($expectClass, $exception, 'An invalid exception was thrown');
        return;
    }

    $this->fail('No exception was thrown');
}

Add it to your test class and call this way:

public function testSomething() {
    $this->assertException(\PDOException::class, function() {
        new \PDO('bad:param');
    });
    $this->assertException(\PDOException::class, function() {
        new \PDO('foo:bar');
    });
}

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

Space between two rows in a table?

You can't change the margin of a table cell. But you CAN change the padding. Change the padding of the TD, which will make the cell larger and push the text away from the side with the increased padding. If you have border lines, however, it still won't be exactly what you want.

Split pandas dataframe in two if it has more than 10 rows

def split_and_save_df(df, name, size, output_dir):
    """
    Split a df and save each chunk in a different csv file.

    Parameters:
        df : pandas df to be splitted
        name : name to give to the output file
        size : chunk size
        output_dir : directory where to write the divided df
    """
    import os
    for i in range(0, df.shape[0],size):
        start  = i
        end    = min(i+size-1, df.shape[0]) 
        subset = df.loc[start:end] 
        output_path = os.path.join(output_dir,f"{name}_{start}_{end}.csv")
        print(f"Going to write into {output_path}")
        subset.to_csv(output_path)
        output_size = os.stat(output_path).st_size
        print(f"Wrote {output_size} bytes")

Including another class in SCSS

Try this:

  1. Create a placeholder base class (%base-class) with the common properties
  2. Extend your class (.my-base-class) with this placeholder.
  3. Now you can extend %base-class in any of your classes (e.g. .my-class).

    %base-class {
       width: 80%;
       margin-left: 10%;
       margin-right: 10%;
    }
    
    .my-base-class {
        @extend %base-class;
    }
    
    .my-class {
        @extend %base-class;
        margin-bottom: 40px;
    }
    

Add a string of text into an input field when user clicks a button

Example for you to work from

HTML:

<input type="text" value="This is some text" id="text" style="width: 150px;" />
<br />
<input type="button" value="Click Me" id="button" />?

jQuery:

<script type="text/javascript">
$(function () {
    $('#button').on('click', function () {
        var text = $('#text');
        text.val(text.val() + ' after clicking');    
    });
});
<script>

Javascript

<script type="text/javascript">
document.getElementById("button").addEventListener('click', function () {
    var text = document.getElementById('text');
    text.value += ' after clicking';
});
</script>

Working jQuery example: http://jsfiddle.net/geMtZ/ ?

Monitoring the Full Disclosure mailinglist

Two generic ways to do the same thing... I'm not aware of any specific open solutions to do this, but it'd be rather trivial to do.

You could write a daily or weekly cron/jenkins job to scrape the previous time period's email from the archive looking for your keyworkds/combinations. Sending a batch digest with what it finds, if anything.

But personally, I'd Setup a specific email account to subscribe to the various security lists you're interested in. Add a simple automated script to parse the new emails for various keywords or combinations of keywords, when it finds a match forward that email on to you/your team. Just be sure to keep the keywords list updated with new products you're using.

You could even do this with a gmail account and custom rules, which is what I currently do, but I have setup an internal inbox in the past with a simple python script to forward emails that were of interest.

How to get raw text from pdf file using java

Extracting all keywords from PDF(from a web page) file on your local machine or Base64 encoded string:

import org.apache.commons.codec.binary.Base64;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class WebPagePdfExtractor {

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();

        System.out.println("From file:   " + webPagePdfExtractor.processRecord(createByteArray()).get("text"));

        System.out.println("From string: " + webPagePdfExtractor.processRecord(getArrayFromBase64EncodedString()).get("text"));
    }

    public Map<String, Object> processRecord(byte[] byteArray) {
        Map<String, Object> map = new HashMap<>();
        try {
            PDFTextStripper stripper = new PDFTextStripper();
            stripper.setSortByPosition(false);
            stripper.setShouldSeparateByBeads(true);

            PDDocument document = PDDocument.load(byteArray);
            String text = stripper.getText(document);
            map.put("text", text.replaceAll("\n|\r|\t", " "));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    private static byte[] getArrayFromBase64EncodedString() {
        String encodedContent = "data:application/pdf;base64,JVBERi0xLjMKJcTl8uXrp/Og0MTGCjQgMCBvYmoKPDwgL0xlbmd0aCA1IDAgUiAvRmlsdGVyIC9GbGF0ZURlY29kZSA+PgpzdHJlYW0KeAGF0E0OgjAQBeA9p3hL3UCHlha2Gg9A0sS1AepPxIDl/rFFErVESDddvPlm8nqU6EFpzARjBCVkLHNkipBzPBsc8UCyt4TKgmCr/9HI+GDqg2x8Luzk8UtfYwX5DVWLnQaLmd+qHTsF3V5QEekWidZuDNpgc7L1FvqGg35fOzPlqslFYJrzZdnkq6YI77TXtrs3GBo7oKvNss9mfhT0IAV+e6CUL5pSTWb0t1tVBKbI5McsXxNmciYKZW5kc3RyZWFtCmVuZG9iago1IDAgb2JqCjE4NQplbmRvYmoKMiAwIG9iago8PCAvVHlwZSAvUGFnZSAvUGFyZW50IDMgMCBSIC9SZXNvdXJjZXMgNiAwIFIgL0NvbnRlbnRzIDQgMCBSIC9NZWRpYUJveCBbMCAwIDU5NSA4NDJdC" +
                "j4+CmVuZG9iago2IDAgb2JqCjw8IC9Qcm9jU2V0IFsgL1BERiAvVGV4dCBdIC9Db2xvclNwYWNlIDw8IC9DczEgNyAwIFIgL0NzMiA4IDAgUiA+PiAvRm9udCA8PAovVFQxIDkgMCBSID4+ID4+CmVuZG9iagoxMCAwIG9iago8PCAvTGVuZ3RoIDExIDAgUiAvTiAxIC9BbHRlcm5hdGUgL0R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3Xx3fUjSneeTmNSlbyjuuX+9Y2JDmF3JOffzxqVOfnuefBXggNmb/gJTtvpCqWQ/TIVSFZ+mQh6ZvkPcRlF+MIr8Ud2SoHvC3OKne1KZ9UU0FiYzVhUqaQgvaGIoMTWwoxnKM67KFOU1BZrGTpfh/uBhz4LEnVtb5/RmvL3ljl7C/Z6ywv3H9W2/0rJYsPTtK5l6W5daN+qqWDHh+6oicYqKpyD9kyocpRTtSXcR8Em1J7muwlW1LexrtSs5JZLuScwa5pXgGyx/hdZxIeA" +
                "JTPMvxBMSaYoSmQ+nHtDywiJbzyzTe7xcfDmR5vTBcyPsKv7yBPEyXopGDxCAHOoUoppRILPQiribnP/IqOjlLka3XEo5eIbu8bCTCqRmej6+99ib/lF6im3/13ItnD8OtF4LyxN+YxQq0iwTyqjsx0mwIFVUkLkZSWbX1dmiLORxlVBGTIWSC" +
                "NNE0wTAxNnJCdIHTeHOcTzt1nM80dUbxARJ9r/0+T2BoAA0leOYPHXrlpnIwoYmg8NPdo9LFdJYupavSQ9JD09Xpmtzw3IjcyNyo3OjcmNzY3LhcWzVUi9WsWqpWVYdUh1arqzXecG+EN9Ib5Y32xnhjvXFem5POpPLJEh5Ff6LMf2vVqgwKOx" +
                "IeHbu64vXswkn3v54zdkzOzp2Oubnjy6B7dMEZfqlnubDymyWVX/SsEFbeWCy3YknJ0NxCWddt/CFxKspCjmFZ7tgfY1ibvokegcNxGL9GKZGsUI5imYqJoV/8GMZcsm0pXJhNRtkbfuofdPmBA3IYu/rV+/Oa6I3VNatqa1fVrF7Xc1xSe4um" +
                "8Xf5df53fnwavfXR+Qud5y5iFJPtvRPjmIQ8JZJlbrdOK+g1EfG2kFBBpY6wxdvy4myRao0tXrSSOtouWuqs7ZH1JrHe1WZqSopTa+JjVOSBGEk/RiVZEgqSgu58RXZfObDIh6OR3+o23uo2RyjHipKn6ZU8Tak9CcETUz5L4pVkSPq3k2cPTBMGYPo2CFUCJx9oLqqqfPitsWvXdX1YtP+x+YemPr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AowMDAwMDAxNzUzIDAwMDAwIG4gCjAwMDAwMDI5OTIgMDAwMDAgbiAKMDAwMDAwMzE2MSAwMDAwMCBuIAowMDAwMDAwNTEyIDAwMDAwIG4gCjAwMDAwMDE3MzIgMDAwMDAgbiAKMDAwMDAwMTc4OSAwMDAwMCBuIAowMDAwMDAyOTcxIDAwMDAwIG4gCjAwMDAwMDMxMTEgMDAwMDAgbiAKMDAwMDAwMzU0NCAwMDAwMCB" +
                "uIAowMDAwMDAzNzk2IDAwMDAwIG4gCjAwMDAwMDg2ODcgMDAwMDAgbiAKMDAwMDAwODcwOCAwMDAwMCBuIAowMDAwMDA4NzI3IDAwMDAwIG4gCjAwMDAwMDg3ODAgMDAwMDAgbiAKMDAwMDAwODc5OSAwMDAwMCBuIAowMDAwMDA4ODE4IDAwMDAwIG4gCjAwMDAwMDg4NDUgMDAwMDAgbiAKMDAwMDAwODg4NyAwMDAwMCBuIAowMDAwMDA4OTA2IDAwMDAwIG4gCnRyYWlsZXIKPDwgL1NpemUgMjYgL1Jvb3QgMTQgMCBSIC9JbmZvIDEgMCBSIC9JRCBbIDxkYjc4M2NhNDM2Mzg4YzI5ZDc5MDQ2NzY3NjUxNjE3OT4KPGRiNzgzY2E0MzYzODhjMjlkNzkwNDY3Njc2NTE2MTc5PiBdID4+CnN0YXJ0eHJlZgo5MTA0CiUlRU9GCg==";
        String content = encodedContent.substring("data:application/pdf;base64," .length());
        return Base64.decodeBase64(content);
    }

    public static byte[] createByteArray() {
        String pathToBinaryData = "/bla-bla/src/main/resources/small.pdf";

        File file = new File(pathToBinaryData);
        if (!file.exists()) {
            System.out.println(" could not be found in folder " + pathToBinaryData);
            return null;
        }

        FileInputStream fin = null;
        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        byte fileContent[] = new byte[(int) file.length()];

        try {
            fin.read(fileContent);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return fileContent;
    }
}

How to execute a MySQL command from a shell script?

All of the previous answers are great. If it is a simple, one line sql command you wish to run, you could also use the -e option.

mysql -h <host> -u<user> -p<password> database -e \
  "SELECT * FROM blah WHERE foo='bar';"

Check if a time is between two times (time DataType)

Let us consider a table which stores the shift details

enter image description here

Please check the SQL queries to generate table and finding the schedule based on an input(time)

Declaring the Table variable

declare @MyShiftTable table(MyShift int,StartTime time,EndTime time)

Adding values to Table variable

insert into @MyShiftTable select 1,'01:17:40.3530000','02:17:40.3530000'
insert into @MyShiftTable select 2,'09:17:40.3530000','03:17:40.3530000'
insert into @MyShiftTable select 3,'10:17:40.3530000','18:17:40.3530000'

Creating another table variable with an additional field named "Flag"

declare @Temp table(MyShift int,StartTime time,EndTime time,Flag int)

Adding values to temporary table with swapping the start and end time

insert into @Temp select MyShift,case when (StartTime>EndTime) then EndTime else StartTime end,case when (StartTime>EndTime) then StartTime else EndTime end,case when (StartTime>EndTime) then 1 else 0 end from @MyShiftTable

Creating input variable to find the Shift

declare @time time=convert(time,'10:12:40.3530000')

Query to find the shift corresponding to the time supplied

select myShift from @Temp where
(@time between StartTime and EndTime and Flag=0) or (@time not between StartTime and EndTime and Flag=1)

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

jQuery: How can I create a simple overlay?

Here is a simple javascript only solution

function displayOverlay(text) {
    $("<table id='overlay'><tbody><tr><td>" + text + "</td></tr></tbody></table>").css({
        "position": "fixed",
        "top": 0,
        "left": 0,
        "width": "100%",
        "height": "100%",
        "background-color": "rgba(0,0,0,.5)",
        "z-index": 10000,
        "vertical-align": "middle",
        "text-align": "center",
        "color": "#fff",
        "font-size": "30px",
        "font-weight": "bold",
        "cursor": "wait"
    }).appendTo("body");
}

function removeOverlay() {
    $("#overlay").remove();
}

Demo:

http://jsfiddle.net/UziTech/9g0pko97/

Gist:

https://gist.github.com/UziTech/7edcaef02afa9734e8f2

Setting the zoom level for a MKMapView

Based on @AdilSoomro's great answer. I have come up with this:

@interface MKMapView (ZoomLevel)
- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel
                   animated:(BOOL)animated;

-(double) getZoomLevel;
@end



@implementation MKMapView (ZoomLevel)

- (void)setCenterCoordinate:(CLLocationCoordinate2D)centerCoordinate
                  zoomLevel:(NSUInteger)zoomLevel animated:(BOOL)animated {
    MKCoordinateSpan span = MKCoordinateSpanMake(0, 360/pow(2, zoomLevel)*self.frame.size.width/256);
    [self setRegion:MKCoordinateRegionMake(centerCoordinate, span) animated:animated];
}


-(double) getZoomLevel {
    return log2(360 * ((self.frame.size.width/256) / self.region.span.longitudeDelta));
}

@end

Javascript Regex: How to put a variable inside a regular expression?

You can always give regular expression as string, i.e. "ReGeX" + testVar + "ReGeX". You'll possibly have to escape some characters inside your string (e.g., double quote), but for most cases it's equivalent.

You can also use RegExp constructor to pass flags in (see the docs).

How to check for a valid URL in Java?

I'd love to post this as a comment to Tendayi Mawushe's answer, but I'm afraid there is not enough space ;)

This is the relevant part from the Apache Commons UrlValidator source:

/**
 * This expression derived/taken from the BNF for URI (RFC2396).
 */
private static final String URL_PATTERN =
        "/^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?/";
//         12            3  4          5       6   7        8 9

/**
 * Schema/Protocol (ie. http:, ftp:, file:, etc).
 */
private static final int PARSE_URL_SCHEME = 2;

/**
 * Includes hostname/ip and port number.
 */
private static final int PARSE_URL_AUTHORITY = 4;

private static final int PARSE_URL_PATH = 5;

private static final int PARSE_URL_QUERY = 7;

private static final int PARSE_URL_FRAGMENT = 9;

You can easily build your own validator from there.

how to send a post request with a web browser

with a form, just set method to "post"

<form action="blah.php" method="post">
  <input type="text" name="data" value="mydata" />
  <input type="submit" />
</form>

String's Maximum length in Java - calling length() method

I have a 2010 iMac with 8GB of RAM, running Eclipse Neon.2 Release (4.6.2) with Java 1.8.0_25. With the VM argument -Xmx6g, I ran the following code:

StringBuilder sb = new StringBuilder();
for (int i = 0; i < Integer.MAX_VALUE; i++) {
    try {
        sb.append('a');
    } catch (Throwable e) {
        System.out.println(i);
        break;
    }
}
System.out.println(sb.toString().length());

This prints:

Requested array size exceeds VM limit
1207959550

So, it seems that the max array size is ~1,207,959,549. Then I realized that we don't actually care if Java runs out of memory: we're just looking for the maximum array size (which seems to be a constant defined somewhere). So:

for (int i = 0; i < 1_000; i++) {
    try {
        char[] array = new char[Integer.MAX_VALUE - i];
        Arrays.fill(array, 'a');
        String string = new String(array);
        System.out.println(string.length());
    } catch (Throwable e) {
        System.out.println(e.getMessage());
        System.out.println("Last: " + (Integer.MAX_VALUE - i));
        System.out.println("Last: " + i);
    }
}

Which prints:

Requested array size exceeds VM limit
Last: 2147483647
Last: 0
Requested array size exceeds VM limit
Last: 2147483646
Last: 1
Java heap space
Last: 2147483645
Last: 2

So, it seems the max is Integer.MAX_VALUE - 2, or (2^31) - 3

P.S. I'm not sure why my StringBuilder maxed out at 1207959550 while my char[] maxed out at (2^31)-3. It seems that AbstractStringBuilder doubles the size of its internal char[] to grow it, so that probably causes the issue.

How do I set up curl to permanently use a proxy?

Many UNIX programs respect the http_proxy environment variable, curl included. The format curl accepts is [protocol://]<host>[:port].

In your shell configuration:

export http_proxy http://proxy.server.com:3128

For proxying HTTPS requests, set https_proxy as well.

Curl also allows you to set this in your .curlrc file (_curlrc on Windows), which you might consider more permanent:

http_proxy=http://proxy.server.com:3128

Terminating idle mysql connections

I don't see any problem, unless you are not managing them using a connection pool.

If you use connection pool, these connections are re-used instead of initiating new connections. so basically, leaving open connections and re-use them it is less problematic than re-creating them each time.

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

In VS 2015, removing 'Analyzers' under 'References' solved the issue

How to calculate an angle from three points?

my angle demo program

Recently, I too have the same problem... In Delphi It's very similar to Objective-C.

procedure TForm1.FormPaint(Sender: TObject);
var ARect: TRect;
    AWidth, AHeight: Integer;
    ABasePoint: TPoint;
    AAngle: Extended;
begin
  FCenter := Point(Width div 2, Height div 2);
  AWidth := Width div 4;
  AHeight := Height div 4;
  ABasePoint := Point(FCenter.X+AWidth, FCenter.Y);
  ARect := Rect(Point(FCenter.X - AWidth, FCenter.Y - AHeight),
    Point(FCenter.X + AWidth, FCenter.Y + AHeight));
  AAngle := ArcTan2(ClickPoint.Y-Center.Y, ClickPoint.X-Center.X) * 180 / pi;
  AngleLabel.Caption := Format('Angle is %5.2f', [AAngle]);
  Canvas.Ellipse(ARect);
  Canvas.MoveTo(FCenter.X, FCenter.Y);
  Canvas.LineTo(FClickPoint.X, FClickPoint.Y);
  Canvas.MoveTo(FCenter.X, FCenter.Y);
  Canvas.LineTo(ABasePoint.X, ABasePoint.Y);
end;

Simulate Keypress With jQuery

The keypress event from jQuery is meant to do this sort of work. You can trigger the event by passing a string "keypress" to .trigger(). However to be more specific you can actually pass a jQuery.Event object (specify the type as "keypress") as well and provide any properties you want such as the keycode being the spacebar.

http://docs.jquery.com/Events/trigger#eventdata

Read the above documentation for more details.

How do I populate a JComboBox with an ArrayList?

By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:

private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
    YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
    return new DefaultComboBoxModel<>(comboBoxModel);
}

In your GUI code you set the entire list into your JComboBox as follows:

DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);

How do I use a regex in a shell script?

To complement the existing helpful answers:

Using Bash's own regex-matching operator, =~, is a faster alternative in this case, given that you're only matching a single value already stored in a variable:

set -- '12-34-5678' # set $1 to sample value

kREGEX_DATE='^[0-9]{2}[-/][0-9]{2}[-/][0-9]{4}$' # note use of [0-9] to avoid \d
[[ $1 =~ $kREGEX_DATE ]]
echo $? # 0 with the sample value, i.e., a successful match

Note, however, that the caveat re using flavor-specific regex constructs such as \d equally applies: While =~ supports EREs (extended regular expressions), it also supports the host platform's specific extension - it's a rare case of Bash's behavior being platform-dependent.

To remain portable (in the context of Bash), stick to the POSIX ERE specification.

Note that =~ even allows you to define capture groups (parenthesized subexpressions) whose matches you can later access through Bash's special ${BASH_REMATCH[@]} array variable.

Further notes:

  • $kREGEX_DATE is used unquoted, which is necessary for the regex to be recognized as such (quoted parts would be treated as literals).

  • While not always necessary, it is advisable to store the regex in a variable first, because Bash has trouble with regex literals containing \.

    • E.g., on Linux, where \< is supported to match word boundaries, [[ 3 =~ \<3 ]] && echo yes doesn't work, but re='\<3'; [[ 3 =~ $re ]] && echo yes does.
  • I've changed variable name REGEX_DATE to kREGEX_DATE (k signaling a (conceptual) constant), so as to ensure that the name isn't an all-uppercase name, because all-uppercase variable names should be avoided to prevent conflicts with special environment and shell variables.

How to write a simple Java program that finds the greatest common divisor between two numbers?

One way to do it is the code below:

        int gcd = 0;
        while (gcdNum2 !=0 && gcdNum1 != 0 ) {
        if(gcdNum1 % gcdNum2 == 0){
            gcd = gcdNum2;
        }
            int aux = gcdNum2; 
            gcdNum2 = gcdNum1 % gcdNum2;
            gcdNum1 = aux;
    }

You do not need recursion to do this.

And be careful, it says that when a number is zero, then the GCD is the number that is not zero.

    while (gcdNum1 == 0) {
    gcdNum1 = 0;
}

You should modify this to fulfill the requirement.

I am not going to tell you how to modify your code entirely, only how to calculate the gcd.

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

jQuery’s .bind() vs. .on()

As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.

jQuery API documentation for .bind()

How can I give an imageview click effect like a button on Android?

You can do this with a single image using something like this:

     //get the image view
    ImageView imageView = (ImageView)findViewById(R.id.ImageView);

    //set the ontouch listener
    imageView.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN: {
                    ImageView view = (ImageView) v;
                    //overlay is black with transparency of 0x77 (119)
                    view.getDrawable().setColorFilter(0x77000000,PorterDuff.Mode.SRC_ATOP);
                    view.invalidate();
                    break;
                }
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL: {
                    ImageView view = (ImageView) v;
                    //clear the overlay
                    view.getDrawable().clearColorFilter();
                    view.invalidate();
                    break;
                }
            }

            return false;
        }
    });

I will probably be making this into a subclass of ImageView (or ImageButton as it is also a subclass of ImageView) for easier re-usability, but this should allow you to apply a "selected" look to an imageview.

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

How do I get JSON data from RESTful service using Python?

You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:

import httplib2 as http
import json

try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

headers = {
    'Accept': 'application/json',
    'Content-Type': 'application/json; charset=UTF-8'
}

uri = 'http://yourservice.com'
path = '/path/to/resource/'

target = urlparse(uri+path)
method = 'GET'
body = ''

h = http.Http()

# If you need authentication some example:
if auth:
    h.add_credentials(auth.user, auth.password)

response, content = h.request(
        target.geturl(),
        method,
        body,
        headers)

# assume that content is a json reply
# parse content with the json module
data = json.loads(content)

Get Line Number of certain phrase in file Python

Open your file, and then do something like...

for line in f:
    nlines += 1
    if (line.find(phrase) >= 0):
        print "Its here.", nlines

There are numerous ways of reading lines from files in Python, but the for line in f technique is more efficient than most.

Wait until a process ends

Try this:

string command = "...";
var process = Process.Start(command);
process.WaitForExit();

C# : Out of Memory exception

OutOfMemoryException (on 32-bit machines) is just as often about Fragmentation as actual hard limits on memory - you'll find lots about this, but here's my first google hit briefly discussing it: http://blogs.msdn.com/b/joshwil/archive/2005/08/10/450202.aspx. (@Anthony Pegram is referring to the same problem in his comment above).

That said, there is one other possibility that comes to mind for your code above: As you're using the "IEnumerable" constructor to the List, you may not giving the object any hints as to the size of the collection you're passing to the List constructor. If the object you are passing is is not a collection (does not implement the ICollection interface), then behind-the-scenes the List implementation is going to need to grow several (or many) times, each time leaving behind a too-small array that needs to be garbage collected. The garbage collector probably won't get to those discarded arrays fast enough, and you'll get your error.

The simplest fix for this would be to use the List(int capacity) constructor to tell the framework what backing array size to allocate (even if you're estimating and just guessing "50000" for example), and then use the AddRange(IEnumerable collection) method to actually populate your list.

So, simplest "Fix" if I'm right: replace

List<Vehicle> vList = new List<Vehicle>(selectedVehicles);

with

List<Vehicle> vList = new List<Vehicle>(50000);  
vList.AddRange(selectedVehicles);

All the other comments and answers still apply in terms of overall design decisions - but this might be a quick fix.

Note (as @Alex commented below), this is only an issue if selectedVehicles is not an ICollection.

How to change RGB color to HSV?

FIRST: make sure you have a color as a bitmap, like this:

Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
paintcolor = bmp.GetPixel(e.X, e.Y);

(e is from the event handler wich picked my color!)

What I did when I had this problem a whilke ago, I first got the rgba (red, green, blue and alpha) values. Next I created 3 floats: float hue, float saturation, float brightness. Then you simply do:

hue = yourcolor.Gethue;
saturation = yourcolor.GetSaturation;
brightness = yourcolor.GetBrightness;

The whole lot looks like this:

Bitmap bmp = (Bitmap)pictureBox1.Image.Clone();
            paintcolor = bmp.GetPixel(e.X, e.Y);
            float hue;
            float saturation;
            float brightness;
            hue = paintcolor.GetHue();
            saturation = paintcolor.GetSaturation();
            brightness = paintcolor.GetBrightness();

If you now want to display them in a label, just do:

yourlabelname.Text = hue.ToString;
yourlabelname.Text = saturation.ToString;
yourlabelname.Text = brightness.ToString;

Here you go, you now have RGB Values into HSV values :)

Hope this helps

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

$(document).ready(function(){
   // Your code here
});

Would seem to do what you are after.

Jquery function BEFORE form submission

You can do something like the following these days by referencing the "beforeSubmit" jquery form event. I'm disabling and enabling the submit button to avoid duplicate requests, submitting via ajax, returning a message that's a json array and displaying the information in a pNotify:

jQuery('body').on('beforeSubmit', "#formID", function() {
    $('.submitter').prop('disabled', true);
    var form = $('#formID');
    $.ajax({
        url    : form.attr('action'),
        type   : 'post',
        data   : form.serialize(),
        success: function (response)
        {
            response = jQuery.parseJSON(response);
            new PNotify({
                text: response.message,
                type: response.status,
                styling: 'bootstrap3',
                delay: 2000,
            });
            $('.submitter').prop('disabled', false);
        },
        error  : function ()
        {
            console.log('internal server error');
        }
    });
});

How to kill all active and inactive oracle sessions for user

For Oracle 11g this may not work as you may receive an error like below

Error report:
SQL Error: ORA-00026: missing or invalid session ID
00026. 00000 -  "missing or invalid session ID"
*Cause:    Missing or invalid session ID string for ALTER SYSTEM KILL SESSION.
*Action:   Retry with a valid session ID.

To rectify this, use below code to identify the sessions

SQL> select inst_id,sid,serial# from gv$session or v$session

NOTE : v$session do not have inst_id field

and Kill them using

alter system kill session 'sid,serial,@inst_id' IMMEDIATE;

Reloading module giving NameError: name 'reload' is not defined

For >= Python3.4:

import importlib
importlib.reload(module)

For <= Python3.3:

import imp
imp.reload(module)

For Python2.x:

Use the in-built reload() function.

reload(module)

Initializing a two dimensional std::vector

The recommended approach is to use fill constructor to initialize a two-dimensional vector with a given default value :

std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));

where, M and N are dimensions for your 2D vector.

Datagridview full row selection but get single cell value

Use Cell Click as other methods mentioned will fire upon data binding, not useful if you want the selected value, then the form to close.

private void dgvProducts_CellClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvProducts.SelectedCells.Count > 0) // Checking to see if any cell is selected
    {
        int mSelectedRowIndex = dgvProducts.SelectedCells[0].RowIndex;

        DataGridViewRow mSelectedRow = dgvProducts.Rows[mSelectedRowIndex];

        string mCatagoryName = Convert.ToString(mSelectedRow.Cells[1].Value);

        SomeOtherMethod(mProductName); // Passing the name to where ever you need it

        this.close();
    }
}

Simplest way to set image as JPanel background

Draw the image on the background of a JPanel that is added to the frame. Use a layout manager to normally add your buttons and other components to the panel. If you add other child panels, perhaps you want to set child.setOpaque(false).

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;
import java.net.URL;

public class BackgroundImageApp {
    private JFrame frame;

    private BackgroundImageApp create() {
        frame = createFrame();
        frame.getContentPane().add(createContent());

        return this;
    }

    private JFrame createFrame() {
        JFrame frame = new JFrame(getClass().getName());
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        return frame;
    }

    private void show() {
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }

    private Component createContent() {
        final Image image = requestImage();

        JPanel panel = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                g.drawImage(image, 0, 0, null);
            }
        };

        panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
        for (String label : new String[]{"One", "Dois", "Drei", "Quatro", "Peace"}) {
            JButton button = new JButton(label);
            button.setAlignmentX(Component.CENTER_ALIGNMENT);
            panel.add(Box.createRigidArea(new Dimension(15, 15)));
            panel.add(button);
        }

        panel.setPreferredSize(new Dimension(500, 500));

        return panel;
    }

    private Image requestImage() {
        Image image = null;

        try {
            image = ImageIO.read(new URL("http://www.johnlennon.com/wp-content/themes/jl/images/home-gallery/2.jpg"));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return image;
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BackgroundImageApp().create().show();
            }
        });
    }
}

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

Determine which element the mouse pointer is on top of in JavaScript

You can look at the target of the mouseover event on some suitable ancestor:

var currentElement = null;

document.addEventListener('mouseover', function (e) {
    currentElement = e.target;
});

Here’s a demo.

How to convert all tables in database to one collation?

If you want a copy-paste bash script:

var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )

var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'

echo $var | cut -d " " -f2- | mysql -uroot -p zabbix

Change zabbix to your database name.

CSS: How to change colour of active navigation page menu

The CSS :active state means the active state of the clicked link - the moment when you clicked on it, but not released the mouse button yet, for example. It doesn't know which page you're on and can't apply any styles to the menu items.

To fix your problem you have to create a class and add it manually to the current page's menu:

a.active { color: #f00 }

<ul>
    <li><a href="index.php" class="active">HOME</a></li>
    <li><a href="two.php">PORTFOLIO</a></li>
    <li><a href="three.php">ABOUT</a></li>
    <li><a href="four.php">CONTACT</a></li>
    <li><a href="five.php">SHOP</a></li>
</ul>

In C - check if a char exists in a char array

strchr for searching a char from start (strrchr from the end):

  char str[] = "This is a sample string";

  if (strchr(str, 'h') != NULL) {
      /* h is in str */
  }

When to use in vs ref vs out

Just to clarify on OP's comment that the use on ref and out is a "reference to a value type or struct declared outside the method", which has already been established in incorrect.

Consider the use of ref on a StringBuilder, which is a reference type:

private void Nullify(StringBuilder sb, string message)
{
    sb.Append(message);
    sb = null;
}

// -- snip --

StringBuilder sb = new StringBuilder();
string message = "Hi Guy";
Nullify(sb, message);
System.Console.WriteLine(sb.ToString());

// Output
// Hi Guy

As apposed to this:

private void Nullify(ref StringBuilder sb, string message)
{
    sb.Append(message);
    sb = null;
}

// -- snip --

StringBuilder sb = new StringBuilder();
string message = "Hi Guy";
Nullify(ref sb, message);
System.Console.WriteLine(sb.ToString());

// Output
// NullReferenceException

How to Select Every Row Where Column Value is NOT Distinct

Rather than using sub queries in where condition which will increase the query time where records are huge.

I would suggest to use Inner Join as a better option to this problem.

Considering the same table this could give the result

SELECT EmailAddress, CustomerName FROM Customers as a 
Inner Join Customers as b on a.CustomerName <> b.CustomerName and a.EmailAddress = b.EmailAddress

For still better results I would suggest you to use CustomerID or any unique field of your table. Duplication of CustomerName is possible.

How to return a dictionary | Python


def query(id):
    for line in file:
        table = line.split(";")
        if id == int(table[0]):
             yield table
    
    

id = int(input("Enter the ID of the user: "))
for id_, name, city in query(id):
  print("ID: " + id_)
  print("Name: " + name)
  print("City: " + city)
file.close()

Using yield..

ASP.NET Setting width of DataBound column in GridView

hey recently i figured it out how to set width if your gridview databound with sql dataset.first set these control RowStyle-Wrap="false" HeaderStyle-Wrap="false" and then you can set the column width as much as you like. ex : ItemStyle-Width="150px" HeaderStyle-Width="150px"

Installing mysql-python on Centos

I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.

For me it worked with the following command:

# pip install mysql-python

Note pre-requisites here:

Install Python pip:

# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm

# yum -y update
Reboot the machine (if kernel is also updated)

# yum -y install python-pip

Install Python devel packages:

# yum install python-devel

Install MySQL devel packages:

# yum install mysql-devel

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

How do I get the classes of all columns in a data frame?

You can simple make use of lapply or sapply builtin functions.

lapply will return you a list -

lapply(dataframe,class)

while sapply will take the best possible return type ex. Vector etc -

sapply(dataframe,class)

Both the commands will return you all the column names with their respective class.

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

Checking for an empty file in C++

How about (not elegant way though )

int main( int argc, char* argv[] )
{
    std::ifstream file;
    file.open("example.txt");

    bool isEmpty(true);
    std::string line;

    while( file >> line ) 
        isEmpty = false;

        std::cout << isEmpty << std::endl;
}

DataGridView changing cell background color

protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[3].Text != "0")
        {
            for (int i = 0; i <= e.Row.Cells.Count - 1; i++)
            {
                e.Row.Cells[i].BackColor = System.Drawing.Color.Beige;
            }
        }
    }
}

How to call webmethod in Asp.net C#

One problem here is that your method expects int values while you are passing string from ajax call. Try to change it to string and parse inside the webmethod if necessary :

[System.Web.Services.WebMethod]
public static string AddTo_Cart(string quantity, string itemId)
{
    //parse parameters here
    SpiritsShared.ShoppingCart.AddItem(itemId, quantity);      
    return "Add";
}

Edit : or Pass int parameters from ajax call.

Two-dimensional array in Swift

From the docs:

You can create multidimensional arrays by nesting pairs of square brackets, where the name of the base type of the elements is contained in the innermost pair of square brackets. For example, you can create a three-dimensional array of integers using three sets of square brackets:

var array3D: [[[Int]]] = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]

When accessing the elements in a multidimensional array, the left-most subscript index refers to the element at that index in the outermost array. The next subscript index to the right refers to the element at that index in the array that’s nested one level in. And so on. This means that in the example above, array3D[0] refers to [[1, 2], [3, 4]], array3D[0][1] refers to [3, 4], and array3D[0][1][1] refers to the value 4.

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

Is there a library function for Root mean square error (RMSE) in python?

sklearn >= 0.22.0

sklearn.metrics has a mean_squared_error function with a squared kwarg (defaults to True). Setting squared to False will return the RMSE.

from sklearn.metrics import mean_squared_error

rms = mean_squared_error(y_actual, y_predicted, squared=False)

sklearn < 0.22.0

sklearn.metrics has a mean_squared_error function. The RMSE is just the square root of whatever it returns.

from sklearn.metrics import mean_squared_error
from math import sqrt

rms = sqrt(mean_squared_error(y_actual, y_predicted))

How can I split a text file using PowerShell?

Sounds like a job for the UNIX command split:

split MyBigFile.csv

Just split my 55 GB csv file in 21k chunks in less than 10 minutes.

It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win

How do I get 'date-1' formatted as mm-dd-yyyy using PowerShell?

You can use the .tostring() method with datetime format specifiers to format to whatever you need:

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

(Get-Date).AddDays(-1).ToString('MM-dd-yyyy')
11-01-2013

How to call two methods on button's onclick method in HTML or JavaScript?

The modern event handling method:

element.addEventListener('click', startDragDrop, false);
element.addEventListener('click', spyOnUser, false);

The first argument is the event, the second is the function and the third specifies whether to allow event bubbling.

From QuirksMode:

W3C’s DOM Level 2 Event specification pays careful attention to the problems of the traditional model. It offers a simple way to register as many event handlers as you like for the same event on one element.

The key to the W3C event registration model is the method addEventListener(). You give it three arguments: the event type, the function to be executed and a boolean (true or false) that I’ll explain later on. To register our well known doSomething() function to the onclick of an element you do:

Full details here: http://www.quirksmode.org/js/events_advanced.html

Using jQuery

if you're using jQuery, there is a nice API for event handling:

$('#myElement').bind('click', function() { doStuff(); });
$('#myElement').bind('click', function() { doMoreStuff(); });
$('#myElement').bind('click', doEvenMoreStuff);

Full details here: http://api.jquery.com/category/events/

Using 'starts with' selector on individual class names

Classes that start with "apple-" plus classes that contain " apple-"

$("div[class^='apple-'],div[class*=' apple-']")

Link to all Visual Studio $ variables

Anybody working on legacy software using Visual Studio 6.0 will find that $(Configuration) and $(ProjectDir) macro's are not defined. For post-build/pre-build events, give a relative path starting with the location of your .dsw file(workspace) as the starting point. In relative path dot represents the current directory and .. represents the parent directory. Give a relative path to the file that need to be processed. Example: ( copy /y .\..\..\Debug\mylib.dll .\..\MyProject\Debug\ )

How to change angular port from 4200 to any other

If you want to use NodeJS environment variable to set up the value of the port of Angular CLI dev server, following approach is possible:

  • create NodeJS script, which will have an access to the environment variable (say, DEV_SERVER_PORT) and could run ng serve with --port parameter value taken from that variable (child_process might be our friend here):
const child_process = require('child_process');
const child = child_process.exec(`ng serve --port=${process.env.DEV_SERVER_PORT}`);
child.stdout.on('data', data => console.log(data.toString()));
  • update package.json to provide this script running via npm
  • do not forget to set up DEV_SERVER_PORT environment variable (can be done via dotenv)

Here is also the complete description of this approach: How to change Angular CLI Development Server Port via .env.

installing apache: no VCRUNTIME140.dll

I was gone through same problem & I resolved it by following steps.

  1. Uninstall earlier version of wamp server, which you are trying to install.
  2. Install which ever file supports to your configuration (64, 86) from en this link
  3. Restart your computer.
  4. Install wampserver now.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

Javascript: open new page in same window

<a href="javascript:;" onclick="window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'">Go</a>;

How to create a function in a cshtml template?

why not just declare that function inside the cshtml file?

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

<h2>index</h2>
@GetSomeString()

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

How can I open a URL in Android's web browser from my application?

If you want to show user a dialogue with all browser list, so he can choose preferred, here is sample code:

private static final String HTTPS = "https://";
private static final String HTTP = "http://";

public static void openBrowser(final Context context, String url) {

     if (!url.startsWith(HTTP) && !url.startsWith(HTTPS)) {
            url = HTTP + url;
     }

     Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
     context.startActivity(Intent.createChooser(intent, "Choose browser"));// Choose browser is arbitrary :)

}

Remove specific commit

Approch 1

First get the commit hash(ex:1406cd61) that you need to revert. simple fix will be below command,

$ git revert 1406cd61

if you have commit more changes related to 1406cd61 files after 1406cd61 commit, Above simple command will not work. Then you have to do the below steps, which is cherry picking.

Approch 2

Please follow below squesnce of actions, Since we are using --force you need to have admin rights over the git repo to do this.

Step 1: Find the commit before the commit you want to remove git log

Step 2: Checkout that commit git checkout <commit hash>

Step 3: Make a new branch using your current checkout commit git checkout -b <new branch>

Step 4: Now you need to add the commit after the removed commit git cherry-pick <commit hash>

Step 5: Now repeat Step 4 for all other commits you want to keep.

Step 6: Once all commits have been added to your new branch and have been commited. Check that everything is in the correct state and working as intended. Double check everything has been commited: git status

Step 7: Switch to your broken branch git checkout <broken branch>

Step 8: Now perform a hard reset on the broken branch to the commit prior to the one your want to remove git reset --hard <commit hash>

Step 9: Merge your fixed branch into this branch git merge <branch name>

Step 10: Push the merged changes back to origin. WARNING: This will overwrite the remote repo! git push --force origin <branch name>

You can do the process without creating a new branch by replacing Step 2 & 3 with Step 8 then not carry out Step 7 & 9.

How to listen for a WebView finishing loading a URL?

@ian this is not 100% accurate. If you have several iframes in a page you will have multiple onPageFinished (and onPageStarted). And if you have several redirects it may also fail. This approach solves (almost) all the problems:

boolean loadingFinished = true;
boolean redirect = false;

mWebView.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String urlNewString) {
        if (!loadingFinished) {
            redirect = true;
        }

        loadingFinished = false;
        webView.loadUrl(urlNewString);
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url) {
        loadingFinished = false;
        //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        if (!redirect) {
           loadingFinished = true;
            //HIDE LOADING IT HAS FINISHED
        } else {
            redirect = false; 
        }
    }
});

UPDATE:

According to the documentation: onPageStarted will NOT be called when the contents of an embedded frame changes, i.e. clicking a link whose target is an iframe.

I found a specific case like that on Twitter where only a pageFinished was called and messed the logic a bit. To solve that I added a scheduled task to remove loading after X seconds. This is not needed in all the other cases.

UPDATE 2:

Now with current Android WebView implementation:

boolean loadingFinished = true;
boolean redirect = false;

    mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, WebResourceRequest request) {
            if (!loadingFinished) {
               redirect = true;
            }

            loadingFinished = false;
            webView.loadUrl(request.getUrl().toString());
            return true;
        }

        @Override
        public void onPageStarted(
                WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            loadingFinished = false;
            //SHOW LOADING IF IT ISNT ALREADY VISIBLE  
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (!redirect) {
               loadingFinished = true;
                //HIDE LOADING IT HAS FINISHED
            } else {
                redirect = false; 
            }
        }
    });

Adding subscribers to a list using Mailchimp's API v3

I got it working. I was adding the authentication to the header incorrectly:

$apikey = '<api_key>';
            $auth = base64_encode( 'user:'.$apikey );

            $data = array(
                'apikey'        => $apikey,
                'email_address' => $email,
                'status'        => 'subscribed',
                'merge_fields'  => array(
                    'FNAME' => $name
                )
            );
            $json_data = json_encode($data);

            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, 'https://us2.api.mailchimp.com/3.0/lists/<list_id>/members/');
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
                                                        'Authorization: Basic '.$auth));
            curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);                                                                                                                  

            $result = curl_exec($ch);

            var_dump($result);
            die('Mailchimp executed');

how to get curl to output only http response body (json) and no other headers etc

#!/bin/bash

req=$(curl -s -X GET http://host:8080/some/resource -H "Accept: application/json") 2>&1
echo "${req}"

COUNT DISTINCT with CONDITIONS

Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

select count(distinct(concat(tag,entryId)))
from customers
where id>0

In the output it will display the count of unique values Hope this helps

How to link home brew python version and set it as default

The problem with me is that I have so many different versions of python, so it opens up a different python3.7 even after I did brew link. I did the following additional steps to make it default after linking

First, open up the document setting up the path of python

 nano ~/.bash_profile

Then something like this shows up:

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

# Setting PATH for Python 3.6
# The original version is saved in .bash_profile.pysave
PATH="/Library/Frameworks/Python.framework/Versions/3.6/bin:${PATH}"
export PATH

The thing here is that my Python for brew framework is not in the Library Folder!! So I changed the framework for python 3.7, which looks like follows in my system

# Setting PATH for Python 3.7
# The original version is saved in .bash_profile.pysave
PATH="/usr/local/Frameworks/Python.framework/Versions/3.7/bin:${PATH}"
export PATH

Change and save the file. Restart the computer, and typing in python3.7, I get the python I installed for brew.

Not sure if my case is applicable to everyone, but worth a try. Not sure if the framework path is the same for everyone, please made sure before trying out.

How to SELECT a dropdown list item by value programmatically

ddlPageSize.Items.FindByValue("25").Selected = true;