Programs & Examples On #Workflow foundation 3

How to add a hook to the application context initialization event?

Create your annotation

  @Retention(RetentionPolicy.RUNTIME)
    public @interface AfterSpringLoadComplete {
    }

Create class

    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            try {
                BeanDefinition definition = factory.getBeanDefinition(name);
                String originalClassName = definition.getBeanClassName();
                Class<?> originalClass = Class.forName(originalClassName);
                Method[] methods = originalClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){
                        Object bean = context.getBean(name);
                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
                        currentMethod.invoke(bean);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }
}

Register this class by @Component annotation or in xml

<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

and use annotation where you wan on any method that you want to run after context initialized, like:

   @AfterSpringLoadComplete
    public void init() {}

Preloading CSS Images

You could use this jQuery plugin waitForImage or you could put you images into an hidden div or (width:0 and height:0) and use onload event on images.

If you only have like 2-3 images you can bind events and trigger them in a chain so after every image you can do some code.

Floating point comparison functions for C#

Continuing from the answers provided by Michael and testing, an important thing to keep in mind when translating the original Java code to C# is that Java and C# define their constants differently. C#, for instance, lacks Java's MIN_NORMAL, and the definitions for MinValue differ greatly.

Java defines MIN_VALUE to be the smallest possible positive value, while C# defines it as the smallest possible representable value overall. The equivalent value in C# is Epsilon.

The lack of MIN_NORMAL is problematic for direct translation of the original algorithm - without it, things start to break down for small values near zero. Java's MIN_NORMAL follows the IEEE specification of the smallest possible number without having the leading bit of the significand as zero, and with that in mind, we can define our own normals for both singles and doubles (which dbc mentioned in the comments to the original answer).

The following C# code for singles passes all of the tests given on The Floating Point Guide, and the double edition passes all of the tests with minor modifications in the test cases to account for the increased precision.

public static bool ApproximatelyEqualEpsilon(float a, float b, float epsilon)
{
    const float floatNormal = (1 << 23) * float.Epsilon;
    float absA = Math.Abs(a);
    float absB = Math.Abs(b);
    float diff = Math.Abs(a - b);

    if (a == b)
    {
        // Shortcut, handles infinities
        return true;
    }

    if (a == 0.0f || b == 0.0f || diff < floatNormal)
    {    
        // a or b is zero, or both are extremely close to it.
        // relative error is less meaningful here
        return diff < (epsilon * floatNormal);
    }

    // use relative error
    return diff / Math.Min((absA + absB), float.MaxValue) < epsilon;
}

The version for doubles is identical save for type changes and that the normal is defined like this instead.

const double doubleNormal = (1L << 52) * double.Epsilon;

How to run a PowerShell script from a batch file

If you want to run a few scripts, you can use Set-executionpolicy -ExecutionPolicy Unrestricted and then reset with Set-executionpolicy -ExecutionPolicy Default.

Note that execution policy is only checked when you start its execution (or so it seems) and so you can run jobs in the background and reset the execution policy immediately.

# Check current setting
Get-ExecutionPolicy

# Disable policy
Set-ExecutionPolicy -ExecutionPolicy Unrestricted
# Choose [Y]es

Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 example.com | tee ping__example.com.txt }
Start-Job { cd c:\working\directory\with\script\ ; ./ping_batch.ps1 google.com  | tee ping__google.com.txt  }

# Can be run immediately
Set-ExecutionPolicy -ExecutionPolicy Default
# [Y]es

Download/Stream file from URL - asp.net

You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is

    //Create a stream for the file
    Stream stream = null;

    //This controls how many bytes to read at a time and send to the client
    int bytesToRead = 10000;

    // Buffer to read bytes in chunk size specified above
    byte[] buffer = new Byte[bytesToRead];

    // The number of bytes read
    try
    {
      //Create a WebRequest to get the file
      HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);

      //Create a response for this request
      HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();

      if (fileReq.ContentLength > 0)
        fileResp.ContentLength = fileReq.ContentLength;

        //Get the Stream returned from the response
        stream = fileResp.GetResponseStream();

        // prepare the response to the client. resp is the client Response
        var resp = HttpContext.Current.Response;

        //Indicate the type of data being sent
        resp.ContentType = "application/octet-stream";

        //Name the file 
        resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());

        int length;
        do
        {
            // Verify that the client is connected.
            if (resp.IsClientConnected)
            {
                // Read data into the buffer.
                length = stream.Read(buffer, 0, bytesToRead);

                // and write it out to the response's output stream
                resp.OutputStream.Write(buffer, 0, length);

                // Flush the data
                resp.Flush();

                //Clear the buffer
                buffer = new Byte[bytesToRead];
            }
            else
            {
                // cancel the download if client has disconnected
                length = -1;
            }
        } while (length > 0); //Repeat until no data is read
    }
    finally
    {
        if (stream != null)
        {
            //Close the input stream
            stream.Close();
        }
    }

Using SimpleXML to create an XML object from scratch

In PHP5, you should use the Document Object Model class instead. Example:

$domDoc = new DOMDocument;
$rootElt = $domDoc->createElement('root');
$rootNode = $domDoc->appendChild($rootElt);

$subElt = $domDoc->createElement('foo');
$attr = $domDoc->createAttribute('ah');
$attrVal = $domDoc->createTextNode('OK');
$attr->appendChild($attrVal);
$subElt->appendChild($attr);
$subNode = $rootNode->appendChild($subElt);

$textNode = $domDoc->createTextNode('Wow, it works!');
$subNode->appendChild($textNode);

echo htmlentities($domDoc->saveXML());

SpringApplication.run main method

Using:

@ComponentScan
@EnableAutoConfiguration
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);  

        //do your ReconTool stuff
    }
}

will work in all circumstances. Whether you want to launch the application from the IDE, or the build tool.

Using maven just use mvn spring-boot:run

while in gradle it would be gradle bootRun

An alternative to adding code under the run method, is to have a Spring Bean that implements CommandLineRunner. That would look like:

@Component
public class ReconTool implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
       //implement your business logic here
    }
}

Check out this guide from Spring's official guide repository.

The full Spring Boot documentation can be found here

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

Just had same problem. Using Xcode 8.3.3 and wanted to use AppIcon in Assests catalogue. Tried all sorts of Stack Overflow answers without success.

Finally learned about a deep clean step from Ken/Apple Forum:

  • removed all icon files, whether from resources (delete - trash) or appicon file (select - remove selected items); removed even assets folder
  • deep cleaned (Use the Product menu w/option key pressed, then choose to 'clean build folder')
  • added a new asset catalogue and called it "Assets" right clicked in Assets folder and added new app icon set - changed that one in inspector to be for iOS >=7 triple

  • checked all my icon files OUTSIDE of Xcode (all were already png files of right resolution, but some had still colour profile attached from photoshop elements or did have indexed colour instead of RGB profile. so I made sure I only save a png file without colour profile and from a background layer) - not sure that was necessary

  • archived the build from Product menu
  • validated and uploaded the build from Window - Organizer

Indent List in HTML and CSS

It sounds like some of your styles are being reset.

By default in most browsers, uls and ols have margin and padding added to them.

You can override this (and many do) by adding a line to your css like so

ul, ol {  //THERE MAY BE OTHER ELEMENTS IN THE LIST
    margin:0;
    padding:0;
}

In this case, you would remove the element from this list or add a margin/padding back, like so

ul{
    margin:1em;
}

Example: http://jsfiddle.net/jasongennaro/vbMbQ/1/

How to populate a dropdownlist with json data in jquery?

try this one its worked for me

_x000D_
_x000D_
$(document).ready(function(e){_x000D_
        $.ajax({_x000D_
           url:"fetch",_x000D_
           processData: false,_x000D_
           dataType:"json",_x000D_
           type: 'POST',_x000D_
           cache: false,_x000D_
           success: function (data, textStatus, jqXHR) {_x000D_
                        _x000D_
                         $.each(data.Table,function(i,tweet){_x000D_
      $("#list").append('<option value="'+tweet.actor_id+'">'+tweet.first_name+'</option>');_x000D_
   });}_x000D_
        });_x000D_
    });
_x000D_
_x000D_
_x000D_

Android - How to download a file from a webserver

Using Async task

call when you want to download file : new DownloadFileFromURL().execute(file_url);

public class MainActivity extends Activity {

    // Progress Dialog
    private ProgressDialog pDialog;
    public static final int progress_bar_type = 0;

    // File url to download
    private static String file_url = "http://www.qwikisoft.com/demo/ashade/20001.kml";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        new DownloadFileFromURL().execute(file_url);

    }

    /**
     * Showing Dialog
     * */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }

    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {

        /**
         * Before starting background thread Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }

        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection connection = url.openConnection();
                connection.connect();

                // this will be useful so that you can show a tipical 0-100%
                // progress bar
                int lenghtOfFile = connection.getContentLength();

                // download the file
                InputStream input = new BufferedInputStream(url.openStream(),
                        8192);

                // Output stream
                OutputStream output = new FileOutputStream(Environment
                        .getExternalStorageDirectory().toString()
                        + "/2011.kml");

                byte data[] = new byte[1024];

                long total = 0;

                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // writing data to file
                    output.write(data, 0, count);
                }

                // flushing output
                output.flush();

                // closing streams
                output.close();
                input.close();

            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }

            return null;
        }

        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
        }

        /**
         * After completing background task Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);

        }

    }
}

if not working in 4.0 then add:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 

How to get base url with jquery or javascript?

I was just on the same stage and this solution works for me

In the view

<?php
    $document = JFactory::getDocument();

    $document->addScriptDeclaration('var base = \''.JURI::base().'\'');
    $document->addScript('components/com_name/js/filter.js');
?>

In js file you access base as a variable for example in your scenario:

console.log(base) // will print
// http://www.example.com/
// http://localhost/example
// http://www.example.com/sub/example

I do not remember where I take this information to give credit, if I find it I will edit the answer

Waiting for another flutter command to release the startup lock

Restart your IDE first and then run the following command in project folder from terminal

killall -9 dart

It worked for me. Hope it will help some of the guys facing the same problem.

How do search engines deal with AngularJS applications?

The crawlers do not need a rich featured pretty styled gui, they only want to see the content, so you do not need to give them a snapshot of a page that has been built for humans.

My solution: to give the crawler what the crawler wants:

You must think of what do the crawler want, and give him only that.

TIP don't mess with the back. Just add a little server-sided frontview using the same API

How to set up a cron job to run an executable every hour?

0 * * * * cd folder_containing_exe && ./exe_name

should work unless there is something else that needs to be setup for the program to run.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

In my case I have replaced my build.gradle file this line

implementation 'com.google.firebase:firebase-core:16.0.8'

with

implementation 'com.google.firebase:firebase-core:15.0.0' 

and added this line

implementation 'com.google.android.gms:play-services-location:15.0.0'

Now its fine

How to set Navigation Drawer to be opened from right to left

Add this code to manifest:

<application android:supportsRtl="true">

and then write this code on Oncreate:

getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

It works for me. ;)

How to remove the arrow from a select element in Firefox

/* Try this in FF30+ Covers up the arrow, turns off the background */ 
/* still lets you style the border around the image and allows selection on the arrow */


@-moz-document url-prefix() {

    .yourClass select {
        text-overflow: '';
        text-indent: -1px;
        -moz-appearance: none;
        background: none;

    }

    /*fix for popup in FF30 */
    .yourClass:after {
        position: absolute;
        margin-left: -27px;
        height: 22px;
        border-top-right-radius: 6px;
        border-bottom-right-radius: 6px;
        content: url('../images/yourArrow.svg');
        pointer-events: none;
        overflow: hidden;
        border-right: 1px solid #yourBorderColour;
        border-top: 1px solid #yourBorderColour;
        border-bottom: 1px solid #yourBorderColour; 
    }
}

can you host a private repository for your organization to use with npm?

I don't think there is an easy way to do this.

A look at the npm documentation tells us, that it is possible:

Can I run my own private registry?

Yes!

The easiest way is to replicate the couch database, and use the same (or similar) design doc to implement the APIs.

If you set up continuous replication from the official CouchDB, and then set your internal CouchDB as the registry config, then you'll be able to read any published packages, in addition to your private ones, and by default will only publish internally. If you then want to publish a package for the whole world to see, you can simply override the --registry config for that command.

There's also an excellent tutorial on how to create a private npm repository in the clock blog.

EDIT (2017-02-26):

Not really new, but there are now paid plans to host private packages on NPM.

Over the years, NPM has become a factor for many non-Node.js companies, too, through the huge frontend ecosystem that's built upon NPM. If your company is already running Sonatype Nexus for hosting Java projects internally, you can also use it for hosting internal NPM packages.

Other options include JFrog Artifactory and Inedo ProGet, but I haven't used those.

Usage of __slots__?

Slots are very useful for library calls to eliminate the "named method dispatch" when making function calls. This is mentioned in the SWIG documentation. For high performance libraries that want to reduce function overhead for commonly called functions using slots is much faster.

Now this may not be directly related to the OPs question. It is related more to building extensions than it does to using the slots syntax on an object. But it does help complete the picture for the usage of slots and some of the reasoning behind them.

Error:java: javacTask: source release 8 requires target release 1.8

Many answers regarding Maven are right but you don't have to configure the plugin directly.

Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.

<project>
  [...]
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  [...]
</project>

Is there a command line utility for rendering GitHub flavored Markdown?

Probably not what you want, but since you mentioned Node.js: I could not find a good tool to preview GitHub Flavored Markdown documentation on my local drive before committing them to GitHub, so today I created one, based on Node.js: https://github.com/ypocat/gfms

So perhaps you can reuse the showdown.js from it for your Wiki, if your question is still actual. If not, maybe other people facing the same problem as I did will find (just as I did) this question and this answer to it.

Paste multiple columns together

library(plyr)

ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[2:4],sep="",collapse="-"))))

#      x
#1 a-d-g
#2 b-e-h
#3 c-f-i

#  and with just the vector of names you have:

ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[c('b','c','d')],sep="",collapse="-"))))

# or equally:
mynames <-c('b','c','d')
ldply(apply(data, 1, function(x) data.frame(
                      x = paste(x[mynames],sep="",collapse="-"))))    

Checking for NULL pointer in C/C++

Frankly, I don't see why it matters. Either one is quite clear and anyone moderately experienced with C or C++ should understand both. One comment, though:

If you plan to recognize the error and not continue executing the function (i.e., you are going to throw an exception or return an error code immediately), you should make it a guard clause:

int f(void* p)
{
    if (!p) { return -1; }

    // p is not null
    return 0;
}

This way, you avoid "arrow code."

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This means that the first parameter you passed is a boolean (true or false).

The first parameter is $result, and it is false because there is a syntax error in the query.

" ... WHERE PartNumber = $partid';"

You should never directly include a request variable in a SQL query, else the users are able to inject SQL in your queries. (See SQL injection.)

You should escape the variable:

" ... WHERE PartNumber = '" . mysqli_escape_string($conn,$partid) . "';"

Or better, use Prepared Statements.

Python import csv to list

Unfortunately I find none of the existing answers particularly satisfying.

Here is a straightforward and complete Python 3 solution, using the csv module.

import csv

with open('../resources/temp_in.csv', newline='') as f:
    reader = csv.reader(f, skipinitialspace=True)
    rows = list(reader)

print(rows)

Notice the skipinitialspace=True argument. This is necessary since, unfortunately, OP's CSV contains whitespace after each comma.

Output:

[['This is the first line', 'Line1'], ['This is the second line', 'Line2'], ['This is the third line', 'Line3']]

How to select all instances of selected region in Sublime Text

Even though there are multiple answers, there is an issue using this approach. It selects all the text that matches, not only the whole words like variables.

As per "Sublime Text: Select all instances of a variable and edit variable name" and the answer in "Sublime Text: Select all instances of a variable and edit variable name", we have to start with a empty selection. That is, start using the shortcut Alt+F3 which would help selecting only the whole words.

invalid byte sequence for encoding "UTF8"

psql=# copy tmp from '/path/to/file.csv' with delimiter ',' csv header encoding 'windows-1251';

Adding encoding option worked in my case.

Remove all the elements that occur in one list from another

Performance Comparisons

Comparing the performance of all the answers mentioned here on Python 3.9.1 and Python 2.7.16.

Python 3.9.1

Answers are mentioned in order of performance:

  1. Arkku's set difference using subtraction "-" operation - (91.3 nsec per loop)

    mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
    5000000 loops, best of 5: 91.3 nsec per loop
    
  2. Moinuddin Quadri's using set().difference()- (133 nsec per loop)

    mquadri$ python3 -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
    2000000 loops, best of 5: 133 nsec per loop
    
  3. Moinuddin Quadri's list comprehension with set based lookup- (366 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 5: 366 nsec per loop
    
  4. Donut's list comprehension on plain list - (489 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
     500000 loops, best of 5: 489 nsec per loop
    
  5. Daniel Pryden's generator expression with set based lookup and type-casting to list - (583 nsec per loop) : Explicitly type-casting to list to get the final object as list, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set based lookup.

     mquadri$ mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
     500000 loops, best of 5: 583 nsec per loop
    
  6. Moinuddin Quadri's using filter() and explicitly type-casting to list (need to explicitly type-cast as in Python 3.x, it returns iterator) - (681 nsec per loop)

     mquadri$ python3 -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(filter(lambda x: x not in l2, l1))"
     500000 loops, best of 5: 681 nsec per loop
    
  7. Akshay Hazari's using combination of functools.reduce + filter -(3.36 usec per loop) : Explicitly type-casting to list as from Python 3.x it started returned returning iterator. Also we need to import functools to use reduce in Python 3.x

     mquadri$ python3 -m timeit "from functools import reduce; l1 = [1,2,6,8]; l2 = [2,3,5,8];" "list(reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2))"
     100000 loops, best of 5: 3.36 usec per loop
    

Python 2.7.16

Answers are mentioned in order of performance:

  1. Arkku's set difference using subtraction "-" operation - (0.0783 usec per loop)

    mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1 - l2"
    10000000 loops, best of 3: 0.0783 usec per loop
    
  2. Moinuddin Quadri's using set().difference()- (0.117 usec per loop)

    mquadri$ mquadri$ python -m timeit -s "l1 = set([1,2,6,8]); l2 = set([2,3,5,8]);" "l1.difference(l2)"
    10000000 loops, best of 3: 0.117 usec per loop
    
  3. Moinuddin Quadri's list comprehension with set based lookup- (0.246 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 3: 0.246 usec per loop
    
  4. Donut's list comprehension on plain list - (0.372 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "[x for x in l1 if x not in l2]"
     1000000 loops, best of 3: 0.372 usec per loop
    
  5. Moinuddin Quadri's using filter() - (0.593 usec per loop)

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "filter(lambda x: x not in l2, l1)"
     1000000 loops, best of 3: 0.593 usec per loop
    
  6. Daniel Pryden's generator expression with set based lookup and type-casting to list - (0.964 per loop) : Explicitly type-casting to list to get the final object as list, as requested by OP. If generator expression is replaced with list comprehension, it'll become same as Moinuddin Quadri's list comprehension with set based lookup.

     mquadri$ python -m timeit -s "l1 = [1,2,6,8]; l2 = set([2,3,5,8]);" "list(x for x in l1 if x not in l2)"
     1000000 loops, best of 3: 0.964 usec per loop
    
  7. Akshay Hazari's using combination of functools.reduce + filter -(2.78 usec per loop)

     mquadri$ python -m timeit "l1 = [1,2,6,8]; l2 = [2,3,5,8];" "reduce(lambda x,y : filter(lambda z: z!=y,x) ,l1,l2)"
     100000 loops, best of 3: 2.78 usec per loop
    

Use of Custom Data Types in VBA

Sure you can:

Option Explicit

'***** User defined type
Public Type MyType
     MyInt As Integer
     MyString As String
     MyDoubleArr(2) As Double
End Type

'***** Testing MyType as single variable
Public Sub MyFirstSub()
    Dim MyVar As MyType

    MyVar.MyInt = 2
    MyVar.MyString = "cool"
    MyVar.MyDoubleArr(0) = 1
    MyVar.MyDoubleArr(1) = 2
    MyVar.MyDoubleArr(2) = 3

    Debug.Print "MyVar: " & MyVar.MyInt & " " & MyVar.MyString & " " & MyVar.MyDoubleArr(0) & " " & MyVar.MyDoubleArr(1) & " " & MyVar.MyDoubleArr(2)
End Sub

'***** Testing MyType as an array
Public Sub MySecondSub()
    Dim MyArr(2) As MyType
    Dim i As Integer

    MyArr(0).MyInt = 31
    MyArr(0).MyString = "VBA"
    MyArr(0).MyDoubleArr(0) = 1
    MyArr(0).MyDoubleArr(1) = 2
    MyArr(0).MyDoubleArr(2) = 3
    MyArr(1).MyInt = 32
    MyArr(1).MyString = "is"
    MyArr(1).MyDoubleArr(0) = 11
    MyArr(1).MyDoubleArr(1) = 22
    MyArr(1).MyDoubleArr(2) = 33
    MyArr(2).MyInt = 33
    MyArr(2).MyString = "cool"
    MyArr(2).MyDoubleArr(0) = 111
    MyArr(2).MyDoubleArr(1) = 222
    MyArr(2).MyDoubleArr(2) = 333

    For i = LBound(MyArr) To UBound(MyArr)
        Debug.Print "MyArr: " & MyArr(i).MyString & " " & MyArr(i).MyInt & " " & MyArr(i).MyDoubleArr(0) & " " & MyArr(i).MyDoubleArr(1) & " " & MyArr(i).MyDoubleArr(2)
    Next
End Sub

How can I update npm on Windows?

You can use these commands:

npm cache clean
npm update -g [package....]

If you are upgrading from a previous version of node, then you will want to update all existing global packages. You can also specify the package name to be updated.

A valid provisioning profile for this executable was not found for debug mode

This looks like a bug (I'm using XCode 7.3.1).

Trying to use XCode->Product->Profile spat out the "no valid provision profile" error.

By sheer dumb luck I got it working simply by running the app on my attached device using a normal compile, then going to the "Debug Navigator" and clicking on "Profile in Instruments" in the top right corner.

enter image description here

Push origin master error on new repository

To actually resolve the issue I used the following command to stage all my files to the commit.

$ git add .
$ git commit -m 'Your message here'
$ git push origin master

The problem I had was that the -u command in git add didn't actually add the new files and the git add -A command wasn't supported on my installation of git. Thus as mentioned in this thread the commit I was trying to stage was empty.

How to convert "0" and "1" to false and true

You can use that form:

return returnValue.Equals("1") ? true : false;

Or more simply (thanks to Jurijs Kastanovs):

return returnValue.Equals("1");

Undefined reference to static class member

No idea why the cast works, but Foo::MEMBER isn't allocated until the first time Foo is loaded, and since you're never loading it, it's never allocated. If you had a reference to a Foo somewhere, it would probably work.

JMS Topic vs Queues

That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.

forEach is not a function error with JavaScript array

parent.children is not an array. It is HTMLCollection and it does not have forEach method. You can convert it to the array first. For example in ES6:

Array.from(parent.children).forEach(child => {
    console.log(child)
});

or using spread operator:

[...parent.children].forEach(function (child) {
    console.log(child)
});

Is there more to an interface than having the correct methods

I think you understand everything Interfaces do, but you're not yet imagining the situations in which an Interface is useful.

If you're instantiating, using and releasing an object all within a narrow scope (for example, within one method call), an Interface doesn't really add anything. Like you noted, the concrete class is known.

Where Interfaces are useful is when an object needs to be created one place and returned to a caller that may not care about the implementation details. Let's change your IBox example to an Shape. Now we can have implementations of Shape such as Rectangle, Circle, Triangle, etc., The implementations of the getArea() and getSize() methods will be completely different for each concrete class.

Now you can use a factory with a variety of createShape(params) methods which will return an appropriate Shape depending on the params passed in. Obviously, the factory will know about what type of Shape is being created, but the caller won't have to care about whether it's a circle, or a square, or so on.

Now, imagine you have a variety of operations you have to perform on your shapes. Maybe you need to sort them by area, set them all to a new size, and then display them in a UI. The Shapes are all created by the factory and then can be passed to the Sorter, Sizer and Display classes very easily. If you need to add a hexagon class some time in the future, you don't have to change anything but the factory. Without the Interface, adding another shape becomes a very messy process.

Using sed to split a string with a delimiter

This should do it:

cat ~/Desktop/myfile.txt | sed s/:/\\n/g

Java correct way convert/cast object to Double

I tried this and it worked:

Object obj = 10;
String str = obj.toString(); 
double d = Double.valueOf(str).doubleValue();

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

get DATEDIFF excluding weekends using sql server

Example query below, here are some details on how I solved it.

Using DATEDIFF(WK, ...) will give us the number of weeks between the 2 dates. SQL Server evaluates this as a difference between week numbers rather than based on the number of days. This is perfect, since we can use this to determine how many weekends passed between the dates.

So we can multiple that value by 2 to get the number of weekend days that occurred and subtract that from the DATEDIFF(dd, ...) to get the number of weekdays.

This doesn't behave 100% correctly when the start or end date falls on Sunday, though. So I added in some case logic at the end of the calculation to handle those instances.

You may also want to consider whether or not the DATEDIFF should be fully inclusive. e.g. Is the difference between 9/10 and 9/11 1 day or 2 days? If the latter, you'll want to add 1 to the final product.

declare @d1 datetime, @d2 datetime
select @d1 = '9/9/2011',  @d2 = '9/18/2011'

select datediff(dd, @d1, @d2) - (datediff(wk, @d1, @d2) * 2) -
       case when datepart(dw, @d1) = 1 then 1 else 0 end +
      case when datepart(dw, @d2) = 1 then 1 else 0 end

How to remove unused C/C++ symbols with GCC and ld?

Programming habits could help too; e.g. add static to functions that are not accessed outside a specific file; use shorter names for symbols (can help a bit, likely not too much); use const char x[] where possible; ... this paper, though it talks about dynamic shared objects, can contain suggestions that, if followed, can help to make your final binary output size smaller (if your target is ELF).

How to change line width in ggplot?

It also looks like if you just put the size argument in the geom_line() portion but without the aes() it will scale appropriately. At least it works this way with geom_density and I had the same problem.

How to find index of an object by key and value in an javascript array

Not a direct answer to your question, though I thing it's worth mentioning it, because your question seems like fitting in the general case of "getting things by name in a key-value storage".

If you are not tight to the way "peoples" is implemented, a more JavaScript-ish way of getting the right guy might be :

var peoples = {
  "bob":  { "dinner": "pizza" },
  "john": { "dinner": "sushi" },
  "larry" { "dinner": "hummus" }
};

// If people is implemented this way, then
// you can get values from their name, like :
var theGuy = peoples["john"];

// You can event get directly to the values
var thatGuysPrefferedDinner = peoples["john"].dinner;

Hope if this is not the answer you wanted, it might help people interested in that "key/value" question.

How to convert int to Integer

i it integer, int to Integer

Integer intObj = new Integer(i);

add to collection

list.add(String.valueOf(intObj));

Why can't I have abstract static methods in C#?

This question is 12 years old but it still needs to be given a better answer. As few noted in the comments and contrarily to what all answers pretend it would certainly make sense to have static abstract methods in C#. As philosopher Daniel Dennett put it, a failure of imagination is not an insight into necessity. There is a common mistake in not realizing that C# is not only an OOP language. A pure OOP perspective on a given concept leads to a restricted and in the current case misguided examination. Polymorphism is not only about subtying polymorphism: it also includes parametric polymorphism (aka generic programming) and C# has been supporting this for a long time now. Within this additional paradigm, abstract classes (and most types) are not only used to type instances. They can also be used as bounds for generic parameters; something that has been understood by users of certain languages (like for example Haskell, but also more recently Scala, Rust or Swift) for years.

In this context you may want to do something like this:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = TAnimal.ScientificName; // abstract static property
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

And here the capacity to express static members that can be specialized by subclasses totally makes sense!

Unfortunately C# does not allow abstract static members but I'd like to propose a pattern that can emulate them reasonably well. This pattern is not perfect (it imposes some restrictions on inheritance) but as far as I can tell it is typesafe.

The main idea is to associate an abstract companion class (here SpeciesFor<TAnimal>) to the one that should contain abstract members (here Animal):

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal
{
    public static SpeciesFor<TAnimal> Instance { get { … } }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

public abstract class Animal { … }

Now we would like to make this work:

void Catch<TAnimal>() where TAnimal : Animal
{
    string scientificName = SpeciesFor<TAnimal>.Instance.ScientificName;
    Console.WriteLine($"Let's catch some {scientificName}");
    …
}

Of course we have two problems to solve:

  1. How do we allow and force an implementer of a subclass of Animal to associate a specific instance of SpeciesFor<TAnimal> to this subclass?
  2. How does the property SpeciesFor<TAnimal>.Instance retrieve this information?

Here is how we can solve 1:

public abstract class Animal<TSelf> where TSelf : Animal<TSelf>
{
    private Animal(…) {}
    
    public abstract class OfSpecies<TSpecies> : Animal<TSelf>
        where TSpecies : SpeciesFor<TSelf>, new()
    {
        protected OfSpecies(…) : base(…) { }
    }
    
    …
}

By making the constructor of Animal<TSelf> private we make sure that all its subclasses are also subclasses of inner class Animal<TSelf>.OfSpecies<TSpecies>. So these subclasses must specify a TSpecies type that has a new() bound.

For 2 we can provide the following implementation:

public abstract class SpeciesFor<TAnimal> where TAnimal : Animal<TAnimal>
{
    private static SpeciesFor<TAnimal> _instance;

    public static SpeciesFor<TAnimal> Instance => _instance ??= MakeInstance();

    private static SpeciesFor<TAnimal> MakeInstance()
    {
        Type t = typeof(TAnimal);
        while (true)
        {
            if (t.IsConstructedGenericType
                    && t.GetGenericTypeDefinition() == typeof(Animal<>.OfSpecies<>))
                return (SpeciesFor<TAnimal>)Activator.CreateInstance(t.GenericTypeArguments[1]);
            t = t.BaseType;
            if (t == null)
                throw new InvalidProgramException();
        }
    }

    // abstract "static" members

    public abstract string ScientificName { get; }
    
    …
}

How can we be sure that the reflection code inside MakeInstance() never throws? As we've already said, almost all classes within the hierarchy of Animal<TSelf> are also subclasses of Animal<TSelf>.OfSpecies<TSpecies>. So we know that for these classes a specific TSpecies must be provided. This type is also necessarily constructible thanks to constraint : new(). But this still leaves abstract types like Animal<Something> that have no associated species. Now we can convince ourself that the curiously recurring template pattern where TAnimal : Animal<TAnimal> makes it impossible to write SpeciesFor<Animal<Something>>.Instance as type Animal<Something> is never a subtype of Animal<Animal<Something>>.

Et voilà:

public class CatSpecies : SpeciesFor<Cat>
{
    // overriden "static" members

    public override string ScientificName => "Felis catus";
    public override Cat CreateInVivoFromDnaTrappedInAmber() { … }
    public override Cat Clone(Cat a) { … }
    public override Cat Breed(Cat a1, Cat a2) { … }
}

public class Cat : Animal<Cat>.OfSpecies<CatSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class DogSpecies : SpeciesFor<Dog>
{
    // overriden "static" members

    public override string ScientificName => "Canis lupus familiaris";
    public override Dog CreateInVivoFromDnaTrappedInAmber() { … }
    public override Dog Clone(Dog a) { … }
    public override Dog Breed(Dog a1, Dog a2) { … }
}

public class Dog : Animal<Dog>.OfSpecies<DogSpecies>
{
    // overriden members

    public override string CuteName { get { … } }
}

public class Program
{
    public static void Main()
    {
        ConductCrazyScientificExperimentsWith<Cat>();
        ConductCrazyScientificExperimentsWith<Dog>();
        ConductCrazyScientificExperimentsWith<Tyranosaurus>();
        ConductCrazyScientificExperimentsWith<Wyvern>();
    }
    
    public static void ConductCrazyScientificExperimentsWith<TAnimal>()
        where TAnimal : Animal<TAnimal>
    {
        // Look Ma! No animal instance polymorphism!
        
        TAnimal a2039 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a2988 = SpeciesFor<TAnimal>.Instance.CreateInVivoFromDnaTrappedInAmber();
        TAnimal a0400 = SpeciesFor<TAnimal>.Instance.Clone(a2988);
        TAnimal a9477 = SpeciesFor<TAnimal>.Instance.Breed(a0400, a2039);
        TAnimal a9404 = SpeciesFor<TAnimal>.Instance.Breed(a2988, a9477);
        
        Console.WriteLine(
            "The confederation of mad scientists is happy to announce the birth " +
            $"of {a9404.CuteName}, our new {SpeciesFor<TAnimal>.Instance.ScientificName}.");
    }
}

A limitation of this pattern is that it is not possible (as far as I can tell) to extend the class hierarchy in a satifying manner. For example we cannot introduce an intermediary Mammal class associated to a MammalClass companion. Another is that it does not work for static members in interfaces which would be more flexible than abstract classes.

Importing Excel into a DataTable Quickly

Caling .Value2 is an expensive operation because it's a COM-interop call. I would instead read the entire range into an array and then loop through the array:

object[,] data = Range.Value2;

// Create new Column in DataTable
for (int cCnt = 1; cCnt <= Range.Columns.Count; cCnt++)
{
    textBox3.Text = cCnt.ToString();

    var Column = new DataColumn();
    Column.DataType = System.Type.GetType("System.String");
    Column.ColumnName = cCnt.ToString();
    DT.Columns.Add(Column);

    // Create row for Data Table
    for (int rCnt = 1; rCnt <= Range.Rows.Count; rCnt++)
    {
        textBox2.Text = rCnt.ToString();

        string CellVal = String.Empty;
        try
        {
            cellVal = (string)(data[rCnt, cCnt]);
        }
        catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException)
        {
            ConvertVal = (double)(data[rCnt, cCnt]);
            cellVal = ConvertVal.ToString();
        }

        DataRow Row;

        // Add to the DataTable
        if (cCnt == 1)
        {

            Row = DT.NewRow();
            Row[cCnt.ToString()] = cellVal;
            DT.Rows.Add(Row);
        }
        else
        {

            Row = DT.Rows[rCnt + 1];
            Row[cCnt.ToString()] = cellVal;

        }
    }
} 

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

HTML form with multiple "actions"

the best way (for me) to make it it's the next infrastructure:

<form method="POST">
<input type="submit" formaction="default_url_when_press_enter" style="visibility: hidden; display: none;">
<!-- all your inputs -->
<input><input><input>
<!-- all your inputs -->
<button formaction="action1">Action1</button>
<button formaction="action2">Action2</button>
<input type="submit" value="Default Action">
</form>

with this structure you will send with enter a direction and the infinite possibilities for the rest of buttons.

In what cases will HTTP_REFERER be empty

I have found the browser referer implementation to be really inconsistent.

For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.

<a href="http://foo.com/foo" download="bar">click to download</a>

Is broken in Chrome - no referer sent.

Set Label Text with JQuery

The checkbox is in a td, so need to get the parent first:

$("input:checkbox").on("change", function() {
    $(this).parent().next().find("label").text("TESTTTT");
});

Alternatively, find a label which has a for with the same id (perhaps more performant than reverse traversal) :

$("input:checkbox").on("change", function() {
    $("label[for='" + $(this).attr('id') + "']").text("TESTTTT");
});

Or, to be more succinct just this.id:

$("input:checkbox").on("change", function() {
    $("label[for='" + this.id + "']").text("TESTTTT");
});

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

How to remove files and directories quickly via terminal (bash shell)

Yes, there is. The -r option tells rm to be recursive, and remove the entire file hierarchy rooted at its arguments; in other words, if given a directory, it will remove all of its contents and then perform what is effectively an rmdir.

The other two options you should know are -i and -f. -i stands for interactive; it makes rm prompt you before deleting each and every file. -f stands for force; it goes ahead and deletes everything without asking. -i is safer, but -f is faster; only use it if you're absolutely sure you're deleting the right thing. You can specify these with -r or not; it's an independent setting.

And as usual, you can combine switches: rm -r -i is just rm -ri, and rm -r -f is rm -rf.

Also note that what you're learning applies to bash on every Unix OS: OS X, Linux, FreeBSD, etc. In fact, rm's syntax is the same in pretty much every shell on every Unix OS. OS X, under the hood, is really a BSD Unix system.

How to add number of days to today's date?

I've found this to be a pain in javascript. Check out this link that helped me. Have you ever thought of extending the date object.

http://pristinecoder.com/Blog/post/javascript-formatting-date-in-javascript

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

How to change Bootstrap's global default font size?

Bootstrap uses the variable:

$font-size-base: 1rem; // Assumes the browser default, typically 16px

I don't recommend mucking with this, but you can. Best practice is to override the browser default base font size with:

html {
  font-size: 14px;
}

Bootstrap will then take that value and use it via rems to set values for all kinds of things.

Elegant ways to support equivalence ("equality") in Python classes

Consider this simple problem:

class Number:

    def __init__(self, number):
        self.number = number


n1 = Number(1)
n2 = Number(1)

n1 == n2 # False -- oops

So, Python by default uses the object identifiers for comparison operations:

id(n1) # 140400634555856
id(n2) # 140400634555920

Overriding the __eq__ function seems to solve the problem:

def __eq__(self, other):
    """Overrides the default implementation"""
    if isinstance(other, Number):
        return self.number == other.number
    return False


n1 == n2 # True
n1 != n2 # True in Python 2 -- oops, False in Python 3

In Python 2, always remember to override the __ne__ function as well, as the documentation states:

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false. Accordingly, when defining __eq__(), one should also define __ne__() so that the operators will behave as expected.

def __ne__(self, other):
    """Overrides the default implementation (unnecessary in Python 3)"""
    return not self.__eq__(other)


n1 == n2 # True
n1 != n2 # False

In Python 3, this is no longer necessary, as the documentation states:

By default, __ne__() delegates to __eq__() and inverts the result unless it is NotImplemented. There are no other implied relationships among the comparison operators, for example, the truth of (x<y or x==y) does not imply x<=y.

But that does not solve all our problems. Let’s add a subclass:

class SubNumber(Number):
    pass


n3 = SubNumber(1)

n1 == n3 # False for classic-style classes -- oops, True for new-style classes
n3 == n1 # True
n1 != n3 # True for classic-style classes -- oops, False for new-style classes
n3 != n1 # False

Note: Python 2 has two kinds of classes:

  • classic-style (or old-style) classes, that do not inherit from object and that are declared as class A:, class A(): or class A(B): where B is a classic-style class;

  • new-style classes, that do inherit from object and that are declared as class A(object) or class A(B): where B is a new-style class. Python 3 has only new-style classes that are declared as class A:, class A(object): or class A(B):.

For classic-style classes, a comparison operation always calls the method of the first operand, while for new-style classes, it always calls the method of the subclass operand, regardless of the order of the operands.

So here, if Number is a classic-style class:

  • n1 == n3 calls n1.__eq__;
  • n3 == n1 calls n3.__eq__;
  • n1 != n3 calls n1.__ne__;
  • n3 != n1 calls n3.__ne__.

And if Number is a new-style class:

  • both n1 == n3 and n3 == n1 call n3.__eq__;
  • both n1 != n3 and n3 != n1 call n3.__ne__.

To fix the non-commutativity issue of the == and != operators for Python 2 classic-style classes, the __eq__ and __ne__ methods should return the NotImplemented value when an operand type is not supported. The documentation defines the NotImplemented value as:

Numeric methods and rich comparison methods may return this value if they do not implement the operation for the operands provided. (The interpreter will then try the reflected operation, or some other fallback, depending on the operator.) Its truth value is true.

In this case the operator delegates the comparison operation to the reflected method of the other operand. The documentation defines reflected methods as:

There are no swapped-argument versions of these methods (to be used when the left argument does not support the operation but the right argument does); rather, __lt__() and __gt__() are each other’s reflection, __le__() and __ge__() are each other’s reflection, and __eq__() and __ne__() are their own reflection.

The result looks like this:

def __eq__(self, other):
    """Overrides the default implementation"""
    if isinstance(other, Number):
        return self.number == other.number
    return NotImplemented

def __ne__(self, other):
    """Overrides the default implementation (unnecessary in Python 3)"""
    x = self.__eq__(other)
    if x is NotImplemented:
        return NotImplemented
    return not x

Returning the NotImplemented value instead of False is the right thing to do even for new-style classes if commutativity of the == and != operators is desired when the operands are of unrelated types (no inheritance).

Are we there yet? Not quite. How many unique numbers do we have?

len(set([n1, n2, n3])) # 3 -- oops

Sets use the hashes of objects, and by default Python returns the hash of the identifier of the object. Let’s try to override it:

def __hash__(self):
    """Overrides the default implementation"""
    return hash(tuple(sorted(self.__dict__.items())))

len(set([n1, n2, n3])) # 1

The end result looks like this (I added some assertions at the end for validation):

class Number:

    def __init__(self, number):
        self.number = number

    def __eq__(self, other):
        """Overrides the default implementation"""
        if isinstance(other, Number):
            return self.number == other.number
        return NotImplemented

    def __ne__(self, other):
        """Overrides the default implementation (unnecessary in Python 3)"""
        x = self.__eq__(other)
        if x is not NotImplemented:
            return not x
        return NotImplemented

    def __hash__(self):
        """Overrides the default implementation"""
        return hash(tuple(sorted(self.__dict__.items())))


class SubNumber(Number):
    pass


n1 = Number(1)
n2 = Number(1)
n3 = SubNumber(1)
n4 = SubNumber(4)

assert n1 == n2
assert n2 == n1
assert not n1 != n2
assert not n2 != n1

assert n1 == n3
assert n3 == n1
assert not n1 != n3
assert not n3 != n1

assert not n1 == n4
assert not n4 == n1
assert n1 != n4
assert n4 != n1

assert len(set([n1, n2, n3, ])) == 1
assert len(set([n1, n2, n3, n4])) == 2

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Is there a way to make a DIV unselectable?

You can use pointer-events: none; in your CSS

div {
  pointer-events: none;
}

Number of days between past date and current date in Google spreadsheet

The following seemed to work well for me:

=DATEDIF(B2, Today(), "D")

How to set a border for an HTML div tag

Try being explicit about all the border properties. For example:

border:1px solid black;

See Border shorthand property. Although the other bits are optional some browsers don't set the width or colour to a default you'd expect. In your case I'd bet that it's the width that's zero unless specified.

OnClick in Excel VBA

I don't think so. But you can create a shape object ( or wordart or something similiar ) hook Click event and place the object to position of the specified cell.

Convert float to double without losing precision

A simple solution that works well, is to parse the double from the string representation of the float:

double val = Double.valueOf(String.valueOf(yourFloat));

Not super efficient, but it works!

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

Make an Android button change background on click through XML

In the latest version of the SDK, you would use the setBackgroundResource method.

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setBackgroundResource(R.drawable.ImageResource);
   }
}

Functions that return a function

Imagine the function as a type, like an int. You can return ints in a function. You can return functions too, they are object of type "function".

Now the syntax problem: because functions returns values, how can you return a function and not it's returning value?

by omitting brackets! Because without brackets, the function won't be executed! So:

return b;

Will return the "function" (imagine it like if you are returning a number), while:

return b();

First executes the function then return the value obtained by executing it, it's a big difference!

Comments in Markdown

How about putting the comments in a non-eval, non-echo R block? i.e.,

```{r echo=FALSE, eval=FALSE}
All the comments!
```

Seems to work well for me.

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

jQuery UI autocomplete with item and id

My code only worked when I added 'return false' to the select function. Without this, the input was set with the right value inside the select function and then it was set to the id value after the select function was over. The return false solved this problem.

$('#sistema_select').autocomplete({

    minLength: 3,
    source: <?php echo $lista_sistemas;?> ,
    select: function (event, ui) {
         $('#sistema_select').val(ui.item.label); // display the selected text
         $('#sistema_select_id').val(ui.item.value); // save selected id to hidden input
         return false;
     },
    change: function( event, ui ) {
        $( "#sistema_select_id" ).val( ui.item? ui.item.value : 0 );
    } 
});

In addition, I added a function to the change event because, if the user writes something in the input or erases a part of the item label after one item was selected, I need to update the hidden field so that I don´t get the wrong (outdated) id. For example, if my source is:

var $local_source = [
       {value: 1,  label: "c++"}, 
       {value: 2,  label: "java"}]

and the user type ja and select the 'java' option with the autocomplete, I store the value 2 in the hidden field. If the user erase a letter from 'java', por exemple ending up with 'jva' in the input field, I can´t pass to my code the id 2, because the user changed the value. In this case I set the id to 0.

Page redirect after certain time PHP

You can try this:

header('Refresh: 10; URL=http://yoursite.com/page.php');

Where 10 is in seconds.

How to read first N lines of a file?


fname = input("Enter file name: ")
num_lines = 0

with open(fname, 'r') as f: #lines count
    for line in f:
        num_lines += 1

num_lines_input = int (input("Enter line numbers: "))

if num_lines_input <= num_lines:
    f = open(fname, "r")
    for x in range(num_lines_input):
        a = f.readline()
        print(a)

else:
    f = open(fname, "r")
    for x in range(num_lines_input):
        a = f.readline()
        print(a)
        print("Don't have", num_lines_input, " lines print as much as you can")


print("Total lines in the text",num_lines)

Mock functions in Go

Personally, I don't use gomock (or any mocking framework for that matter; mocking in Go is very easy without it). I would either pass a dependency to the downloader() function as a parameter, or I would make downloader() a method on a type, and the type can hold the get_page dependency:

Method 1: Pass get_page() as a parameter of downloader()

type PageGetter func(url string) string

func downloader(pageGetterFunc PageGetter) {
    // ...
    content := pageGetterFunc(BASE_URL)
    // ...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    downloader(get_page)
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader(t *testing.T) {
    downloader(mock_get_page)
}

Method2: Make download() a method of a type Downloader:

If you don't want to pass the dependency as a parameter, you could also make get_page() a member of a type, and make download() a method of that type, which can then use get_page:

type PageGetter func(url string) string

type Downloader struct {
    get_page PageGetter
}

func NewDownloader(pg PageGetter) *Downloader {
    return &Downloader{get_page: pg}
}

func (d *Downloader) download() {
    //...
    content := d.get_page(BASE_URL)
    //...
}

Main:

func get_page(url string) string { /* ... */ }

func main() {
    d := NewDownloader(get_page)
    d.download()
}

Test:

func mock_get_page(url string) string {
    // mock your 'get_page()' function here
}

func TestDownloader() {
    d := NewDownloader(mock_get_page)
    d.download()
}

How to set the UITableView Section title programmatically (iPhone/iPad)?

Use the UITableViewDataSource method

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

How to run mvim (MacVim) from Terminal?

If you have homeBrew installed, this is all you have to do:

brew install macvim
brew linkapps

Then type mvim in your terminal to run MacVim.

Most efficient way to check for DBNull and then assign to a variable?

I have IsDBNull in a program which reads a lot of data from a database. With IsDBNull it loads data in about 20 seconds. Without IsDBNull, about 1 second.

So I think it is better to use:

public String TryGetString(SqlDataReader sqlReader, int row)
{
    String res = "";
    try
    {
        res = sqlReader.GetString(row);
    }
    catch (Exception)
    { 
    }
    return res;
}

Difference between RUN and CMD in a Dockerfile

RUN - command triggers while we build the docker image.

CMD - command triggers while we launch the created docker image.

Linux command to list all available commands and aliases

There is the

type -a mycommand

command which lists all aliases and commands in $PATH where mycommand is used. Can be used to check if the command exists in several variants. Other than that... There's probably some script around that parses $PATH and all aliases, but don't know about any such script.

Using Switch Statement to Handle Button Clicks

Just change the class (I suppose it's the main Activity) to implement View.OnClickListener and on the onClick method put the general onClick actions you want to put:

public class MediaPlayer extends Activity implements OnClickListener {

@Override
public void onCreate(Bundle savedInstanceState) {
    Button b1 = (Button) findViewById(R.id.buttonplay);       
    b1.setOnClickListener(this);
    //{YOUR APP}
}


@Override
public void onClick(View v) {
    // Perform action on click
    switch(v.getId()) {
    case R.id.buttonplay:
        //Play voicefile
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).start();
        break;
    case R.id.buttonstop:
        //Stop MediaPlayer
        MediaPlayer.create(getBaseContext(), R.raw.voicefile).stop();
        break;
    }

}}

I took it from this video: http://www.youtube.com/watch?v=rm-hNlTD1H0 . It's good for starters.

JSON and escaping characters

This is SUPER late and probably not relevant anymore, but if anyone stumbles upon this answer, I believe I know the cause.

So the JSON encoded string is perfectly valid with the degree symbol in it, as the other answer mentions. The problem is most likely in the character encoding that you are reading/writing with. Depending on how you are using Gson, you are probably passing it a java.io.Reader instance. Any time you are creating a Reader from an InputStream, you need to specify the character encoding, or java.nio.charset.Charset instance (it's usually best to use java.nio.charset.StandardCharsets.UTF_8). If you don't specify a Charset, Java will use your platform default encoding, which on Windows is usually CP-1252.

Remove header and footer from window.print()

Firefox :

  • Add moznomarginboxes attribute in <html>

Example :

<html moznomarginboxes mozdisallowselectionprint>

Convert np.array of type float64 to type uint8 scaling values

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

Could not load file or assembly '***.dll' or one of its dependencies

I ran into this recently. It turned out that the old DLL was compiled with a previous version (Visual Studio 2008) and was referencing that version of the dynamic runtime libraries. I was trying to run it on a system that only had .NET 4.0 on it and I'd never installed any dynamic runtime libraries. The solution? I recompiled the DLL to link the static runtime libraries.

Check your application error log in Event Viewer (EVENTVWR.EXE). It will give you more information on the error and will probably point you at the real cause of the problem.

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

Python argparse command line flags without arguments

Here's a quick way to do it, won't require anything besides sys.. though functionality is limited:

flag = "--flag" in sys.argv[1:]

[1:] is in case if the full file name is --flag

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

Install gcc.

If you're on linux, use the package manager.

If you're on Windows, use MinGW.

SQL Server: Get table primary key using sql query

This should list all the constraints and at the end you can put your filters

/* CAST IS DONE , SO THAT OUTPUT INTEXT FILE REMAINS WITH SCREEN LIMIT*/
WITH   ALL_KEYS_IN_TABLE (CONSTRAINT_NAME,CONSTRAINT_TYPE,PARENT_TABLE_NAME,PARENT_COL_NAME,PARENT_COL_NAME_DATA_TYPE,REFERENCE_TABLE_NAME,REFERENCE_COL_NAME) 
AS
(
SELECT  CONSTRAINT_NAME= CAST (PKnUKEY.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE=CAST (PKnUKEY.type_desc AS VARCHAR(30)) ,
        PARENT_TABLE_NAME=CAST (PKnUTable.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( PKnUKEYCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE=  oParentColDtl.DATA_TYPE,        
        REFERENCE_TABLE_NAME='' ,
        REFERENCE_COL_NAME='' 

FROM sys.key_constraints as PKnUKEY
    INNER JOIN sys.tables as PKnUTable
            ON PKnUTable.object_id = PKnUKEY.parent_object_id
    INNER JOIN sys.index_columns as PKnUColIdx
            ON PKnUColIdx.object_id = PKnUTable.object_id
            AND PKnUColIdx.index_id = PKnUKEY.unique_index_id
    INNER JOIN sys.columns as PKnUKEYCol
            ON PKnUKEYCol.object_id = PKnUTable.object_id
            AND PKnUKEYCol.column_id = PKnUColIdx.column_id
     INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=PKnUTable.name
            AND oParentColDtl.COLUMN_NAME=PKnUKEYCol.name
UNION ALL
SELECT  CONSTRAINT_NAME= CAST (oConstraint.name AS VARCHAR(30)) ,
        CONSTRAINT_TYPE='FK',
        PARENT_TABLE_NAME=CAST (oParent.name AS VARCHAR(30)) ,
        PARENT_COL_NAME=CAST ( oParentCol.name AS VARCHAR(30)) ,
        PARENT_COL_NAME_DATA_TYPE= oParentColDtl.DATA_TYPE,     
        REFERENCE_TABLE_NAME=CAST ( oReference.name AS VARCHAR(30)) ,
        REFERENCE_COL_NAME=CAST (oReferenceCol.name AS VARCHAR(30)) 
FROM sys.foreign_key_columns FKC
    INNER JOIN sys.sysobjects oConstraint
            ON FKC.constraint_object_id=oConstraint.id 
    INNER JOIN sys.sysobjects oParent
            ON FKC.parent_object_id=oParent.id
    INNER JOIN sys.all_columns oParentCol
            ON FKC.parent_object_id=oParentCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.parent_column_id=oParentCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/
    INNER JOIN sys.sysobjects oReference
            ON FKC.referenced_object_id=oReference.id
    INNER JOIN INFORMATION_SCHEMA.COLUMNS oParentColDtl
            ON oParentColDtl.TABLE_NAME=oParent.name
            AND oParentColDtl.COLUMN_NAME=oParentCol.name
    INNER JOIN sys.all_columns oReferenceCol
            ON FKC.referenced_object_id=oReferenceCol.object_id /* ID of the object to which this column belongs.*/
            AND FKC.referenced_column_id=oReferenceCol.column_id/* ID of the column. Is unique within the object.Column IDs might not be sequential.*/

)

select * from   ALL_KEYS_IN_TABLE
where   
    PARENT_TABLE_NAME  in ('YOUR_TABLE_NAME') 
    or REFERENCE_TABLE_NAME  in ('YOUR_TABLE_NAME')
ORDER BY PARENT_TABLE_NAME,CONSTRAINT_NAME;

For reference please read thru - http://blogs.msdn.com/b/sqltips/archive/2005/09/16/469136.aspx

Jquery Change Height based on Browser Size/Resize

$(function(){
    $(window).resize(function(){
        var h = $(window).height();
        var w = $(window).width();
        $("#elementToResize").css('height',(h < 768 || w < 1024) ? 500 : 400);
    });
});

Scrollbars etc have an effect on the window size so you may want to tweak to desired size.

Autocompletion in Vim

There is also https://github.com/Valloric/YouCompleteMe and it includes things like Jedi and also has fuzzy match. So far I found YCM to be the fastest among what I have tried.

Edit: There also exists some new ones like https://github.com/maralla/completor.vim

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

You should copy the image files from the "drawable-24" folder to the "drawable" folder.

More Pythonic Way to Run a Process X Times

Personally:

for _ in range(50):
    print "Some thing"

if you don't need i. If you use Python < 3 and you want to repeat the loop a lot of times, use xrange as there is no need to generate the whole list beforehand.

Uint8Array to string in Javascript

If you can't use the TextDecoder API because it is not supported on IE:

  1. You can use the FastestSmallestTextEncoderDecoder polyfill recommended by the Mozilla Developer Network website;
  2. You can use this function also provided at the MDN website:

_x000D_
_x000D_
function utf8ArrayToString(aBytes) {_x000D_
    var sView = "";_x000D_
    _x000D_
    for (var nPart, nLen = aBytes.length, nIdx = 0; nIdx < nLen; nIdx++) {_x000D_
        nPart = aBytes[nIdx];_x000D_
        _x000D_
        sView += String.fromCharCode(_x000D_
            nPart > 251 && nPart < 254 && nIdx + 5 < nLen ? /* six bytes */_x000D_
                /* (nPart - 252 << 30) may be not so safe in ECMAScript! So...: */_x000D_
                (nPart - 252) * 1073741824 + (aBytes[++nIdx] - 128 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 247 && nPart < 252 && nIdx + 4 < nLen ? /* five bytes */_x000D_
                (nPart - 248 << 24) + (aBytes[++nIdx] - 128 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 239 && nPart < 248 && nIdx + 3 < nLen ? /* four bytes */_x000D_
                (nPart - 240 << 18) + (aBytes[++nIdx] - 128 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 223 && nPart < 240 && nIdx + 2 < nLen ? /* three bytes */_x000D_
                (nPart - 224 << 12) + (aBytes[++nIdx] - 128 << 6) + aBytes[++nIdx] - 128_x000D_
            : nPart > 191 && nPart < 224 && nIdx + 1 < nLen ? /* two bytes */_x000D_
                (nPart - 192 << 6) + aBytes[++nIdx] - 128_x000D_
            : /* nPart < 127 ? */ /* one byte */_x000D_
                nPart_x000D_
        );_x000D_
    }_x000D_
    _x000D_
    return sView;_x000D_
}_x000D_
_x000D_
let str = utf8ArrayToString([50,72,226,130,130,32,43,32,79,226,130,130,32,226,135,140,32,50,72,226,130,130,79]);_x000D_
_x000D_
// Must show 2H2 + O2 ? 2H2O_x000D_
console.log(str);
_x000D_
_x000D_
_x000D_

Chrome disable SSL checking for sites?

Mac Users please execute the below command from terminal to disable the certificate warning.

/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --ignore-certificate-errors --ignore-urlfetcher-cert-requests &> /dev/null

Note that this will also have Google Chrome mark all HTTPS sites as insecure in the URL bar.

Converting 24 hour time to 12 hour time w/ AM & PM using Javascript

You could try this more generic function:

function to12HourFormat(date = (new Date)) {
  return {
    hours: ((date.getHours() + 11) % 12 + 1),
    minutes: date.getMinutes(),
    meridian: (date.getHours() >= 12) ? 'PM' : 'AM',
  };
}

Returns a flexible object format.

https://jsbin.com/vexejanovo/edit

Writing new lines to a text file in PowerShell

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath

Translating touch events from Javascript to jQuery

jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent (see the Special Properties subheading on this page).

How to add months to a date in JavaScript?

I took a look at the datejs and stripped out the code necessary to add months to a date handling edge cases (leap year, shorter months, etc):

Date.isLeapYear = function (year) { 
    return (((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0)); 
};

Date.getDaysInMonth = function (year, month) {
    return [31, (Date.isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month];
};

Date.prototype.isLeapYear = function () { 
    return Date.isLeapYear(this.getFullYear()); 
};

Date.prototype.getDaysInMonth = function () { 
    return Date.getDaysInMonth(this.getFullYear(), this.getMonth());
};

Date.prototype.addMonths = function (value) {
    var n = this.getDate();
    this.setDate(1);
    this.setMonth(this.getMonth() + value);
    this.setDate(Math.min(n, this.getDaysInMonth()));
    return this;
};

This will add "addMonths()" function to any javascript date object that should handle edge cases. Thanks to Coolite Inc!

Use:

var myDate = new Date("01/31/2012");
var result1 = myDate.addMonths(1);

var myDate2 = new Date("01/31/2011");
var result2 = myDate2.addMonths(1);

->> newDate.addMonths -> mydate.addMonths

result1 = "Feb 29 2012"

result2 = "Feb 28 2011"

jQuery `.is(":visible")` not working in Chrome

I need to use visibility:hidden insted of display:none because visibility takes events, while display does not.

So I do .attr('visibility') === "visible"

How to hide Android soft keyboard on EditText

This will help you

editText.setInputType(InputType.TYPE_NULL);

Edit:

To show soft keyboard, you have to write following code in long key press event of menu button

editText.setInputType(InputType.TYPE_CLASS_TEXT);
            editText.requestFocus();
            InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            mgr.showSoftInput(editText, InputMethodManager.SHOW_FORCED);

Font Awesome not working, icons showing as squares

My problem was with adding the

<link rel="stylesheet" href="bower_components/font-awesome/css/font-awesome.min.css">

inside a

<!-- build:css assets/styles/main.css -->
<!-- endbuild -->

tag

I fixed it by placing it outside the tag.

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

Spring MVC Controller redirect using URL parameters instead of in response

@RequestMapping(path="/apps/add", method=RequestMethod.POST)
public String addApps(String appUrl, Model model, final RedirectAttributes redirectAttrs) {
    if (!validate(appUrl)) {
       redirectAttrs.addFlashAttribute("error", "Validation failed");
    }
    return "redirect:/apps/add"
} 

@RequestMapping(path="/apps/add", method=RequestMethod.GET)
public String addAppss(Model model) {
    String error = model.asMap().get("error");
}

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

While other answers nicely described all differences between C++ casts, I would like to add a short note why you should not use C-style casts (Type) var and Type(var).

For C++ beginners C-style casts look like being the superset operation over C++ casts (static_cast<>(), dynamic_cast<>(), const_cast<>(), reinterpret_cast<>()) and someone could prefer them over the C++ casts. In fact C-style cast is the superset and shorter to write.

The main problem of C-style casts is that they hide developer real intention of the cast. The C-style casts can do virtually all types of casting from normally safe casts done by static_cast<>() and dynamic_cast<>() to potentially dangerous casts like const_cast<>(), where const modifier can be removed so the const variables can be modified and reinterpret_cast<>() that can even reinterpret integer values to pointers.

Here is the sample.

int a=rand(); // Random number.

int* pa1=reinterpret_cast<int*>(a); // OK. Here developer clearly expressed he wanted to do this potentially dangerous operation.

int* pa2=static_cast<int*>(a); // Compiler error.
int* pa3=dynamic_cast<int*>(a); // Compiler error.

int* pa4=(int*) a; // OK. C-style cast can do such cast. The question is if it was intentional or developer just did some typo.

*pa4=5; // Program crashes.

The main reason why C++ casts were added to the language was to allow a developer to clarify his intentions - why he is going to do that cast. By using C-style casts which are perfectly valid in C++ you are making your code less readable and more error prone especially for other developers who didn't create your code. So to make your code more readable and explicit you should always prefer C++ casts over C-style casts.

Here is a short quote from Bjarne Stroustrup's (the author of C++) book The C++ Programming Language 4th edition - page 302.

This C-style cast is far more dangerous than the named conversion operators because the notation is harder to spot in a large program and the kind of conversion intended by the programmer is not explicit.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

I had similar issues when trying to connect to Google's OAuth2 service.

I ended up writing the POST manually, not using WebRequest, like this:

TcpClient client = new TcpClient("accounts.google.com", 443);
Stream netStream = client.GetStream();
SslStream sslStream = new SslStream(netStream);
sslStream.AuthenticateAsClient("accounts.google.com");

{
    byte[] contentAsBytes = Encoding.ASCII.GetBytes(content.ToString());

    StringBuilder msg = new StringBuilder();
    msg.AppendLine("POST /o/oauth2/token HTTP/1.1");
    msg.AppendLine("Host: accounts.google.com");
    msg.AppendLine("Content-Type: application/x-www-form-urlencoded");
    msg.AppendLine("Content-Length: " + contentAsBytes.Length.ToString());
    msg.AppendLine("");
    Debug.WriteLine("Request");
    Debug.WriteLine(msg.ToString());
    Debug.WriteLine(content.ToString());

    byte[] headerAsBytes = Encoding.ASCII.GetBytes(msg.ToString());
    sslStream.Write(headerAsBytes);
    sslStream.Write(contentAsBytes);
}

Debug.WriteLine("Response");

StreamReader reader = new StreamReader(sslStream);
while (true)
{  // Print the response line by line to the debug stream for inspection.
    string line = reader.ReadLine();
    if (line == null) break;
    Debug.WriteLine(line);
}

The response that gets written to the response stream contains the specific error text that you're after.

In particular, my problem was that I was putting endlines between url-encoded data pieces. When I took them out, everything worked. You might be able to use a similar technique to connect to your service and read the actual response error text.

Using os.walk() to recursively traverse directories in Python

Given a folder name, walk through its entire hierarchy recursively.

#! /usr/local/bin/python3
# findLargeFiles.py - given a folder name, walk through its entire hierarchy
#                   - print folders and files within each folder

import os

def recursive_walk(folder):
    for folderName, subfolders, filenames in os.walk(folder):
        if subfolders:
            for subfolder in subfolders:
                recursive_walk(subfolder)
        print('\nFolder: ' + folderName + '\n')
        for filename in filenames:
            print(filename + '\n')

recursive_walk('/name/of/folder')

Return Boolean Value on SQL Select Statement

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

Test if number is odd or even

I am making an assumption that there is a counter already in place. in $i which is incremented at the end of a loop, This works for me using a shorthand query.

$row_pos = ($i & 1) ? 'odd' : 'even';

So what does this do, well it queries the statement we are making in essence $i is odd, depending whether its true or false will decide what gets returned. The returned value populates our variable $row_pos

My use of this is to place it inside the foreach loop, right before i need it, This makes it a very efficient one liner to give me the appropriate class names, this is because i already have a counter for the id's to make use of later in the program. This is a brief example of how i will use this part.

<div class='row-{$row_pos}'> random data <div>

This gives me odd and even classes on each row so i can use the correct class and stripe my printed results down the page.

The full example of what i use note the id has the counter applied to it and the class has my odd/even result applied to it.:

$i=0;
foreach ($a as $k => $v) {

    $row_pos = ($i & 1) ? 'odd' : 'even';
    echo "<div id='A{$i}' class='row-{$row_pos}'>{$v['f_name']} {$v['l_name']} - {$v['amount']} - {$v['date']}</div>\n";

$i++;
}

in summary, this gives me a very simple way to create a pretty table.

C++ template typedef

C++11 added alias declarations, which are generalization of typedef, allowing templates:

template <size_t N>
using Vector = Matrix<N, 1>;

The type Vector<3> is equivalent to Matrix<3, 1>.


In C++03, the closest approximation was:

template <size_t N>
struct Vector
{
    typedef Matrix<N, 1> type;
};

Here, the type Vector<3>::type is equivalent to Matrix<3, 1>.

How to select a range of the second row to the last row

Try this:

Dim Lastrow As Integer
Lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

Range("A2:L" & Lastrow).Select

Let's pretend that the value of Lastrow is 50. When you use the following:

Range("A2:L2" & Lastrow).Select

Then it is selecting a range from A2 to L250.

How do I combine two data-frames based on two columns?

See the documentation on ?merge, which states:

By default the data frames are merged on the columns with names they both have, 
 but separate specifications of the columns can be given by by.x and by.y.

This clearly implies that merge will merge data frames based on more than one column. From the final example given in the documentation:

x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match

This example was meant to demonstrate the use of incomparables, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x and y using by.x and by.y.

str_replace with array

Alternatively to the answer marked as correct, if you have to replace words instead of chars you can do it with this piece of code :

$query = "INSERT INTO my_table VALUES (?, ?, ?, ?);";
$values = Array("apple", "oranges", "mangos", "papayas");
foreach (array_fill(0, count($values), '?') as $key => $wildcard) {
    $query = substr_replace($query, '"'.$values[$key].'"', strpos($query, $wildcard), strlen($wildcard));
}
echo $query;

Demo here : http://sandbox.onlinephpfunctions.com/code/56de88aef7eece3d199d57a863974b84a7224fd7

How to get Android application id?

i'm not sure what "application id" you are referring to, but for a unique identifier of your application you can use:

getApplication().getPackageName() method from your current activity

"elseif" syntax in JavaScript

Actually, technically when indented properly, it would be:

if (condition) {
    ...
} else {
    if (condition) {
        ...
    } else {
        ...
    }
}

There is no else if, strictly speaking.

(Update: Of course, as pointed out, the above is not considered good style.)

How to add anything in <head> through jquery/javascript?

Try a javascript pure:

Library JS:

appendHtml = function(element, html) {
    var div = document.createElement('div');
    div.innerHTML = html;
    while (div.children.length > 0) {
        element.appendChild(div.children[0]);
    }
}

Type: appendHtml(document.head, '<link rel="stylesheet" type="text/css" href="http://example.com/example.css"/>');

or jQuery:

$('head').append($('<link rel="stylesheet" type="text/css" />').attr('href', 'http://example.com/example.css'));

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

Make copy of an array

If you must work with raw arrays and not ArrayList then Arrays has what you need. If you look at the source code, these are the absolutely best ways to get a copy of an array. They do have a good bit of defensive programming because the System.arraycopy() method throws lots of unchecked exceptions if you feed it illogical parameters.

You can use either Arrays.copyOf() which will copy from the first to Nth element to the new shorter array.

public static <T> T[] copyOf(T[] original, int newLength)

Copies the specified array, truncating or padding with nulls (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values. For any indices that are valid in the copy but not the original, the copy will contain null. Such indices will exist if and only if the specified length is greater than that of the original array. The resulting array is of exactly the same class as the original array.

2770
2771    public static <T,U> T[] More ...copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
2772        T[] copy = ((Object)newType == (Object)Object[].class)
2773            ? (T[]) new Object[newLength]
2774            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
2775        System.arraycopy(original, 0, copy, 0,
2776                         Math.min(original.length, newLength));
2777        return copy;
2778    }

or Arrays.copyOfRange() will also do the trick:

public static <T> T[] copyOfRange(T[] original, int from, int to)

Copies the specified range of the specified array into a new array. The initial index of the range (from) must lie between zero and original.length, inclusive. The value at original[from] is placed into the initial element of the copy (unless from == original.length or from == to). Values from subsequent elements in the original array are placed into subsequent elements in the copy. The final index of the range (to), which must be greater than or equal to from, may be greater than original.length, in which case null is placed in all elements of the copy whose index is greater than or equal to original.length - from. The length of the returned array will be to - from. The resulting array is of exactly the same class as the original array.

3035    public static <T,U> T[] More ...copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType) {
3036        int newLength = to - from;
3037        if (newLength < 0)
3038            throw new IllegalArgumentException(from + " > " + to);
3039        T[] copy = ((Object)newType == (Object)Object[].class)
3040            ? (T[]) new Object[newLength]
3041            : (T[]) Array.newInstance(newType.getComponentType(), newLength);
3042        System.arraycopy(original, from, copy, 0,
3043                         Math.min(original.length - from, newLength));
3044        return copy;
3045    }

As you can see, both of these are just wrapper functions over System.arraycopy with defensive logic that what you are trying to do is valid.

System.arraycopy is the absolute fastest way to copy arrays.

Save and load MemoryStream to/from a file

I use a Panel Control to add a image or even stream video, but you can save the image on SQL Server as Image or MySQL as largeblob. This code works for me a lot. Check it out.

Here you save the image

MemoryStream ms = new MemoryStream();
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, panel1.Bounds);
bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg); // here you can change the Image format
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
ms.Close();

And here you can load, but I used a PictureBox Control.

MemoryStream ms = new MemoryStream(picarr);
ms.Seek(0, SeekOrigin.Begin);
fotos.pictureBox1.Image = System.Drawing.Image.FromStream(ms);

Hope helps.

Make the image go behind the text and keep it in center using CSS

I style my css in its own file. So I'm not sure how you need to type it in as your are styling inside your html file. But you can use the Img{ position: relative Top: 150px; Left: 40px; } This would move my image up 150px and towards the right 40px. This method makes it so you can move anything you want on your page any where on your page If this is confusing just look on YouTube about position: relative

I also use the same method to move my h1 tag on top of my image.

In my html5 file my image is first and below that I have my h1 tag. Idk if this effects witch will be displayed on top of the other one.

Hope this helps.

Reading and displaying data from a .txt file

public class PassdataintoFile {

    public static void main(String[] args) throws IOException  {
        try {
            PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
            PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
             pw1.println("Hi chinni");
             pw1.print("your succesfully entered text into file");
             pw1.close();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
           String line;
           while((line = br.readLine())!= null)
           {
               System.out.println(line);
           }
           br.close();
    }

}

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

PHP script to loop through all of the files in a directory?

You can also make use of FilesystemIterator. It requires even less code then DirectoryIterator, and automatically removes . and ...

// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');

$entries = array();
foreach ($fileSystemIterator as $fileInfo){
    $entries[] = $fileInfo->getFilename();
}

var_dump($entries);

//OUTPUT
object(FilesystemIterator)[1]

array (size=14)
  0 => string 'aa[1].jpg' (length=9)
  1 => string 'Chrysanthemum.jpg' (length=17)
  2 => string 'Desert.jpg' (length=10)
  3 => string 'giphy_billclinton_sad.gif' (length=25)
  4 => string 'giphy_shut_your.gif' (length=19)
  5 => string 'Hydrangeas.jpg' (length=14)
  6 => string 'Jellyfish.jpg' (length=13)
  7 => string 'Koala.jpg' (length=9)
  8 => string 'Lighthouse.jpg' (length=14)
  9 => string 'Penguins.jpg' (length=12)
  10 => string 'pnggrad16rgb.png' (length=16)
  11 => string 'pnggrad16rgba.png' (length=17)
  12 => string 'pnggradHDrgba.png' (length=17)
  13 => string 'Tulips.jpg' (length=10)

Link: http://php.net/manual/en/class.filesystemiterator.php

Excel: Use a cell value as a parameter for a SQL query

I had the same problem as you, Noboby can understand me, But I solved it in this way.

SELECT NAME, TELEFONE, DATA
FROM   [sheet1$a1:q633]
WHERE  NAME IN (SELECT * FROM  [sheet2$a1:a2])

you need insert a parameter in other sheet, the SQL will consider that information like as database, then you can select the information and compare them into parameter you like.

Submitting form and pass data to controller method of type FileStreamResult

This is because you have specified the form method as GET

Change code in the view to this:

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post, new { id = @item.JobId })){
}

How can I access Oracle from Python?

In addition to cx_Oracle, you need to have the Oracle client library installed and the paths set correctly in order for cx_Oracle to find it - try opening the cx_Oracle DLL in "Dependency Walker" (http://www.dependencywalker.com/) to see what the missing DLL is.

How to make the HTML link activated by clicking on the <li>?

a {
  display: block;
  position: relative;
}

I think that is all you need.

Generating a random & unique 8 character string using MySQL

If you're OK with "random" but entirely predictable license plates, you can use a linear-feedback shift register to choose the next plate number - it's guaranteed to go through every number before repeating. However, without some complex math, you won't be able to go through every 8 character alphanumeric string (you'll get 2^41 out of the 36^8 (78%) possible plates). To make this fill your space better, you could exclude a letter from the plates (maybe O), giving you 97%.

How do I make an html link look like a button?

Much belated answer:

I've been wrestling with this on and off since I first started working in ASP. Here's the best I've come up with:

Concept: I create a custom control that has a tag. Then in the button I put an onclick event that sets document.location to the desired value with JavaScript.

I called the control ButtonLink, so that I could easily get if confused with LinkButton.

aspx:

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ButtonLink.ascx.vb" Inherits="controls_ButtonLink" %>

<asp:Button runat="server" ID="button"/>

code behind:

Partial Class controls_ButtonLink
Inherits System.Web.UI.UserControl

Dim _url As String
Dim _confirm As String

Public Property NavigateUrl As String
    Get
        Return _url
    End Get
    Set(value As String)
        _url = value
        BuildJs()
    End Set
End Property
Public Property confirm As String
    Get
        Return _confirm
    End Get
    Set(value As String)
        _confirm = value
        BuildJs()
    End Set
End Property
Public Property Text As String
    Get
        Return button.Text
    End Get
    Set(value As String)
        button.Text = value
    End Set
End Property
Public Property enabled As Boolean
    Get
        Return button.Enabled
    End Get
    Set(value As Boolean)
        button.Enabled = value
    End Set
End Property
Public Property CssClass As String
    Get
        Return button.CssClass
    End Get
    Set(value As String)
        button.CssClass = value
    End Set
End Property

Sub BuildJs()
    ' This is a little kludgey in that if the user gives a url and a confirm message, we'll build the onclick string twice.
    ' But it's not that big a deal.
    If String.IsNullOrEmpty(_url) Then
        button.OnClientClick = Nothing
    ElseIf String.IsNullOrEmpty(_confirm) Then
        button.OnClientClick = String.Format("document.location='{0}';return false;", ResolveClientUrl(_url))
    Else
        button.OnClientClick = String.Format("if (confirm('{0}')) {{document.location='{1}';}} return false;", _confirm, ResolveClientUrl(_url))
    End If
End Sub
End Class

Advantages of this scheme: It looks like a control. You write a single tag for it, <ButtonLink id="mybutton" navigateurl="blahblah"/>

The resulting button is a "real" HTML button and so looks just like a real button. You don't have to try to simulate the look of a button with CSS and then struggle with different looks on different browsers.

While the abilities are limited, you can easily extend it by adding more properties. It's likely that most properties would just have to "pass thru" to the underlying button, like I did for text, enabled and cssclass.

If anybody's got a simpler, cleaner or otherwise better solution, I'd be happy to hear it. This is a pain, but it works.

SQL Combine Two Columns in Select Statement

In MySQL you can use:

SELECT CONCAT(Address1, " ", Address2)
WHERE SOUNDEX(CONCAT(Address1, " ", Address2)) = SOUNDEX("Center St 3B")

The SOUNDEX function works similarly in most database systems, I can't think of the syntax for MSSQL at the minute, but it wouldn't be too far away from the above.

Relative div height

Percentage in width works but percentage in height will not work unless you specify a specific height for any parent in the dependent loop...

See this : percentage in height doesn’t work?

Generate a Hash from string in Javascript

My quick (very long) one liner based on FNV's Multiply+Xor method:

my_string.split('').map(v=>v.charCodeAt(0)).reduce((a,v)=>a+((a<<7)+(a<<3))^v).toString(16);

Cookies on localhost with explicit domain

Results I had varied by browser.

Chrome- 127.0.0.1 worked but localhost .localhost and "" did not. Firefox- .localhost worked but localhost, 127.0.0.1, and "" did not.

Have not tested in Opera, IE, or Safari

Installing Google Protocol Buffers on mac

If you landed here looking for how to install Protocol Buffers on Mac, it can be done using Homebrew by running the command below

brew install protobuf

It installs the latest version of protobuf available. For me, at the time of writing, this installed the v3.7.1

If you'd like to install an older version, please look up the available ones from the package page Protobuf Package - Homebrew and install that specific version of the package.

The oldest available protobuf version in this package is v3.6.1.3

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)
 }

GetType used in PowerShell, difference between variables

Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():

PS > $a.GetType().fullname
System.DayOfWeek

PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject

How to show alert message in mvc 4 controller?

<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">

"Large data" workflows using pandas

I'd like to point out the Vaex package.

Vaex is a python library for lazy Out-of-Core DataFrames (similar to Pandas), to visualize and explore big tabular datasets. It can calculate statistics such as mean, sum, count, standard deviation etc, on an N-dimensional grid up to a billion (109) objects/rows per second. Visualization is done using histograms, density plots and 3d volume rendering, allowing interactive exploration of big data. Vaex uses memory mapping, zero memory copy policy and lazy computations for best performance (no memory wasted).

Have a look at the documentation: https://vaex.readthedocs.io/en/latest/ The API is very close to the API of pandas.

IntelliJ IDEA JDK configuration on Mac OS

If you are on Mac OS X or Ubuntu, the problem is caused by the symlinks to the JDK. File | Invalidate Caches should help. If it doesn't, specify the JDK path to the direct JDK Home folder, not a symlink.

Invalidate Caches menu item is available under IntelliJ IDEA File menu.

Direct JDK path after the recent Apple Java update is:

/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

In IDEA you can configure the new JSDK in File | Project Structure, select SDKs on the left, then press [+] button, then specify the above JDK home path, you should get something like this:

JDK 1.6 on Mac

T-sql - determine if value is integer

I am not a Pro in SQL but what about checking if it is devideable by 1 ? For me it does the job.

SELECT *
FROM table    
WHERE fieldname % 1 = 0

Dynamically update values of a chartjs chart

I don't think it's possible right now.

However that's a feature which should come soon, as the author hinted here: https://github.com/nnnick/Chart.js/issues/161#issuecomment-20487775

How to change Status Bar text color in iOS

If you have an embedded navigation controller created via Interface Builder, be sure to set the following in a class that manages your navigation controller:

-(UIStatusBarStyle)preferredStatusBarStyle{ 
    return UIStatusBarStyleLightContent; 
} 

That should be all you need.

Context.startForegroundService() did not then call Service.startForeground()

I am facing same issue and after spending time found a solutons you can try below code. If your using Service then put this code in onCreate else your using Intent Service then put this code in onHandleIntent.

if (Build.VERSION.SDK_INT >= 26) {
        String CHANNEL_ID = "my_app";
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID,
                "MyApp", NotificationManager.IMPORTANCE_DEFAULT);
        ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).createNotificationChannel(channel);
        Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("")
                .setContentText("").build();
        startForeground(1, notification);
    }

How can I mock requests and the response?

I will add this information since I had a hard time figuring how to mock an async api call.

Here is what I did to mock an async call.

Here is the function I wanted to test

async def get_user_info(headers, payload):
    return await httpx.AsyncClient().post(URI, json=payload, headers=headers)

You still need the MockResponse class

class MockResponse:
    def __init__(self, json_data, status_code):
        self.json_data = json_data
        self.status_code = status_code

    def json(self):
        return self.json_data

You add the MockResponseAsync class

class MockResponseAsync:
    def __init__(self, json_data, status_code):
        self.response = MockResponse(json_data, status_code)

    async def getResponse(self):
        return self.response

Here is the test. The important thing here is I create the response before since init function can't be async and the call to getResponse is async so it all checked out.

@pytest.mark.asyncio
@patch('httpx.AsyncClient')
async def test_get_user_info_valid(self, mock_post):
    """test_get_user_info_valid"""
    # Given
    token_bd = "abc"
    username = "bob"
    payload = {
        'USERNAME': username,
        'DBNAME': 'TEST'
    }
    headers = {
        'Authorization': 'Bearer ' + token_bd,
        'Content-Type': 'application/json'
    }
    async_response = MockResponseAsync("", 200)
    mock_post.return_value.post.return_value = async_response.getResponse()

    # When
    await api_bd.get_user_info(headers, payload)

    # Then
    mock_post.return_value.post.assert_called_once_with(
        URI, json=payload, headers=headers)

If you have a better way of doing that tell me but I think it's pretty clean like that.

Difference between decimal, float and double in .NET?

The Decimal, Double, and Float variable types are different in the way that they store the values. Precision is the main difference where float is a single precision (32 bit) floating point data type, double is a double precision (64 bit) floating point data type and decimal is a 128-bit floating point data type.

Float - 32 bit (7 digits)

Double - 64 bit (15-16 digits)

Decimal - 128 bit (28-29 significant digits)

More about...the difference between Decimal, Float and Double

Querying Datatable with where condition

You can do it with Linq, as mamoo showed, but the oldies are good too:

var filteredDataTable = dt.Select(@"EmpId > 2
    AND (EmpName <> 'abc' OR EmpName <> 'xyz')
    AND EmpName like '%il%'" );

extract part of a string using bash/cut/split

What about sed? That will work in a single command:

sed 's#.*/\([^:]*\).*#\1#' <<<$string
  • The # are being used for regex dividers instead of / since the string has / in it.
  • .*/ grabs the string up to the last backslash.
  • \( .. \) marks a capture group. This is \([^:]*\).
    • The [^:] says any character _except a colon, and the * means zero or more.
  • .* means the rest of the line.
  • \1 means substitute what was found in the first (and only) capture group. This is the name.

Here's the breakdown matching the string with the regular expression:

        /var/cpanel/users/           joebloggs  :DNS9=domain.com joebloggs
sed 's#.*/                          \([^:]*\)   .*              #\1       #'

How to reset the state of a Redux store?

why don't you just use return module.exports.default() ;)

export default (state = {pending: false, error: null}, action = {}) => {
    switch (action.type) {
        case "RESET_POST":
            return module.exports.default();
        case "SEND_POST_PENDING":
            return {...state, pending: true, error: null};
        // ....
    }
    return state;
}

Note: make sure you set action default value to {} and you are ok because you don't want to encounter error when you check action.type inside the switch statement.

Full-screen responsive background image

Backstretch

Check out this one-liner plugin that scales a background image responsively.

All you need to do is:

1. Include the library:

<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>

2. Call the method:

$.backstretch("http://dl.dropbox.com/u/515046/www/garfield-interior.jpg");

I used it for a simple "under construction website" site I had and it worked perfectly.

How to export SQL Server database to MySQL?

I had some data I had to get from mssql into mysql, had difficulty finding a solution. So what I did in the end (a bit of a long winded way to do it, but as a last resort it works) was:

  • Open the mssql database in sql server management studio express (I used 2005)
  • Open each table in turn and
  • Click the top left corner box to select whole table:

  • Copy data to clipboard (ctrl + v)

  • Open ms excel
  • Paste data from clipboard
  • Save excel file as .csv
  • Repeat the above for each table
  • You should now be able to import the data into mysql

Hope this helps

C# string reference type?

I believe your code is analogous to the following, and you should not have expected the value to have changed for the same reason it wouldn't here:

 public static void Main()
 {
     StringWrapper testVariable = new StringWrapper("before passing");
     Console.WriteLine(testVariable);
     TestI(testVariable);
     Console.WriteLine(testVariable);
 }

 public static void TestI(StringWrapper testParameter)
 {
     testParameter = new StringWrapper("after passing");

     // this will change the object that testParameter is pointing/referring
     // to but it doesn't change testVariable unless you use a reference
     // parameter as indicated in other answers
 }

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Personally, I add the following line to my app/build.gradle:

implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"

With this syntax, version is dynamical.

What is the difference between a 'closure' and a 'lambda'?

A lambda is just an anonymous function - a function defined with no name. In some languages, such as Scheme, they are equivalent to named functions. In fact, the function definition is re-written as binding a lambda to a variable internally. In other languages, like Python, there are some (rather needless) distinctions between them, but they behave the same way otherwise.

A closure is any function which closes over the environment in which it was defined. This means that it can access variables not in its parameter list. Examples:

def func(): return h
def anotherfunc(h):
   return func()

This will cause an error, because func does not close over the environment in anotherfunc - h is undefined. func only closes over the global environment. This will work:

def anotherfunc(h):
    def func(): return h
    return func()

Because here, func is defined in anotherfunc, and in python 2.3 and greater (or some number like this) when they almost got closures correct (mutation still doesn't work), this means that it closes over anotherfunc's environment and can access variables inside of it. In Python 3.1+, mutation works too when using the nonlocal keyword.

Another important point - func will continue to close over anotherfunc's environment even when it's no longer being evaluated in anotherfunc. This code will also work:

def anotherfunc(h):
    def func(): return h
    return func

print anotherfunc(10)()

This will print 10.

This, as you notice, has nothing to do with lambdas - they are two different (although related) concepts.

How to solve npm error "npm ERR! code ELIFECYCLE"

Cleaning Cache and Node_module are not enough. Follow this steps:

  • npm cache clean --force
  • delete node_modules folder
  • delete package-lock.json file
  • npm install

It works for me like this.

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

You must just put the values into parentheses:

'%s in %s' % (unicode(self.author),  unicode(self.publication))

Here, for the first %s the unicode(self.author) will be placed. And for the second %s, the unicode(self.publication) will be used.

Note: You should favor string formatting over the % Notation. More info here

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

I found another solution to get the data. according to the documentation Please check documentation link

In service file add following.

import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';

@Injectable()
export class MoviesService {

  constructor(private db: AngularFireDatabase) {}
  getMovies() {
    this.db.list('/movies').valueChanges();
  }
}

In Component add following.

import { Component, OnInit } from '@angular/core';
import { MoviesService } from './movies.service';

@Component({
  selector: 'app-movies',
  templateUrl: './movies.component.html',
  styleUrls: ['./movies.component.css']
})
export class MoviesComponent implements OnInit {
  movies$;

  constructor(private moviesDb: MoviesService) { 
   this.movies$ = moviesDb.getMovies();
 }

In your html file add following.

<li  *ngFor="let m of movies$ | async">{{ m.name }} </li>

Proper way to concatenate variable strings

Good question. But I think there is no good answer which fits your criteria. The best I can think of is to use an extra vars file.

A task like this:

- include_vars: concat.yml

And in concat.yml you have your definition:

newvar: "{{ var1 }}-{{ var2 }}-{{ var3 }}"

prevent iphone default keyboard when focusing an <input>

@rene-pot is correct. You will however have a not-allowed sign on the desktop version of the website. Way around this, apply the readonly="true" to a div that will show up on the mobile view only and not on desktop. See what we did here http://www.naivashahotels.com/naivasha-hotels/lake-naivasha-country-club/

Set "Homepage" in Asp.Net MVC

If you don't want to change the router, just go to the HomeController and change MyNewViewHere in the index like this:

    public ActionResult Index()
    {
        return View("MyNewViewHere");
    }

Why does javascript map function return undefined?

My solution would be to use filter after the map.

This should support every JS data type.

example:

const notUndefined = anyValue => typeof anyValue !== 'undefined'    
const noUndefinedList = someList
          .map(// mapping condition)
          .filter(notUndefined); // by doing this, 
                      //you can ensure what's returned is not undefined

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

@XmlElement
public void setAge(int age) {
    this.age = age;
}

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

Loop through JSON in EJS

JSON.stringify returns a String. So, for example:

var data = [
    { id: 1, name: "bob" },
    { id: 2, name: "john" },
    { id: 3, name: "jake" },
];

JSON.stringify(data)

will return the equivalent of:

"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]"

as a String value.

So when you have

<% for(var i=0; i<JSON.stringify(data).length; i++) {%>

what that ends up looking like is:

<% for(var i=0; i<"[{\"id\":1,\"name\":\"bob\"},{\"id\":2,\"name\":\"john\"},{\"id\":3,\"name\":\"jake\"}]".length; i++) {%>

which is probably not what you want. What you probably do want is something like this:

<table>
<% for(var i=0; i < data.length; i++) { %>
   <tr>
     <td><%= data[i].id %></td>
     <td><%= data[i].name %></td>
   </tr>
<% } %>
</table>

This will output the following table (using the example data from above):

<table>
  <tr>
    <td>1</td>
    <td>bob</td>
  </tr>
  <tr>
    <td>2</td>
    <td>john</td>
  </tr>
  <tr>
    <td>3</td>
    <td>jake</td>
  </tr>
</table>

How should I escape commas and speech marks in CSV files so they work in Excel?

According to Yashu's instructions, I wrote the following function (it's PL/SQL code, but it should be easily adaptable to any other language).

FUNCTION field(str IN VARCHAR2) RETURN VARCHAR2 IS
    C_NEWLINE CONSTANT CHAR(1) := '
'; -- newline is intentional

    v_aux VARCHAR2(32000);
    v_has_double_quotes BOOLEAN;
    v_has_comma BOOLEAN;
    v_has_newline BOOLEAN;
BEGIN
    v_has_double_quotes := instr(str, '"') > 0;
    v_has_comma := instr(str,',') > 0;
    v_has_newline := instr(str, C_NEWLINE) > 0;

    IF v_has_double_quotes OR v_has_comma OR v_has_newline THEN
        IF v_has_double_quotes THEN
            v_aux := replace(str,'"','""');
        ELSE
            v_aux := str;
        END IF;
        return '"'||v_aux||'"';
    ELSE
        return str;
    END IF;
END;

String array initialization in Java

You mean like:

String names[] = {"Ankit","Bohra","Xyz"};

But you can only do this in the same statement when you declare it

blur vs focusout -- any real differences?

As stated in the JQuery documentation

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

Return from a promise then()

You cannot return value after resolving promise. Instead call another function when promise is resolved:

function justTesting() {
    promise.then(function(output) {
        // instead of return call another function
        afterResolve(output + 1);
    });
}

function afterResolve(result) {
    // do something with result
}

var test = justTesting();

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

PHP7 : install ext-dom issue

I faced this exact same issue with Laravel 8.x on Ubuntu 20. I run: sudo apt install php7.4-xml and composer update within the project directory. This fixed the issue.

How to update UI from another thread running in another class

You are going to have to come back to your main thread (also called UI thread) in order to update the UI. Any other thread trying to update your UI will just cause exceptions to be thrown all over the place.

So because you are in WPF, you can use the Dispatcher and more specifically a beginInvoke on this dispatcher. This will allow you to execute what needs done (typically Update the UI) in the UI thread.

You migh also want to "register" the UI in your business, by maintaining a reference to a control/form, so you can use its dispatcher.

How to redirect to another page in node.js

If the user successful login into your Node app, I'm thinking that you are using Express, isn't ? Well you can redirect easy by using res.redirect. Like:

app.post('/auth', function(req, res) {
  // Your logic and then redirect
  res.redirect('/user_profile');
});

How to write and read a file with a HashMap?

HashMap implements Serializable so you can use normal serialization to write hashmap to file

Here is the link for Java - Serialization example

Safest way to convert float to integer in python?

Use int(your non integer number) will nail it.

print int(2.3) # "2"
print int(math.sqrt(5)) # "2"

ImportError: No module named request

from @Zzmilanzz's answer I used

try: #python3
    from urllib.request import urlopen
except: #python2
    from urllib2 import urlopen

R: invalid multibyte string

I realize this is pretty late, but I had a similar problem and I figured I'd post what worked for me. I used the iconv utility (e.g., "iconv file.pcl -f UTF-8 -t ISO-8859-1 -c"). The "-c" option skips characters that can't be translated.

Understanding the main method of python

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.

sys.argv[1] meaning in script

Just adding to Frederic's answer, for example if you call your script as follows:

./myscript.py foo bar

sys.argv[0] would be "./myscript.py" sys.argv[1] would be "foo" and sys.argv[2] would be "bar" ... and so forth.

In your example code, if you call the script as follows ./myscript.py foo , the script's output will be "Hello there foo".

window.onbeforeunload and window.onunload is not working in Firefox, Safari, Opera?

I was able to get it to work in IE and FF with jQuery's:

$(window).bind('beforeunload', function(){

});

instead of: unload, onunload, or onbeforeunload

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

Fatal error: Class 'ZipArchive' not found in

First of all, The solution for remote server:

If you are using cpanel you may have zip extension installed but not activate. You need to active it. For this case you need to go to cpanel > inside software section > click on PHP version. Then find zip and check it. Now save.

You should see like the image. enter image description here

Refresh page. The error should disappear.

Note: If you dont found, contact server provider. They will install for you.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

This can be accomplished with a simple VBA function. Excel has support for a Worksheet Change Sub which can be programmed to put a date in a related column every time it fires.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then
        Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")
    End If
End Sub

A quick explanation. The following "if" statement checks for two things: (1) if it is the second column that changed (Column B), and (2) if the cell 3 columns over (Column E) is currently empty.

If Target.Column = 2 And Target.Offset(0, 3).Value = "" Then

If both conditions are true, then it puts the date into the cell in Column E with the NOW() function.

Target.Offset(0, 3) = Format(Now(), "HH:MM:SS")

Range.Offset

Range.Column

C++ String Declaring

using the standard <string> header

std::string Something = "Some Text";

http://www.dreamincode.net/forums/topic/42209-c-strings/

Android - Set text to TextView

final TextView err = (TextView)findViewById(R.id.texto);
err.setText("Escriba su mensaje y luego seleccione el canal.");

you can find every thing you need about textview here

How to run a single test with Mocha?

For those who are looking to run a single file but they cannot make it work, what worked for me was that I needed to wrap my test cases in a describe suite as below and then use the describe title e.g. 'My Test Description' as pattern.

describe('My Test Description', () => {
  it('test case 1', () => {
    // My test code
  })
  it('test case 2', () => {
  // My test code
  })
})

then run

yarn test -g "My Test Description"

or

npm run test -g "My Test Description"

Is there a float input type in HTML5?

You can use:

<input type="number" step="any" min="0" max="100" value="22.33">

Cropping an UIImage

CGSize size = [originalImage size];
int padding = 20;
int pictureSize = 300;
int startCroppingPosition = 100;
if (size.height > size.width) {
    pictureSize = size.width - (2.0 * padding);
    startCroppingPosition = (size.height - pictureSize) / 2.0; 
} else {
    pictureSize = size.height - (2.0 * padding);
    startCroppingPosition = (size.width - pictureSize) / 2.0;
}
// WTF: Don't forget that the CGImageCreateWithImageInRect believes that 
// the image is 180 rotated, so x and y are inverted, same for height and width.
CGRect cropRect = CGRectMake(startCroppingPosition, padding, pictureSize, pictureSize);
CGImageRef imageRef = CGImageCreateWithImageInRect([originalImage CGImage], cropRect);
UIImage *newImage = [UIImage imageWithCGImage:imageRef scale:1.0 orientation:originalImage.imageOrientation];
[m_photoView setImage:newImage];
CGImageRelease(imageRef);

Most of the responses I've seen only deals with a position of (0, 0) for (x, y). Ok that's one case but I'd like my cropping operation to be centered. What took me a while to figure out is the line following the WTF comment.

Let's take the case of an image captured with a portrait orientation:

  1. The original image height is higher than its width (Woo, no surprise so far!)
  2. The image that the CGImageCreateWithImageInRect method imagines in its own world is not really a portrait though but a landscape (That is also why if you don't use the orientation argument in the imageWithCGImage constructor, it will show up as 180 rotated).
  3. So, you should kind of imagine that it is a landscape, the (0, 0) position being the top right corner of the image.

Hope it makes sense! If it does not, try different values you'll see that the logic is inverted when it comes to choosing the right x, y, width, and height for your cropRect.

Load local JSON file into variable

There are two possible problems:

  1. AJAX is asynchronous, so json will be undefined when you return from the outer function. When the file has been loaded, the callback function will set json to some value but at that time, nobody cares anymore.

    I see that you tried to fix this with 'async': false. To check whether this works, add this line to the code and check your browser's console:

    console.log(['json', json]);
    
  2. The path might be wrong. Use the same path that you used to load your script in the HTML document. So if your script is js/script.js, use js/content.json

    Some browsers can show you which URLs they tried to access and how that went (success/error codes, HTML headers, etc). Check your browser's development tools to see what happens.

Explain the concept of a stack frame in a nutshell

If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily

Let me explain how stack works:

First you have to know how functions are represented in stack :

Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.

enter image description here

Let's understand with example :

def hello(x):
    if x==1:
        return "op"
    else:
        u=1
        e=12
        s=hello(x-1)
        e+=1
        print(s)
        print(x)
        u+=1
    return e

hello(4)

Now understand parts of this program :

enter image description here

Now let's see what is stack and what are stack parts:

enter image description here

Allocation of the stack :

Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.

See this in practice:

enter image description here

Deallocation of the block:

So now whenever a function encounters return statement, it delete the current frame from the stack.

While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.

enter image description here

get specific row from spark dataframe

This is how I achieved the same in Scala. I am not sure if it is more efficient than the valid answer, but it requires less coding

val parquetFileDF = sqlContext.read.parquet("myParquetFule.parquet")

val myRow7th = parquetFileDF.rdd.take(7).last

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Infinite Recursion with Jackson JSON and Hibernate JPA issue

The point is to place the @JsonIgnore in the setter method as follow. in my case.

Township.java

@Access(AccessType.PROPERTY)
@OneToMany(fetch = FetchType.LAZY)
@JoinColumn(name="townshipId", nullable=false ,insertable=false, updatable=false)
public List<Village> getVillages() {
    return villages;
}

@JsonIgnore
@Access(AccessType.PROPERTY)
public void setVillages(List<Village> villages) {
    this.villages = villages;
}

Village.java

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "townshipId", insertable=false, updatable=false)
Township township;

@Column(name = "townshipId", nullable=false)
Long townshipId;

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

If you're recompiling a disassembled APK with APK tool:

Just Set Memory Allocation a little bigger

set switch -Xmx1024mto -Xmx2048m

java -Xmx2048m -jar signapk.jar -w testkey.x509.pem testkey.pk8 "%APKOUT%" "%SIGNED%"

you're good to go.. :)

Detect all changes to a <input type="text"> (immediately) using JQuery

2017 answer: the input event does exactly this for anything more recent than IE8.

$(el).on('input', callback)

How to set my default shell on Mac?

Here's another way to do it:

Assuming you installed it with MacPorts, which can be done by doing:

sudo port install fish

Your shell will be located in /opt/local/bin/fish.

You need to tell OSX that this is a valid shell. To do that, add this path to the end of the /etc/shells file.

Once you've done this, you can change the shell by going to System Preferences -> Accounts. Click on the Lock to allow changes. Right-click on the account, and choose "Advanced Options...". In the "Login shell" field, add the path to fish.

What is (functional) reactive programming?

An easy way of reaching a first intuition about what it's like is to imagine your program is a spreadsheet and all of your variables are cells. If any of the cells in a spreadsheet change, any cells that refer to that cell change as well. It's just the same with FRP. Now imagine that some of the cells change on their own (or rather, are taken from the outside world): in a GUI situation, the position of the mouse would be a good example.

That necessarily misses out rather a lot. The metaphor breaks down pretty fast when you actually use a FRP system. For one, there are usually attempts to model discrete events as well (e.g. the mouse being clicked). I'm only putting this here to give you an idea what it's like.

convert php date to mysql format

If you know the format of date in $_POST[intake_date] you can use explode to get year , month and time and then concatenate to form a valid mySql date. for example if you are getting something like 12/15/1988 in date you can do like this

    $date = explode($_POST['intake_date'], '/');
    mysql_date = $date[2].'-'$date[1].'-'$date[0];

though if you have valid date date('y-m-d', strtotime($date)); should also work

Command CompileSwift failed with a nonzero exit code in Xcode 10

Running pod install --repo-update and closing and reopening x-code fixed this issue on all of my pods that had this error.