Programs & Examples On #Yield return

yield return is a C# construct that's used to create an iterator block, which makes implementing IEnumerable easier.

Proper use of 'yield return'

I tend to use yield-return when I calculate the next item in the list (or even the next group of items).

Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.

Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In your particular example, you have the full list of products, so I'd use Version 2.

Is " " a replacement of " "?

  •   is the character entity reference (meant to be easily parseable by humans).
  •   is the numeric entity reference (meant to be easily parseable by machines).

They are the same except for the fact that the latter does not need another lookup table to find its actual value. The lookup table is called a DTD, by the way.

You can read more about character entity references in the offical W3C documents.

Error: "setFile(null,false) call failed" when using log4j

i just add write permission to "logs" folder and it works for me

add write permission

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

Change the image source on rollover using jQuery

$('img').mouseover(function(){
  var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
  $(this).attr("src", newSrc); 
});
$('img').mouseout(function(){
  var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
  $(this).attr("src", newSrc); 
});

Comparing strings in Java

Using the == operator will compare the references to the strings not the string themselves.

Ok, you have to toString() the Editable. I loaded up some of the code I had before that dealt with this situation.

String passwd1Text = passw1.getText().toString();
String passwd2Text = passw2.getText().toString();

if (passwd1Text.equals(passwd2Text))
{
}

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

"The import org.springframework cannot be resolved."

There are few steps you can follow

  1. remove repository folder

    C:/Users/user_name/.m2

  2. Then run command using IDE terminal or open cmd in your project folder

    mvn clean install

  3. Restart your ide

  4. If not solve your problem then run this command

    mvn idea:idea

Interfaces — What's the point?

The simplest way to think about interfaces is to recognize what inheritance means. If class CC inherits class C, it means both that:

  1. Class CC can use any public or protected members of class C as though they were its own, and thus only needs to implement things which do not exist in the parent class.
  2. A reference to a CC can be passed or assigned to a routine or variable that expects a reference to a C.

Those two function of inheritance are in some sense independent; although inheritance applies both simultaneously, it is also possible to apply the second without the first. This is useful because allowing an object to inherit members from two or more unrelated classes is much more complicated than allowing one type of thing to be substitutable for multiple types.

An interface is somewhat like an abstract base class, but with a key difference: an object which inherits a base class cannot inherit any other class. By contrast, an object may implement an interface without affecting its ability to inherit any desired class or implement any other interfaces.

One nice feature of this (underutilized in the .net framework, IMHO) is that they make it possible to indicate declaratively the things an object can do. Some objects, for example, will want data-source object from which they can retrieve things by index (as is possible with a List), but they won't need to store anything there. Other routines will need a data-depository object where they can store things not by index (as with Collection.Add), but they won't need to read anything back. Some data types will allow access by index, but won't allow writing; others will allow writing, but won't allow access by index. Some, of course, will allow both.

If ReadableByIndex and Appendable were unrelated base classes, it would be impossible to define a type which could be passed both to things expecting a ReadableByIndex and things expecting an Appendable. One could try to mitigate this by having ReadableByIndex or Appendable derive from the other; the derived class would have to make available public members for both purposes, but warn that some public members might not actually work. Some of Microsoft's classes and interfaces do that, but that's rather icky. A cleaner approach is to have interfaces for the different purposes, and then have objects implement interfaces for the things they can actually do. If one had an interface IReadableByIndex and another interface IAppendable, classes which could do one or the other could implement the appropriate interfaces for the things they can do.

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

How to declare a global variable in C++

Declare extern int x; in file.h. And define int x; only in one cpp file.cpp.

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

Best way to determine user's locale within browser

I did a bit of research regarding this & I have summarised my findings so far in below table

enter image description here

So the recommended solution is to write a a server side script to parse the Accept-Language header & pass it to client for setting the language of the website. It's weird that why the server would be needed to detect the language preference of client but that's how it is as of now There are other various hacks available to detect the language but reading the Accept-Language header is the recommended solution as per my understanding.

Get list from pandas DataFrame column headers

It's interesting but df.columns.values.tolist() is almost 3 times faster then df.columns.tolist() but I thought that they are the same:

In [97]: %timeit df.columns.values.tolist()
100000 loops, best of 3: 2.97 µs per loop

In [98]: %timeit df.columns.tolist()
10000 loops, best of 3: 9.67 µs per loop

How to read if a checkbox is checked in PHP?

Well, the above examples work only when you want to INSERT a value, not useful for UPDATE different values to different columns, so here is my little trick to update:


//EMPTY ALL VALUES TO 0 
$queryMU ='UPDATE '.$db->dbprefix().'settings SET menu_news = 0, menu_gallery = 0, menu_events = 0, menu_contact = 0';
            $stmtMU = $db->prepare($queryMU);
            $stmtMU->execute();
if(!empty($_POST['check_menus'])) {
    foreach($_POST['check_menus'] as $checkU) {
try {
//UPDATE only the values checked
    $queryMU ='UPDATE '.$db->dbprefix().'settings SET '.$checkU.'= 1';
            $stmtMU = $db->prepare($queryMU);
            $stmtMU->execute();  
        } catch(PDOException $e) {
          $msg = 'Error: ' . $e->getMessage();}

        }
}
<input type="checkbox" value="menu_news" name="check_menus[]" />
<input type="checkbox" value="menu_gallery" name="check_menus[]" />

....

The secret is just update all VALUES first (in this case to 0), and since the will only send the checked values, that means everything you get should be set to 1, so everything you get set it to 1.

Example is PHP but applies for everything.

Have fun :)

How to select all elements with a particular ID in jQuery?

$("div[id^=" + controlid + "]") will return all the controls with the same name but you need to ensure that the text should not present in any of the controls

How to clear browsing history using JavaScript?

No,that would be a security issue.


However, it's possible to clear the history in JavaScript within a Google chrome extension. chrome.history.deleteAll().
Use

window.location.replace('pageName.html');

similar behavior as an HTTP redirect

Read How to redirect to another webpage in JavaScript/jQuery?

What's the environment variable for the path to the desktop?

Multilingual Version, tested on Japanese OS
Batch File

set getdesk=REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop
FOR /f "delims=(=" %%G IN ('%getdesk% ^|find "_SZ"') DO set desktop=%%G
set desktop1=%desktop:*USERPROFILE%\=%
cd "%userprofile%\%desktop1%"
set getdesk=
set desktop1=
set desktop=

Where can I get Google developer key

tl;dr

Developer Key = Api Key (any of yours)

find it in Google Console -> Google API -> Credentials

In git how is fetch different than pull and how is merge different than rebase?

fetch vs pull

fetch will download any changes from the remote* branch, updating your repository data, but leaving your local* branch unchanged.

pull will perform a fetch and additionally merge the changes into your local branch.

What's the difference? pull updates you local branch with changes from the pulled branch. A fetch does not advance your local branch.

merge vs rebase

Given the following history:

          C---D---E local
         /
    A---B---F---G remote

merge joins two development histories together. It does this by replaying the changes that occurred on your local branch after it diverged on top of the remote branch, and record the result in a new commit. This operation preserves the ancestry of each commit.

The effect of a merge will be:

          C---D---E local
         /         \
    A---B---F---G---H remote

rebase will take commits that exist in your local branch and re-apply them on top of the remote branch. This operation re-writes the ancestors of your local commits.

The effect of a rebase will be:

                  C'--D'--E' local
                 /
    A---B---F---G remote

What's the difference? A merge does not change the ancestry of commits. A rebase rewrites the ancestry of your local commits.

* This explanation assumes that the current branch is a local branch, and that the branch specified as the argument to fetch, pull, merge, or rebase is a remote branch. This is the usual case. pull, for example, will download any changes from the specified branch, update your repository and merge the changes into the current branch.

Is there a JSON equivalent of XQuery/XPath?

JMESPath seems to be very popular these days (as of 2020) and addresses a number of issues with JSONPath. It's available for many languages.

Load vs. Stress testing

The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.

Stress testing

In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.

While on the other hand Load Testing

In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.

In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?

using wildcards in LDAP search filters/queries

This should work, at least according to the Search Filter Syntax article on MSDN network.

The "hang-up" you have noticed is probably just a delay. Try running the same query with narrower scope (for example the specific OU where the test object is located), as it may take very long time for processing if you run it against all AD objects.

You may also try separating the filter into two parts:

(|(displayName=*searchstring)(displayName=searchstring*))

MySQL: Fastest way to count number of rows

I handled tables for the German Government with sometimes 60 million records.

And we needed to know many times the total rows.

So we database programmers decided that in every table is record one always the record in which the total record numbers is stored. We updated this number, depending on INSERT or DELETE rows.

We tried all other ways. This is by far the fastest way.

How to create a popup window (PopupWindow) in Android

are you done with the layout inflating? maybe you can try this!!

View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p

Use of Java's Collections.singletonList()?

From the javadoc

@param  the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.

example

import java.util.*;

public class HelloWorld {
    public static void main(String args[]) {
        // create an array of string objs
        String initList[] = { "One", "Two", "Four", "One",};

        // create one list
        List list = new ArrayList(Arrays.asList(initList));

        System.out.println("List value before: "+list);

        // create singleton list
        list = Collections.singletonList("OnlyOneElement");
        list.add("five"); //throws UnsupportedOperationException
        System.out.println("List value after: "+list);
    }
}

Use it when code expects a read-only list, but you only want to pass one element in it. singletonList is (thread-)safe and fast.

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

Believe it or not, I just encountered this sudden problem after performing a Windows Update on Windows 10. Somehow, that update messed up my existing Malwarebytes Anti-Exploit program, and ultimately caused Android Studio to be unable to invoke the JVM (I couldn't even open cmd.exe!).

Solution was to remove the Malwarebytes Anti-Exploit program (this may be fixed in the future).

How to get filename without extension from file path in Ruby

Note that double quotes strings escape \'s.

'C:\projects\blah.dll'.split('\\').last

How to access a dictionary element in a Django template?

you can use the dot notation:

Dot lookups can be summarized like this: when the template system encounters a dot in a variable name, it tries the following lookups, in this order:

  • Dictionary lookup (e.g., foo["bar"])
  • Attribute lookup (e.g., foo.bar)
  • Method call (e.g., foo.bar())
  • List-index lookup (e.g., foo[2])

The system uses the first lookup type that works. It’s short-circuit logic.

What are the differences between "=" and "<-" assignment operators in R?

This may also add to understanding of the difference between those two operators:

df <- data.frame(
      a = rnorm(10),
      b <- rnorm(10)
)

For the first element R has assigned values and proper name, while the name of the second element looks a bit strange.

str(df)
# 'data.frame': 10 obs. of  2 variables:
#  $ a             : num  0.6393 1.125 -1.2514 0.0729 -1.3292 ...
#  $ b....rnorm.10.: num  0.2485 0.0391 -1.6532 -0.3366 1.1951 ...

R version 3.3.2 (2016-10-31); macOS Sierra 10.12.1

How do I draw a circle in iOS Swift?

Make a class UIView and assign it this code for a simple circle

import UIKit
@IBDesignable
class DRAW: UIView {

    override func draw(_ rect: CGRect) {

        var path = UIBezierPath()
        path = UIBezierPath(ovalIn: CGRect(x: 50, y: 50, width: 100, height: 100))
        UIColor.yellow.setStroke()
        UIColor.red.setFill()
        path.lineWidth = 5
        path.stroke()
        path.fill()


    }


}

Pycharm does not show plot

I had the same problem. Check wether plt.isinteractive() is True. Setting it to 'False' helped for me.

plt.interactive(False)

Does Eclipse have line-wrap

In Version: 2019-12 (4.14.0) on MAC

Go to Windows -> Editor -> Toggle Word Wrap

how to call scalar function in sql server 2008

You have a scalar valued function as opposed to a table valued function. The from clause is used for tables. Just query the value directly in the column list.

select dbo.fun_functional_score('01091400003')

Professional jQuery based Combobox control?

Here's one that looks very promising. It's a true combo - you see what you type. Has a cool feature I haven't seen elsewhere: paging results.

FlexBox

javascript code to check special characters

Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.

function isValid(str) {
    var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";

    for (var i = 0; i < str.length; i++) {
       if (iChars.indexOf(str.charAt(i)) != -1) {
           alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
           return false;
       }
    }
    return true;
}

I tried this in my chrome console and it worked well.

Multiprocessing vs Threading Python

Process may have multiple threads. These threads may share memory and are the units of execution within a process.

Processes run on the CPU, so threads are residing under each process. Processes are individual entities which run independently. If you want to share data or state between each process, you may use a memory-storage tool such as Cache(redis, memcache), Files, or a Database.

How to get the path of running java program

Try this code:

final File f = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

replace 'MyClass' with your class containing the main method.

Alternatively you can also use

System.getProperty("java.class.path")

Above mentioned System property provides

Path used to find directories and JAR archives containing class files. Elements of the class path are separated by a platform-specific character specified in the path.separator property.

SQL Server IN vs. EXISTS Performance

The execution plans are typically going to be identical in these cases, but until you see how the optimizer factors in all the other aspects of indexes etc., you really will never know.

How to get a list of all files in Cloud Storage in a Firebase app?

For node js, I used this code

const Storage = require('@google-cloud/storage');
const storage = new Storage({projectId: 'PROJECT_ID', keyFilename: 'D:\\keyFileName.json'});
const bucket = storage.bucket('project.appspot.com'); //gs://project.appspot.com
bucket.getFiles().then(results => {
    const files = results[0];
    console.log('Total files:', files.length);
    files.forEach(file => {
      file.download({destination: `D:\\${file}`}).catch(error => console.log('Error: ', error))
    });
}).catch(err => {
    console.error('ERROR:', err);
  });

curl: (60) SSL certificate problem: unable to get local issuer certificate

You have to change server cert from cert.pem to fullchain.pem
I had the same issue with Perl HTTPS Daemon:
I have changed:
SSL_cert_file => '/etc/letsencrypt/live/mydomain/cert.pem'
to:
SSL_cert_file => '/etc/letsencrypt/live/mydomain/fullchain.pem'

How can I put CSS and HTML code in the same file?

Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.

How to have an auto incrementing version number (Visual Studio)?

Here's the quote on AssemblyInfo.cs from MSDN:

You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (). For example, [assembly:AssemblyVersion("2.3.25.1")] indicates 2 as the major version, 3 as the minor version, 25 as the build number, and 1 as the revision number. A version number such as [assembly:AssemblyVersion("1.2.")] specifies 1 as the major version, 2 as the minor version, and accepts the default build and revision numbers. A version number such as [assembly:AssemblyVersion("1.2.15.*")] specifies 1 as the major version, 2 as the minor version, 15 as the build number, and accepts the default revision number. The default build number increments daily. The default revision number is random

This effectively says, if you put a 1.1.* into assembly info, only build number will autoincrement, and it will happen not after every build, but daily. Revision number will change every build, but randomly, rather than in an incrementing fashion.

This is probably enough for most use cases. If that's not what you're looking for, you're stuck with having to write a script which will autoincrement version # on pre-build step

What exactly is the 'react-scripts start' command?

create-react-app and react-scripts

react-scripts is a set of scripts from the create-react-app starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.

react-scripts start sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.

with create-react-app you have following features out of the box.

  • React, JSX, ES6, and Flow syntax support.
  • Language extras beyond ES6 like the object spread operator.
  • Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  • A fast interactive unit test runner with built-in support for coverage reporting.
  • A live development server that warns about common mistakes.
  • A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
  • An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
  • Hassle-free updates for the above tools with a single dependency.

npm scripts

npm start is a shortcut for npm run start.

npm run is used to run scripts that you define in the scripts object of your package.json

if there is no start key in the scripts object, it will default to node server.js

Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.

How do I get the App version and build number using Swift?

My answer (as at Aug 2015), given Swift keeps evolving:

let version = NSBundle.mainBundle().infoDictionary!["CFBundleVersion"] as! String

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

Lightweight Javascript DB for use in Node.js

I had the same requirements as you but couldn't find a suitable database. nStore was promising but the API was not nearly complete enough and not very coherent.

That's why I made NeDB, which a dependency-less embedded database for Node.js projects. You can use it with a simple require(), it is persistent, and its API is the most commonly used subset of the very well-known MongoDB API.

https://github.com/louischatriot/nedb

How to restart Jenkins manually?

For Mac

Stop Jenkins

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist

Start Jenkins

sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist

pass JSON to HTTP POST Request

You don't want multipart, but a "plain" POST request (with Content-Type: application/json) instead. Here is all you need:

var request = require('request');

var requestData = {
  request: {
    slice: [
      {
        origin: "ZRH",
        destination: "DUS",
        date: "2014-12-02"
      }
    ],
    passengers: {
      adultCount: 1,
      infantInLapCount: 0,
      infantInSeatCount: 0,
      childCount: 0,
      seniorCount: 0
    },
    solutions: 2,
    refundable: false
  }
};

request('https://www.googleapis.com/qpxExpress/v1/trips/search?key=myApiKey',
        { json: true, body: requestData },
        function(err, res, body) {
  // `body` is a js object if request was successful
});

tSQL - Conversion from varchar to numeric works for all but integer

Actually whether there are digits or not is irrelevant. The . (dot) is forbidden if you want to cast to int. Dot can't - logically - be part of Integer definition, so even:

select cast ('7.0' as int)
select cast ('7.' as int)

will fail but both are fine for floats.

Vue.js unknown custom element

I had the same error

[Vue warn]: Unknown custom element: - did you register the component correctly? For recursive components, make sure to provide the "name" option.

however, I totally forgot to run npm install && npm run dev to compiling the js files.

maybe this helps newbies like me.

How to make a gui in python

Tkinter is the "standard" GUI for Python, meaning it should be available with every Python installation.

In terms of learning it, and particularly learning how to use recent versions of Tkinter (which have improved a lot), I very highly recommend the TkDocs tutorial that I put together a while back - see http://www.tkdocs.com

Loaded with examples, covers basic concepts and all of the core widgets.

How to find difference between two Joda-Time DateTimes in minutes

Something like...

Minutes.minutesBetween(getStart(), getEnd()).getMinutes();

How to wait 5 seconds with jQuery?

setTimeout(function(){


},5000); 

Place your code inside of the { }

300 = 0.3 seconds

700 = 0.7 seconds

1000 = 1 second

2000= 2 seconds

2200 = 2.2 seconds

3500 = 3.5 seconds

10000 = 10 seconds

etc.

How to pass data in the ajax DELETE request other than headers

I was able to successfully pass through the data attribute in the ajax method. Here is my code

$.ajax({
     url: "/api/Gigs/Cancel",
     type: "DELETE",
     data: {
             "GigId": link.attr('data-gig-id')
           }

  })

The link.attr method simply returned the value of 'data-gig-id' .

Shell script to get the process ID on Linux

As a start there is no need to do a ps -aux | grep... The command pidof is far better to use. And almost never ever do kill -9 see here

to get the output from a command in bash, use something like

pid=$(pidof ruby)

or use pkill directly.

Add a user control to a wpf window

Make sure there is an namespace definition (xmlns) for the namespace your control belong to.

xmlns:myControls="clr-namespace:YourCustomNamespace.Controls;assembly=YourAssemblyName"
<myControls:thecontrol/>

Global npm install location on windows?

Just press windows button and type %APPDATA% and type enter.

Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.

Returning binary file from controller in ASP.NET Web API

Try using a simple HttpResponseMessage with its Content property set to a StreamContent:

// using System.IO;
// using System.Net.Http;
// using System.Net.Http.Headers;

public HttpResponseMessage Post(string version, string environment,
    string filetype)
{
    var path = @"C:\Temp\test.exe";
    HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
    var stream = new FileStream(path, FileMode.Open, FileAccess.Read);
    result.Content = new StreamContent(stream);
    result.Content.Headers.ContentType = 
        new MediaTypeHeaderValue("application/octet-stream");
    return result;
}

A few things to note about the stream used:

  • You must not call stream.Dispose(), since Web API still needs to be able to access it when it processes the controller method's result to send data back to the client. Therefore, do not use a using (var stream = …) block. Web API will dispose the stream for you.

  • Make sure that the stream has its current position set to 0 (i.e. the beginning of the stream's data). In the above example, this is a given since you've only just opened the file. However, in other scenarios (such as when you first write some binary data to a MemoryStream), make sure to stream.Seek(0, SeekOrigin.Begin); or set stream.Position = 0;

  • With file streams, explicitly specifying FileAccess.Read permission can help prevent access rights issues on web servers; IIS application pool accounts are often given only read / list / execute access rights to the wwwroot.

How to write trycatch in R

Here goes a straightforward example:

# Do something, or tell me why it failed
my_update_function <- function(x){
    tryCatch(
        # This is what I want to do...
        {
        y = x * 2
        return(y)
        },
        # ... but if an error occurs, tell me what happened: 
        error=function(error_message) {
            message("This is my custom message.")
            message("And below is the error message from R:")
            message(error_message)
            return(NA)
        }
    )
}

If you also want to capture a "warning", just add warning= similar to the error= part.

What is the 'dynamic' type in C# 4.0 used for?

The dynamic keyword is new to C# 4.0, and is used to tell the compiler that a variable's type can change or that it is not known until runtime. Think of it as being able to interact with an Object without having to cast it.

dynamic cust = GetCustomer();
cust.FirstName = "foo"; // works as expected
cust.Process(); // works as expected
cust.MissingMethod(); // No method found!

Notice we did not need to cast nor declare cust as type Customer. Because we declared it dynamic, the runtime takes over and then searches and sets the FirstName property for us. Now, of course, when you are using a dynamic variable, you are giving up compiler type checking. This means the call cust.MissingMethod() will compile and not fail until runtime. The result of this operation is a RuntimeBinderException because MissingMethod is not defined on the Customer class.

The example above shows how dynamic works when calling methods and properties. Another powerful (and potentially dangerous) feature is being able to reuse variables for different types of data. I'm sure the Python, Ruby, and Perl programmers out there can think of a million ways to take advantage of this, but I've been using C# so long that it just feels "wrong" to me.

dynamic foo = 123;
foo = "bar";

OK, so you most likely will not be writing code like the above very often. There may be times, however, when variable reuse can come in handy or clean up a dirty piece of legacy code. One simple case I run into often is constantly having to cast between decimal and double.

decimal foo = GetDecimalValue();
foo = foo / 2.5; // Does not compile
foo = Math.Sqrt(foo); // Does not compile
string bar = foo.ToString("c");

The second line does not compile because 2.5 is typed as a double and line 3 does not compile because Math.Sqrt expects a double. Obviously, all you have to do is cast and/or change your variable type, but there may be situations where dynamic makes sense to use.

dynamic foo = GetDecimalValue(); // still returns a decimal
foo = foo / 2.5; // The runtime takes care of this for us
foo = Math.Sqrt(foo); // Again, the DLR works its magic
string bar = foo.ToString("c");

Read more feature : http://www.codeproject.com/KB/cs/CSharp4Features.aspx

How to view data saved in android database(SQLite)?

1. Download SQLite Manager
2. Go to your DDMS tab in Eclipse
3. Go to the File Explorer --> data --> data --> "Your Package Name" --> pull file from device 4. Open file in SQLite Manager.
5. View data.

What is the best way to seed a database in Rails?

Usually there are 2 types of seed data required.

  • Basic data upon which the core of your application may rely. I call this the common seeds.
  • Environmental data, for example to develop the app it is useful to have a bunch of data in a known state that us can use for working on the app locally (the Factory Girl answer above covers this kind of data).

In my experience I was always coming across the need for these two types of data. So I put together a small gem that extends Rails' seeds and lets you add multiple common seed files under db/seeds/ and any environmental seed data under db/seeds/ENV for example db/seeds/development.

I have found this approach is enough to give my seed data some structure and gives me the power to setup my development or staging environment in a known state just by running:

rake db:setup

Fixtures are fragile and flakey to maintain, as are regular sql dumps.

How to specify Memory & CPU limit in docker compose version 3

deploy:
  resources:
    limits:
      cpus: '0.001'
      memory: 50M
    reservations:
      cpus: '0.0001'
      memory: 20M

More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources

In you specific case:

version: "3"
services:
  node:
    image: USER/Your-Pre-Built-Image
    environment:
      - VIRTUAL_HOST=localhost
    volumes:
      - logs:/app/out/
    command: ["npm","start"]
    cap_drop:
      - NET_ADMIN
      - SYS_ADMIN
    deploy:
      resources:
        limits:
          cpus: '0.001'
          memory: 50M
        reservations:
          cpus: '0.0001'
          memory: 20M

volumes:
  - logs

networks:
  default:
    driver: overlay

Note:

  • Expose is not necessary, it will be exposed per default on your stack network.
  • Images have to be pre-built. Build within v3 is not possible
  • "Restart" is also deprecated. You can use restart under deploy with on-failure action
  • You can use a standalone one node "swarm", v3 most improvements (if not all) are for swarm

Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:

ports:
  - 80:80

Java Spring Boot: How to map my app root (“/”) to index.html?

  1. index.html file should come under below location - src/resources/public/index.html OR src/resources/static/index.html if both location defined then which first occur index.html will call from that directory.
  2. The source code looks like -

    package com.bluestone.pms.app.boot; 
    import org.springframework.boot.Banner;
    import org.springframework.boot.Banner;
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.boot.web.support.SpringBootServletInitializer;
    import org.springframework.context.annotation.ComponentScan;
    
    
    
    @SpringBootApplication 
    @EnableAutoConfiguration
    @ComponentScan(basePackages = {"com.your.pkg"}) 
    public class BootApplication extends SpringBootServletInitializer {
    
    
    
    /**
     * @param args Arguments
    */
    public static void main(String[] args) {
    SpringApplication application = new SpringApplication(BootApplication.class);
    /* Setting Boot banner off default value is true */
    application.setBannerMode(Banner.Mode.OFF);
    application.run(args);
    }
    
    /**
      * @param builder a builder for the application context
      * @return the application builder
      * @see SpringApplicationBuilder
     */
     @Override
     protected SpringApplicationBuilder configure(SpringApplicationBuilder 
      builder) {
        return super.configure(builder);
       }
    }
    

How to check the function's return value if true or false

ValidateForm returns boolean,not a string.
When you do this if(ValidateForm() == 'false'), is the same of if(false == 'false'), which is not true.

function post(url, formId) {
    if(!ValidateForm()) {
        // False
    } else {
        // True
    }
}

Description for event id from source cannot be found

For me, the problem was that my target profile by accident got set to ".Net Framework 4 Client profile". When I rebuilt the service in question using the ".Net Framework 4", the problem went away!

How to use <md-icon> in Angular Material?

md-icons aren't in the bower release of angular-material yet. I've been using Polymer's icons, they'll probably be the same anyway.

bower install polymer/core-icons

Set a:hover based on class

how about .main-nav-item:hover

this keeps the specificity low

How to test if list element exists?

One solution that hasn't come up yet is using length, which successfully handles NULL. As far as I can tell, all values except NULL have a length greater than 0.

x <- list(4, -1, NULL, NA, Inf, -Inf, NaN, T, x = 0, y = "", z = c(1,2,3))
lapply(x, function(el) print(length(el)))
[1] 1
[1] 1
[1] 0
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 1
[1] 3

Thus we could make a simple function that works with both named and numbered indices:

element.exists <- function(var, element)
{
  tryCatch({
    if(length(var[[element]]) > -1)
      return(T)
  }, error = function(e) {
    return(F)
  })
}

If the element doesn't exist, it causes an out-of-bounds condition caught by the tryCatch block.

Rails 4 Authenticity Token

This is a security feature in Rails. Add this line of code in the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Simple Steps

  1. 1 Open SQL Server Configuration Manager
  2. Under SQL Server Services Select Your Server
  3. Right Click and Select Properties
  4. Log on Tab Change Built-in-account tick
  5. in the drop down list select Network Service
  6. Apply and start The service

Split string with PowerShell and do something with each token

To complement Justus Thane's helpful answer:

  • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

    • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
      • Leading and trailing whitespace is ignored.
      • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
  • In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object cmdlet became available: the .ForEach() array (collection) method, as described in this blog post (alongside the .Where() method, a more powerful, expression-based alternative to Where-Object).

Here's a solution based on these features:

PS> (-split '   One      for the money   ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]

Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One and for were treated as a single separator.

How to get a single value from FormGroup

Another option:

this.form.value['nameOfControl']

Why I got " cannot be resolved to a type" error?

I had this problem while the other class (CarService) was still empty, no methods, nothing. When it had methods and variables, the error was gone.

Select DataFrame rows between two dates

Inspired by unutbu

print(df.dtypes)                                 #Make sure the format is 'object'. Rerunning this after index will not show values.
columnName = 'YourColumnName'
df[columnName+'index'] = df[columnName]          #Create a new column for index
df.set_index(columnName+'index', inplace=True)   #To build index on the timestamp/dates
df.loc['2020-09-03 01:00':'2020-09-06']          #Select range from the index. This is your new Dataframe.

Return empty cell from formula in Excel

If the goal is to be able to display a cell as empty when it in fact has the value zero, then instead of using a formula that results in a blank or empty cell (since there's no empty() function) instead,

  • where you want a blank cell, return a 0 instead of "" and THEN

  • set the number format for the cells like so, where you will have to come up with what you want for positive and negative numbers (the first two items separated by semi-colons). In my case, the numbers I had were 0, 1, 2... and I wanted 0 to show up empty. (I never did figure out what the text parameter was used for, but it seemed to be required).

    0;0;"";"text"@
    

NLS_NUMERIC_CHARACTERS setting for decimal

To know SESSION decimal separator, you can use following SQL command:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select SUBSTR(value,1,1) as "SEPARATOR"
      ,'using NLS-PARAMETER' as "Explanation"
  from nls_session_parameters
  where parameter = 'NLS_NUMERIC_CHARACTERS'

UNION ALL

select SUBSTR(0.5,1,1) as "SEPARATOR" 
      ,'using NUMBER IMPLICIT CASTING' as "Explanation"
  from DUAL;

The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS table. The decimal separator is the first character of the returned value.

The second SELECT command convert IMPLICITELY the 0.5 rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.

The both command return same value.

I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.

To test what I say, I have used following SQL commands:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;

DECLARE
    S VARCHAR2(10) := '?';
BEGIN

    select .5 INTO S from dual;

    DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/

The shorter command to know decimal separator is:

SELECT .5 FROM DUAL;

That return 0,5 if decimal separator is a COMMA and 0.5 if decimal separator is a POINT.

Is there any JSON Web Token (JWT) example in C#?

Thanks everyone. I found a base implementation of a Json Web Token and expanded on it with the Google flavor. I still haven't gotten it completely worked out but it's 97% there. This project lost it's steam, so hopefully this will help someone else get a good head-start:

Note: Changes I made to the base implementation (Can't remember where I found it,) are:

  1. Changed HS256 -> RS256
  2. Swapped the JWT and alg order in the header. Not sure who got it wrong, Google or the spec, but google takes it the way It is below according to their docs.
public enum JwtHashAlgorithm
{
    RS256,
    HS384,
    HS512
}

public class JsonWebToken
{
    private static Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>> HashAlgorithms;

    static JsonWebToken()
    {
        HashAlgorithms = new Dictionary<JwtHashAlgorithm, Func<byte[], byte[], byte[]>>
            {
                { JwtHashAlgorithm.RS256, (key, value) => { using (var sha = new HMACSHA256(key)) { return sha.ComputeHash(value); } } },
                { JwtHashAlgorithm.HS384, (key, value) => { using (var sha = new HMACSHA384(key)) { return sha.ComputeHash(value); } } },
                { JwtHashAlgorithm.HS512, (key, value) => { using (var sha = new HMACSHA512(key)) { return sha.ComputeHash(value); } } }
            };
    }

    public static string Encode(object payload, string key, JwtHashAlgorithm algorithm)
    {
        return Encode(payload, Encoding.UTF8.GetBytes(key), algorithm);
    }

    public static string Encode(object payload, byte[] keyBytes, JwtHashAlgorithm algorithm)
    {
        var segments = new List<string>();
        var header = new { alg = algorithm.ToString(), typ = "JWT" };

        byte[] headerBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(header, Formatting.None));
        byte[] payloadBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(payload, Formatting.None));
        //byte[] payloadBytes = Encoding.UTF8.GetBytes(@"{"iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com","scope":"https://www.googleapis.com/auth/prediction","aud":"https://accounts.google.com/o/oauth2/token","exp":1328554385,"iat":1328550785}");

        segments.Add(Base64UrlEncode(headerBytes));
        segments.Add(Base64UrlEncode(payloadBytes));

        var stringToSign = string.Join(".", segments.ToArray());

        var bytesToSign = Encoding.UTF8.GetBytes(stringToSign);

        byte[] signature = HashAlgorithms[algorithm](keyBytes, bytesToSign);
        segments.Add(Base64UrlEncode(signature));

        return string.Join(".", segments.ToArray());
    }

    public static string Decode(string token, string key)
    {
        return Decode(token, key, true);
    }

    public static string Decode(string token, string key, bool verify)
    {
        var parts = token.Split('.');
        var header = parts[0];
        var payload = parts[1];
        byte[] crypto = Base64UrlDecode(parts[2]);

        var headerJson = Encoding.UTF8.GetString(Base64UrlDecode(header));
        var headerData = JObject.Parse(headerJson);
        var payloadJson = Encoding.UTF8.GetString(Base64UrlDecode(payload));
        var payloadData = JObject.Parse(payloadJson);

        if (verify)
        {
            var bytesToSign = Encoding.UTF8.GetBytes(string.Concat(header, ".", payload));
            var keyBytes = Encoding.UTF8.GetBytes(key);
            var algorithm = (string)headerData["alg"];

            var signature = HashAlgorithms[GetHashAlgorithm(algorithm)](keyBytes, bytesToSign);
            var decodedCrypto = Convert.ToBase64String(crypto);
            var decodedSignature = Convert.ToBase64String(signature);

            if (decodedCrypto != decodedSignature)
            {
                throw new ApplicationException(string.Format("Invalid signature. Expected {0} got {1}", decodedCrypto, decodedSignature));
            }
        }

        return payloadData.ToString();
    }

    private static JwtHashAlgorithm GetHashAlgorithm(string algorithm)
    {
        switch (algorithm)
        {
            case "RS256": return JwtHashAlgorithm.RS256;
            case "HS384": return JwtHashAlgorithm.HS384;
            case "HS512": return JwtHashAlgorithm.HS512;
            default: throw new InvalidOperationException("Algorithm not supported.");
        }
    }

    // from JWT spec
    private static string Base64UrlEncode(byte[] input)
    {
        var output = Convert.ToBase64String(input);
        output = output.Split('=')[0]; // Remove any trailing '='s
        output = output.Replace('+', '-'); // 62nd char of encoding
        output = output.Replace('/', '_'); // 63rd char of encoding
        return output;
    }

    // from JWT spec
    private static byte[] Base64UrlDecode(string input)
    {
        var output = input;
        output = output.Replace('-', '+'); // 62nd char of encoding
        output = output.Replace('_', '/'); // 63rd char of encoding
        switch (output.Length % 4) // Pad with trailing '='s
        {
            case 0: break; // No pad chars in this case
            case 2: output += "=="; break; // Two pad chars
            case 3: output += "="; break; // One pad char
            default: throw new System.Exception("Illegal base64url string!");
        }
        var converted = Convert.FromBase64String(output); // Standard base64 decoder
        return converted;
    }
}

And then my google specific JWT class:

public class GoogleJsonWebToken
{
    public static string Encode(string email, string certificateFilePath)
    {
        var utc0 = new DateTime(1970,1,1,0,0,0,0, DateTimeKind.Utc);
        var issueTime = DateTime.Now;

        var iat = (int)issueTime.Subtract(utc0).TotalSeconds;
        var exp = (int)issueTime.AddMinutes(55).Subtract(utc0).TotalSeconds; // Expiration time is up to 1 hour, but lets play on safe side

        var payload = new
        {
            iss = email,
            scope = "https://www.googleapis.com/auth/gan.readonly",
            aud = "https://accounts.google.com/o/oauth2/token",
            exp = exp,
            iat = iat
        };

        var certificate = new X509Certificate2(certificateFilePath, "notasecret");

        var privateKey = certificate.Export(X509ContentType.Cert);

        return JsonWebToken.Encode(payload, privateKey, JwtHashAlgorithm.RS256);
    }
}

Handling back button in Android Navigation Component

Newest Update - April 25th, 2019

New release androidx.activity ver. 1.0.0-alpha07 brings some changes

More explanations in android official guide: Provide custom back navigation

Example:

public class MyFragment extends Fragment {

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

        // This callback will only be called when MyFragment is at least Started.
        OnBackPressedCallback callback = new OnBackPressedCallback(true /* enabled by default */) {
            @Override
            public void handleOnBackPressed() {
                // Handle the back button event
            }
        };
        requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

        // The callback can be enabled or disabled here or in handleOnBackPressed()
    }
    ...
}

Old Updates

UPD: April 3rd, 2019

Now its simplified. More info here

Example:

requireActivity().getOnBackPressedDispatcher().addCallback(getViewLifecycleOwner(), this);

@Override
public boolean handleOnBackPressed() {
    //Do your job here
    //use next line if you just need navigate up
    //NavHostFragment.findNavController(this).navigateUp(); 
    //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
    return true;
    }

Deprecated (since Version 1.0.0-alpha06 April 3rd, 2019) :

Since this, it can be implemented just using JetPack implementation OnBackPressedCallback in your fragment and add it to activity: getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);

Your fragment should looks like this:

public MyFragment extends Fragment implements OnBackPressedCallback {

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        
        getActivity().addOnBackPressedCallback(getViewLifecycleOwner(),this);
}
    
    @Override
    public boolean handleOnBackPressed() {
        //Do your job here
        //use next line if you just need navigate up
        //NavHostFragment.findNavController(this).navigateUp(); 
        //Log.e(getClass().getSimpleName(), "handleOnBackPressed");
        return true;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        getActivity().removeOnBackPressedCallback(this);
    }
}

UPD: Your activity should extends AppCompatActivityor FragmentActivity and in Gradle file:

 implementation 'androidx.appcompat:appcompat:{lastVersion}'

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

In PostMan we have ->Pre-request Script. Paste the Below snippet.

const dateNow = new Date();
postman.setGlobalVariable("todayDate", dateNow.toLocaleDateString());

And now we are ready to use.

{
"firstName": "SANKAR",
"lastName": "B",
"email": "[email protected]",
"creationDate": "{{todayDate}}"
}

If you are using JPA Entity classes then use the below snippet

    @JsonFormat(pattern="MM/dd/yyyy")
    @Column(name = "creation_date")
    private Date creationDate;

enter image description here enter image description here

Loading cross-domain endpoint with AJAX

You need CORS proxy which proxies your request from your browser to requested service with appropriate CORS headers. List of such services are in code snippet below. You can also run provided code snippet to see ping to such services from your location.

_x000D_
_x000D_
$('li').each(function() {_x000D_
  var self = this;_x000D_
  ping($(this).text()).then(function(delta) {_x000D_
    console.log($(self).text(), delta, ' ms');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.rawgit.com/jdfreder/pingjs/c2190a3649759f2bd8569a72ae2b597b2546c871/ping.js"></script>_x000D_
<ul>_x000D_
  <li>https://crossorigin.me/</li>_x000D_
  <li>https://cors-anywhere.herokuapp.com/</li>_x000D_
  <li>http://cors.io/</li>_x000D_
  <li>https://cors.5apps.com/?uri=</li>_x000D_
  <li>http://whateverorigin.org/get?url=</li>_x000D_
  <li>https://anyorigin.com/get?url=</li>_x000D_
  <li>http://corsproxy.nodester.com/?src=</li>_x000D_
  <li>https://jsonp.afeld.me/?url=</li>_x000D_
  <li>http://benalman.com/code/projects/php-simple-proxy/ba-simple-proxy.php?url=</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Create a new workspace in Eclipse

I use File -> Switch Workspace -> Other... and type in my new workspace name.

New workspace composite screenshot (EDIT: Added the composite screen shot.)

Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.

How do I unset an element in an array in javascript?

there is an important difference between delete and splice:

ORIGINAL ARRAY:

[<1 empty item>, 'one',<3 empty items>, 'five', <3 empty items>,'nine']

AFTER SPLICE (array.splice(1,1)):

[ <4 empty items>, 'five', <3 empty items>, 'nine' ]

AFTER DELETE (delete array[1]):

[ <5 empty items>, 'five', <3 empty items>, 'nine' ]

MySQL joins and COUNT(*) from another table

SELECT DISTINCT groups.id, 
       (SELECT COUNT(*) FROM group_members
        WHERE member_id = groups.id) AS memberCount
FROM groups

Java: Enum parameter in method

This should do it:

private enum Alignment { LEFT, RIGHT };    
String drawCellValue (int maxCellLength, String cellValue, Alignment align){
  if (align == Alignment.LEFT)
  {
    //Process it...
  }
}

Selecting non-blank cells in Excel with VBA

I know I'm am very late on this, but here some usefull samples:

'select the used cells in column 3 of worksheet wks
wks.columns(3).SpecialCells(xlCellTypeConstants).Select

or

'change all formulas in col 3 to values
with sheet1.columns(3).SpecialCells(xlCellTypeFormulas)
    .value = .value
end with

To find the last used row in column, never rely on LastCell, which is unreliable (it is not reset after deleting data). Instead, I use someting like

 lngLast = cells(rows.count,3).end(xlUp).row

Android Webview gives net::ERR_CACHE_MISS message

Use

if (Build.VERSION.SDK_INT >= 19) {
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    }

It should solve the error.

sql query with multiple where statements

This..

(
        (meta_key = 'lat' AND meta_value >= '60.23457047672217')
    OR
        (meta_key = 'lat' AND meta_value <= '60.23457047672217')
)

is the same as

(
        (meta_key = 'lat')
)

Adding it all together (the same applies to the long filter) you have this impossible WHERE clause which will give no rows because meta_key cannot be 2 values in one row

WHERE
    (meta_key = 'lat' AND meta_key = 'long' )

You need to review your operators to make sure you get the correct logic

How do I show/hide a UIBarButtonItem?

I worked with xib and with UIToolbar. BarButtonItem was created in xib file. I created IBOutlet for BarButtonItem. And I used this code to hide my BarButtonItem

 self.myBarButtonItem.enabled = NO;
 self.myBarButtonItem.title =  nil;

this helped me.

Getting title and meta tags from external website

Unfortunately, the built in php function get_meta_tags() requires the name parameter, and certain sites, such as twitter leave that off in favor of the property attribute. This function, using a mix of regex and dom document, will return a keyed array of metatags from a webpage. It checks for the name parameter, then the property parameter. This has been tested on instragram, pinterest and twitter.

/**
 * Extract metatags from a webpage
 */
function extract_tags_from_url($url) {
  $tags = array();

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

  $contents = curl_exec($ch);
  curl_close($ch);

  if (empty($contents)) {
    return $tags;
  }

  if (preg_match_all('/<meta([^>]+)content="([^>]+)>/', $contents, $matches)) {
    $doc = new DOMDocument();
    $doc->loadHTML('<?xml encoding="utf-8" ?>' . implode($matches[0]));
    $tags = array();
    foreach($doc->getElementsByTagName('meta') as $metaTag) {
      if($metaTag->getAttribute('name') != "") {
        $tags[$metaTag->getAttribute('name')] = $metaTag->getAttribute('content');
      }
      elseif ($metaTag->getAttribute('property') != "") {
        $tags[$metaTag->getAttribute('property')] = $metaTag->getAttribute('content');
      }
    }
  }

  return $tags;
}

C++ Fatal Error LNK1120: 1 unresolved externals

You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.

refresh div with jquery

I tried the first solution and it works but the end user can easily identify that the div's are refreshing as it is fadeIn(), without fade in i tried .toggle().toggle() and it works perfect. you can try like this

_x000D_
_x000D_
$("#panel").toggle().toggle();
_x000D_
_x000D_
_x000D_

it works perfectly for me as i'm developing a messenger and need to minimize and maximize the chat box's and this does it best rather than the above code.

How do I determine if a checkbox is checked?

Following will return true when checkbox is checked and false when not.

$(this).is(":checked")

Replace $(this) with the variable you want to check.

And used in a condition:

if ($(this).is(":checked")) {
  // do something
}

Android: Unable to add window. Permission denied for this window type

I did manage to finally display a window on the lock screen with the use of TYPE_SYSTEM_OVERLAY instead of TYPE_KEYGUARD_DIALOG. This works as expected and adds the window on the lock screen.

The problem with this is that the window is added on top of everything it possibly can. That is, the window will even appear on top of your keypad/pattern lock in case of secure lock screens. In the case of an unsecured lock screen, it will appear on top of the notification tray if you open it from the lock screen.

For me, that is unacceptable. I hope that this may help anybody else facing this problem.

How to change JDK version for an Eclipse project

Click on the Window tab in Eclipse, go to Preferences and when that window comes up, go to Java ? Installed JREs ? Execution Environment and choose JavaSE-1.5. You then have to go to Compiler and set the Compiler compliance level.

Changing JRE

Enter image description here

What's the right way to pass form element state to sibling/parent elements?

Having used React to build an app now, I'd like to share some thoughts to this question I asked half a year ago.

I recommend you to read

The first post is extremely helpful to understanding how you should structure your React app.

Flux answers the question why should you structure your React app this way (as opposed to how to structure it). React is only 50% of the system, and with Flux you get to see the whole picture and see how they constitute a coherent system.

Back to the question.

As for my first solution, it is totally OK to let the handler go the reverse direction, as the data is still going single-direction.

However, whether letting a handler trigger a setState in P can be right or wrong depending on your situation.

If the app is a simple Markdown converter, C1 being the raw input and C2 being the HTML output, it's OK to let C1 trigger a setState in P, but some might argue this is not the recommended way to do it.

However, if the app is a todo list, C1 being the input for creating a new todo, C2 the todo list in HTML, you probably want to handler to go two level up than P -- to the dispatcher, which let the store update the data store, which then send the data to P and populate the views. See that Flux article. Here is an example: Flux - TodoMVC

Generally, I prefer the way described in the todo list example. The less state you have in your app the better.

Maximum concurrent Socket.IO connections

This article may help you along the way: http://drewww.github.io/socket.io-benchmarking/

I wondered the same question, so I ended up writing a small test (using XHR-polling) to see when the connections started to fail (or fall behind). I found (in my case) that the sockets started acting up at around 1400-1800 concurrent connections.

This is a short gist I made, similar to the test I used: https://gist.github.com/jmyrland/5535279

Multiline for WPF TextBox

Contrary to @Andre Luus, setting Height="Auto" will not make the TextBox stretch. The solution I found was to set VerticalAlignment="Stretch"

Calling a method inside another method in same class

It is not recursion, it is overloading. The two add methods (the one in your snippet, and the one "provided" by ArrayList that you are extending) are not the same method, cause they are declared with different parameters.

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

How can I add "href" attribute to a link dynamically using JavaScript?

First, try changing <a>Link</a> to <span id=test><a>Link</a></span>.

Then, add something like this in the javascript function that you're calling:

var abc = 'somelink';
document.getElementById('test').innerHTML = '<a href="' + abc + '">Link</a>';

This way the link will look like this:

<a href="somelink">Link</a>

Scanner only reads first word instead of line

Use input.nextLine(); instead of input.next();

push multiple elements to array

There are many answers recommend to use: Array.prototype.push(a, b). It's nice way, BUT if you will have really big b, you will have stack overflow error (because of too many args). Be careful here.

See What is the most efficient way to concatenate N arrays? for more details.

Check if a string contains an element from a list (of strings)

If speed is critical, you might want to look for the Aho-Corasick algorithm for sets of patterns.

It's a trie with failure links, that is, complexity is O(n+m+k), where n is the length of the input text, m the cumulative length of the patterns and k the number of matches. You just have to modify the algorithm to terminate after the first match is found.

Child with max-height: 100% overflows parent

_x000D_
_x000D_
.container {_x000D_
  background: blue;_x000D_
  padding: 10px;_x000D_
  max-height: 200px;_x000D_
  max-width: 200px;_x000D_
  float: left;_x000D_
  margin-right: 20px;_x000D_
}_x000D_
_x000D_
.img1 {_x000D_
  display: block;_x000D_
  max-height: 100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
.img2 {_x000D_
  display: block;_x000D_
  max-height: inherit;_x000D_
  max-width: inherit;_x000D_
}
_x000D_
<!-- example 1  -->_x000D_
<div class="container">_x000D_
  <img class='img1' src="http://via.placeholder.com/350x450" />_x000D_
</div>_x000D_
_x000D_
<!-- example 2  -->_x000D_
_x000D_
<div class="container">_x000D_
  <img class='img2' src="http://via.placeholder.com/350x450" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I played around a little. On a larger image in firefox, I got a good result with using the inherit property value. Will this help you?

.container {
    background: blue;
    padding: 10px;
    max-height: 100px;
    max-width: 100px;
    text-align:center;
}

img {
    max-height: inherit;
    max-width: inherit;
}

Redirecting to authentication dialog - "An error occurred. Please try again later"

I have had the same problem as you.

From the Facebook Developers Apps page, make sure that the Sandbox Mode is disabled.

enter image description here

Bootstrap modal opening on page load

Use a document.ready() event around your call.

$(document).ready(function () {

    $('#memberModal').modal('show');

});

jsFiddle updated - http://jsfiddle.net/uvnggL8w/1/

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

How to access first element of JSON object array?

After you parse it with Javascript, try this:

mandrill_events[0].event

How to convert JSON object to JavaScript array?

var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];

for(var i in json_data)
    result.push([i, json_data [i]]);


var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);

http://jsfiddle.net/MV5rj/

How to add a TextView to LinearLayout in Android

Hey i have checked your code, there is no serious error in your code. this is complete code:

main.xml:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:id="@+id/info"
android:layout_height="wrap_content" 
android:orientation="vertical">
</LinearLayout>

this is Stackoverflow.java

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.TextView;

public class Stackoverflow extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        View linearLayout =  findViewById(R.id.info);
        //LinearLayout layout = (LinearLayout) findViewById(R.id.info);

        TextView valueTV = new TextView(this);
        valueTV.setText("hallo hallo");
        valueTV.setId(5);
        valueTV.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));

        ((LinearLayout) linearLayout).addView(valueTV);
    }
}

copy this code, and run it. it is completely error free. take care...

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

AngularJs - ng-model in a SELECT

You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions

<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>

Where is the application.properties file in a Spring Boot project?

You will need to add the application.properties file in your classpath.

If you are using Maven or Gradle, you can just put the file under src/main/resources.
If you are not using Maven or any other build tools, put that under your src folder and you should be fine.

Then you can just add an entry server.port = xxxx in the properties file.

How to get current instance name from T-SQL

Just to add some clarification to the registry queries. They only list the instances of the matching bitness (32 or 64) for the current instance.

The actual registry key for 32-bit SQL instances on a 64-bit OS is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Microsoft SQL Server

You can query this on a 64-bit instance to get all 32-bit instances as well. The 32-bit instance seems restricted to the Wow6432Node so cannot read the 64-bit registry tree.

Twitter Bootstrap 3.0 how do I "badge badge-important" now

Just add this one-line class in your CSS, and use the bootstrap label component.

.label-as-badge {
    border-radius: 1em;
}

Compare this label and badge side by side:

<span class="label label-default label-as-badge">hello</span>
<span class="badge">world</span>

enter image description here

They appear the same. But in the CSS, label uses em so it scales nicely, and it still has all the "-color" classes. So the label will scale to bigger font sizes better, and can be colored with label-success, label-warning, etc. Here are two examples:

<span class="label label-success label-as-badge">Yay! Rah!</span>

enter image description here

Or where things are bigger:

<div style="font-size: 36px"><!-- pretend an enclosing class has big font size -->
    <span class="label label-success label-as-badge">Yay! Rah!</span>
</div>

enter image description here


11/16/2015: Looking at how we'll do this in Bootstrap 4

Looks like .badge classes are completely gone. But there's a built-in .label-pill class (here) that looks like what we want.

.label-pill {
  padding-right: .6em;
  padding-left: .6em;
  border-radius: 10rem;
}

In use it looks like this:

<span class="label label-pill label-default">Default</span>
<span class="label label-pill label-primary">Primary</span>
<span class="label label-pill label-success">Success</span>
<span class="label label-pill label-info">Info</span>
<span class="label label-pill label-warning">Warning</span>
<span class="label label-pill label-danger">Danger</span>

enter image description here


11/04/2014: Here's an update on why cross-pollinating alert classes with .badge is not so great. I think this picture sums it up:

enter image description here

Those alert classes were not designed to go with badges. It renders them with a "hint" of the intended colors, but in the end consistency is thrown out the window and readability is questionable. Those alert-hacked badges are not visually cohesive.

The .label-as-badge solution is only extending the bootstrap design. We are keeping intact all the decision making made by the bootstrap designers, namely the consideration they gave for readability and cohesion across all the possible colors, as well as the color choices themselves. The .label-as-badge class only adds rounded corners, and nothing else. There are no color definitions introduced. Thus, a single line of CSS.

Yep, it is easier to just hack away and drop in those .alert-xxxxx classes -- you don't have to add any lines of CSS. Or you could care more about the little things and add one line.

How can I make a weak protocol reference in 'pure' Swift (without @objc)

Supplemental Answer

I was always confused about whether delegates should be weak or not. Recently I've learned more about delegates and when to use weak references, so let me add some supplemental points here for the sake of future viewers.

  • The purpose of using the weak keyword is to avoid strong reference cycles (retain cycles). Strong reference cycles happen when two class instances have strong references to each other. Their reference counts never go to zero so they never get deallocated.

  • You only need to use weak if the delegate is a class. Swift structs and enums are value types (their values are copied when a new instance is made), not reference types, so they don't make strong reference cycles.

  • weak references are always optional (otherwise you would used unowned) and always use var (not let) so that the optional can be set to nil when it is deallocated.

  • A parent class should naturally have a strong reference to its child classes and thus not use the weak keyword. When a child wants a reference to its parent, though, it should make it a weak reference by using the weak keyword.

  • weak should be used when you want a reference to a class that you don't own, not just for a child referencing its parent. When two non-hierarchical classes need to reference each other, choose one to be weak. The one you choose depends on the situation. See the answers to this question for more on this.

  • As a general rule, delegates should be marked as weak because most delegates are referencing classes that they do not own. This is definitely true when a child is using a delegate to communicate with a parent. Using a weak reference for the delegate is what the documentation recommends. (But see this, too.)

  • Protocols can be used for both reference types (classes) and value types (structs, enums). So in the likely case that you need to make a delegate weak, you have to make it an object-only protocol. The way to do that is to add AnyObject to the protocol's inheritance list. (In the past you did this using the class keyword, but AnyObject is preferred now.)

    protocol MyClassDelegate: AnyObject {
        // ...
    }
    
    class SomeClass {
        weak var delegate: MyClassDelegate?
    }
    

Further Study

Reading the following articles is what helped me to understand this much better. They also discuss related issues like the unowned keyword and the strong reference cycles that happen with closures.

Related

Still Reachable Leak detected by Valgrind

Here is a proper explanation of "still reachable":

"Still reachable" are leaks assigned to global and static-local variables. Because valgrind tracks global and static variables it can exclude memory allocations that are assigned "once-and-forget". A global variable assigned an allocation once and never reassigned that allocation is typically not a "leak" in the sense that it does not grow indefinitely. It is still a leak in the strict sense, but can usually be ignored unless you are pedantic.

Local variables that are assigned allocations and not free'd are almost always leaks.

Here is an example

int foo(void)
{
    static char *working_buf = NULL;
    char *temp_buf;
    if (!working_buf) {
         working_buf = (char *) malloc(16 * 1024);
    }
    temp_buf = (char *) malloc(5 * 1024);

    ....
    ....
    ....

}

Valgrind will report working_buf as "still reachable - 16k" and temp_buf as "definitely lost - 5k".

How to see full query from SHOW PROCESSLIST

I just read in the MySQL documentation that SHOW FULL PROCESSLIST by default only lists the threads from your current user connection.

Quote from the MySQL SHOW FULL PROCESSLIST documentation:

If you have the PROCESS privilege, you can see all threads.

So you can enable the Process_priv column in your mysql.user table. Remember to execute FLUSH PRIVILEGES afterwards :)

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

Examples for string find in Python

find( sub[, start[, end]])

Return the lowest index in the string where substring sub is found, such that sub is contained in the range [start, end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.

From the docs.

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

Can I make a function available in every controller in angular?

You can also combine them I guess:

<!doctype html>
<html ng-app="myApp">
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
    <script type="text/javascript">
        var myApp = angular.module('myApp', []);

        myApp.factory('myService', function() {
            return {
                foo: function() {
                    alert("I'm foo!");
                }
            };
        });

        myApp.run(function($rootScope, myService) {
            $rootScope.appData = myService;
        });

        myApp.controller('MainCtrl', ['$scope', function($scope){

        }]);

    </script>
</head>
<body ng-controller="MainCtrl">
    <button ng-click="appData.foo()">Call foo</button>
</body>
</html>

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

Convert String to Carbon

Why not try using the following:

$dateTimeString = $aDateString." ".$aTimeString;
$dueDateTime = Carbon::createFromFormat('Y-m-d H:i:s', $dateTimeString, 'Europe/London');   

UITableview: How to Disable Selection for Some Rows but Not Others

None from the answers above really addresses the issue correctly. The reason is that we want to disable selection of the cell but not necessarily of subviews inside the cell.

In my case I was presenting a UISwitch in the middle of the row and I wanted to disable selection for the rest of the row (which is empty) but not for the switch! The proper way of doing that is hence in the method

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath

where a statement of the form

[cell setSelectionStyle:UITableViewCellSelectionStyleNone];

disables selection for the specific cell while at the same time allows the user to manipulate the switch and hence use the appropriate selector. This is not true if somebody disables user interaction through the

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

method which merely prepares the cell and does not allow interaction with the UISwitch.

Moreover, using the method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

in order to deselect the cell with a statement of the form

[tableView deselectRowAtIndexPath:indexPath animated:NO];

still shows the row being selected while the user presses on the original contentView of the cell.

Just my two cents. I am pretty sure many will find this useful.

Finding elements not in a list

Your code is not doing what I think you think it is doing. The line for item in z: will iterate through z, each time making item equal to one single element of z. The original item list is therefore overwritten before you've done anything with it.

I think you want something like this:

item = [0,1,2,3,4,5,6,7,8,9]

for element in item:
    if element not in z:
        print element

But you could easily do this like:

[x for x in item if x not in z]

or (if you don't mind losing duplicates of non-unique elements):

set(item) - set(z)

Some projects cannot be imported because they already exist in the workspace error in Eclipse

I built the eclipse dependencies in the project terminal and then tried to import the project and it worked.

How to handle static content in Spring MVC?

From Spring 3, all the resources needs to mapped in a different way. You need to use the tag to specify the location of the resources.

Example :

<mvc:resources mapping="/resources/**" location="/resources/" />

By doing this way, you are directing the dispatcher servlet to look into the directory resources to look for the static content.

Retrieve version from maven pom.xml in code

When using spring boot, this link might be useful: https://docs.spring.io/spring-boot/docs/2.3.x/reference/html/howto.html#howto-properties-and-configuration

With spring-boot-starter-parent you just need to add the following to your application config file:

# get values from pom.xml
[email protected]@

After that the value is available like this:

@Value("${pom.version}")
private String pomVersion;

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

How can I get the DateTime for the start of the week?

For Monday

DateTime startAtMonday = DateTime.Now.AddDays(DayOfWeek.Monday - DateTime.Now.DayOfWeek);

For Sunday

DateTime startAtSunday = DateTime.Now.AddDays(DayOfWeek.Sunday- DateTime.Now.DayOfWeek);

Measuring function execution time in R

Although other solutions are useful for a single function, I recommend the following piece of code where is more general and effective:

Rprof(tf <- "log.log", memory.profiling = TRUE)
# the code you want to profile must be in between
Rprof (NULL) ; print(summaryRprof(tf))

How to use paginator from material angular?

After spending few hours on this i think this is best way to apply pagination. And more importantly it works. This is my paginator code <mat-paginator #paginatoR [length]="length" [pageSize]="pageSize" [pageSizeOptions]="pageSizeOptions">

Inside my component @ViewChild(MatPaginator) paginator: MatPaginator; to view child and finally you have to bind paginator to table dataSource and this is how it is done ngAfterViewInit() {this.dataSource.paginator = this.paginator;} Easy right? if it works for you then mark this as answer.

Changing the tmp folder of mysql

if you dont have apparmor or selinux issues, but still get errorcode 13's:

mysql must be able to access the full path. I.e. all folders must be mysql accessible, not just the one you intend in pointing to.

example, you try using this in your mysql configuration: tmp = /some/folder/on/disk

# will work, as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some

# will not work, also as user root:
mkdir -p /some/folder/on/disk
chown -R mysql:mysql /some/folder/on/disk

How to write character & in android strings.xml

For special character I normally use the Unicode definition, for the '&' for example: \u0026 if I am correct. Here is a nice reference page: http://jrgraphix.net/research/unicode_blocks.php?block=0

Android Studio not showing modules in project structure

Had similar issue when running version control on a project in Android Studio (0.4.2). When pulling it down to a new location and importing the modules, only the "Android SDK" were showing in the Project Structure.

I removed the .idea/ folder from the version control, by adding it to .gitignore file, and did a fresh pull and imported the modules. Now all the settings appeared correctly in the Project Settings and Platform Settings for the Project Structure.

How to implement a binary search tree in Python?

Here is a quick example of a binary insert:

class Node:
    def __init__(self, val):
        self.l_child = None
        self.r_child = None
        self.data = val

def binary_insert(root, node):
    if root is None:
        root = node
    else:
        if root.data > node.data:
            if root.l_child is None:
                root.l_child = node
            else:
                binary_insert(root.l_child, node)
        else:
            if root.r_child is None:
                root.r_child = node
            else:
                binary_insert(root.r_child, node)

def in_order_print(root):
    if not root:
        return
    in_order_print(root.l_child)
    print root.data
    in_order_print(root.r_child)

def pre_order_print(root):
    if not root:
        return        
    print root.data
    pre_order_print(root.l_child)
    pre_order_print(root.r_child)    

r = Node(3)
binary_insert(r, Node(7))
binary_insert(r, Node(1))
binary_insert(r, Node(5))

     3
    / \
   1   7
      /
     5

print "in order:"
in_order_print(r)

print "pre order"
pre_order_print(r)

in order:
1
3
5
7
pre order
3
1
7
5

How do I get the SelectedItem or SelectedIndex of ListView in vb.net?

Please Try This for Getting column Index

Private Sub lvDetail_MouseMove(sender As Object, e As MouseEventArgs) Handles lvDetail.MouseClick

    Dim info As ListViewHitTestInfo = lvDetail.HitTest(e.X, e.Y)
    Dim rowIndex As Integer = lvDetail.FocusedItem.Index
    lvDetail.Items(rowIndex).Selected = True
    Dim xTxt = info.SubItem.Text
    For i = 0 To lvDetail.Columns.Count - 1
        If lvDetail.SelectedItems(0).SubItems(i).Text = xTxt Then
            MsgBox(i)
        End If
    Next
End Sub

Font Awesome icon inside text input element

You're right. :before and :after pseudo content is not intended to work on replaced content like img and input elements. Adding a wrapping element and declare a font-family is one of the possibilities, as is using a background image. Or maybe a html5 placeholder text fits your needs:

<input name="username" placeholder="&#61447;">

Browsers that don’t support the placeholder attribute will simply ignore it.

UPDATE

The before content selector selects the input: input[type="text"]:before. You should select the wrapper: .wrapper:before. See http://jsfiddle.net/allcaps/gA4rx/ . I also added the placeholder suggestion where the wrapper is redundant.

.wrapper input[type="text"] {
    position: relative; 
}

input { font-family: 'FontAwesome'; } /* This is for the placeholder */

.wrapper:before {
    font-family: 'FontAwesome';
    color:red;
    position: relative;
    left: -5px;
    content: "\f007";
}

<p class="wrapper"><input placeholder="&#61447; Username"></p>

Fallback

Font Awesome uses the Unicode Private Use Area (PUA) to store icons. Other characters are not present and fall back to the browser default. That should be the same as any other input. If you define a font on input elements, then supply the same font as fallback for situations where us use an icon. Like this:

input { font-family: 'FontAwesome', YourFont; }

How should I throw a divide by zero exception in Java without actually dividing by zero?

Do this:

if (denominator == 0) throw new ArithmeticException("denominator == 0");

ArithmeticException is the exception which is normally thrown when you divide by 0.

VBA test if cell is in a range

From the Help:

Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If

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

If you cannot install aditional applications, then you can telnet (you will need to install this feature for your windows 7 by following this) the remote server:

TELNET server_name 80

followed by:

HEAD /virtual/directory/file.ext

or

GET /virtual/directory/file.ext

depending on if you want just the header (HEAD) or the full contents (GET)

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

Extract and delete all .gz in a directory- Linux

There's more than one way to do this obviously.

    # This will find files recursively (you can limit it by using some 'find' parameters. 
    # see the man pages
    # Final backslash required for exec example to work
    find . -name '*.gz' -exec gunzip '{}' \;

    # This will do it only in the current directory
    for a in *.gz; do gunzip $a; done

I'm sure there's other ways as well, but this is probably the simplest.

And to remove it, just do a rm -rf *.gz in the applicable directory

How can I center an image in Bootstrap?

Since the img is an inline element, Just use text-center on it's container. Using mx-auto will center the container (column) too.

<div class="row">
    <div class="col-4 mx-auto text-center">
        <img src="..">
    </div>
</div>

By default, images are display:inline. If you only want the center the image (and not the other column content), make the image display:block using the d-block class, and then mx-auto will work.

<div class="row">
  <div class="col-4">
    <img class="mx-auto d-block" src="..">
  </div>
</div>

Demo: http://codeply.com/go/iakGGLdB8s

Spark specify multiple column conditions for dataframe join

There is a Spark column/expression API join for such case:

Leaddetails.join(
    Utm_Master, 
    Leaddetails("LeadSource") <=> Utm_Master("LeadSource")
        && Leaddetails("Utm_Source") <=> Utm_Master("Utm_Source")
        && Leaddetails("Utm_Medium") <=> Utm_Master("Utm_Medium")
        && Leaddetails("Utm_Campaign") <=> Utm_Master("Utm_Campaign"),
    "left"
)

The <=> operator in the example means "Equality test that is safe for null values".

The main difference with simple Equality test (===) is that the first one is safe to use in case one of the columns may have null values.

How to count the number of true elements in a NumPy bool array

In terms of comparing two numpy arrays and counting the number of matches (e.g. correct class prediction in machine learning), I found the below example for two dimensions useful:

import numpy as np
result = np.random.randint(3,size=(5,2)) # 5x2 random integer array
target = np.random.randint(3,size=(5,2)) # 5x2 random integer array

res = np.equal(result,target)
print result
print target
print np.sum(res[:,0])
print np.sum(res[:,1])

which can be extended to D dimensions.

The results are:

Prediction:

[[1 2]
 [2 0]
 [2 0]
 [1 2]
 [1 2]]

Target:

[[0 1]
 [1 0]
 [2 0]
 [0 0]
 [2 1]]

Count of correct prediction for D=1: 1

Count of correct prediction for D=2: 2

Why Choose Struct Over Class?

I wouldn't say that structs offer less functionality.

Sure, self is immutable except in a mutating function, but that's about it.

Inheritance works fine as long as you stick to the good old idea that every class should be either abstract or final.

Implement abstract classes as protocols and final classes as structs.

The nice thing about structs is that you can make your fields mutable without creating shared mutable state because copy on write takes care of that :)

That's why the properties / fields in the following example are all mutable, which I would not do in Java or C# or swift classes.

Example inheritance structure with a bit of dirty and straightforward usage at the bottom in the function named "example":

protocol EventVisitor
{
    func visit(event: TimeEvent)
    func visit(event: StatusEvent)
}

protocol Event
{
    var ts: Int64 { get set }

    func accept(visitor: EventVisitor)
}

struct TimeEvent : Event
{
    var ts: Int64
    var time: Int64

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }
}

protocol StatusEventVisitor
{
    func visit(event: StatusLostStatusEvent)
    func visit(event: StatusChangedStatusEvent)
}

protocol StatusEvent : Event
{
    var deviceId: Int64 { get set }

    func accept(visitor: StatusEventVisitor)
}

struct StatusLostStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var reason: String

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

struct StatusChangedStatusEvent : StatusEvent
{
    var ts: Int64
    var deviceId: Int64
    var newStatus: UInt32
    var oldStatus: UInt32

    func accept(visitor: EventVisitor)
    {
        visitor.visit(self)
    }

    func accept(visitor: StatusEventVisitor)
    {
        visitor.visit(self)
    }
}

func readEvent(fd: Int) -> Event
{
    return TimeEvent(ts: 123, time: 56789)
}

func example()
{
    class Visitor : EventVisitor
    {
        var status: UInt32 = 3;

        func visit(event: TimeEvent)
        {
            print("A time event: \(event)")
        }

        func visit(event: StatusEvent)
        {
            print("A status event: \(event)")

            if let change = event as? StatusChangedStatusEvent
            {
                status = change.newStatus
            }
        }
    }

    let visitor = Visitor()

    readEvent(1).accept(visitor)

    print("status: \(visitor.status)")
}

.gitignore is ignored by Git

If it seems like Git isn't noticing the changes you made to your .gitignore file, you might want to check the following points:

  • There might be a global .gitignore file that might interfere with your local one
  • When you add something into a .gitignore file, try this:

    git add [uncommitted changes you want to keep] && git commit
    git rm -r --cached .
    git add .
    git commit -m "fixed untracked files"
    
  • If you remove something from a .gitignore file, and the above steps maybe don't work,if you found the above steps are not working, try this:

    git add -f [files you want to track again]
    git commit -m "Refresh removing files from .gitignore file."
    
    // For example, if you want the .java type file to be tracked again,
    // The command should be:
    //     git add -f *.java
    

Failed to execute 'createObjectURL' on 'URL':

I fixed it downloading the latest version from GgitHub GitHub url

Delete specific values from column with where condition?

UPDATE YourTable SET columnName = null WHERE YourCondition

How do I line up 3 divs on the same row?

I'm surprised that nobody gave CSS table layout as a solution:

_x000D_
_x000D_
.Row {_x000D_
    display: table;_x000D_
    width: 100%; /*Optional*/_x000D_
    table-layout: fixed; /*Optional*/_x000D_
    border-spacing: 10px; /*Optional*/_x000D_
}_x000D_
.Column {_x000D_
    display: table-cell;_x000D_
    background-color: red; /*Optional*/_x000D_
}
_x000D_
<div class="Row">_x000D_
    <div class="Column">C1</div>_x000D_
    <div class="Column">C2</div>_x000D_
    <div class="Column">C3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Works in IE8+

Check out a JSFiddle Demo

What is use of c_str function In c++

Oh must add my own pick here, you will use this when you encode/decode some string obj you transfer between two programs.

Lets say you use base64encode some array in python, and then you want to decode that into c++. Once you have the string you decode from base64decode in c++. In order to get it back to array of float, all you need to do here is

float arr[1024];
memcpy(arr, ur_string.c_str(), sizeof(float) * 1024);

This is pretty common use I suppose.

Passing multiple parameters with $.ajax url

Why are you combining GET and POST? Use one or the other.

$.ajax({
    type: 'post',
    data: {
        timestamp: timestamp,
        uid: uid
        ...
    }
});

php:

$uid =$_POST['uid'];

Or, just format your request properly (you're missing the ampersands for the get parameters).

url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,

java.nio.file.Path for a classpath resource

You need to define the Filesystem to read resource from jar file as mentioned in https://docs.oracle.com/javase/8/docs/technotes/guides/io/fsp/zipfilesystemprovider.html. I success to read resource from jar file with below codes:

Map<String, Object> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {

        Path path = fs.getPath("/path/myResource");

        try (Stream<String> lines = Files.lines(path)) {
            ....
        }
    }

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

Pandas read_csv low_memory and dtype options

I had a similar issue with a ~400MB file. Setting low_memory=False did the trick for me. Do the simple things first,I would check that your dataframe isn't bigger than your system memory, reboot, clear the RAM before proceeding. If you're still running into errors, its worth making sure your .csv file is ok, take a quick look in Excel and make sure there's no obvious corruption. Broken original data can wreak havoc...

Android Overriding onBackPressed()

You may just call the onBackPressed()and if you want some activity to display after the back button you have mention the

Intent intent = new Intent(ResetPinActivity.this, MenuActivity.class);
    startActivity(intent);
    finish();

that worked for me.

How can I compile my Perl script so it can be executed on systems without perl installed?

Look at PAR (Perl Archiving Toolkit).

PAR is a Cross-Platform Packaging and Deployment tool, dubbed as a cross between Java's JAR and Perl2EXE/PerlApp.

Export table data from one SQL Server to another

Just to show yet another option (for SQL Server 2008 and above):

  1. right-click on Database -> select 'Tasks' -> select 'Generate Scripts'
  2. Select specific database objects you want to copy. Let's say one or more tables. Click Next
  3. Click Advanced and scroll down to 'Types of Data to script' and choose 'Schema and Data'. Click OK
  4. Choose where to save generated script and proceed by clicking Next

Using await outside of an async function

There is always this of course:

(async () => {
    await ...

    // all of the script.... 

})();
// nothing else

This makes a quick function with async where you can use await. It saves you the need to make an async function which is great! //credits Silve2611

What does body-parser do with express?

If you don't want to use seperate npm package body-parser, latest express (4.16+) has built-in body-parser middleware and can be used like this,

const app = express();
app.use(express.json({ limit: '100mb' }));

p.s. Not all functionalities of body parse are present in the express. Refer documentation for full usage here

Generating statistics from Git repository

Just want to add gitqlite into the mix of answers here, which is a command-line tool that enables execution of SQL queries on git data, such as SELECT * FROM commits WHERE author_name = 'foo' etc.

Full disclosure, I'm a creator/maintainer of the project!

How to make for loops in Java increase by increments other than 1

The "increment" portion of a loop statement has to change the value of the index variable to have any effect. The longhand form of "++j" is "j = j + 1". So, as other answers have said, the correct form of your increment is "j = j + 3", which doesn't have as terse a shorthand as incrementing by one. "j + 3", as you know by now, doesn't actually change j; it's an expression whose evaluation has no effect.

When to use React "componentDidUpdate" method?

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {
   this.fetchData(this.props.userName);
 }
}

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

For more info, refer to the official docs:

Add / remove input field dynamically with jQuery

enter image description here You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.

Python function attributes - uses and abuses

You can do objects the JavaScript way... It makes no sense but it works ;)

>>> def FakeObject():
...   def test():
...     print "foo"
...   FakeObject.test = test
...   return FakeObject
>>> x = FakeObject()
>>> x.test()
foo

What exactly is the difference between Web API and REST API in MVC?

ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework.

REST

RESTs sweet spot is when you are exposing a public API over the internet to handle CRUD operations on data. REST is focused on accessing named resources through a single consistent interface.

SOAP

SOAP brings it’s own protocol and focuses on exposing pieces of application logic (not data) as services. SOAP exposes operations. SOAP is focused on accessing named operations, each implement some business logic through different interfaces.

Though SOAP is commonly referred to as “web services” this is a misnomer. SOAP has very little if anything to do with the Web. REST provides true “Web services” based on URIs and HTTP.

Reference: http://spf13.com/post/soap-vs-rest

And finally: What they could be referring to is REST vs. RPC See this: http://encosia.com/rest-vs-rpc-in-asp-net-web-api-who-cares-it-does-both/

When should you use constexpr capability in C++11?

Another use (not yet mentioned) is constexpr constructors. This allows creating compile time constants which don't have to be initialized during runtime.

const std::complex<double> meaning_of_imagination(0, 42); 

Pair that with user defined literals and you have full support for literal user defined classes.

3.14D + 42_i;

If using maven, usually you put log4j.properties under java or resources?

If your log4j.properties or log4j.xml file not found under src/main/resources use this PropertyConfigurator.configure("log4j.xml");

   PropertyConfigurator.configure("log4j.xml");
   Logger logger = LoggerFactory.getLogger(MyClass.class);
   logger.error(message);

Import an existing git project into GitLab?

Here are the steps provided by the Gitlab:

cd existing_repo
git remote rename origin old-origin
git remote add origin https://gitlab.example.com/rmishra/demoapp.git
git push -u origin --all
git push -u origin --tags

Win32Exception (0x80004005): The wait operation timed out

To all those who know more than me, rather than marking it unhelpful or misleading, read it one more time. I had issues with my Virtual Machine (VM) becoming unresponsive due to all resources being consumed by locked threads, so killing threads is the only option I had. I am not recommending this to anyone who are running long queries but may help to those who are stuck with unresponsive VM or something. Its up-to individuals to take the call. Yes it will kill your query but it saved my VM machine being destroyed.

Serverstack already answered similar question. It solved my issue with SQL on VM machine. Please check here

You need to run following command to fix issues with indexes.

exec sp_updatestats

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

Is there a simple, elegant way to define singletons?

OK, singleton could be good or evil, I know. This is my implementation, and I simply extend a classic approach to introduce a cache inside and produce many instances of a different type or, many instances of same type, but with different arguments.

I called it Singleton_group, because it groups similar instances together and prevent that an object of the same class, with same arguments, could be created:

# Peppelinux's cached singleton
class Singleton_group(object):
    __instances_args_dict = {}
    def __new__(cls, *args, **kwargs):
        if not cls.__instances_args_dict.get((cls.__name__, args, str(kwargs))):
            cls.__instances_args_dict[(cls.__name__, args, str(kwargs))] = super(Singleton_group, cls).__new__(cls, *args, **kwargs)
        return cls.__instances_args_dict.get((cls.__name__, args, str(kwargs)))


# It's a dummy real world use example:
class test(Singleton_group):
    def __init__(self, salute):
        self.salute = salute

a = test('bye')
b = test('hi')
c = test('bye')
d = test('hi')
e = test('goodbye')
f = test('goodbye')

id(a)
3070148780L

id(b)
3070148908L

id(c)
3070148780L

b == d
True


b._Singleton_group__instances_args_dict

{('test', ('bye',), '{}'): <__main__.test object at 0xb6fec0ac>,
 ('test', ('goodbye',), '{}'): <__main__.test object at 0xb6fec32c>,
 ('test', ('hi',), '{}'): <__main__.test object at 0xb6fec12c>}

Every object carries the singleton cache... This could be evil, but it works great for some :)

Initializing a list to a known number of elements in Python

Wanting to initalize an array of fixed size is a perfectly acceptable thing to do in any programming language; it isn't like the programmer wants to put a break statement in a while(true) loop. Believe me, especially if the elements are just going to be overwritten and not merely added/subtracted, like is the case of many dynamic programming algorithms, you don't want to mess around with append statements and checking if the element hasn't been initialized yet on the fly (that's a lot of code gents).

object = [0 for x in range(1000)]

This will work for what the programmer is trying to achieve.

How to Install pip for python 3.7 on Ubuntu 18?

When i use apt install python3-pip, i get a lot of packages need install, but i donot need them. So, i DO like this:

apt update
apt-get install python3-setuptools
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python3 get-pip.py
rm -f get-pip.py

how to sort an ArrayList in ascending order using Collections and Comparator

Two ways to get this done:

Collections.sort(myArray)

given elements inside myArray implements Comparable

Second

Collections.sort(myArray, new MyArrayElementComparator());

where MyArrayElementComparator is Comparator for elements inside myArray

What is the IntelliJ shortcut key to create a javadoc comment?

You can use the action 'Fix doc comment'. It doesn't have a default shortcut, but you can assign the Alt+Shift+J shortcut to it in the Keymap, because this shortcut isn't used for anything else. By default, you can also press Ctrl+Shift+A two times and begin typing Fix doc comment in order to find the action.

Move to next item using Java 8 foreach loop in stream

Using return; will work just fine. It will not prevent the full loop from completing. It will only stop executing the current iteration of the forEach loop.

Try the following little program:

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    stringList.stream().forEach(str -> {
        if (str.equals("b")) return; // only skips this iteration.

        System.out.println(str);
    });
}

Output:

a
c

Notice how the return; is executed for the b iteration, but c prints on the following iteration just fine.

Why does this work?

The reason the behavior seems unintuitive at first is because we are used to the return statement interrupting the execution of the whole method. So in this case, we expect the main method execution as a whole to be halted.

However, what needs to be understood is that a lambda expression, such as:

str -> {
    if (str.equals("b")) return;

    System.out.println(str);
}

... really needs to be considered as its own distinct "method", completely separate from the main method, despite it being conveniently located within it. So really, the return statement only halts the execution of the lambda expression.

The second thing that needs to be understood is that:

stringList.stream().forEach()

... is really just a normal loop under the covers that executes the lambda expression for every iteration.

With these 2 points in mind, the above code can be rewritten in the following equivalent way (for educational purposes only):

public static void main(String[] args) {
    ArrayList<String> stringList = new ArrayList<>();
    stringList.add("a");
    stringList.add("b");
    stringList.add("c");

    for(String s : stringList) {
        lambdaExpressionEquivalent(s);
    }
}

private static void lambdaExpressionEquivalent(String str) {
    if (str.equals("b")) {
        return;
    }

    System.out.println(str);
}

With this "less magic" code equivalent, the scope of the return statement becomes more apparent.

Show/hide div if checkbox selected

<input type="checkbox" name="check1" value="checkbox" onchange="showMe('div1')" /> checkbox

<div id="div1" style="display:none;">NOTICE</div>

  <script type="text/javascript">
<!--
   function showMe (box) {
    var chboxs = document.getElementById("div1").style.display;
    var vis = "none";
        if(chboxs=="none"){
         vis = "block"; }
        if(chboxs=="block"){
         vis = "none"; }
    document.getElementById(box).style.display = vis;
}
  //-->
</script>

How to convert MySQL time to UNIX timestamp using PHP?

Instead of strtotime you should use DateTime with PHP. You can also regard the timezone this way:

$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();

$mysqltime is of type MySQL Datetime, e. g. 2018-02-26 07:53:00.

PHP cURL HTTP PUT

Using Postman for Chrome, selecting CODE you get this... And works

_x000D_
_x000D_
<?php_x000D_
_x000D_
$curl = curl_init();_x000D_
_x000D_
curl_setopt_array($curl, array(_x000D_
  CURLOPT_URL => "https://blablabla.com/comorl",_x000D_
  CURLOPT_RETURNTRANSFER => true,_x000D_
  CURLOPT_ENCODING => "",_x000D_
  CURLOPT_MAXREDIRS => 10,_x000D_
  CURLOPT_TIMEOUT => 30,_x000D_
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,_x000D_
  CURLOPT_CUSTOMREQUEST => "PUT",_x000D_
  CURLOPT_POSTFIELDS => "{\n  \"customer\" : \"con\",\n  \"customerID\" : \"5108\",\n  \"customerEmail\" : \"[email protected]\",\n  \"Phone\" : \"34600000000\",\n  \"Active\" : false,\n  \"AudioWelcome\" : \"https://audio.com/welcome-defecto-es.mp3\"\n\n}",_x000D_
  CURLOPT_HTTPHEADER => array(_x000D_
    "cache-control: no-cache",_x000D_
    "content-type: application/json",_x000D_
    "x-api-key: whateveriyouneedinyourheader"_x000D_
  ),_x000D_
));_x000D_
_x000D_
$response = curl_exec($curl);_x000D_
$err = curl_error($curl);_x000D_
_x000D_
curl_close($curl);_x000D_
_x000D_
if ($err) {_x000D_
  echo "cURL Error #:" . $err;_x000D_
} else {_x000D_
  echo $response;_x000D_
}_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

Getting a slice of keys from a map

You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

package main

import (
    "fmt"
    "reflect"
)

func main() {
    abc := map[string]int{
        "a": 1,
        "b": 2,
        "c": 3,
    }

    keys := reflect.ValueOf(abc).MapKeys()

    fmt.Println(keys) // [a b c]
}

How to update values in a specific row in a Python Pandas DataFrame?

There are probably a few ways to do this, but one approach would be to merge the two dataframes together on the filename/m column, then populate the column 'n' from the right dataframe if a match was found. The n_x, n_y in the code refer to the left/right dataframes in the merge.

In[100] : df = pd.merge(df1, df2, how='left', on=['filename','m'])

In[101] : df
Out[101]: 
    filename   m   n_x  n_y
0  test0.dat  12  None  NaN
1  test2.dat  13  None   16

In[102] : df['n'] = df['n_y'].fillna(df['n_x'])

In[103] : df = df.drop(['n_x','n_y'], axis=1)

In[104] : df
Out[104]: 
    filename   m     n
0  test0.dat  12  None
1  test2.dat  13    16

Is the size of C "int" 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

That depends on the platform you're using, as well as how your compiler is configured. The only authoritative answer is to use the sizeof operator to see how big an integer is in your specific situation.


What are the factors that it depends on?

Range might be best considered, rather than size. Both will vary in practice, though it's much more fool-proof to choose variable types by range than size as we shall see. It's also important to note that the standard encourages us to consider choosing our integer types based on range rather than size, but for now let's ignore the standard practice, and let our curiosity explore sizeof, bytes and CHAR_BIT, and integer representation... let's burrow down the rabbit hole and see it for ourselves...


sizeof, bytes and CHAR_BIT

The following statement, taken from the C standard (linked to above), describes this in words that I don't think can be improved upon.

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.

Assuming a clear understanding will lead us to a discussion about bytes. It's commonly assumed that a byte is eight bits, when in fact CHAR_BIT tells you how many bits are in a byte. That's just another one of those nuances which isn't considered when talking about the common two (or four) byte integers.

Let's wrap things up so far:

  • sizeof => size in bytes, and
  • CHAR_BIT => number of bits in byte

Thus, Depending on your system, sizeof (unsigned int) could be any value greater than zero (not just 2 or 4), as if CHAR_BIT is 16, then a single (sixteen-bit) byte has enough bits in it to represent the sixteen bit integer described by the standards (quoted below). That's not necessarily useful information, is it? Let's delve deeper...


Integer representation

The C standard specifies the minimum precision/range for all standard integer types (and CHAR_BIT, too, fwiw) here. From this, we can derive a minimum for how many bits are required to store the value, but we may as well just choose our variables based on ranges. Nonetheless, a huge part of the detail required for this answer resides here. For example, the following that the standard unsigned int requires (at least) sixteen bits of storage:

UINT_MAX                                65535 // 2¹6 - 1

Thus we can see that unsigned int require (at least) 16 bits, which is where you get the two bytes (assuming CHAR_BIT is 8)... and later when that limit increased to 2³² - 1, people were stating 4 bytes instead. This explains the phenomena you've observed:

Most of the textbooks say integer variables occupy 2 bytes. But when I run a program printing the successive addresses of an array of integers it shows the difference of 4.

You're using an ancient textbook and compiler which is teaching you non-portable C; the author who wrote your textbook might not even be aware of CHAR_BIT. You should upgrade your textbook (and compiler), and strive to remember that I.T. is an ever-evolving field that you need to stay ahead of to compete... Enough about that, though; let's see what other non-portable secrets those underlying integer bytes store...

Value bits are what the common misconceptions appear to be counting. The above example uses an unsigned integer type which typically contains only value bits, so it's easy to miss the devil in the detail.

Sign bits... In the above example I quoted UINT_MAX as being the upper limit for unsigned int because it's a trivial example to extract the value 16 from the comment. For signed types, in order to distinguish between positive and negative values (that's the sign), we need to also include the sign bit.

INT_MIN                                -32768 // -(2¹5)
INT_MAX                                +32767 // 2¹5 - 1

Padding bits... While it's not common to encounter computers that have padding bits in integers, the C standard allows that to happen; some machines (i.e. this one) implement larger integer types by combining two smaller (signed) integer values together... and when you combine signed integers, you get a wasted sign bit. That wasted bit is considered padding in C. Other examples of padding bits might include parity bits and trap bits.


As you can see, the standard seems to encourage considering ranges like INT_MIN..INT_MAX and other minimum/maximum values from the standard when choosing integer types, and discourages relying upon sizes as there are other subtle factors likely to be forgotten such as CHAR_BIT and padding bits which might affect the value of sizeof (int) (i.e. the common misconceptions of two-byte and four-byte integers neglects these details).

Hide div element when screen size is smaller than a specific size

@media only screen and (max-width: 1026px) { 
  #fadeshow1 { 
    display: none; 
  } 
}

Any time the screen is less than 1026 pixels wide, anything inside the { } will apply.

Some browsers don't support media queries. You can get round this using a javascript library like Respond.JS

failed to load ad : 3

W/Ads: Failed to load ad: 3

It Means that your code is correct but due to less amount of request to the server your ads are not Visible. To check the Test ADS you Should put the code in loop for some time, and you have to give multiple requests so that your admob receives multiple requests and will load the ads immediately.

Add the below code

for(int i=0;i<1000;i++) {
            AdRequest adRequest = new AdRequest
                    .Builder()
                    .addTestDevice("B431EE858B5F1986E4D89CA31250F732")
                    .build();
            accountSettingsBinding.adView.loadAd(adRequest);
        } 

Restart Your application multiple times.

Remove the Loop after you start receiving ads.

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

PackagesNotFoundError: The following packages are not available from current channels:

I was trying to install fancyimpute package for imputation but there was not luck. But when i tried below commands, it got installed: Commands:

conda update conda
conda update anaconda
pip install fancyimpute 

(here i was trying to give command conda install fancyimpute which did't work)

Programmatically change UITextField Keyboard type

to make the text field accept alpha numeric only set this property

textField.keyboardType = UIKeyboardTypeNamePhonePad;

C# Ignore certificate errors?

This code worked for me. I had to add TLS2 because that's what the URL I am interested in was using.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
ServicePointManager.ServerCertificateValidationCallback +=
    (sender, cert, chain, sslPolicyErrors) => { return true; };
using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(UserDataUrl);
    client.DefaultRequestHeaders.Accept.Clear();
    client.DefaultRequestHeaders.Accept.Add(new
      MediaTypeWithQualityHeaderValue("application/json"));
    Task<string> response = client.GetStringAsync(UserDataUrl);
    response.Wait();

    if (response.Exception != null)
    {
         return null;
    }

    return JsonConvert.DeserializeObject<UserData>(response.Result);
}

Print array to a file

just use file_put_contents('file',$myarray); file_put_contents() works with arrays too.

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

select *
from user
left join edge
on user.userid = edge.tailuser
and edge.headuser = 5043

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)