Programs & Examples On #Minecraft

Use this tag for programming-related questions about the computer game Minecraft. Note: Minecraft questions are generally OFF-TOPIC on Stack Overflow unless they relate to creating mods or otherwise developing for the game. Questions related to game play are best asked on gaming.stackexchange.com.

How to redirect DNS to different ports

Possible solutions:

  1. Use nginx on the server as a proxy that will listen to port A and multiplex to port B or C.

  2. If you use AWS you can use the load balancer to redirect the request to specific port based on the host.

Launch Minecraft from command line - username and password as prefix

You can do this, you just need to circumvent the launcher.

In %appdata%\.minecraft\bin (or ~/.minecraft/bin on unixy systems), there is a minecraft.jar file. This is the actual game - the launcher runs this.

Invoke it like so:

java -Xms512m -Xmx1g -Djava.library.path=natives/ -cp "minecraft.jar;lwjgl.jar;lwjgl_util.jar" net.minecraft.client.Minecraft <username> <sessionID>

Set the working directory to .minecraft/bin.

To get the session ID, POST (request this page):

https://login.minecraft.net?user=<username>&password=<password>&version=13

You'll get a response like this:

1343825972000:deprecated:SirCmpwn:7ae9007b9909de05ea58e94199a33b30c310c69c:dba0c48e1c584963b9e93a038a66bb98

The fourth field is the session ID. More details here. Read those details, this answer is outdated

Here's an example of logging in to minecraft.net in C#.

Java Could not reserve enough space for object heap error

4gb RAM doesn't mean you can use it all for java process. Lots of RAM is needed for system processes. Dont go above 2GB or it will be trouble some.

Before starting jvm just check how much RAM is available and then set memory accordingly.

Send and receive messages through NSNotificationCenter in Objective-C?

SWIFT 5.1 of selected answer for newbies

class TestClass {
    deinit {
        // If you don't remove yourself as an observer, the Notification Center
        // will continue to try and send notification objects to the deallocated
        // object.
        NotificationCenter.default.removeObserver(self)
    }

    init() {
        super.init()

        // Add this instance of TestClass as an observer of the TestNotification.
        // We tell the notification center to inform us of "TestNotification"
        // notifications using the receiveTestNotification: selector. By
        // specifying object:nil, we tell the notification center that we are not
        // interested in who posted the notification. If you provided an actual
        // object rather than nil, the notification center will only notify you
        // when the notification was posted by that particular object.

        NotificationCenter.default.addObserver(self, selector: #selector(receiveTest(_:)), name: NSNotification.Name("TestNotification"), object: nil)
    }

    @objc func receiveTest(_ notification: Notification?) {
        // [notification name] should always be @"TestNotification"
        // unless you use this method for observation of other notifications
        // as well.

        if notification?.name.isEqual(toString: "TestNotification") != nil {
            print("Successfully received the test notification!")
        }
    }
}

... somewhere else in another class ...

 func someMethod(){
        // All instances of TestClass will be notified
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "TestNotification"), object: self)
 }

WHERE statement after a UNION in SQL?

You probably need to wrap the UNION in a sub-SELECT and apply the WHERE clause afterward:

SELECT * FROM (
    SELECT * FROM Table1 WHERE Field1 = Value1
    UNION
    SELECT * FROM Table2 WHERE Field1 = Value2
) AS t WHERE Field2 = Value3

Basically, the UNION is looking for two complete SELECT statements to combine, and the WHERE clause is part of the SELECT statement.

It may make more sense to apply the outer WHERE clause to both of the inner queries. You'll probably want to benchmark the performance of both approaches and see which works better for you.

How can I check if an InputStream is empty without reading from it?

How about using inputStreamReader.ready() to find out?

import java.io.InputStreamReader;

/// ...

InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
    // do something
}

// ...

Set focus on textbox in WPF

txtCompanyID.Focusable = true;
Keyboard.Focus(txtCompanyID);

msdn:

There can be only one element on the whole desktop that has keyboard focus. In WPF, the element that has keyboard focus will have IsKeyboardFocused set to true.

You could break after the setting line and check the value of IsKeyboardFocused property. Also check if you really reach that line or maybe you set some other element to get focus after that.

Equivalent of *Nix 'which' command in PowerShell?

I have this which advanced function in my PowerShell profile:

    function which {
    <#
    .SYNOPSIS
    Identifies the source of a PowerShell command.
    .DESCRIPTION
    Identifies the source of a PowerShell command. External commands (Applications) are identified by the path to the executable
    (which must be in the system PATH); cmdlets and functions are identified as such and the name of the module they are defined in
    provided; aliases are expanded and the source of the alias definition is returned.
    .INPUTS
    No inputs; you cannot pipe data to this function.
    .OUTPUTS
    .PARAMETER Name
    The name of the command to be identified.
    .EXAMPLE
    PS C:\Users\Smith\Documents> which Get-Command
    
    Get-Command: Cmdlet in module Microsoft.PowerShell.Core
    
    (Identifies type and source of command)
    .EXAMPLE
    PS C:\Users\Smith\Documents> which notepad
    
    C:\WINDOWS\SYSTEM32\notepad.exe
    
    (Indicates the full path of the executable)
    #>
        param(
        [String]$name
        )
    
        $cmd = Get-Command $name
        $redirect = $null
        switch ($cmd.CommandType) {
            "Alias"          { "{0}: Alias for ({1})" -f $cmd.Name, (. { which $cmd.Definition } ) }
            "Application"    { $cmd.Source }
            "Cmdlet"         { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "Function"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "Workflow"       { "{0}: {1} {2}" -f $cmd.Name, $cmd.CommandType, (. { if ($cmd.Source.Length) { "in module {0}" -f $cmd.Source} else { "from unspecified source" } } ) }
            "ExternalScript" { $cmd.Source }
            default          { $cmd }
        }
    }

Using WGET to run a cronjob PHP

wget -O- http://www.example.com/cronit.php >> /dev/null

This means send the file to stdout, and send stdout to /dev/null

What is initial scale, user-scalable, minimum-scale, maximum-scale attribute in meta tag?

user-scalable:

user-scalable=yes (default) to allow the user to zoom in or out on the web page;

user-scalable=no to prevent the user from zooming in or out.

You can get more detailed information by reading the following articles.

Demo Code (recommended)

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta http-equiv="X-UA-Compatible" content="IE=edge">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=0.5, maximum-scale=3.0">_x000D_
</head>_x000D_
<body>_x000D_
    <header>_x000D_
    </header>_x000D_
    <main>_x000D_
        <section>_x000D_
            <h1>do not using <mark>user-scalable=no</mark></h1>_x000D_
        </section>_x000D_
    </main>_x000D_
    <footer>_x000D_
    </footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

javascript change background color on click

You can sets the body's background colour using document.body.style.backgroundColor = "red"; so this can be put into a function that's called when the user clicks. The next part can be done by using document.getElementByID("divID").style.backgroundColor = "red"; window.setTimeout("yourFunction()",10000); which calls yourFunction in 10 seconds to change the colour back.

Magento - Retrieve products with a specific attribute value

To Get TEXT attributes added from admin to front end on product listing page.

Thanks Anita Mourya

I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.

METHOD 1

on list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?>

FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH

<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>

<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>

METHOD 2

Mage/Catalog/Block/Product/List.phtml OVER RIDE and set in 'local folder'

i.e. Copy From

Mage/Catalog/Block/Product/List.phtml

and PASTE TO

app/code/local/Mage/Catalog/Block/Product/List.phtml

change the function by adding 2 lines shown in bold below.

protected function _getProductCollection()
{
       if (is_null($this->_productCollection)) {
           $layer = Mage::getSingleton('catalog/layer');
           /* @var $layer Mage_Catalog_Model_Layer */
           if ($this->getShowRootCategory()) {
               $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
           }

           // if this is a product view page
           if (Mage::registry('product')) {
               // get collection of categories this product is associated with
               $categories = Mage::registry('product')->getCategoryCollection()
                   ->setPage(1, 1)
                   ->load();
               // if the product is associated with any category
               if ($categories->count()) {
                   // show products from this category
                   $this->setCategoryId(current($categories->getIterator()));
               }
           }

           $origCategory = null;
           if ($this->getCategoryId()) {
               $category = Mage::getModel('catalog/category')->load($this->getCategoryId());

               if ($category->getId()) {
                   $origCategory = $layer->getCurrentCategory();
                   $layer->setCurrentCategory($category);
               }
           }
           $this->_productCollection = $layer->getProductCollection();

           $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

           if ($origCategory) {
               $layer->setCurrentCategory($origCategory);
           }
       }
       **//CMI-PK added na_author to filter on product listing page//
       $this->_productCollection->addAttributeToSelect('na_author');**
       return $this->_productCollection;

}

and you will be happy to see it....!!

How to generate components in a specific folder with Angular CLI?

Use 'ng generate component ./target_directory/Component_Name'

How to declare an ArrayList with values?

The Guava library contains convenience methods for creating lists and other collections which makes this much prettier than using the standard library classes.

Example:

ArrayList<String> list = newArrayList("a", "b", "c");

(This assumes import static com.google.common.collect.Lists.newArrayList;)

What is the $$hashKey added to my JSON.stringify result

It comes with the ng-repeat directive usually. To do dom manipulation AngularJS flags objects with special id.

This is common with Angular. For example if u get object with ngResource your object will embed all the resource API and you'll see methods like $save, etc. With cookies too AngularJS will add a property __ngDebug.

javascript window.location in new tab

We have to dynamically set the attribute target="_blank" and it will open it in new tab. document.getElementsByTagName("a")[0].setAttribute('target', '_blank')

document.getElementsByTagName("a")[0].click()

If you want to open in new window, get the href link and use window.open

var link = document.getElementsByTagName("a")[0].getAttribute("href");

window.open(url, "","height=500,width=500");

Don't provide the second parameter as _blank in the above.

adb server version doesn't match this client

In my case, the problem was caused by Virtuous Ten Studio, which has the adb.exe in External/ADB directory.

Go there and run .\adb.exe kill-server and you'll be good.

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

You can try the following snippet:

 var str = "How,are,you,doing,today?";
    var res = str.split(",");
    console.log("My Result:", res)

How is the java memory pool divided?

Java Heap Memory is part of memory allocated to JVM by Operating System.

Objects reside in an area called the heap. The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected.

enter image description here

You can find more details about Eden Space, Survivor Space, Tenured Space and Permanent Generation in below SE question:

Young , Tenured and Perm generation

PermGen has been replaced with Metaspace since Java 8 release.

Regarding your queries:

  1. Eden Space, Survivor Space, Tenured Space are part of heap memory
  2. Metaspace and Code Cache are part of non-heap memory.

Codecache: The Java Virtual Machine (JVM) generates native code and stores it in a memory area called the codecache. The JVM generates native code for a variety of reasons, including for the dynamically generated interpreter loop, Java Native Interface (JNI) stubs, and for Java methods that are compiled into native code by the just-in-time (JIT) compiler. The JIT is by far the biggest user of the codecache.

How can I keep a container running on Kubernetes?

  1. In your Dockerfile use this command:

    CMD ["sh", "-c", "tail -f /dev/null"]
    
  2. Build your docker image.

  3. Push it to your cluster or similar, just to make sure the image it's available.
  4. kubectl run debug-container -it --image=<your-image>
    

Get Current date in epoch from Unix shell script

echo $(($(date +%s) / 60 / 60 / 24))

How do I get the full path of the current file's directory?

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

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

application/javascript is the correct type to use but since it's not supported by IE6-8 you're going to be stuck with text/javascript. If you don't care about validity (HTML5 excluded) then just don't specify a type.

Jquery - How to make $.post() use contentType=application/json?

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})

See : jQuery.ajax()

Neatest way to remove linebreaks in Perl

Note from 2017: File::Slurp is not recommended due to design mistakes and unmaintained errors. Use File::Slurper or Path::Tiny instead.

extending on your answer

use File::Slurp ();
my $value = File::Slurp::slurp($filename);
$value =~ s/\R*//g;

File::Slurp abstracts away the File IO stuff and just returns a string for you.

NOTE

  1. Important to note the addition of /g , without it, given a multi-line string, it will only replace the first offending character.

  2. Also, the removal of $, which is redundant for this purpose, as we want to strip all line breaks, not just line-breaks before whatever is meant by $ on this OS.

  3. In a multi-line string, $ matches the end of the string and that would be problematic ).

  4. Point 3 means that point 2 is made with the assumption that you'd also want to use /m otherwise '$' would be basically meaningless for anything practical in a string with >1 lines, or, doing single line processing, an OS which actually understands $ and manages to find the \R* that proceed the $

Examples

while( my $line = <$foo> ){
      $line =~ $regex;
}

Given the above notation, an OS which does not understand whatever your files '\n' or '\r' delimiters, in the default scenario with the OS's default delimiter set for $/ will result in reading your whole file as one contiguous string ( unless your string has the $OS's delimiters in it, where it will delimit by that )

So in this case all of these regex are useless:

  • /\R*$// : Will only erase the last sequence of \R in the file
  • /\R*// : Will only erase the first sequence of \R in the file
  • /\012?\015?// : When will only erase the first 012\015 , \012 , or \015 sequence, \015\012 will result in either \012 or \015 being emitted.

  • /\R*$// : If there happens to be no byte sequences of '\015$OSDELIMITER' in the file, then then NO linebreaks will be removed except for the OS's own ones.

It would appear nobody gets what I'm talking about, so here is example code, that is tested to NOT remove line feeds. Run it, you'll see that it leaves the linefeeds in.

#!/usr/bin/perl 

use strict;
use warnings;

my $fn = 'TestFile.txt';

my $LF = "\012";
my $CR = "\015";

my $UnixNL = $LF;
my $DOSNL  = $CR . $LF;
my $MacNL  = $CR;

sub generate { 
    my $filename = shift;
    my $lineDelimiter = shift;

    open my $fh, '>', $filename;
    for ( 0 .. 10 )
    {
        print $fh "{0}";
        print $fh join "", map { chr( int( rand(26) + 60 ) ) } 0 .. 20;
        print $fh "{1}";
        print $fh $lineDelimiter->();
        print $fh "{2}";
    }
    close $fh;
}

sub parse { 
    my $filename = shift;
    my $osDelimiter = shift;
    my $message = shift;
    print "Parsing $message File $filename : \n";

    local $/ = $osDelimiter;

    open my $fh, '<', $filename;
    while ( my $line = <$fh> )
    {

        $line =~ s/\R*$//;
        print ">|" . $line . "|<";

    }
    print "Done.\n\n";
}


my @all = ( $DOSNL,$MacNL,$UnixNL);
generate 'Windows.txt' , sub { $DOSNL }; 
generate 'Mac.txt' , sub { $MacNL };
generate 'Unix.txt', sub { $UnixNL };
generate 'Mixed.txt', sub {
    return @all[ int(rand(2)) ];
};


for my $os ( ["$MacNL", "On Mac"], ["$DOSNL", "On Windows"], ["$UnixNL", "On Unix"]){
    for ( qw( Windows Mac Unix Mixed ) ){
        parse $_ . ".txt", @{ $os };
    }
}

For the CLEARLY Unprocessed output, see here: http://pastebin.com/f2c063d74

Note there are certain combinations that of course work, but they are likely the ones you yourself naívely tested.

Note that in this output, all results must be of the form >|$string|<>|$string|< with NO LINE FEEDS to be considered valid output.

and $string is of the general form {0}$data{1}$delimiter{2} where in all output sources, there should be either :

  1. Nothing between {1} and {2}
  2. only |<>| between {1} and {2}

JavaScript: client-side vs. server-side validation

Yes, client side validation can be totally bypassed, always. You need to do both, client side to provide a better user experience, and server side to be sure that the input you get is actually validated and not just supposedly validated by the client.

Authorize attribute in ASP.NET MVC

Real power comes with understanding and implementation membership provider together with role provider. You can assign users into roles and according to that restriction you can apply different access roles for different user to controller actions or controller itself.

 [Authorize(Users = "Betty, Johnny")]
 public ActionResult SpecificUserOnly()
 {
     return View();
 }

or you can restrict according to group

[Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
    return View();
}

How do I link to Google Maps with a particular longitude and latitude?

Find your location in the Google Earth program, and click the icon "View in Google Maps". The URL bar in your browser will show the URL you need.

Random / noise functions for GLSL

A straight, jagged version of 1d Perlin, essentially a random lfo zigzag.

half  rn(float xx){         
    half x0=floor(xx);
    half x1=x0+1;
    half v0 = frac(sin (x0*.014686)*31718.927+x0);
    half v1 = frac(sin (x1*.014686)*31718.927+x1);          

    return (v0*(1-frac(xx))+v1*(frac(xx)))*2-1*sin(xx);
}

I also have found 1-2-3-4d perlin noise on shadertoy owner inigo quilez perlin tutorial website, and voronoi and so forth, he has full fast implementations and codes for them.

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Firestore Getting documents id from collection

Since you are using angularFire, it doesn't make any sense if you are going back to default firebase methods for your implementation. AngularFire itself has the proper mechanisms implemented. Just have to use it.

valueChanges() method of angularFire provides an overload for getting the ID of each document of the collection by simply adding a object as a parameter to the method.

valueChanges({ idField: 'id' })

Here 'idField' must be same as it is. 'id' can be anything that you want your document IDs to be called.

Then the each document object on the returned array will look like this.

{
  field1 = <field1 value>,
  field2 = <field2 value>,
  ..
  id = 'whatEverTheDocumentIdWas'
}

Then you can easily get the document ID by referencing to the field that you named.

AngularFire 5.2.0

Error Code: 1406. Data too long for column - MySQL

I think that switching off the STRICT mode is not a good option because the app can start losing the data entered by users.

If you receive values for the TESTcol from an app you could add model validation, like in Rails

validates :TESTcol, length: { maximum: 45 }

If you manipulate with values in SQL script you could truncate the string with the SUBSTRING command

INSERT INTO TEST
VALUES
(
    1,
    SUBSTRING('Vikas Kumar Gupta Kratika Shukla Kritika Shukla', 0, 45)
);

How to upgrade pip3?

To upgrade your pip3, try running:

sudo -H pip3 install --upgrade pip3

To upgrade pip as well, you can follow it by:

sudo -H pip2 install --upgrade pip

How can I make a div not larger than its contents?

What works for me is:

display: table;

in the div. (Tested on Firefox and Google Chrome).

Super-simple example of C# observer/observable with delegates

    /**********************Simple Example ***********************/    

class Program
        {
            static void Main(string[] args)
            {
                Parent p = new Parent();
            }
        }

        ////////////////////////////////////////////

        public delegate void DelegateName(string data);

        class Child
        {
            public event DelegateName delegateName;

            public void call()
            {
                delegateName("Narottam");
            }
        }

        ///////////////////////////////////////////

        class Parent
        {
            public Parent()
            {
                Child c = new Child();
                c.delegateName += new DelegateName(print);
                //or like this
                //c.delegateName += print;
                c.call();
            }

            public void print(string name)
            {
                Console.WriteLine("yes we got the name : " + name);
            }
        }

Query to convert from datetime to date mysql

Use the DATE function:

SELECT DATE(orders.date_purchased) AS date

How do I change a TCP socket to be non-blocking?

Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2), poll(2) or some other system calls available on your system.

See The C10K problem for the comparison of approaches to scalable IO multiplexing.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

How to kill MySQL connections

While you can't kill all open connections with a single command, you can create a set of queries to do that for you if there are too many to do by hand.

This example will create a series of KILL <pid>; queries for all some_user's connections from 192.168.1.1 to my_db.

SELECT 
CONCAT('KILL ', id, ';') 
FROM INFORMATION_SCHEMA.PROCESSLIST 
WHERE `User` = 'some_user' 
AND `Host` = '192.168.1.1';
AND `db` = 'my_db';

Is there a cross-domain iframe height auto-resizer that works?

I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.

I'll drop in a simplified example below.

// /js/embed-iframe-content.js

(function(){
    // Note the id, we need to set this correctly on the script tag responsible for
    // requesting this file.
    var me = document.getElementById('my-iframe-content-loader-script-tag');

    function loadIFrame() {
        var ifrm = document.createElement('iframe');
        ifrm.id = 'my-iframe-identifier';
        ifrm.setAttribute('src', 'http://www.google.com');
        ifrm.style.width = '100%';
        ifrm.style.border = 0;
        // we initially hide the iframe to avoid seeing the iframe resizing
        ifrm.style.opacity = 0;
        ifrm.onload = function () {
            // this will resize our iframe
            iFrameResize({ log: true }, '#my-iframe-identifier');
            // make our iframe visible
            ifrm.style.opacity = 1;
        };

        me.insertAdjacentElement('afterend', ifrm);
    }

    if (!window.iFrameResize) {
        // We first need to ensure we inject the js required to resize our iframe.

        var resizerScriptTag = document.createElement('script');
        resizerScriptTag.type = 'text/javascript';

        // IMPORTANT: insert the script tag before attaching the onload and setting the src.
        me.insertAdjacentElement('afterend', ifrm);

        // IMPORTANT: attach the onload before setting the src.
        resizerScriptTag.onload = loadIFrame;

        // This a CDN resource to get the iFrameResizer code.
        // NOTE: You must have the below "coupled" script hosted by the content that
        // is loaded within the iframe:
        // https://unpkg.com/[email protected]/js/iframeResizer.contentWindow.min.js
        resizerScriptTag.src = 'https://unpkg.com/[email protected]/js/iframeResizer.min.js';
    } else {
        // Cool, the iFrameResizer exists so we can just load our iframe.
        loadIFrame();
    }    
}())

Then the iframe content can be injected anywhere within another page/site by using the script like so:

<script
  id="my-iframe-content-loader-script-tag"
  type="text/javascript"
  src="/js/embed-iframe-content.js"
></script>

The iframe content will be injected below wherever you place the script tag.

Hope this is helpful to someone.

Run a command over SSH with JSch

I am using JSCH since about 2000 and still find it a good library to use. I agree it is not documented well enough but the provided examples seem good enough to understand that is required in several minutes, and user friendly Swing, while this is quite original approach, allows to test the example quickly to make sure it actually works. It is not always true that every good project needs three times more documentation than the amount of code written, and even when such is present, this not always helps to write faster a working prototype of your concept.

Getting time span between two times in C#?

Two points:

  1. Check your inputs. I can't imagine a situation where you'd get 2 hours by subtracting the time values you're talking about. If I do this:

        DateTime startTime = Convert.ToDateTime("7:00 AM");
        DateTime endtime = Convert.ToDateTime("2:00 PM");
        TimeSpan duration = startTime - endtime;
    

    ... I get -07:00:00 as the result. And even if I forget to provide the AM/PM value:

        DateTime startTime = Convert.ToDateTime("7:00");
        DateTime endtime = Convert.ToDateTime("2:00");
        TimeSpan duration = startTime - endtime;
    

    ... I get 05:00:00. So either your inputs don't contain the values you have listed or you are in a machine environment where they are begin parsed in an unexpected way. Or you're not actually getting the results you are reporting.

  2. To find the difference between a start and end time, you need to do endTime - startTime, not the other way around.

Difference between RUN and CMD in a Dockerfile

I found this article very helpful to understand the difference between them:

RUN - RUN instruction allows you to install your application and packages required for it. It executes any commands on top of the current image and creates a new layer by committing the results. Often you will find multiple RUN instructions in a Dockerfile.

CMD - CMD instruction allows you to set a default command, which will be executed only when you run container without specifying a command. If Docker container runs with a command, the default command will be ignored. If Dockerfile has more than one CMD instruction, all but last
CMD instructions are ignored.

How to check if a string starts with one of several prefixes?

Of course, be mindful that your program will only be useful in english speaking countries if you detect dates this way. You might want to consider:

Set<String> dayNames = Calendar.getInstance()
 .getDisplayNames(Calendar.DAY_OF_WEEK,
      Calendar.SHORT,
      Locale.getDefault())
 .keySet();

From there you can use .startsWith or .matches or whatever other method that others have mentioned above. This way you get the default locale for the jvm. You could always pass in the locale (and maybe default it to the system locale if it's null) as well to be more robust.

What does this thread join code mean?

A picture is worth a thousand words.

    Main thread-->----->--->-->--block##########continue--->---->
                 \                 |               |
sub thread start()\                | join()        |
                   \               |               |
                    ---sub thread----->--->--->--finish    

Hope to useful, for more detail click here

Maven Modules + Building a Single Specific Module

Maven absolutely was designed for this type of dependency.

mvn package won't install anything in your local repository it just packages the project and leaves it in the target folder.

Do mvn install in parent project (A), with this all the sub-modules will be installed in your computer's Maven repository, if there are no changes you just need to compile/package the sub-module (B) and Maven will take the already packaged and installed dependencies just right.

You just need to a mvn install in the parent project if you updated some portion of the code.

Converting a list to a set changes element order

Answering your first question, a set is a data structure optimized for set operations. Like a mathematical set, it does not enforce or maintain any particular order of the elements. The abstract concept of a set does not enforce order, so the implementation is not required to. When you create a set from a list, Python has the liberty to change the order of the elements for the needs of the internal implementation it uses for a set, which is able to perform set operations efficiently.

413 Request Entity Too Large - File Upload Issue

-in php.ini (inside /etc/php.ini)

 max_input_time = 24000
 max_execution_time = 24000
 upload_max_filesize = 12000M
 post_max_size = 24000M
 memory_limit = 12000M

-in nginx.conf(inside /opt/nginx/conf)

client_max_body_size 24000M

Its working for my case

How to unmerge a Git merge?

You can reset your branch to the state it was in just before the merge if you find the commit it was on then.

One way is to use git reflog, it will list all the HEADs you've had. I find that git reflog --relative-date is very useful as it shows how long ago each change happened.

Once you find that commit just do a git reset --hard <commit id> and your branch will be as it was before.

If you have SourceTree, you can look up the <commit id> there if git reflog is too overwhelming.

Java character array initializer

Here is the code

String str = "Hi There";
char[] arr = str.toCharArray();

for(int i=0;i<arr.length;i++)
    System.out.print(" "+arr[i]);

How to Clear Console in Java?

Use the following code:


System.out.println("\f");

'\f' is an escape sequence which represents FormFeed. This is what I have used in my projects to clear the console. This is simpler than the other codes, I guess.

Remove style attribute from HTML tags

I'm using such thing to clean-up the style='...' section out of tags with keeping of other attributes at the moment.

$output = preg_replace('/<([^>]+)(\sstyle=(?P<stq>["\'])(.*)\k<stq>)([^<]*)>/iUs', '<$1$5>', $input);

How to initialize a List<T> to a given size (as opposed to capacity)?

You can use Linq to cleverly initialize your list with a default value. (Similar to David B's answer.)

var defaultStrings = (new int[10]).Select(x => "my value").ToList();

Go one step farther and initialize each string with distinct values "string 1", "string 2", "string 3", etc:

int x = 1;
var numberedStrings = (new int[10]).Select(x => "string " + x++).ToList();

In Angular, What is 'pathmatch: full' and what effect does it have?

The path-matching strategy, one of 'prefix' or 'full'. Default is 'prefix'.

By default, the router checks URL elements from the left to see if the URL matches a given path, and stops when there is a match. For example, '/team/11/user' matches 'team/:id'.

The path-match strategy 'full' matches against the entire URL. It is important to do this when redirecting empty-path routes. Otherwise, because an empty path is a prefix of any URL, the router would apply the redirect even when navigating to the redirect destination, creating an endless loop.

Source : https://angular.io/api/router/Route#properties

How to implement a queue using two stacks?

Below is the solution in javascript language using ES6 syntax.

Stack.js

//stack using array
class Stack {
  constructor() {
    this.data = [];
  }

  push(data) {
    this.data.push(data);
  }

  pop() {
    return this.data.pop();
  }

  peek() {
    return this.data[this.data.length - 1];
  }

  size(){
    return this.data.length;
  }
}

export { Stack };

QueueUsingTwoStacks.js

import { Stack } from "./Stack";

class QueueUsingTwoStacks {
  constructor() {
    this.stack1 = new Stack();
    this.stack2 = new Stack();
  }

  enqueue(data) {
    this.stack1.push(data);
  }

  dequeue() {
    //if both stacks are empty, return undefined
    if (this.stack1.size() === 0 && this.stack2.size() === 0)
      return undefined;

    //if stack2 is empty, pop all elements from stack1 to stack2 till stack1 is empty
    if (this.stack2.size() === 0) {
      while (this.stack1.size() !== 0) {
        this.stack2.push(this.stack1.pop());
      }
    }

    //pop and return the element from stack 2
    return this.stack2.pop();
  }
}

export { QueueUsingTwoStacks };

Below is the usage:

index.js

import { StackUsingTwoQueues } from './StackUsingTwoQueues';

let que = new QueueUsingTwoStacks();
que.enqueue("A");
que.enqueue("B");
que.enqueue("C");

console.log(que.dequeue());  //output: "A"

How can I export a GridView.DataSource to a datatable or dataset?

Assuming your DataSource is of type DataTable, you can just do this:

myGridView.DataSource as DataTable

Angular 4 default radio button checked by default

if you're using reactive forms then you can use the following way. consider the following example.

in component.html

 `<p class="mr-3"> Require Shipping: 

          <input type="radio" class="ml-2" value="true" name="requiresShipping" 
           id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  Yes  &nbsp;

          <input type="radio" class="ml-2" value="false" name="requiresShipping" 
          id="requiresShipping" formControlName="requiresShipping">

                   &nbsp;  No   &nbsp;
 </p>`

in component.ts

`
 export class ClassName implements OnInit {
      public yourForm: FormGroup
      
      constructor(
            private fromBuilder: FormBuilder
      ) {
            this.yourForm= this.fromBuilder.group({
                  requiresShipping: this.fromBuilder.control('true'),
            })
        }
 }

`

now you will get the default selected radio button.

enter image description here

How to get the element clicked (for the whole document)?

I know this post is really old but, to get the contents of an element in reference to its ID, this is what I would do:

window.onclick = e => {
    console.log(e.target);
    console.log(e.target.id, ' -->', e.target.innerHTML);
}

How to copy a folder via cmd?

xcopy  e:\source_folder f:\destination_folder /e /i /h

The /h is just in case there are hidden files. The /i creates a destination folder if there are muliple source files.

No generated R.java file in my project

This could also be the problem of an incorrect xml layout file for example. If your xml files are not valid (containing errors) the R file will not re-generate after a clean-up. If you fix this, the R file will be generated automatically again.

What is the difference between RTP or RTSP in a streaming server?

Some basics:

RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.

RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....

In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)

To start with you can go through sample code provided by live555

How to set custom header in Volley Request

Looking for solution to this problem as well. see something here: http://developer.android.com/training/volley/request.html

is it a good idea to directly use ImageRequest instead of ImageLoader? Seems ImageLoader uses it internally anyway. Does it miss anything important other than ImageLoader's cache support?

ImageView mImageView;
String url = "http://i.imgur.com/7spzG.png";
mImageView = (ImageView) findViewById(R.id.myImage);
...

// Retrieves an image specified by the URL, displays it in the UI.
mRequestQueue = Volley.newRequestQueue(context);;
ImageRequest request = new ImageRequest(url,
  new Response.Listener() {
      @Override
      public void onResponse(Bitmap bitmap) {
          mImageView.setImageBitmap(bitmap);
      }
  }, 0, 0, null,
  new Response.ErrorListener() {
      public void onErrorResponse(VolleyError error) {
          mImageView.setImageResource(R.drawable.image_load_error);
      }
  })   {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new Map<String, String>();
        params.put("User-Agent", "one");
        params.put("header22", "two");

        return params;
    };
mRequestQueue.add(request);

How to convert an array of key-value tuples into an object

Update June 2020

ECMAScript 2021 brings Object.fromEntries which does exactly the requirement:

_x000D_
_x000D_
const array =    [ [ 'cardType', 'iDEBIT' ],
      [ 'txnAmount', '17.64' ],
      [ 'txnId', '20181' ],
      [ 'txnType', 'Purchase' ],
      [ 'txnDate', '2015/08/13 21:50:04' ],
      [ 'respCode', '0' ],
      [ 'isoCode', '0' ],
      [ 'authCode', '' ],
      [ 'acquirerInvoice', '0' ],
      [ 'message', '' ],
      [ 'isComplete', 'true' ],
      [ 'isTimeout', 'false' ] ];
      
const obj = Object.fromEntries(array);
console.log(obj);
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries

This will do it:

_x000D_
_x000D_
const array =    [ [ 'cardType', 'iDEBIT' ],
      [ 'txnAmount', '17.64' ],
      [ 'txnId', '20181' ],
      [ 'txnType', 'Purchase' ],
      [ 'txnDate', '2015/08/13 21:50:04' ],
      [ 'respCode', '0' ],
      [ 'isoCode', '0' ],
      [ 'authCode', '' ],
      [ 'acquirerInvoice', '0' ],
      [ 'message', '' ],
      [ 'isComplete', 'true' ],
      [ 'isTimeout', 'false' ] ];
    
var obj = {};
array.forEach(function(data){
    obj[data[0]] = data[1]
});
console.log(obj);
_x000D_
_x000D_
_x000D_


Click events on Pie Charts in Chart.js

  var ctx = document.getElementById('pie-chart').getContext('2d');
 var myPieChart = new Chart(ctx, {
                // The type of chart we want to create
                type: 'pie',

            });

             //define click event
  $("#pie-chart").click(
            function (evt) {
                var activePoints = myPieChart.getElementsAtEvent(evt);
                var labeltag = activePoints[0]._view.label;

                      });

How to find tags with only certain attributes - BeautifulSoup

if you want to only search with attribute name with any value

from bs4 import BeautifulSoup
import re

soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})

as per Steve Lorimer better to pass True instead of regex

results = soup.findAll("td", {"valign" : True})

PHP - Failed to open stream : No such file or directory

  1. Look at the exact error

My code worked fine on all machines but only on this one started giving problem (which used to work find I guess). Used echo "document_root" path to debug and also looked closely at the error, found this

Warning: include(D:/MyProjects/testproject//functions/connections.php): failed to open stream:

You can easily see where the problems are. The problems are // before functions

$document_root = $_SERVER['DOCUMENT_ROOT'];
echo "root: $document_root";
include($document_root.'/functions/connections.php');

So simply remove the lading / from include and it should work fine. What is interesting is this behaviors is different on different versions. I run the same code on Laptop, Macbook Pro and this PC, all worked fine untill. Hope this helps someone.

  1. Copy past the file location in the browser to make sure file exists. Sometimes files get deleted unexpectedly (happened with me) and it was also the issue in my case.

How to write a Python module/package?

Since nobody did cover this question of the OP yet:

What I wanted to do:

Make a python module install-able with "pip install ..."

Here is an absolute minimal example, showing the basic steps of preparing and uploading your package to PyPI using setuptools and twine.

This is by no means a substitute for reading at least the tutorial, there is much more to it than covered in this very basic example.

Creating the package itself is already covered by other answers here, so let us assume we have that step covered and our project structure like this:

.
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

In order to use setuptools for packaging, we need to add a file setup.py, this goes into the root folder of our project:

.
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At the minimum, we specify the metadata for our package, our setup.py would look like this:

from setuptools import setup

setup(
    name='hellostackoverflow',
    version='0.0.1',
    description='a pip-installable package example',
    license='MIT',
    packages=['hellostackoverflow'],
    author='Benjamin Gerfelder',
    author_email='[email protected]',
    keywords=['example'],
    url='https://github.com/bgse/hellostackoverflow'
)

Since we have set license='MIT', we include a copy in our project as LICENCE.txt, alongside a readme file in reStructuredText as README.rst:

.
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we are ready to go to start packaging using setuptools, if we do not have it already installed, we can install it with pip:

pip install setuptools

In order to do that and create a source distribution, at our project root folder we call our setup.py from the command line, specifying we want sdist:

python setup.py sdist

This will create our distribution package and egg-info, and result in a folder structure like this, with our package in dist:

.
+-- dist/
+-- hellostackoverflow.egg-info/
+-- LICENCE.txt
+-- README.rst
+-- setup.py
+-- hellostackoverflow/
    +-- __init__.py
    +-- hellostackoverflow.py

At this point, we have a package we can install using pip, so from our project root (assuming you have all the naming like in this example):

pip install ./dist/hellostackoverflow-0.0.1.tar.gz

If all goes well, we can now open a Python interpreter, I would say somewhere outside our project directory to avoid any confusion, and try to use our shiny new package:

Python 3.5.2 (default, Sep 14 2017, 22:51:06) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from hellostackoverflow import hellostackoverflow
>>> hellostackoverflow.greeting()
'Hello Stack Overflow!'

Now that we have confirmed the package installs and works, we can upload it to PyPI.

Since we do not want to pollute the live repository with our experiments, we create an account for the testing repository, and install twine for the upload process:

pip install twine

Now we're almost there, with our account created we simply tell twine to upload our package, it will ask for our credentials and upload our package to the specified repository:

twine upload --repository-url https://test.pypi.org/legacy/ dist/*

We can now log into our account on the PyPI test repository and marvel at our freshly uploaded package for a while, and then grab it using pip:

pip install --index-url https://test.pypi.org/simple/ hellostackoverflow

As we can see, the basic process is not very complicated. As I said earlier, there is a lot more to it than covered here, so go ahead and read the tutorial for more in-depth explanation.

How to display a Windows Form in full screen on top of the taskbar?

I believe that it can be done by simply setting your FormBorderStyle Property to None and the WindowState to Maximized. If you are using Visual Studio both of those can be found in the IDE so there is no need to do so programmatically. Make sure to include some way of closing/exiting the program before doing this cause this will remove that oh so helpful X in the upper right corner.

EDIT:

Try this instead. It is a snippet that I have kept for a long time. I can't even remember who to credit for it, but it works.

/*
 * A function to put a System.Windows.Forms.Form in fullscreen mode
 * Author: Danny Battison
 * Contact: [email protected]
 */

        // a struct containing important information about the state to restore to
        struct clientRect
        {
            public Point location;
            public int width;
            public int height;
        };
        // this should be in the scope your class
        clientRect restore;
                bool fullscreen = false;

        /// <summary>
        /// Makes the form either fullscreen, or restores it to it's original size/location
        /// </summary>
        void Fullscreen()
        {
            if (fullscreen == false)
            {
                this.restore.location = this.Location;
                this.restore.width = this.Width;
                this.restore.height = this.Height;
                this.TopMost = true;
                this.Location = new Point(0,0);
                this.FormBorderStyle = FormBorderStyle.None;
                this.Width = Screen.PrimaryScreen.Bounds.Width;
                this.Height = Screen.PrimaryScreen.Bounds.Height;
            }
            else
            {
                this.TopMost = false;
                this.Location = this.restore.location;
                this.Width = this.restore.width;
                this.Height = this.restore.height;
                                // these are the two variables you may wish to change, depending
                                // on the design of your form (WindowState and FormBorderStyle)
                this.WindowState = FormWindowState.Normal;
                this.FormBorderStyle = FormBorderStyle.Sizable;
            }
        }

How to copy the first few lines of a giant file, and add a line of text at the end of it using some Linux commands?

First few lines: man head.

Append lines: use the >> operator (?) in Bash:

echo 'This goes at the end of the file' >> file

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

Display a tooltip over a button using Windows Forms

private void Form1_Load(object sender, System.EventArgs e)
{
    ToolTip toolTip1 = new ToolTip();
    toolTip1.AutoPopDelay = 5000;
    toolTip1.InitialDelay = 1000;
    toolTip1.ReshowDelay = 500;
    toolTip1.ShowAlways = true;
    toolTip1.SetToolTip(this.button1, "My button1");
    toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

Regex for Comma delimited list

This one will reject extraneous commas at the start or end of the line, if that's important to you.

((, )?(^)?(possible|value|patterns))*

Replace possible|value|patterns with a regex that matches your allowed values.

How to change a string into uppercase

for making uppercase from lowercase to upper just use

"string".upper()

where "string" is your string that you want to convert uppercase

for this question concern it will like this:

s.upper()

for making lowercase from uppercase string just use

"string".lower()

where "string" is your string that you want to convert lowercase

for this question concern it will like this:

s.lower()

If you want to make your whole string variable use

s="sadf"
# sadf

s=s.upper()
# SADF

Determining whether an object is a member of a collection in VBA

In your specific case (TableDefs) iterating over the collection and checking the Name is a good approach. This is OK because the key for the collection (Name) is a property of the class in the collection.

But in the general case of VBA collections, the key will not necessarily be part of the object in the collection (e.g. you could be using a Collection as a dictionary, with a key that has nothing to do with the object in the collection). In this case, you have no choice but to try accessing the item and catching the error.

How do I use regex in a SQLite query?

SQLite3 supports the REGEXP operator:

WHERE x REGEXP <regex>

http://www.sqlite.org/lang_expr.html#regexp

getting a checkbox array value from POST

Because your <form> element is inside the foreach loop, you are generating multiple forms. I assume you want multiple checkboxes in one form.

Try this...

<form method="post">
foreach{
<?php echo'
<input id="'.$userid.'" value="'.$userid.'"  name="invite[]" type="checkbox">
<input type="submit">';
?>
}
</form>

Is there a way to cast float as a decimal without rounding and preserving its precision?

Try SELECT CAST(field1 AS DECIMAL(10,2)) field1 and replace 10,2 with whatever precision you need.

XML parsing of a variable string in JavaScript

Apparently jQuery now provides jQuery.parseXML http://api.jquery.com/jQuery.parseXML/ as of version 1.5

jQuery.parseXML( data ) Returns: XMLDocument

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

PermissionError: [Errno 13] Permission denied

In my case the problem was that I hid the file (The file had hidden atribute):
How to deal with the problem in python:

import os

# This is how to hide the file
os.system(f"attrib +h {filePath}")
file_ = open(filePath, "wb")
>>> PermissionError <<<


# and this is how to show it again making the file writable again:
os.system(f"attrib -h {filePath}")
file_ = open(filePath, "wb")
# This works

# and just to let you know there is also this way
# so you don't need to import os
import subprocess
subprocess.check_call(["attrib", "-H", _path])


SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I understand that the answer was useful however for some reason it does not work for me however I have moved the situation with the following code and it is perfect

    <?php

$codigoarticulo = $_POST['codigoarticulo'];
$nombrearticulo = $_POST['nombrearticulo'];
$seccion        = $_POST['seccion'];
$precio         = $_POST['precio'];
$fecha          = $_POST['fecha'];
$importado      = $_POST['importado'];
$paisdeorigen   = $_POST['paisdeorigen'];
try {

  $server = 'mysql: host=localhost; dbname=usuarios';
  $user   = 'root';
  $pass   = '';
  $base   = new PDO($server, $user, $pass);

  $base->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $base->query("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $base->exec("SET character_set_results = 'utf8',
                     character_set_client = 'utf8',
                     character_set_connection = 'utf8',
                     character_set_database = 'utf8',
                     character_set_server = 'utf8'");

  $sql = "
  INSERT INTO productos
  (CÓDIGOARTÍCULO, NOMBREARTÍCULO, SECCIÓN, PRECIO, FECHA, IMPORTADO, PAÍSDEORIGEN)
  VALUES
  (:c_art, :n_art, :sec, :pre, :fecha_art, :import, :p_orig)";
// SE ejecuta la consulta ben prepare
  $result = $base->prepare($sql);
//  se pasan por parametros aqui
  $result->bindParam(':c_art', $codigoarticulo);
  $result->bindParam(':n_art', $nombrearticulo);
  $result->bindParam(':sec', $seccion);
  $result->bindParam(':pre', $precio);
  $result->bindParam(':fecha_art', $fecha);
  $result->bindParam(':import', $importado);
  $result->bindParam(':p_orig', $paisdeorigen);
  $result->execute();
  echo 'Articulo agregado';
} catch (Exception $e) {

  echo 'Error';
  echo $e->getMessage();
} finally {

}

?>

Submit form and stay on same page?

When you hit on the submit button, the page is sent to the server. If you want to send it async, you can do it with ajax.

asp.net: How can I remove an item from a dropdownlist?

myDropDown.Items.Remove(myDropDown.Items.FindByText("Chicago"));

How to use BeginInvoke C#

Action is a Type of Delegate provided by the .NET framework. The Action points to a method with no parameters and does not return a value.

() => is lambda expression syntax. Lambda expressions are not of Type Delegate. Invoke requires Delegate so Action can be used to wrap the lambda expression and provide the expected Type to Invoke()

Invoke causes said Action to execute on the thread that created the Control's window handle. Changing threads is often necessary to avoid Exceptions. For example, if one tries to set the Rtf property on a RichTextBox when an Invoke is necessary, without first calling Invoke, then a Cross-thread operation not valid exception will be thrown. Check Control.InvokeRequired before calling Invoke.

BeginInvoke is the Asynchronous version of Invoke. Asynchronous means the thread will not block the caller as opposed to a synchronous call which is blocking.

Hexadecimal To Decimal in Shell Script

To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With :

$ echo $((16#FF))
255

with :

$ echo "ibase=16; FF" | bc
255

with :

$ perl -le 'print hex("FF");'
255

with :

$ printf "%d\n" 0xFF
255

with :

$ python -c 'print(int("FF", 16))'
255

with :

$ ruby -e 'p "FF".to_i(16)'
255

with :

$ nodejs <<< "console.log(parseInt('FF', 16))"
255

with :

$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255

with :

$ groovy -e 'println Integer.parseInt("FF",16)'
255

Can't find bundle for base name /Bundle, locale en_US

I use Eclipse (without Maven) so I place the .properties file in src folder that also contains the java source code, in order to have the .properties file in the classes folder after building the project. It works fine. Take a look at this post: https://www.mkyong.com/jsf2/cant-find-bundle-for-base-name-xxx-locale-en_us/

Hope this help you.

Is there a developers api for craigslist.org

Ultimately no. You can query for listings with a search string from an RSS feed such as this:

http://YOURCITY.craigslist.org/search/sss?format=rss&query=SearchString

As far as posting, craiglist has not opened their API. However, this SO Question may shed some light and a possible solution - although not a very reliable one.

Craigslist Automated Posting API?

Write a note to craigslist asking them to open their API,

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

PHP remove special character from string

mysqli_set_charset($con,"utf8");
$title = ' LEVEL – EXTENDED'; 
$newtitle = preg_replace('/[^(\x20-\x7F)]*/','', $title);     
echo $newtitle;

Result :  LEVEL EXTENDED

Many Strange Character be removed by applying below the mysql connection code. but in some circumstances of removing this type strange character like †you can use preg_replace above format.

What are all the possible values for HTTP "Content-Type" header?

If you are using jaxrs or any other, then there will be a class called mediatype.User interceptor before sending the request and compare it against this.

How to merge many PDF files into a single one?

You can also use Ghostscript to merge different PDFs. You can even use it to merge a mix of PDFs, PostScript (PS) and EPS into one single output PDF file:

gs \
  -o merged.pdf \
  -sDEVICE=pdfwrite \
  -dPDFSETTINGS=/prepress \
   input_1.pdf \
   input_2.pdf \
   input_3.eps \
   input_4.ps \
   input_5.pdf

However, I agree with other answers: for your use case of merging PDF file types only, pdftk may be the best (and certainly fastest) option.

Update:
If processing time is not the main concern, but if the main concern is file size (or a fine-grained control over certain features of the output file), then the Ghostscript way certainly offers more power to you. To highlight a few of the differences:

  • Ghostscript can 'consolidate' the fonts of the input files which leads to a smaller file size of the output. It also can re-sample images, or scale all pages to a different size, or achieve a controlled color conversion from RGB to CMYK (or vice versa) should you need this (but that will require more CLI options than outlined in above command).
  • pdftk will just concatenate each file, and will not convert any colors. If each of your 16 input PDFs contains 5 subsetted fonts, the resulting output will contain 80 subsetted fonts. The resulting PDF's size is (nearly exactly) the sum of the input file bytes.

Pointers, smart pointers or shared pointers?

Smart pointers will clean themselves up after they go out of scope (thereby removing fear of most memory leaks). Shared pointers are smart pointers that keep a count of how many instances of the pointer exist, and only clean up the memory when the count reaches zero. In general, only use shared pointers (but be sure to use the correct kind--there is a different one for arrays). They have a lot to do with RAII.

PHP - Debugging Curl

Another (crude) option is to utilize netcat for dumping the full request:

nc -l -p 8000 -w 3 | tee curldbg.txt

And of course sending the failing request to it:

curl_setup(CURLOPT_URL, "http://localhost/testytest");

Notably that will always hang+fail, since netcat won't ever construct a valid HTTP response. It's really just for inspecting what really got sent. The better option, of course, is using a http request debugging service.

How to create a directory and give permission in single command

Just to expand on and improve some of the above answers:

First, I'll check the mkdir man page for GNU Coreutils 8.26 -- it gives us this information about the option '-m' and '-p' (can also be given as --mode=MODE and --parents, respectively):

...set[s] file mode (as in chmod), not a=rwx - umask

...no error if existing, make parent directories as needed

The statements are vague and unclear in my opinion. But basically, it says that you can make the directory with permissions specified by "chmod numeric notation" (octals) or you can go "the other way" and use a/your umask.

Side note: I say "the other way" since the umask value is actually exactly what it sounds like -- a mask, hiding/removing permissions rather than "granting" them as with chmod's numeric octal notation.

You can execute the shell-builtin command umask to see what your 3-digit umask is; for me, it's 022. This means that when I execute mkdir yodirectory in a given folder (say, mahome) and stat it, I'll get some output resembling this:

               755                   richard:richard         /mahome/yodirectory
 #          permissions                 user:group      what I just made (yodirectory),
 # (owner,group,others--in that order)                 where I made it (i.e. in mahome)
 # 

Now, to add just a tiny bit more about those octal permissions. When you make a directory, "your system" take your default directory perms' [which applies for new directories (its value should 777)] and slaps on yo(u)mask, effectively hiding some of those perms'. My umask is 022--now if we "subtract" 022 from 777 (technically subtracting is an oversimplification and not always correct - we are actually turning off perms or masking them)...we get 755 as stated (or "statted") earlier.

We can omit the '0' in front of the 3-digit octal (so they don't have to be 4 digits) since in our case we didn't want (or rather didn't mention) any sticky bits, setuids or setgids (you might want to look into those, btw, they might be useful since you are going 777). So in other words, 0777 implies (or is equivalent to) 777 (but 777 isn't necessarily equivalent to 0777--since 777 only specifies the permissions, not the setuids, setgids, etc.)

Now, to apply this to your question in a broader sense--you have (already) got a few options. All the answers above work (at least according to my coreutils). But you may (or are pretty likely to) run into problems with the above solutions when you want to create subdirectories (nested directories) with 777 permissions all at once. Specifically, if I do the following in mahome with a umask of 022:

mkdir -m 777 -p yodirectory/yostuff/mastuffinyostuff
# OR (you can swap 777 for 0777 if you so desire, outcome will be the same)
install -d -m 777 -p yodirectory/yostuff/mastuffinyostuff

I will get perms 755 for both yodirectory and yostuff, with only 777 perms for mastuffinyostuff. So it appears that the umask is all that's slapped on yodirectory and yostuff...to get around this we can use a subshell:

( umask 000 && mkdir -p yodirectory/yostuff/mastuffinyostuff )

and that's it. 777 perms for yostuff, mastuffinyostuff, and yodirectory.

How do I make this file.sh executable via double click?

Remove the extension altogether and then double-click it. Most system shell scripts are like this. As long as it has a shebang it will work.

How do I change db schema to dbo

You can batch change schemas of multiple database objects as described in this post:

How to change schema of all tables, views and stored procedures in MSSQL

How to perform Join between multiple tables in LINQ lambda

What you've seen is what you get - and it's exactly what you asked for, here:

(ppc, c) => new { productproductcategory = ppc, category = c}

That's a lambda expression returning an anonymous type with those two properties.

In your CategorizedProducts, you just need to go via those properties:

CategorizedProducts catProducts = query.Select(
      m => new { 
             ProdId = m.productproductcategory.product.Id, 
             CatId = m.category.CatId, 
             // other assignments 
           });

In Python, how to check if a string only contains certain characters?

Final(?) edit

Answer, wrapped up in a function, with annotated interactive session:

>>> import re
>>> def special_match(strg, search=re.compile(r'[^a-z0-9.]').search):
...     return not bool(search(strg))
...
>>> special_match("")
True
>>> special_match("az09.")
True
>>> special_match("az09.\n")
False
# The above test case is to catch out any attempt to use re.match()
# with a `$` instead of `\Z` -- see point (6) below.
>>> special_match("az09.#")
False
>>> special_match("az09.X")
False
>>>

Note: There is a comparison with using re.match() further down in this answer. Further timings show that match() would win with much longer strings; match() seems to have a much larger overhead than search() when the final answer is True; this is puzzling (perhaps it's the cost of returning a MatchObject instead of None) and may warrant further rummaging.

==== Earlier text ====

The [previously] accepted answer could use a few improvements:

(1) Presentation gives the appearance of being the result of an interactive Python session:

reg=re.compile('^[a-z0-9\.]+$')
>>>reg.match('jsdlfjdsf12324..3432jsdflsdf')
True

but match() doesn't return True

(2) For use with match(), the ^ at the start of the pattern is redundant, and appears to be slightly slower than the same pattern without the ^

(3) Should foster the use of raw string automatically unthinkingly for any re pattern

(4) The backslash in front of the dot/period is redundant

(5) Slower than the OP's code!

prompt>rem OP's version -- NOTE: OP used raw string!

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9\.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.43 usec per loop

prompt>rem OP's version w/o backslash

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[^a-z0-9.]')" "not bool(reg.search(t))"
1000000 loops, best of 3: 1.44 usec per loop

prompt>rem cleaned-up version of accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile(r'[a-z0-9.]+\Z')" "bool(reg.match(t))"
100000 loops, best of 3: 2.07 usec per loop

prompt>rem accepted answer

prompt>\python26\python -mtimeit -s"t='jsdlfjdsf12324..3432jsdflsdf';import
re;reg=re.compile('^[a-z0-9\.]+$')" "bool(reg.match(t))"
100000 loops, best of 3: 2.08 usec per loop

(6) Can produce the wrong answer!!

>>> import re
>>> bool(re.compile('^[a-z0-9\.]+$').match('1234\n'))
True # uh-oh
>>> bool(re.compile('^[a-z0-9\.]+\Z').match('1234\n'))
False

Bootstrap 4 Center Vertical and Horizontal Alignment

been going thru a lot of posts on getting a form centered in the page and none of them worked. code below is from a react component using bootstrap 4.1. height should be 100vh and not 100%

<div className="container">
      <div className="d-flex justify-content-center align-items-center" style={height}>
        <form>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Email" type="email"/>
          </div>
          <div className="form-group">
            <input className="form-control form-control-lg" placeholder="Password" type="password"/>
          </div>
          <div className="form-group">
            <button className="btn btn-info btn-lg btn-block">Sign In</button>
          </div>
        </form>
      </div>
    </div>

where height in style is:

const height = { height: '100vh' }

Where can I find a list of escape characters required for my JSON ajax return type?

As explained in the section 9 of the official ECMA specification (http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf) in JSON, the following chars have to be escaped:

  • U+0022 (", the quotation mark)
  • U+005C (\, the backslash or reverse solidus)
  • U+0000 to U+001F (the ASCII control characters)

In addition, in order to safely embed JSON in HTML, the following chars have to be also escaped:

  • U+002F (/)
  • U+0027 (')
  • U+003C (<)
  • U+003E (>)
  • U+0026 (&)
  • U+0085 (Next Line)
  • U+2028 (Line Separator)
  • U+2029 (Paragraph Separator)

Some of the above characters can be escaped with the following short escape sequences defined in the standard:

  • \" represents the quotation mark character (U+0022).
  • \\ represents the reverse solidus character (U+005C).
  • \/ represents the solidus character (U+002F).
  • \b represents the backspace character (U+0008).
  • \f represents the form feed character (U+000C).
  • \n represents the line feed character (U+000A).
  • \r represents the carriage return character (U+000D).
  • \t represents the character tabulation character (U+0009).

The other characters which need to be escaped will use the \uXXXX notation, that is \u followed by the four hexadecimal digits that encode the code point.

The \uXXXX can be also used instead of the short escape sequence, or to optionally escape any other character from the Basic Multilingual Plane (BMP).

Does not contain a static 'main' method suitable for an entry point

For some others coming here:

In my case I had copied a .csproj from a sample project which included <EnableDefaultCompileItems>false</EnableDefaultCompileItems> without including the Program.cs file. Fix was to either remove EnableDefaultCompileItems or include Program.cs in the compile explicitly

.NET HttpClient. How to POST string value?

There is an article about your question on asp.net's website. I hope it can help you.

How to call an api with asp net

http://www.asp.net/web-api/overview/advanced/calling-a-web-api-from-a-net-client

Here is a small part from the POST section of the article

The following code sends a POST request that contains a Product instance in JSON format:

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}

How can I convert an HTML element to a canvas element?

No such thing, sorry.

Though the spec states:

A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.

Which may be as close as you'll get.

A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.

The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.

Dynamically allocating an array of objects

For building containers you obviously want to use one of the standard containers (such as a std::vector). But this is a perfect example of the things you need to consider when your object contains RAW pointers.

If your object has a RAW pointer then you need to remember the rule of 3 (now the rule of 5 in C++11).

  • Constructor
  • Destructor
  • Copy Constructor
  • Assignment Operator
  • Move Constructor (C++11)
  • Move Assignment (C++11)

This is because if not defined the compiler will generate its own version of these methods (see below). The compiler generated versions are not always useful when dealing with RAW pointers.

The copy constructor is the hard one to get correct (it's non trivial if you want to provide the strong exception guarantee). The Assignment operator can be defined in terms of the Copy Constructor as you can use the copy and swap idiom internally.

See below for full details on the absolute minimum for a class containing a pointer to an array of integers.

Knowing that it is non trivial to get it correct you should consider using std::vector rather than a pointer to an array of integers. The vector is easy to use (and expand) and covers all the problems associated with exceptions. Compare the following class with the definition of A below.

class A
{ 
    std::vector<int>   mArray;
    public:
        A(){}
        A(size_t s) :mArray(s)  {}
};

Looking at your problem:

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    // As you surmised the problem is on this line.
    arrayOfAs[i] = A(3);

    // What is happening:
    // 1) A(3) Build your A object (fine)
    // 2) A::operator=(A const&) is called to assign the value
    //    onto the result of the array access. Because you did
    //    not define this operator the compiler generated one is
    //    used.
}

The compiler generated assignment operator is fine for nearly all situations, but when RAW pointers are in play you need to pay attention. In your case it is causing a problem because of the shallow copy problem. You have ended up with two objects that contain pointers to the same piece of memory. When the A(3) goes out of scope at the end of the loop it calls delete [] on its pointer. Thus the other object (in the array) now contains a pointer to memory that has been returned to the system.

The compiler generated copy constructor; copies each member variable by using that members copy constructor. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

The compiler generated assignment operator; copies each member variable by using that members assignment operator. For pointers this just means the pointer value is copied from the source object to the destination object (hence shallow copy).

So the minimum for a class that contains a pointer:

class A
{
    size_t     mSize;
    int*       mArray;
    public:
         // Simple constructor/destructor are obvious.
         A(size_t s = 0) {mSize=s;mArray = new int[mSize];}
        ~A()             {delete [] mArray;}

         // Copy constructor needs more work
         A(A const& copy)
         {
             mSize  = copy.mSize;
             mArray = new int[copy.mSize];

             // Don't need to worry about copying integers.
             // But if the object has a copy constructor then
             // it would also need to worry about throws from the copy constructor.
             std::copy(&copy.mArray[0],&copy.mArray[c.mSize],mArray);

         }

         // Define assignment operator in terms of the copy constructor
         // Modified: There is a slight twist to the copy swap idiom, that you can
         //           Remove the manual copy made by passing the rhs by value thus
         //           providing an implicit copy generated by the compiler.
         A& operator=(A rhs) // Pass by value (thus generating a copy)
         {
             rhs.swap(*this); // Now swap data with the copy.
                              // The rhs parameter will delete the array when it
                              // goes out of scope at the end of the function
             return *this;
         }
         void swap(A& s) noexcept
         {
             using std::swap;
             swap(this.mArray,s.mArray);
             swap(this.mSize ,s.mSize);
         }

         // C++11
         A(A&& src) noexcept
             : mSize(0)
             , mArray(NULL)
         {
             src.swap(*this);
         }
         A& operator=(A&& src) noexcept
         {
             src.swap(*this);     // You are moving the state of the src object
                                  // into this one. The state of the src object
                                  // after the move must be valid but indeterminate.
                                  //
                                  // The easiest way to do this is to swap the states
                                  // of the two objects.
                                  //
                                  // Note: Doing any operation on src after a move 
                                  // is risky (apart from destroy) until you put it 
                                  // into a specific state. Your object should have
                                  // appropriate methods for this.
                                  // 
                                  // Example: Assignment (operator = should work).
                                  //          std::vector() has clear() which sets
                                  //          a specific state without needing to
                                  //          know the current state.
             return *this;
         }   
 }

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

Unable to start MySQL server

Try manually start the service from Windows services, Start -> cmd.exe -> services.msc. Also try to configure the MySQL server to run on another port and try starting it again. Change the my.ini file to change the port number.

Why does intellisense and code suggestion stop working when Visual Studio is open?

Visual Studio 2019

The only thing that worked for me: Go to Tools -> Options -> Text editor -> C# -> Intellisense

And turn off

enter image description here

Turns out I was too eager to try everything that's new in VS :) It was broken in only one solutions though.

jQuery document.createElement equivalent?

jQuery out of the box doesn't have the equivalent of a createElement. In fact the majority of jQuery's work is done internally using innerHTML over pure DOM manipulation. As Adam mentioned above this is how you can achieve similar results.

There are also plugins available that make use of the DOM over innerHTML like appendDOM, DOMEC and FlyDOM just to name a few. Performance wise the native jquery is still the most performant (mainly becasue it uses innerHTML)

How to check if android checkbox is checked within its onClick method (declared in XML)?

You can try this code:

public void itemClicked(View v) {
 //code to check if this checkbox is checked!
 if(((Checkbox)v).isChecked()){
   // code inside if
 }
}

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Allow 2 decimal places in <input type="number">

If case anyone is looking for a regex that allows only numbers with an optional 2 decimal places

^\d*(\.\d{0,2})?$

For an example, I have found solution below to be fairly reliable

HTML:

<input name="my_field" pattern="^\d*(\.\d{0,2})?$" />

JS / JQuery:

$(document).on('keydown', 'input[pattern]', function(e){
  var input = $(this);
  var oldVal = input.val();
  var regex = new RegExp(input.attr('pattern'), 'g');

  setTimeout(function(){
    var newVal = input.val();
    if(!regex.test(newVal)){
      input.val(oldVal); 
    }
  }, 0);
});

Update

setTimeout is not working correctly anymore for this, maybe browsers have changed. Some other async solution will need to be devised.

Hide text within HTML?

you can use css property to hide style="display:none;"

<div style="display:none;">CREDITS_HERE</div>

failed to find target with hash string 'android-22'

Okay you must try this guys it works for me:

  1. Open SDK Manager and Install SDK build tools 22.0.1
  2. Sync gradle That'all

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Warning message

~/venv/lib/python3.4/site-packages/urllib3/connectionpool.py:857: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings InsecureRequestWarning)

In Debian 8 this steps works

  1. In python3 code
import urllib3
urllib3.disable_warnings()
  1. Install two packages on Debian

libssl1.0.0_1.0.2l-1_bpo8+1_amd64.deb

libssl-dev_1.0.2l-1_bpo8+1_amd64.deb

debian mirror

To build dependencies with new library

  1. Create new venv for python project
python3 -m venv .venv
source .venv/bin/activate

Clean Install modules under python project inside virtual environment by

python3 -m pip install -e .

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

if you use external libraries in your program and you try to pack all together in a jar file it's not that simple, because of classpath issues etc.

I'd prefer to use OneJar for this issue.

Including non-Python files with setup.py

None of the answers worked for me because my files were at the top level, outside the package. I used a custom build command instead.

import os
import setuptools
from setuptools.command.build_py import build_py
from shutil import copyfile

HERE = os.path.abspath(os.path.dirname(__file__))
NAME = "thepackage"

class BuildCommand(build_py):
    def run(self):
        build_py.run(self)

        if not self.dry_run:
            target_dir = os.path.join(self.build_lib, NAME)
            for fn in ["VERSION", "LICENSE.txt"]:
                copyfile(os.path.join(HERE, fn), os.path.join(target_dir,fn))

 
 
setuptools.setup(
    name=NAME,
    cmdclass={"build_py": BuildCommand},
    description=DESCRIPTION,
    ...
)

Export pictures from excel file into jpg using VBA

''' Set Range you want to export to the folder

Workbooks("your workbook name").Sheets("yoursheet name").Select

Dim rgExp As Range: Set rgExp = Range("A1:H31")
''' Copy range as picture onto Clipboard
rgExp.CopyPicture Appearance:=xlScreen, Format:=xlBitmap
''' Create an empty chart with exact size of range copied
With ActiveSheet.ChartObjects.Add(Left:=rgExp.Left, Top:=rgExp.Top, _
Width:=rgExp.Width, Height:=rgExp.Height)
.Name = "ChartVolumeMetricsDevEXPORT"
.Activate
End With
''' Paste into chart area, export to file, delete chart.
ActiveChart.Paste
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Chart.Export "C:\ExportmyChart.jpg"
ActiveSheet.ChartObjects("ChartVolumeMetricsDevEXPORT").Delete

SQL Server Management Studio – tips for improving the TSQL coding process

F5 to run the current query is an easy win, after that, the generic MS editor commands of CTRL + K + C to comment out the selected text and then CTRL + K + U to uncomment.

What does 'index 0 is out of bounds for axis 0 with size 0' mean?

This is an IndexError in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.

# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64) 

# check its shape      
In [15]: arr.shape  
Out[15]: (0,)

with this array arr in place, if we now try to assign any value to some index, for example to the index 0 as in the case below

In [16]: arr[0] = 23     

Then, we will get an IndexError, as below:


IndexError                                Traceback (most recent call last)
<ipython-input-16-0891244a3c59> in <module>
----> 1 arr[0] = 23

IndexError: index 0 is out of bounds for axis 0 with size 0

The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0).

In [19]: arr.size * arr.itemsize  
Out[19]: 0

So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0 and fix that.

How do I change select2 box height

You could do this with some simple css. From what I read, you want to set the Height of the element with the class "select2-choices".

.select2-choices {
  min-height: 150px;
  max-height: 150px;
  overflow-y: auto;
}

That should give you a set height of 150px and it will scroll if needed. Simply adjust the height till your image fits as desired.

You can also use css to set the height of the select2-results (the drop down portion of the select control).

ul.select2-results {
 max-height: 200px;
}

200px is the default height, so change it for the desired height of the drop down.

How to check if a function exists on a SQL database

Why not just:

IF object_id('YourFunctionName', 'FN') IS NOT NULL
BEGIN
    DROP FUNCTION [dbo].[YourFunctionName]
END
GO

The second argument of object_id is optional, but can help to identify the correct object. There are numerous possible values for this type argument, particularly:

  • FN : Scalar function
  • IF : Inline table-valued function
  • TF : Table-valued-function
  • FS : Assembly (CLR) scalar-function
  • FT : Assembly (CLR) table-valued function

Replace new line/return with space using regex

This should take care of space, tab and newline:

data = data.replaceAll("[ \t\n\r]*", " ");

Map<String, String>, how to print both the "key string" and "value string" together

final Map<String, String> mss1 = new ProcessBuilder().environment();
mss1.entrySet()
        .stream()
        //depending on how you want to join K and V use different delimiter
        .map(entry -> 
        String.join(":", entry.getKey(),entry.getValue()))
        .forEach(System.out::println);

What's the difference between struct and class in .NET?

Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value

Structs:

  • Are value types and do not require heap allocation.
  • Memory allocation is different and is stored in stack
  • Useful for small data structures
  • Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.
  • Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • Do not support user-specified inheritance, and they implicitly inherit from type object

Class:

  • Reference Type value
  • Stored in Heap
  • Store a reference to a dynamically allocated object
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • Multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable

Code Sample

    static void Main(string[] args)
    {
        //Struct
        myStruct objStruct = new myStruct();
        objStruct.x = 10;
        Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);
        Console.WriteLine();
        methodStruct(objStruct);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);
        Console.WriteLine();

        //Class
        myClass objClass = new myClass(10);
        Console.WriteLine("Initial value of Class Object is: " + objClass.x);
        Console.WriteLine();
        methodClass(objClass);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Class Object is: " + objClass.x);
        Console.Read();
    }
    static void methodStruct(myStruct newStruct)
    {
        newStruct.x = 20;
        Console.WriteLine("Inside Struct Method");
        Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);
    }
    static void methodClass(myClass newClass)
    {
        newClass.x = 20;
        Console.WriteLine("Inside Class Method");
        Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);
    }
    public struct myStruct
    {
        public int x;
        public myStruct(int xCons)
        {
            this.x = xCons;
        }
    }
    public class myClass
    {
        public int x;
        public myClass(int xCons)
        {
            this.x = xCons;
        }
    }

Output

Initial value of Struct Object is: 10

Inside Struct Method Inside Method value of Struct Object is: 20

After Method call value of Struct Object is: 10

Initial value of Class Object is: 10

Inside Class Method Inside Method value of Class Object is: 20

After Method call value of Class Object is: 20

Here you can clearly see the difference between call by value and call by reference.

Where does mysql store data?

I just installed MySQL Server 5.7 on Windows 10 and my.ini file is located here c:\ProgramData\MySQL\MySQL Server 5.7\my.ini.

The Data folder (where your dbs are created) is here C:/ProgramData/MySQL/MySQL Server 5.7\Data.

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

edit this bellow:

_x000D_
_x000D_
$("#message").dialog({_x000D_
 autoOpen:false,_x000D_
 modal:true,_x000D_
 resizable: false,_x000D_
 width:'80%',
_x000D_
_x000D_
_x000D_

How to stop a vb script running in windows

Running scripts can be terminated from the Task Manager.

However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.

Self destruct script:

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True 
WshShell.Run "taskkill /f /im wscript.exe", , True  

Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.

type your shortcut key and all scripts end. Cheers

Eclipse Indigo - Cannot install Android ADT Plugin

Execute eclipse with root level

$sudo /opt/eclipse/eclipse

How can I convert a date to GMT?

You can simply use the toUTCString (or toISOString) methods of the date object.

Example:

new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()

// Output:  "Fri, 20 Jan 2012 16:51:36 GMT"

If you prefer better control of the output format, consider using a library such as date-fns or moment.js.

Also, in your question, you've actually converted the time incorrectly. When an offset is shown in a timestamp string, it means that the date and time values in the string have already been adjusted from UTC by that value. To convert back to UTC, invert the sign before applying the offset.

11:51:36 -0300  ==  14:51:36Z

JavaScript: changing the value of onclick with or without jQuery

BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:

if(isie)
   tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
   $(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index

Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.

package javax.servlet.http does not exist

If you are working with maven project, then add following dependency to your pom.xml

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

How to resolve git stash conflict without commit?

Its not the best way to do it but it works:

$ git stash apply
$ >> resolve your conflict <<
$ >> do what you want to do with your code <<
$ git checkout HEAD -- file/path/to/your/file

Chrome blocks different origin requests

This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).

To avoid it, the browser check the Same-origin policy

Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

Calculate execution time of a SQL query?

Please use

-- turn on statistics IO for IO related 
SET STATISTICS IO ON 
GO

and for time calculation use

SET STATISTICS TIME ON
GO

then It will give result for every query . In messages window near query input window.

How to implement __iter__(self) for a container object (Python)

example for inhert from dict, modify its iter, for example, skip key 2 when in for loop

# method 1
class Dict(dict):
    def __iter__(self):
        keys = self.keys()
        for i in keys:
            if i == 2:
                continue
            yield i

# method 2
class Dict(dict):
    def __iter__(self):
        for i in super(Dict, self).__iter__():
            if i == 2:
                continue
            yield i

Delete data with foreign key in SQL Server table

SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

Deserialize a JSON array in C#

This should work...

JavaScriptSerializer ser = new JavaScriptSerializer();
var records = new ser.Deserialize<List<Record>>(jsonData);

public class Person
{
    public string Name;
    public int Age;
    public string Location;
}
public class Record
{
    public Person record;
}

How do you log all events fired by an element in jQuery?

$('body').on("click mousedown mouseup focus blur keydown change mouseup click dblclick mousemove mouseover mouseout mousewheel keydown keyup keypress textInput touchstart touchmove touchend touchcancel resize scroll zoom focus blur select change submit reset",function(e){
     console.log(e);
}); 

Accessing Object Memory Address

You could reimplement the default repr this way:

def __repr__(self):
    return '<%s.%s object at %s>' % (
        self.__class__.__module__,
        self.__class__.__name__,
        hex(id(self))
    )

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

How to declare a inline object with inline variables without a parent class

You can also do this:

var x = new object[] {
    new { firstName = "john", lastName = "walter" },
    new { brand = "BMW" }
};

And if they are the same anonymous type (firstName and lastName), you won't need to cast as object.

var y = new [] {
    new { firstName = "john", lastName = "walter" },
    new { firstName = "jill", lastName = "white" }
};

Ajax post request in laravel 5 return error 500 (Internal Server Error)

By default Laravel comes with CSRF middleware.

You have 2 options:

  1. Send token in you request
  2. Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array

MySQL remove all whitespaces from the entire column

Since the question is how to replace ALL whitespaces

UPDATE `table` 
SET `col_name` = REPLACE
(REPLACE(REPLACE(`col_name`, ' ', ''), '\t', ''), '\n', '');

How do I install PyCrypto on Windows?

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

This error "RuntimeError: chmod error" occurs because the install script didn't find the chmod command.

How in the world do I get around this?

Solution

You only need to add the MSYS binaries to the PATH and re-run the install script.

(N.B: Note that MinGW comes with MSYS so )

Example

For example, if we are in folder C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1>

C:\.....>set PATH=C:\MinGW\msys\1.0\bin;%PATH%
C:\.....>python setup.py install

Optional: you might need to clean before you re-run the script:

`C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1> python setup.py clean`

Regular expression to find URLs within a string

Here a little bit more optimized regexp:

(?:(?:(https?|ftp|file):\/\/|www\.|ftp\.)|([\w\-_]+(?:\.|\s*\[dot\]\s*[A-Z\-_]+)+))([A-Z\-\.,@?^=%&amp;:\/~\+#]*[A-Z\-\@?^=%&amp;\/~\+#]){2,6}?

Here is test with data: https://regex101.com/r/sFzzpY/6

enter image description here

How to create UILabel programmatically using Swift?

Another code swift3

let myLabel = UILabel()
    myLabel.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
    myLabel.center = CGPoint(x: 0, y: 0)
    myLabel.textAlignment = .center
    myLabel.text = "myLabel!!!!!"
    self.view.addSubview(myLabel)

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

It looks like a common gaps-and-islands problem. The difference between two sequences of row numbers rn1 and rn2 give the "group" number.

Run this query CTE-by-CTE and examine intermediate results to see how it works.

Sample data

I expanded sample data from the question a little.

DECLARE @Source TABLE
(
    EmployeeID int,
    DateStarted date,
    DepartmentID int
)

INSERT INTO @Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001),

(10005,'2013-05-01',001),
(10005,'2013-11-09',001),
(10005,'2013-12-01',002),
(10005,'2014-10-01',001),
(10005,'2016-12-01',001);

Query for SQL Server 2008

There is no LEAD function in SQL Server 2008, so I had to use self-join via OUTER APPLY to get the value of the "next" row for the DateEnd.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,A.DateEnd
FROM
    CTE_Groups
    OUTER APPLY
    (
        SELECT TOP(1) G2.DateStart AS DateEnd
        FROM CTE_Groups AS G2
        WHERE
            G2.EmployeeID = CTE_Groups.EmployeeID
            AND G2.DateStart > CTE_Groups.DateStart
        ORDER BY G2.DateStart
    ) AS A
ORDER BY
    EmployeeID
    ,DateStart
;

Query for SQL Server 2012+

Starting with SQL Server 2012 there is a LEAD function that makes this task more efficient.

WITH
CTE
AS
(
    SELECT
        EmployeeID
        ,DateStarted
        ,DepartmentID
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS rn1
        ,ROW_NUMBER() OVER (PARTITION BY EmployeeID, DepartmentID ORDER BY DateStarted) AS rn2
    FROM @Source
)
,CTE_Groups
AS
(
    SELECT
        EmployeeID
        ,MIN(DateStarted) AS DateStart
        ,DepartmentID
    FROM CTE
    GROUP BY
        EmployeeID
        ,DepartmentID
        ,rn1 - rn2
)
SELECT
    CTE_Groups.EmployeeID
    ,CTE_Groups.DepartmentID
    ,CTE_Groups.DateStart
    ,LEAD(CTE_Groups.DateStart) OVER (PARTITION BY CTE_Groups.EmployeeID ORDER BY CTE_Groups.DateStart) AS DateEnd
FROM
    CTE_Groups
ORDER BY
    EmployeeID
    ,DateStart
;

Result

+------------+--------------+------------+------------+
| EmployeeID | DepartmentID | DateStart  |  DateEnd   |
+------------+--------------+------------+------------+
|      10001 |            1 | 2013-01-01 | 2013-12-01 |
|      10001 |            2 | 2013-12-01 | 2014-10-01 |
|      10001 |            1 | 2014-10-01 | NULL       |
|      10005 |            1 | 2013-05-01 | 2013-12-01 |
|      10005 |            2 | 2013-12-01 | 2014-10-01 |
|      10005 |            1 | 2014-10-01 | NULL       |
+------------+--------------+------------+------------+

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

How do I get a substring of a string in Python?

You've got it right there except for "end". It's called slice notation. Your example should read:

new_sub_string = myString[2:]

If you leave out the second parameter it is implicitly the end of the string.

for or while loop to do something n times

The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

It is worth noting that in Python a for or while statement can have break, continue and else statements where:

  • break - terminates the loop
  • continue - moves on to the next time around the loop without executing following code this time around
  • else - is executed if the loop completed without any break statements being executed.

N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

So the answer to your question is 'it all depends on what you are trying to do'!

Get data from file input in JQuery

 <script src="~/fileupload/fileinput.min.js"></script>
 <link href="~/fileupload/fileinput.min.css" rel="stylesheet" />

Download above files named fileinput add the path i your index page.

<div class="col-sm-9 col-lg-5" style="margin: 0 0 0 8px;">
<input id="uploadFile1" name="file" type="file" class="file-loading"       
 `enter code here`accept=".pdf" multiple>
</div>

<script>
        $("#uploadFile1").fileinput({
            autoReplace: true,
            maxFileCount: 5
        });
</script>

How to make div follow scrolling smoothly with jQuery?

There's a fantastic jQuery tutorial for this at https://web.archive.org/web/20121012171851/http://jqueryfordesigners.com/fixed-floating-elements/.

It replicates the Apple.com shopping cart type of sidebar scrolling. The Google query that might have served you well is "fixed floating sidebar".

How do I create a link to add an entry to a calendar?

You can have the program create an .ics (iCal) version of the calendar and then you can import this .ics into whichever calendar program you'd like: Google, Outlook, etc.

I know this post is quite old, so I won't bother inputting any code. But please comment on this if you'd like me to provide an outline of how to do this.

Custom exception type

You could implement your own exceptions and their handling for example like here:

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e) {
    if (e instanceof NotNumberException) {
        alert("not a number");
    }
    else
    if (e instanceof NotPositiveNumberException) {
        alert("not a positive number");
    }
}

There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):

// define exceptions "classes" 
function NotNumberException() {}
function NotPositiveNumberException() {}

// try some code
try {
    // some function/code that can throw
    if (isNaN(value))
        throw new NotNumberException();
    else
    if (value < 0)
        throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
    alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
    alert("not a positive number");
}

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Parse a URI String into Name-Value Collection

If you come across Android Java SDK;

This solution might be too late but it's the latest solution today.

You can use the below way to get the value of the some query, if there is no value it will return null.

String some = Uri.parse(url).getQueryParameter("some");

In order to get all the names of the query collection.

Set<String> names = Uri.parse(url).getQueryParameterNames();

Keystore type: which one to use?

If you are using Java 8 or newer you should definitely choose PKCS12, the default since Java 9 (JEP 229).

The advantages compared to JKS and JCEKS are:

  • Secret keys, private keys and certificates can be stored
  • PKCS12 is a standard format, it can be read by other programs and libraries1
  • Improved security: JKS and JCEKS are pretty insecure. This can be seen by the number of tools for brute forcing passwords of these keystore types, especially popular among Android developers.2, 3

1 There is JDK-8202837, which has been fixed in Java 11

2 The iteration count for PBE used by all keystore types (including PKCS12) used to be rather weak (CVE-2017-10356), however this has been fixed in 9.0.1, 8u151, 7u161, and 6u171

3 For further reading:

Include PHP inside JavaScript (.js) files

There is not any safe way to include php file into js.

One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.

abc.php

<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>

After use it directly in your js file wherever you want to use.

abc.js

function test(){
   alert('Print php variable : '+ abc +', '+number); 
}

function printArrVar(){
  alert('print php array variable : '+ JSON.stringify(mydata)); 
}

Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.

this is the standard way you can call php script data into js file without including js into php code or php script into js.

Adding external resources (CSS/JavaScript/images etc) in JSP

Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file

<style type="text/css">
    <%@include file="css/style.css" %>
</style>
<script type="text/javascript">
    <%@include file="js/script.js" %>
</script>

Create list of single item repeated N times

>>> [5] * 4
[5, 5, 5, 5]

Be careful when the item being repeated is a list. The list will not be cloned: all the elements will refer to the same list!

>>> x=[5]
>>> y=[x] * 4
>>> y
[[5], [5], [5], [5]]
>>> y[0][0] = 6
>>> y
[[6], [6], [6], [6]]

Git ignore file for Xcode projects

I included these suggestions in a Gist I created on Github: http://gist.github.com/137348

Feel free to fork it, and make it better.

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

Logging with Retrofit 2

Here is an Interceptor that logs both the request and response bodies (using Timber, based on an example from the OkHttp docs and some other SO answers):

public class TimberLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();

        long t1 = System.nanoTime();
        Timber.i("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers());
        Timber.v("REQUEST BODY BEGIN\n%s\nREQUEST BODY END", bodyToString(request));

        Response response = chain.proceed(request);

        ResponseBody responseBody = response.body();
        String responseBodyString = response.body().string();

        // now we have extracted the response body but in the process
        // we have consumed the original reponse and can't read it again
        // so we need to build a new one to return from this method

        Response newResponse = response.newBuilder().body(ResponseBody.create(responseBody.contentType(), responseBodyString.getBytes())).build();

        long t2 = System.nanoTime();
        Timber.i("Received response for %s in %.1fms%n%s", response.request().url(), (t2 - t1) / 1e6d, response.headers());
        Timber.v("RESPONSE BODY BEGIN:\n%s\nRESPONSE BODY END", responseBodyString);

        return newResponse;
    }

    private static String bodyToString(final Request request){

        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }
}

How do I check if file exists in jQuery or pure JavaScript?

A similar and more up-to-date approach.

$.get(url)
    .done(function() { 
        // exists code 
    }).fail(function() { 
        // not exists code
    })

Dialog with transparent background in Android

I've faced the simpler problem and the solution i came up with was applying a transparent bachground THEME. Write these lines in your styles

    <item name="android:windowBackground">@drawable/blue_searchbuttonpopupbackground</item>
</style>
<style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
</style>

And then add

android:theme="@style/Theme.Transparent"

in your main manifest file , inside the block of the dialog activity.

Plus in your dialog activity XML set

 android:background= "#00000000"

Get all table names of a particular database by SQL query?

To select the database query below :

use DatabaseName

Now

SELECT * FROM INFORMATION_SCHEMA.TABLES

Now you can see the created tables below in console .

PFA.

Query

How to build query string with Javascript

This doesn't directly answer your question, but here's a generic function which will create a URL that contains query string parameters. The parameters (names and values) are safely escaped for inclusion in a URL.

function buildUrl(url, parameters){
  var qs = "";
  for(var key in parameters) {
    var value = parameters[key];
    qs += encodeURIComponent(key) + "=" + encodeURIComponent(value) + "&";
  }
  if (qs.length > 0){
    qs = qs.substring(0, qs.length-1); //chop off last "&"
    url = url + "?" + qs;
  }
  return url;
}

// example:
var url = "http://example.com/";

var parameters = {
  name: "George Washington",
  dob: "17320222"
};

console.log(buildUrl(url, parameters));
// => http://www.example.com/?name=George%20Washington&dob=17320222

How to test if a file is a directory in a batch script?

Here's my solution:

REM make sure ERRORLEVEL is 0
TYPE NUL

REM try to PUSHD into the path (store current dir and switch to another one)
PUSHD "insert path here..." >NUL 2>&1

REM if ERRORLEVEL is still 0, it's most definitely a directory
IF %ERRORLEVEL% EQU 0 command...

REM if needed/wanted, go back to previous directory
POPD

Which tool to build a simple web front-end to my database

I think PHP is a good solution. It's simple to set up, free and there is plenty of documentation on how to create a database management app. Ruby on Rails is faster to code but a bit more difficult to set up.

Remove header and footer from window.print()

In Chrome it's possible to hide this automatic header/footer using

@page { margin: 0; }

Since the contents will extend to page's limits, the page printing header/footer will be absent. You should, of course, in this case, set some margins/paddings in your body element so that the content won't extend all the way to the page's edge. Since common printers just can't get no-margins printing and it's probably not what you want, you should use something like this:

@media print {
  @page { margin: 0; }
  body { margin: 1.6cm; }
}

As Martin pointed out in a comment, if the page have a long element that scrolls past one page (like a big table), the margin is ignored and the printed version will look weird.

At the time original of this answer (May 2013), it only worked on Chrome, not sure about it now, never needed to try again. If you need support for a browser that can't hable, you can create a PDF on the fly and print that (you can create a self-printing PDF embedding JavaScript on it), but that's a huge hassle.

How to output MySQL query results in CSV format?

The following produces tab-delimited and valid CSV output. Unlike most of the other answers, this technique correctly handles escaping of tabs, commas, quotes, and new lines without any stream filter like sed, awk, or tr. The example shows how to pipe a remote mysql table directly into a local sqlite database using streams. This works without FILE permission or SELECT INTO OUTFILE permission. I have added new lines for readability.

mysql -B -C --raw -u 'username' --password='password' --host='hostname' 'databasename'
-e 'SELECT
    CONCAT('\''"'\'',REPLACE(`id`,'\''"'\'', '\''""'\''),'\''"'\'') AS '\''id'\'',
    CONCAT('\''"'\'',REPLACE(`value`,'\''"'\'', '\''""'\''),'\''"'\'') AS '\''value'\''
    FROM sampledata'
2>/dev/null | sqlite3 -csv -separator $'\t' mydb.db '.import /dev/stdin mycsvtable'

The 2>/dev/null is needed to suppress the warning about the password on the command line.

If your data has NULLs, you can use the IFNULL() function in the query.

How to manually trigger click event in ReactJS?

Riffing on Aaron Hakala's answer with useRef inspired by this answer https://stackoverflow.com/a/54316368/3893510

const myRef = useRef(null);

  const clickElement = (ref) => {
    ref.current.dispatchEvent(
      new MouseEvent('click', {
        view: window,
        bubbles: true,
        cancelable: true,
        buttons: 1,
      }),
    );
  };

And your JSX:

<button onClick={() => clickElement(myRef)}>Click<button/>
<input ref={myRef}>

Force flushing of output to a file while bash script is still running

Thanks @user3258569, script is maybe the only thing that works in busybox!

The shell was freezing for me after it, though. Looking for the cause, I found these big red warnings "don't use in a non-interactive shells" in script manual page:

script is primarily designed for interactive terminal sessions. When stdin is not a terminal (for example: echo foo | script), then the session can hang, because the interactive shell within the script session misses EOF and script has no clue when to close the session. See the NOTES section for more information.

True. script -c "make_hay" -f /dev/null | grep "needle" was freezing the shell for me.

Countrary to the warning, I thought that echo "make_hay" | script WILL pass a EOF, so I tried

echo "make_hay; exit" | script -f /dev/null | grep 'needle'

and it worked!

Note the warnings in the man page. This may not work for you.

How to open spss data files in excel?

In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.

Here's the software

And here are the steps to export the data.

word-wrap break-word does not work in this example

This combination of properties helped for me:

display: inline-block;
overflow-wrap: break-word;
word-wrap: break-word;
word-break: normal;
line-break: strict;
hyphens: none;
-webkit-hyphens: none;
-moz-hyphens: none;

Youtube autoplay not working on mobile devices with embedded HTML5 player

Have a look on code below. Tested and found working on Mobile and Tablet devices.

<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>

<script>
  // 2. This code loads the IFrame Player API code asynchronously.
  var tag = document.createElement('script');

  tag.src = "https://www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  // 3. This function creates an <iframe> (and YouTube player)
  //    after the API code downloads.
  var player;
  function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
      height: '390',
      width: '640',
      videoId: 'M7lc1UVf-VE',
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
  }

  // 4. The API will call this function when the video player is ready.
  function onPlayerReady(event) {
    event.target.playVideo();
  }

  // 5. The API calls this function when the player's state changes.
  //    The function indicates that when playing a video (state=1),
  //    the player should play for six seconds and then stop.
  var done = false;
  function onPlayerStateChange(event) {
    if (event.data == YT.PlayerState.PLAYING && !done) {
      setTimeout(stopVideo, 6000);
      done = true;
    }
  }
  function stopVideo() {
    player.stopVideo();
  }
</script>

SELECT * WHERE NOT EXISTS

You didn't join the table in your query.

Your original query will always return nothing unless there are no records at all in eotm_dyn, in which case it will return everything.

Assuming these tables should be joined on employeeID, use the following:

SELECT  *
FROM    employees e
WHERE   NOT EXISTS
        (
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID = e.id
        )

You can join these tables with a LEFT JOIN keyword and filter out the NULL's, but this will likely be less efficient than using NOT EXISTS.

Read/Parse text file line by line in VBA

You Can use this code to read line by line in text file and You could also check about the first character is "*" then you can leave that..

Public Sub Test()

    Dim ReadData as String

    Open "C:\satheesh\myfile\file.txt" For Input As #1

    Do Until EOF(1) 
       Line Input #1, ReadData 'Adding Line to read the whole line, not only first 128 positions
    If Not Left(ReadData, 1) = "*" then
       '' you can write the variable ReadData into the database or file
    End If 

    Loop

    Close #1

End Sub

How do I create a dictionary with keys from a list and values defaulting to (say) zero?

dict((el,0) for el in a) will work well.

Python 2.7 and above also support dict comprehensions. That syntax is {el:0 for el in a}.

What is the difference between __str__ and __repr__?

Understand __str__ and __repr__ intuitively and permanently distinguish them at all.

__str__ return the string disguised body of a given object for readable of eyes
__repr__ return the real flesh body of a given object (return itself) for unambiguity to identify.

See it in an example

In [30]: str(datetime.datetime.now())
Out[30]: '2017-12-07 15:41:14.002752'
Disguised in string form

As to __repr__

In [32]: datetime.datetime.now()
Out[32]: datetime.datetime(2017, 12, 7, 15, 43, 27, 297769)
Presence in real body which allows to be manipulated directly.

We can do arithmetic operation on __repr__ results conveniently.

In [33]: datetime.datetime.now()
Out[33]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521)
In [34]: datetime.datetime(2017, 12, 7, 15, 47, 9, 741521) - datetime.datetime(2
    ...: 017, 12, 7, 15, 43, 27, 297769)
Out[34]: datetime.timedelta(0, 222, 443752)

if apply the operation on __str__

In [35]: '2017-12-07 15:43:14.002752' - '2017-12-07 15:41:14.002752'
TypeError: unsupported operand type(s) for -: 'str' and 'str'

Returns nothing but error.

Another example.

In [36]: str('string_body')
Out[36]: 'string_body' # in string form

In [37]: repr('real_body')
Out[37]: "'real_body'" #its real body hide inside

Hope this help you build concrete grounds to explore more answers.

How do I return multiple values from a function in C?

Two different approaches:

  1. Pass in your return values by pointer, and modify them inside the function. You declare your function as void, but it's returning via the values passed in as pointers.
  2. Define a struct that aggregates your return values.

I think that #1 is a little more obvious about what's going on, although it can get tedious if you have too many return values. In that case, option #2 works fairly well, although there's some mental overhead involved in making specialized structs for this purpose.

CSS3 Box Shadow on Top, Left, and Right Only

The following code did it for me to make a shadow inset of the right side:

-moz-box-shadow: inset -10px 0px 10px -10px #000;
-webkit-box-shadow: inset -10px 0px 10px -10px #000;
box-shadow: inset -10px 0px 10px -10px #000;

Hope it will help!!!!

pop/remove items out of a python tuple

Yes we can do it. First convert the tuple into an list, then delete the element in the list after that again convert back into tuple.

Demo:

my_tuple = (10, 20, 30, 40, 50)

# converting the tuple to the list
my_list = list(my_tuple)
print my_list  # output: [10, 20, 30, 40, 50]

# Here i wanna delete second element "20"
my_list.pop(1) # output: [10, 30, 40, 50]
# As you aware that pop(1) indicates second position

# Here i wanna remove the element "50"
my_list.remove(50) # output: [10, 30, 40]

# again converting the my_list back to my_tuple
my_tuple = tuple(my_list)


print my_tuple # output: (10, 30, 40)

Thanks

Postgres could not connect to server

I got same issue because I'm using a wrong Postgres's username in code. I logged into postgres psql -d postgres and enter \du to take role name and correct Postgres's username.

So when you guys face this issue, you guys need to make sure you're using correct Postgres username, password, hostname and database...

Hope this will help anyone

Java Inheritance - calling superclass method

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
    if (something) {
        super.alphaMethod1();
        return;
    }
    // Rest of the code for other situations
}

Like this it will only call A's method when needed and will remain invisible for the class user.

Convert Set to List without creating new List

Map<String, List> mainMap = new HashMap<String, List>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName, new ArrayList(set));
}

Is there an upside down caret character?

So I wanted the caret exactly as in OWA, so I downloaded office365icons.woff from https://owa.example.com/owa/prem/15.1.1913.10/resources/styles/fonts/office365icons.woff (have to be logged in to do it, so did it through browser) and then, copying the boiled-down style from the website:

  @font-face {
      font-family: 'Office365Icons';
      src: url('/fonts/office365icons.woff') format('woff');
      font-weight: normal;
      font-style: normal;
  }

  span.o-icon {
      font-family: 'Office365Icons';
      font-size: 14pt;
      line-height: 21px;
      color: #666;
  }

And finally:

<span class="o-icon">&#xe088;</span>

ExecuteNonQuery doesn't return results

What kind of query do you perform? Using ExecuteNonQuery is intended for UPDATE, INSERT and DELETE queries. As per the documentation:

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

I'm currently working on such a statement and figured out another fact to notice: INSERT OR REPLACE will replace any values not supplied in the statement. For instance if your table contains a column "lastname" which you didn't supply a value for, INSERT OR REPLACE will nullify the "lastname" if possible (constraints allow it) or fail.

How to trigger a build only if changes happen on particular set of files

If the logic for choosing the files is not trivial, I would trigger script execution on each change and then write a script to check if indeed a build is required, then triggering a build if it is.

Is there a difference between using a dict literal and a dict constructor?

There is no dict literal to create dict-inherited classes, custom dict classes with additional methods. In such case custom dict class constructor should be used, for example:

class NestedDict(dict):

    # ... skipped

state_type_map = NestedDict(**{
    'owns': 'Another',
    'uses': 'Another',
})

How to change background color of cell in table using java script

document.getElementById('id1').bgColor = '#00FF00';

seems to work. I don't think .style.backgroundColor does.

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

This is a simple solution for merging two dictionaries where += can be applied to the values, it has to iterate over a dictionary only once

a = {'a':1, 'b':2, 'c':3}

dicts = [{'b':3, 'c':4, 'd':5},
         {'c':9, 'a':9, 'd':9}]

def merge_dicts(merged,mergedfrom):
    for k,v in mergedfrom.items():
        if k in merged:
            merged[k] += v
        else:
            merged[k] = v
    return merged

for dct in dicts:
    a = merge_dicts(a,dct)
print (a)
#{'c': 16, 'b': 5, 'd': 14, 'a': 10}

Get program execution time in the shell

You can get much more detailed information than the bash built-in time (which Robert Gamble mentions) using time(1). Normally this is /usr/bin/time.

Editor's note: To ensure that you're invoking the external utility time rather than your shell's time keyword, invoke it as /usr/bin/time.
time is a POSIX-mandated utility, but the only option it is required to support is -p.
Specific platforms implement specific, nonstandard extensions: -v works with GNU's time utility, as demonstrated below (the question is tagged ); the BSD/macOS implementation uses -l to produce similar output - see man 1 time.

Example of verbose output:

$ /usr/bin/time -v sleep 1
       Command being timed: "sleep 1"
       User time (seconds): 0.00
       System time (seconds): 0.00
       Percent of CPU this job got: 1%
       Elapsed (wall clock) time (h:mm:ss or m:ss): 0:01.05
       Average shared text size (kbytes): 0
       Average unshared data size (kbytes): 0
       Average stack size (kbytes): 0
       Average total size (kbytes): 0
       Maximum resident set size (kbytes): 0
       Average resident set size (kbytes): 0
       Major (requiring I/O) page faults: 0
       Minor (reclaiming a frame) page faults: 210
       Voluntary context switches: 2
       Involuntary context switches: 1
       Swaps: 0
       File system inputs: 0
       File system outputs: 0
       Socket messages sent: 0
       Socket messages received: 0
       Signals delivered: 0
       Page size (bytes): 4096
       Exit status: 0