Programs & Examples On #Query hints

PHP calculate age

//replace / with - so strtotime works
$dob = strtotime(str_replace("/","-",$birthdayDate));       
$tdate = time();
return date('Y', $tdate) - date('Y', $dob);

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

SQL ROWNUM how to return rows between a specific range

SELECT * FROM
(SELECT ROW_NUMBER() OVER(ORDER BY Id) AS RowNum, * FROM maps006) AS DerivedTable
WHERE RowNum BETWEEN 49 AND 101

Which is faster: Stack allocation or Heap allocation

Never do premature assumption as other application code and usage can impact your function. So looking at function is isolation is of no use.

If you are serious with application then VTune it or use any similar profiling tool and look at hotspots.

Ketan

How to set image to UIImage

Like vikingosgundo said, but keep in mind that if you use [UIImage imageNamed:image] then the image is cached and eats away memory. So unless you plan on using the same image in many places, you should load the image, with imageWithContentsOfFile: and imageWithData:

This will save you significant memory and speeds up your app.

Use jQuery to hide a DIV when the user clicks outside of it

So many answers, must be a right of passage to have added one... I didn't see a current (jQuery 3.1.1) answers - so:

$(function() {
    $('body').on('mouseup', function() {
        $('#your-selector').hide();
    });
});

Slicing a dictionary

Write a dict subclass that accepts a list of keys as an "item" and returns a "slice" of the dictionary:

class SliceableDict(dict):
    default = None
    def __getitem__(self, key):
        if isinstance(key, list):   # use one return statement below
            # uses default value if a key does not exist
            return {k: self.get(k, self.default) for k in key}
            # raises KeyError if a key does not exist
            return {k: self[k] for k in key}
            # omits key if it does not exist
            return {k: self[k] for k in key if k in self}
        return dict.get(self, key)

Usage:

d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d[[1, 5]]   # {1: 2, 5: 6}

Or if you want to use a separate method for this type of access, you can use * to accept any number of arguments:

class SliceableDict(dict):
    def slice(self, *keys):
        return {k: self[k] for k in keys}
        # or one of the others from the first example

d = SliceableDict({1:2, 3:4, 5:6, 7:8})
d.slice(1, 5)     # {1: 2, 5: 6}
keys = 1, 5
d.slice(*keys)    # same

HTML tag <a> want to add both href and onclick working

Use ng-click in place of onclick. and its as simple as that:

<a href="www.mysite.com" ng-click="return theFunction();">Item</a>

<script type="text/javascript">
function theFunction () {
    // return true or false, depending on whether you want to allow 
    // the`href` property to follow through or not
 }
</script>

How to import module when module name has a '-' dash or hyphen in it?

you can't. foo-bar is not an identifier. rename the file to foo_bar.py

Edit: If import is not your goal (as in: you don't care what happens with sys.modules, you don't need it to import itself), just getting all of the file's globals into your own scope, you can use execfile

# contents of foo-bar.py
baz = 'quux'
>>> execfile('foo-bar.py')
>>> baz
'quux'
>>> 

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

Difficulty with ng-model, ng-repeat, and inputs

how do something like:

<select ng-model="myModel($index+1)">

And in my inspector element be:

<select ng-model="myModel1">
...
<select ng-model="myModel2">

Javascript replace all "%20" with a space

using unescape(stringValue)

_x000D_
_x000D_
var str = "Passwords%20do%20not%20match%21";
document.write(unescape(str))
_x000D_
_x000D_
_x000D_

//Output
Passwords do not match!

use decodeURI(stringValue)

_x000D_
_x000D_
var str = "Passwords%20do%20not%20match%21";
 document.write(decodeURI(str))
_x000D_
_x000D_
_x000D_

Space = %20
? = %3F
! = %21
# = %23
...etc

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

For anyone else and just an addition to Robert, If your nav has flex display value, you can float the element that you need to the right, by adding this to its css

{
    margin-left: auto;
}

How to make a promise from setTimeout

const setTimeoutAsync = (cb, delay) =>
  new Promise((resolve) => {
    setTimeout(() => {
      resolve(cb());
    }, delay);
  });

We can pass custom 'cb fxn' like this one

Which command in VBA can count the number of characters in a string variable?

Len(word)

Although that's not what your question title asks =)

Setting the correct PATH for Eclipse

For me none worked. I compared my existing eclipse.ini with a new one and started removing options and testing if eclipse worked.

The only option that prevented eclipse from starting was -XX:+UseParallelGC, so I removed it and voilá!

Python Requests and persistent sessions

This will work for you in Python;

# Call JIRA API with HTTPBasicAuth
import json
import requests
from requests.auth import HTTPBasicAuth

JIRA_EMAIL = "****"
JIRA_TOKEN = "****"
BASE_URL = "https://****.atlassian.net"
API_URL = "/rest/api/3/serverInfo"

API_URL = BASE_URL+API_URL

BASIC_AUTH = HTTPBasicAuth(JIRA_EMAIL, JIRA_TOKEN)
HEADERS = {'Content-Type' : 'application/json;charset=iso-8859-1'}

response = requests.get(
    API_URL,
    headers=HEADERS,
    auth=BASIC_AUTH
)

print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Comparing strings, c++

.compare() returns an integer, which is a measure of the difference between the two strings.

  • A return value of 0 indicates that the two strings compare as equal.
  • A positive value means that the compared string is longer, or the first non-matching character is greater.
  • A negative value means that the compared string is shorter, or the first non-matching character is lower.

operator== simply returns a boolean, indicating whether the strings are equal or not.

If you don't need the extra detail, you may as well just use ==.

How to export data with Oracle SQL Developer?

In SQL Developer, from the top menu choose Tools > Data Export. This launches the Data Export wizard. It's pretty straightforward from there.

There is a tutorial on the OTN site. Find it here.

Redirect on select option in select box

    {{-- dynamic select/dropdown --}}
    <select class="form-control m-bot15" name="district_id" 
        onchange ="location = this.options[this.selectedIndex].value;"
        >
          <option value="">--Select--</option>
          <option value="?">All</option>

            @foreach($location as $district)
                <option  value="?district_id={{ $district->district_id }}" >
                  {{ $district->district }}
                </option> 
            @endforeach   

    </select>

How do I clear/delete the current line in terminal?

I'm not sure if you love it but I use Ctrl+A (to go beginning the line) and Ctrl+K (to delete the line) I was familiar with these commands from emacs, and figured out them accidently.

Increasing the timeout value in a WCF service

In addition to the binding timeouts (which are in Timespans), You may also need this as well. This is in seconds.

<system.web>
    <httpRuntime executionTimeout="600"/><!-- = 10 minutes -->

C# Connecting Through Proxy

This one-liner works for me:

WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;

CredentialCache.DefaultNetWorkCredentials is the proxy settings set in Internet Explorer.

WebRequest.DefaultWebProxy.Credentials is used for all internet connectivity in the application.

Two decimal places using printf( )

Try using a format like %d.%02d

int iAmount = 10050;
printf("The number with fake decimal point is %d.%02d", iAmount/100, iAmount%100);

Another approach is to type cast it to double before printing it using %f like this:

printf("The number with fake decimal point is %0.2f", (double)(iAmount)/100);

My 2 cents :)

Export and import table dump (.sql) using pgAdmin

Using PgAdmin step 1: select schema and right click and go to Backup..enter image description here

step 2: Give the file name and click the backup button.

enter image description here

step 3: In detail message copy the backup file path.

enter image description here

step 4:

Go to other schema and right click and go to Restore. (see step 1)

step 5:

In popup menu paste aboved file path to filename category and click Restore button.

enter image description here

How to get screen width and height

This is what finally worked for me:

DisplayMetrics metrics = this.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;

CSS : center form in page horizontally and vertically

How about using a grid? it's 2019 and support is reasonable

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: red;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  display: grid;_x000D_
  background-color: bisque;_x000D_
  height: 100vh;_x000D_
  place-items: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
<div class="content">_x000D_
  <form action="#" method="POST">_x000D_
    <fieldset>_x000D_
      <legend>Information:</legend>_x000D_
      <label for="name">Name:</label>_x000D_
      <input type="text" id="name" name="user_name">_x000D_
    </fieldset>_x000D_
    <button type="button" formmethod="POST" formaction="#">Submit</button>_x000D_
  </form>_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

Error: Generic Array Creation

You can't create arrays with a generic component type.

Create an array of an explicit type, like Object[], instead. You can then cast this to PCB[] if you want, but I don't recommend it in most cases.

PCB[] res = (PCB[]) new Object[list.size()]; /* Not type-safe. */

If you want type safety, use a collection like java.util.List<PCB> instead of an array.

By the way, if list is already a java.util.List, you should use one of its toArray() methods, instead of duplicating them in your code. This doesn't get your around the type-safety problem though.

How to give environmental variable path for file appender in configuration file in log4j

Maybe... :

datestamp=yyyy-MM-dd/HH:mm:ss.SSS/zzz
layout=%d{${datestamp}} ms=%-4r [%t] %-5p %l %n%m %n%n

# infoFile 
log4j.appender.infoFile=org.apache.log4j.RollingFileAppender
log4j.appender.infoFile.File=${MY_HOME}/logs/message.log
log4j.appender.infoFile.layout=org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern=${layout}

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

Compare two objects' properties to find differences?

Yes. Use Reflection. With Reflection, you can do things like:

//given object of some type
object myObjectFromSomewhere;
Type myObjOriginalType = myObjectFromSomewhere.GetType();
PropertyInfo[] myProps = myObjOriginalType.GetProperties();

And then you can use the resulting PropertyInfo classes to compare all manner of things.

.crx file install in chrome

Update: appears to have stopped working since Chrome 80

Drag & Drop the '.crx' file on to the 'Extensions' page

  1. Settings - icon > Tools > Extensions
    ( the 'hamburger' icon in the top-right corner )

  2. Enable Developer Mode ( toggle button in top-right corner )

  3. Drag and drop the '.crx' extension file onto the Extensions page from step 1
    ( crx file should likely be in your Downloads directory )

  4. Install

Source: Chrome YouTube Downloader - install instructions

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

Sending email in .NET through Gmail

Source : Send email in ASP.NET C#

Below is a sample working code for sending in a mail using C#, in the below example I am using google’s smtp server.

The code is pretty self explanatory, replace email and password with your email and password values.

public void SendEmail(string address, string subject, string message)
{
    string email = "[email protected]";
    string password = "put-your-GMAIL-password-here";

    var loginInfo = new NetworkCredential(email, password);
    var msg = new MailMessage();
    var smtpClient = new SmtpClient("smtp.gmail.com", 587);

    msg.From = new MailAddress(email);
    msg.To.Add(new MailAddress(address));
    msg.Subject = subject;
    msg.Body = message;
    msg.IsBodyHtml = true;

    smtpClient.EnableSsl = true;
    smtpClient.UseDefaultCredentials = false;
    smtpClient.Credentials = loginInfo;
    smtpClient.Send(msg);
}

Difference between DOMContentLoaded and load events

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

Eclipse doesn't stop at breakpoints

I suddenly experienced the skipping of breakpoints as well in Eclipse Juno CDT. For me the issue was that I had set optimization levels up. Once I set it back to none it was working fine. To set optimization levels go to Project Properties -> C/C++ Build -> Settings -> Tool Settings pan depending on which compiler you are using go to -> Optimization and set Optimization Level to: None (-O0). Hope this helps! Best

Convert Unix timestamp to a date string

The standard Perl solution is:

echo $TIMESTAMP | perl -nE 'say scalar gmtime $_'

(or localtime, if preferred)

How to hide Android soft keyboard on EditText

Simply Use EditText.setFocusable(false); in activity

or use in xml

android:focusable="false"

How do I clear a search box with an 'x' in bootstrap 3?

Here is my working solution with search and clear icon for Angularjs\Bootstrap with CSS.

    <div class="form-group has-feedback has-clear">
                    <input type="search" class="form-control removeXicon" ng-model="filter" style="max-width:100%" placeholder="Search..." />
                    <div ng-switch on="!!filter">
                        <div ng-switch-when="false">
                            <span class="glyphicon glyphicon-search form-control-feedback"></span>
                        </div>
                        <div ng-switch-when="true">
                            <span class="glyphicon glyphicon-remove-sign form-control-feedback" ng-click="$parent.filter = ''" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></span>
                        </div>
                    </div>                        
                </div>

------

CSS

/* hide the built-in IE10+ clear field icon */
.removeXicon::-ms-clear {
  display: none;
}

/* hide the built-in chrome clear field icon */
.removeXicon::-webkit-search-decoration,
.removeXicon::-webkit-search-cancel-button,
.removeXicon::-webkit-search-results-button,
.removeXicon::-webkit-search-results-decoration { 
      display: none; 
}

Why is pydot unable to find GraphViz's executables in Windows 8?

Tried all installation sequence as described in all solutions/posting/blogs, finally realized anaconda was not able to read the Environment variables. Closed Anaconda and Spyder. Then opened Anaconda in Administrator mode (on Windows 64 bit OS machine) and then opened Spyder. Script worked fine with PYDOT calls.

Get gateway ip address in android

This solution will give you the Network parameters. Check out this solution

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

How do I count unique values inside a list

Use a set:

words = ['a', 'b', 'c', 'a']
unique_words = set(words)             # == set(['a', 'b', 'c'])
unique_word_count = len(unique_words) # == 3

Armed with this, your solution could be as simple as:

words = []
ipta = raw_input("Word: ")

while ipta:
  words.append(ipta)
  ipta = raw_input("Word: ")

unique_word_count = len(set(words))

print "There are %d unique words!" % unique_word_count

Show history of a file?

git log -p will generate the a patch (the diff) for every commit selected. For a single file, use git log --follow -p $file.

If you're looking for a particular change, use git bisect to find the change in log(n) views by splitting the number of commits in half until you find where what you're looking for changed.

Also consider looking back in history using git blame to follow changes to the line in question if you know what that is. This command shows the most recent revision to affect a certain line. You may have to go back a few versions to find the first change where something was introduced if somebody has tweaked it over time, but that could give you a good start.

Finally, gitk as a GUI does show me the patch immediately for any commit I click on.

Example enter image description here:

Remove Style on Element

You can edit style with pure Javascript. No library needed, supported by all browsers except IE where you need to set to '' instead of null (see comments).

var element = document.getElementById('sample_id');

element.style.width = null;
element.style.height = null;

For more information, you can refer to HTMLElement.style documentation on MDN.

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

str="abcdef"

str.index('c') #=> 2 #String matching approach
str=~/c/ #=> 2 #Regexp approach 
$~ #=> #<MatchData "c">

Hope it helps. :)

Excel: VLOOKUP that returns true or false?

ISNA is the best function to use. I just did. I wanted all cells whose value was NOT in an array to conditionally format to a certain color.

=ISNA(VLOOKUP($A2,Sheet1!$A:$D,2,FALSE))

How to cut a string after a specific character in unix

For completeness, using cut

cut -d : -f 2 <<< $var

And using only bash:

IFS=: read a b <<< $var ; echo $b

Using OpenGl with C#?

Concerning the (somewhat off topic I know but since it was brought up earlier) XNA vs OpenGL choice, it might be beneficial in several cases to go with OpenGL instead of XNA (and in other XNA instead of OpenGL...).

If you are going to run the applications on Linux or Mac using Mono, it might be a good choice to go with OpenGL. Also, which isn't so widely known I think, if you have customers that are going to run your applications in a Citrix environment, then DirectX/Direct3D/XNA won't be as economical a choice as OpenGL. The reason for this is that OpenGL applications can be co-hosted on a lesser number of servers (due to performance issues a single server cannot host an infinite number of application instances) than DirectX/XNA applications which demands dedicated virtual servers to run in hardware accelerated mode. Other requirements exists like supported graphics cards etc but I will keep to the XNA vs OpenGL issue. As an IT Architect, Software developer etc this will have to be considered before choosing between OpenGL and DirectX/XNA...

A side note is that WebGL is based on OpenGL ES3 afaik...

As a further note, these are not the only considerations, but they might make the choice easier for some...

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

How to automatically allow blocked content in IE?

You have two options:

  1. Use a Mark of the Web. This will enable a single html page to load. It See here for details. To do this, add the following to your web page below the doctype and above the html tag:

    <!-- saved from url=(0014)about:internet -->

  2. Disable this feature. To do so go to Internet Options->Advanced->Security->Allow Active Content... Then close IE. When you restart IE, it will not give you this error.

php foreach with multidimensional array

This would have been a comment under Brad's answer, but I don't have a high enough reputation.

Recently I found that I needed the key of the multidimensional array too, i.e., it wasn't just an index for the array, in the foreach loop.

In order to achieve that, you could use something very similar to the accepted answer, but instead split the key and value as follows

foreach ($mda as $mdaKey => $mdaData) {
    echo $mdaKey . ": " . $mdaData["value"];
}

Hope that helps someone.

How to sort a list of objects based on an attribute of the objects?

Add rich comparison operators to the object class, then use sort() method of the list.
See rich comparison in python.


Update: Although this method would work, I think solution from Triptych is better suited to your case because way simpler.

What is this date format? 2011-08-12T20:17:46.384Z

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

CSS Display an Image Resized and Cropped

Try using the clip-path property:

The clip-path property lets you clip an element to a basic shape or to an SVG source.

Note: The clip-path property will replace the deprecated clip property.

_x000D_
_x000D_
img {_x000D_
  width: 150px;_x000D_
  clip-path: inset(30px 35px);_x000D_
}
_x000D_
<img src="http://i.stack.imgur.com/wPh0S.jpg">
_x000D_
_x000D_
_x000D_

More examples here.

scp with port number specified

scp help tells us that port is specified by uppercase P.

~$ scp
usage: scp [-12346BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
           [-l limit] [-o ssh_option] [-P port] [-S program]
           [[user@]host1:]file1 ... [[user@]host2:]file2

Hope this helps.

How can I check if a View exists in a Database?

There are already many ways specified above but one of my favourite is missing..

GO
IF OBJECT_ID('nView', 'V') IS NOT NULL
    DROP VIEW nView;
GO

WHERE nView is the name of view

UPDATE 2017-03-25: as @hanesjw suggested to drop a Store Procedure use P instead of V as the second argument of OBJECT_ID

GO
IF OBJECT_ID( 'nProcedure', 'P' ) IS NOT NULL 
    DROP PROCEDURE dbo.sprocName; 
GO

What is the best or most commonly used JMX Console / Client

I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.

I have been primarily using it for GC tuning and finding bottlenecks.

Using Pairs or 2-tuples in Java

Apache Commons provided some common java utilities including a Pair. It implements Map.Entry, Comparable and Serializable.

How to use Spring Boot with MySQL database and JPA?

For Jpa based application: base package scan @EnableJpaRepositories(basePackages = "repository") You can try it once!!!
Project Structure

com
 +- stack
     +- app
     |   +- Application.java
     +- controller
     |   +- EmployeeController.java
     +- service
     |   +- EmployeeService.java
     +- repository
     |   +- EmployeeRepository.java
     +- model
     |   +- Employee.java
-pom.xml
dependencies: 
    mysql, lombok, data-jpa

application.properties

#Data source :
spring.datasource.url=jdbc:mysql://localhost:3306/employee?useSSL=false
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.generate-ddl=true
spring.datasource.driverClassName=com.mysql.jdbc.Driver

#Jpa/Hibernate :
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update

Employee.java

@Entity
@Table (name = "employee")
@Getter
@Setter
public class Employee {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    private Long id;

    @Column (name = "first_name")
    private String firstName;
    @Column (name = "last_name")
    private String lastName;
    @Column (name = "email")
    private String email;
    @Column (name = "phone_number")
    private String phoneNumber;
    @Column (name = "emp_desg")
    private String desgination;
}

EmployeeRepository.java

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
}

EmployeeController.java

@RestController
public class EmployeeController {

    @Autowired
    private EmployeeService empService;

    @GetMapping (value = "/employees")
    public List<Employee> getAllEmployee(){
        return empService.getAllEmployees();
    }

    @PostMapping (value = "/employee")
    public ResponseEntity<Employee> addEmp(@RequestBody Employee emp, HttpServletRequest 
                                         request) throws URISyntaxException {
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(request.getRequestURI() + "/" + emp.getId()));
        empService.saveEmployee(emp);
        return new ResponseEntity<Employee>(emp, headers, HttpStatus.CREATED);
    }

EmployeeService.java

public interface EmployeeService {
    public List<Employee> getAllEmployees();
    public Employee saveEmployee(Employee emp);
}

EmployeeServiceImpl.java

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository empRepository;

    @Override
    public List<Employee> getAllEmployees() {
        return empRepository.findAll();
    }

    @Override
    public Employee saveEmployee(Employee emp) {
        return empRepository.save(emp);
    }
}

EmployeeApplication.java

@SpringBootApplication
@EnableJpaRepositories(basePackages = "repository")
public class EmployeeApplication {
    public static void main(String[] args) {
        SpringApplication.run(EmployeeApplication.class, args);
    }
}

Codeigniter unset session

I use the old PHP way..It unsets all session variables and doesn't require to specify each one of them in an array. And after unsetting the variables we destroy the session

Index was outside the bounds of the Array. (Microsoft.SqlServer.smo)

I had a similar experience with using SMO via C# with the stack trace:

[1896] System.IndexOutOfRangeException: Index was outside the bounds of the array. 
[1896]    at Microsoft.SqlServer.Management.Smo.BitStorage.SetBit(Int32 itemIndex, BitIndex bitIndex, Boolean value) 
[1896]    at Microsoft.SqlServer.Management.Smo.SqlSmoObject.AddObjectPropsFromDataReader(IDataReader reader, Boolean skipIfDirty, Int32 startColIdx, Int32 endColIdx) 
[1896]    at Microsoft.SqlServer.Management.Smo.SqlSmoObject.ImplInitialize(String[] fields, OrderBy[] orderby) 
[1896]    at Microsoft.SqlServer.Management.Smo.SqlSmoObject.Initialize(Boolean allProperties) 
[1896]    at Microsoft.SqlServer.Management.Smo.SqlSmoObject.OnPropertyMissing(String propname, Boolean useDefaultValue) 
[1896]    at Microsoft.SqlServer.Management.Smo.PropertyCollection.RetrieveProperty(Int32 index, Boolean useDefaultOnMissingValue) 
[1896]    at Microsoft.SqlServer.Management.Smo.PropertyCollection.GetValueWithNullReplacement(String propertyName, Boolean throwOnNullValue, Boolean useDefaultOnMissingValue) 
[1896]    at Microsoft.SqlServer.Management.Smo.Information.get_MasterDBPath()

It turned out my versions of the CLR/NCLI/SMO were 10.50.1600.1. Upgrading them to 10.53.6000.34 fixed it - thus allowing the 2008R2 SMO to do many things with 2012 and 2014 servers.

Get them from the feature pack

https://www.microsoft.com/en-gb/download/details.aspx?id=44272

In Node.js, how do I "include" functions from my other files?

It worked with me like the following....

Lib1.js

//Any other private code here 

// Code you want to export
exports.function1 = function(params) {.......};
exports.function2 = function(params) {.......};

// Again any private code

now in the Main.js file you need to include Lib1.js

var mylib = requires('lib1.js');
mylib.function1(params);
mylib.function2(params);

Please remember to put the Lib1.js in node_modules folder.

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

The problem is also identified in your status bar at the bottom:

overwrite label in status bar

You are in overwrite mode instead of insert mode.

The “Insert” key toggles between insert and overwrite modes.

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

Hide Spinner in Input Number - Firefox 29

I mixed few answers from answers above and from How to remove the arrows from input[type="number"] in Opera in scss:

input[type=number] {
  &,
  &::-webkit-inner-spin-button,
  &::-webkit-outer-spin-button {
    -webkit-appearance: none;
    -moz-appearance: textfield;
    appearance: none;

    &:hover,
    &:focus {
      -moz-appearance: number-input;
    }
  }
}

Tested on chrome, firefox, safari

Node.js Web Application examples/tutorials

Update

Dav Glass from Yahoo has given a talk at YuiConf2010 in November which is now available in Video from.

He shows to great extend how one can use YUI3 to render out widgets on the server side an make them work with GET requests when JS is disabled, or just make them work normally when it's active.

He also shows examples of how to use server side DOM to apply style sheets before rendering and other cool stuff.

The demos can be found on his GitHub Account.

The part that's missing IMO to make this really awesome, is some kind of underlying storage of the widget state. So that one can visit the page without JavaScript and everything works as expected, then they turn JS on and now the widget have the same state as before but work without page reloading, then throw in some saving to the server + WebSockets to sync between multiple open browser.... and the next generation of unobtrusive and gracefully degrading ARIA's is born.

Original Answer

Well go ahead and built it yourself then.

Seriously, 90% of all WebApps out there work fine with a REST approach, of course you could do magical things like superior user tracking, tracking of downloads in real time, checking which parts of videos are being watched etc.

One problem is scalability, as soon as you have more then 1 Node process, many (but not all) of the benefits of having the data stored between requests go away, so you have to make sure that clients always hit the same process. And even then, bigger things will yet again need a database layer.

Node.js isn't the solution to everything, I'm sure people will build really great stuff in the future, but that needs some time, right now many are just porting stuff over to Node to get things going.

What (IMHO) makes Node.js so great, is the fact that it streamlines the Development process, you have to write less code, it works perfectly with JSON, you loose all that context switching.

I mainly did gaming experiments so far, but I can for sure say that there will be many cool multi player (or even MMO) things in the future, that use both HTML5 and Node.js.

Node.js is still gaining traction, it's not even near to the RoR Hype some years ago (just take a look at the Node.js tag here on SO, hardly 4-5 questions a day).

Rome (or RoR) wasn't built over night, and neither will Node.js be.

Node.js has all the potential it needs, but people are still trying things out, so I'd suggest you to join them :)

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

An example of retrieving data from a table having columns column1, column2 ,column3 column4, cloumn1 and 2 hold int values and column 3 and 4 hold varchar(10)

import java.sql.*; 
// need to import this as the STEP 1. Has the classes that you mentioned  
public class JDBCexample {
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 
    static final String DB_URL = "jdbc:mysql://LocalHost:3306/databaseNameHere"; 
    // DON'T PUT ANY SPACES IN BETWEEN and give the name of the database (case insensitive) 

    // database credentials
    static final String USER = "root";
    // usually when you install MySQL, it logs in as root 
    static final String PASS = "";
    // and the default password is blank

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;

        try {
    // registering the driver__STEP 2
            Class.forName("com.mysql.jdbc.Driver"); 
    // returns a Class object of com.mysql.jdbc.Driver
    // (forName(""); initializes the class passed to it as String) i.e initializing the
    // "suitable" driver
            System.out.println("connecting to the database");
    // opening a connection__STEP 3
            conn = DriverManager.getConnection(DB_URL, USER, PASS);
    // executing a query__STEP 4 
            System.out.println("creating a statement..");
            stmt = conn.createStatement();
    // creating an object to create statements in SQL
            String sql;
            sql = "SELECT column1, cloumn2, column3, column4 from jdbcTest;";
    // this is what you would have typed in CLI for MySQL
            ResultSet rs = stmt.executeQuery(sql);
    // executing the query__STEP 5 (and retrieving the results in an object of ResultSet)
    // extracting data from result set
            while(rs.next()){
    // retrieve by column name
                int value1 = rs.getInt("column1");
                int value2 = rs.getInt("column2");
                String value3 = rs.getString("column3");
                String value4 = rs.getString("columnm4");
    // displaying values:
                System.out.println("column1 "+ value1);
                System.out.println("column2 "+ value2);
                System.out.println("column3 "+ value3);
                System.out.println("column4 "+ value4);

            }
    // cleaning up__STEP 6
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
    //  handle sql exception
            e.printStackTrace();
        }catch (Exception e) {
    // TODO: handle exception for class.forName
            e.printStackTrace();
        }finally{  
    //closing the resources..STEP 7
            try {
                if (stmt != null)
                    stmt.close();
            } catch (SQLException e2) {
                e2.printStackTrace();
            }try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e2) {
                e2.printStackTrace();
            }
        }
        System.out.println("good bye");
    }
}

Get value from JToken that may not exist (best practices)

This takes care of nulls

var body = JObject.Parse("anyjsonString");

body?.SelectToken("path-string-prop")?.ToString();

body?.SelectToken("path-double-prop")?.ToObject<double>();

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

Making PHP var_dump() values display one line per value

I've also researched this issue and not found the right answer. This doesn't work for me:

echo '<pre>' . var_dump($variable) . '</pre>';

This will not provide a nice display of the array for me, with line breaks (I'm using Firefox 31.3.0)

However, after some experimentation, this solved the problem (notice the php is closed at first):

... ?> <pre><?php echo var_dump($variable) ?></pre> <?php ...

This solves the problem and displays a nice, easy-to-read array for me on my browser. You see how the tags are not wrapped in PHP; only the echo var_dump part is.

npm not working - "read ECONNRESET"

npm config rm proxy

npm config rm https-proxy

works for me!

Disable keyboard on EditText

Here is a website that will give you what you need

As a summary, it provides links to InputMethodManager and View from Android Developers. It will reference to the getWindowToken inside of View and hideSoftInputFromWindow() for InputMethodManager

A better answer is given in the link, hope this helps.

here is an example to consume the onTouch event:

editText_input_field.setOnTouchListener(otl);

private OnTouchListener otl = new OnTouchListener() {
  public boolean onTouch (View v, MotionEvent event) {
        return true; // the listener has consumed the event
  }
};

Here is another example from the same website. This claims to work but seems like a bad idea since your EditBox is NULL it will be no longer an editor:

MyEditor.setOnTouchListener(new OnTouchListener(){

  @Override
  public boolean onTouch(View v, MotionEvent event) {
    int inType = MyEditor.getInputType(); // backup the input type
    MyEditor.setInputType(InputType.TYPE_NULL); // disable soft input
    MyEditor.onTouchEvent(event); // call native handler
    MyEditor.setInputType(inType); // restore input type
    return true; // consume touch even
  }
});

Hope this points you in the right direction

C - Convert an uppercase letter to lowercase

In ASCII the upper and lower case alphabet is 0x20 (in ASCII 0x20 is space ' ') apart from each other, so this is another way to do it.

int lower(int a) 
{
    return a | ' ';  
}

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

How to compare two NSDates: Which is more recent?

Let's assume two dates:

NSDate *date1;
NSDate *date2;

Then the following comparison will tell which is earlier/later/same:

if ([date1 compare:date2] == NSOrderedDescending) {
    NSLog(@"date1 is later than date2");
} else if ([date1 compare:date2] == NSOrderedAscending) {
    NSLog(@"date1 is earlier than date2");
} else {
    NSLog(@"dates are the same");
}

Please refer to the NSDate class documentation for more details.

Save each sheet in a workbook to separate CSV files

A small modification to answer from Alex is turning on and off of auto calculation.

Surprisingly the unmodified code was working fine with VLOOKUP but failed with OFFSET. Also turning auto calculation off speeds up the save drastically.

Public Sub SaveAllSheetsAsCSV()
On Error GoTo Heaven

' each sheet reference
Dim Sheet As Worksheet
' path to output to
Dim OutputPath As String
' name of each csv
Dim OutputFile As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.EnableEvents = False

' Save the file in current director
OutputPath = ThisWorkbook.Path


If OutputPath <> "" Then
Application.Calculation = xlCalculationManual

' save for each sheet
For Each Sheet In Sheets

    OutputFile = OutputPath & Application.PathSeparator & Sheet.Name & ".csv"

    ' make a copy to create a new book with this sheet
    ' otherwise you will always only get the first sheet

    Sheet.Copy
    ' this copy will now become active
     ActiveWorkbook.SaveAs Filename:=OutputFile, FileFormat:=xlCSV,     CreateBackup:=False
    ActiveWorkbook.Close
Next

Application.Calculation = xlCalculationAutomatic

End If

Finally:
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.EnableEvents = True

Exit Sub

Heaven:
MsgBox "Couldn't save all sheets to CSV." & vbCrLf & _
        "Source: " & Err.Source & " " & vbCrLf & _
        "Number: " & Err.Number & " " & vbCrLf & _
        "Description: " & Err.Description & " " & vbCrLf

GoTo Finally
End Sub

How do you show animated GIFs on a Windows Form (c#)

Note that in Windows, you traditionally don't use animated Gifs, but little AVI animations: there is a Windows native control just to display them. There are even tools to convert animated Gifs to AVI (and vice-versa).

Firebug-like debugger for Google Chrome

Just adding some talking points as someone who uses Firebug / Chrome Inspector every day:

  1. At the time of writing, there's only Google DOM inspector and no it doesn't have all the features of Firebug

  2. Inspector is a 'lite' version of Firebug: The interface is not as good IMO, element inspection in both recent versions is now clunky, but Firebug is still better; I find myself trying to find the love for Chrome (since it's a better, faster browser experience), but for development work, it still just sucks for me.

  3. Live preview / modification of DOM / CSS is still way better in Firebug; calculated CSS and box model view are better in Firebug;

  4. Somehow it's just easier to read/use Firebug maybe because of the ease of navigating, manipulating/modifying the document in several key areas? Who knows. I'm used to the interface and I think Chrome Inspector is not as good although this is a subjective thing I admit.

  5. The Cookies/Net tab are extremely useful to me in Firebug. Maybe Chrome Inspector has this now? Last time I checked it did not, because Chrome updates itself in the background without your intervention (gets your consent by default like all good overlords).

  6. Last point: The day that Google Chrome gets a fully-featured Firebug is the day Firefox basically dies for developers because Firefox had 3 years to make Firefox's layout engine Gecko as fast as WebKit and they didn't. Sorry to put it so bluntly but it's the truth.

You see, now everyone wants to move away from Flash in lieu of jQuery motivated by mobile accessibility and interactivity (iPhone, iPad, Android) and JavaScript is 'suddenly' a big deal (that's sarcasm), so that ship has sailed, Firefox. And that makes me sad, as a Mozilla fanperson. Chrome is simply a better browser until Firefox upgrades their JavaScript engine.

No signing certificate "iOS Distribution" found

I got the "No signing certificate" error when running Xcode 11.3 on macOS 10.14.x Mojave. (but after Xcode 12 was released.)

I was also using Fastlane. My fix was to set generate_apple_certs to false when running Match. This seemed to generate signing certificates that were backwards-compatible with Xcode 11.3

Match documentation - https://docs.fastlane.tools/actions/match/

This is the relevant section of my Fastfile:

platform :ios do
  lane :certs do
    force = false
    match(type: "development", generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.dev")
    match(type: "adhoc",       generate_apple_certs: false, force: force, app_identifier: "your.app.identifier.beta")
    match(type: "appstore",    generate_apple_certs: false, force: force, app_identifier: "your.app.identifier")
  end

  ...

Android EditText delete(backspace) key event

I have tested @Jeff's solution on version 4.2, 4.4, 6.0. On 4.2 and 6.0, it works well. But on 4.4, it doesn't work.

I found an easy way to work around this problem. The key point is to insert an invisible character into the content of EditText at the begining, and don't let user move cursor before this character. My way is to insert a white-space character with an ImageSpan of Zero Width on it. Here is my code.

                @Override
                public void afterTextChanged(Editable s) {
                    String ss = s.toString();
                    if (!ss.startsWith(" ")) {
                        int selection = holder.editText.getSelectionEnd();
                        s.insert(0, " ");
                        ss = s.toString();
                        holder.editText.setSelection(selection + 1);
                    }
                    if (ss.startsWith(" ")) {
                        ImageSpan[] spans = s.getSpans(0, 1, ImageSpan.class);
                        if (spans == null || spans.length == 0) {
                            s.setSpan(new ImageSpan(getResources().getDrawable(R.drawable.zero_wdith_drawable)), 0 , 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                }

And we need custom an EditText which has a SelectionChangeListener

public class EditTextSelectable extends android.support.v7.widget.AppCompatEditText {
public interface OnSelectChangeListener {
    void onSelectChange(int start, int end);
}

private OnSelectChangeListener mListener;

public void setListener(OnSelectChangeListener listener) {
    mListener = listener;
}

...constructors...

@Override
protected void onSelectionChanged(int selStart, int selEnd) {
    if (mListener != null) {
        mListener.onSelectChange(selStart, selEnd);
    }
    super.onSelectionChanged(selStart, selEnd);
}

}

And the last step

holder.editText.setListener(new EditTextSelectable.OnSelectChangeListener() {
                @Override
                public void onSelectChange(int start, int end) {
                    if (start == 0 && holder.editText.getText().length() != 0) {
                        holder.editText.setSelection(1, Math.max(1, end));
                    }
                }
            });

And now, we are done~ We can detect backspace key event when EditText has no actual content, and user will know nothing about our trick.

Free c# QR-Code generator

Generate QR Code Image in ASP.NET Using Google Chart API

Google Chart API returns an image in response to a URL GET or POST request. All the data required to create the graphic is included in the URL, including the image type and size.

var url = string.Format("http://chart.apis.google.com/chart?cht=qr&chs={1}x{2}&chl={0}", txtCode.Text, txtWidth.Text, txtHeight.Text);
                WebResponse response = default(WebResponse);
                Stream remoteStream = default(Stream);
                StreamReader readStream = default(StreamReader);
                WebRequest request = WebRequest.Create(url);
                response = request.GetResponse();
                remoteStream = response.GetResponseStream();
                readStream = new StreamReader(remoteStream);
                System.Drawing.Image img = System.Drawing.Image.FromStream(remoteStream);
                img.Save("D:/QRCode/" + txtCode.Text + ".png");
                response.Close();
                remoteStream.Close();
                readStream.Close();
                txtCode.Text = string.Empty;
                txtWidth.Text = string.Empty;
                txtHeight.Text = string.Empty;
                lblMsg.Text = "The QR Code generated successfully";

Click here for complete source code to download

Demo of application for free QR Code generator using C#

enter image description here

KnockoutJs v2.3.0 : Error You cannot apply bindings multiple times to the same element

Something that can happen as well which throws this exception is the following. Say you have:

ko.applyBindings(myViewModel1, document.getElementById('element1'));
...
ko.applyBindings(myViewModel2, document.getElementById('element2'));

Now, when both #element1 and #element2 don't exist you'll get the error. The reason is that Knockout's applyBindings falls back on document.body as root element when #element1 and #element2 are not found. Now it tries to apply binding twice on the body...

Not a nice fallback of Knockout if you ask me. I'd rather have a clear error message that the element does not exist in the DOM (yet).

Hope this helps some people.

How to put Google Maps V2 on a Fragment using ViewPager

Dynamically adding map fragment to view Pager:

If you are targeting an application earlier than API level 12 make an instance of SupportedMapFragment and add it to your view page adapter.

SupportMapFragment supportMapFragment=SupportMapFragment.newInstance();
        supportMapFragment.getMapAsync(this);

API level 12 or higher support MapFragment objects

MapFragment mMapFragment=MapFragment.newInstance();
            mMapFragment.getMapAsync(this);

Python urllib2, basic HTTP authentication, and tr.im

Take a look at this SO post answer and also look at this basic authentication tutorial from the urllib2 missing manual.

In order for urllib2 basic authentication to work, the http response must contain HTTP code 401 Unauthorized and a key "WWW-Authenticate" with the value "Basic" otherwise, Python won't send your login info, and you will need to either use Requests, or urllib.urlopen(url) with your login in the url, or add a the header like in @Flowpoke's answer.

You can view your error by putting your urlopen in a try block:

try:
    urllib2.urlopen(urllib2.Request(url))
except urllib2.HTTPError, e:
    print e.headers
    print e.headers.has_key('WWW-Authenticate')

Remove object from a list of objects in python

You could try this to dynamically remove an object from an array without looping through it? Where e and t are just random objects.

>>> e = {'b':1, 'w': 2}
>>> t = {'b':1, 'w': 3}
>>> p = [e,t]
>>> p
[{'b': 1, 'w': 2}, {'b': 1, 'w': 3}]
>>>
>>> p.pop(p.index({'b':1, 'w': 3}))
{'b': 1, 'w': 3}
>>> p
[{'b': 1, 'w': 2}]
>>>

How to overlay density plots in R?

Whenever there are issues of mismatched axis limits, the right tool in base graphics is to use matplot. The key is to leverage the from and to arguments to density.default. It's a bit hackish, but fairly straightforward to roll yourself:

set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)

xrng = range(x1, x2)

#force the x values at which density is
#  evaluated to be the same between 'density'
#  calls by specifying 'from' and 'to'
#  (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])

matplot(kde1$x, cbind(kde1$y, kde2$y))

A plot depicting the output of the call to matplot. Two curves are observed, one red, the other black; the black curve extends higher than the red, while the red curve is the "fatter".

Add bells and whistles as desired (matplot accepts all the standard plot/par arguments, e.g. lty, type, col, lwd, ...).

Disable arrow key scrolling in users browser

I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

window.addEventListener('keydown', (e) => {
    if (e.target.localName != 'input') {   // if you need to filter <input> elements
        switch (e.keyCode) {
            case 37: // left
            case 39: // right
                e.preventDefault();
                break;
            case 38: // up
            case 40: // down
                e.preventDefault();
                break;
            default:
                break;
        }
    }
}, {
    capture: true,   // this disables arrow key scrolling in modern Chrome
    passive: false   // this is optional, my code works without it
});

Quote for EventTarget.addEventListener() from MDN

options Optional
   An options object specifies characteristics about the event listener. The available options are:

capture
   A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
once
   ...
passive
   A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

Editable text to string

Based on this code (which you provided in response to Alex's answer):

Editable newTxt=(Editable)userName1.getText(); 
String newString = newTxt.toString();

It looks like you're trying to get the text out of a TextView or EditText. If that's the case then this should work:

String newString = userName1.getText().toString(); 

Best approach to real time http streaming to HTML5 video client

I wrote an HTML5 video player around broadway h264 codec (emscripten) that can play live (no delay) h264 video on all browsers (desktop, iOS, ...).

Video stream is sent through websocket to the client, decoded frame per frame and displayed in a canva (using webgl for acceleration)

Check out https://github.com/131/h264-live-player on github.

Filter items which array contains any of given values

You should use Terms Query

{
    "query" : {
        "terms" : {
            "tags" : ["c", "d"]
        }
    }
}

How to break out or exit a method in Java?

To add to the other answers, you can also exit a method by throwing an exception manually:

throw new Exception();

enter image description here

Trigger a Travis-CI rebuild without pushing a commit?

If you open the Settings tab for the repository on GitHub, click on Integrations & services, find Travis CI and click Edit, you should see a Test Service button. This will trigger a build.

How to create a dotted <hr/> tag?

You could just have <hr style="border-top: dotted 1px;" /> . That should work.

How can I create a self-signed cert for localhost?

I would recomment Pluralsight's tool for creating self-signed-certs: http://blog.pluralsight.com/selfcert-create-a-self-signed-certificate-interactively-gui-or-programmatically-in-net

Make your cert as a .pfx and import it into IIS. And add it as a trusted root cert authority.

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

if path.exists(Score_file):
      try : 
         with open(Score_file , "rb") as prev_Scr:

            return Unpickler(prev_Scr).load()

    except EOFError : 

        return dict() 

Laravel - check if Ajax request

Maybe this helps. You have to refer the @param

         /**       
         * Display a listing of the resource.
         *
         * @param  Illuminate\Http\Request $request
         * @return Response
         */
        public function index(Request $request)
        {
            if($request->ajax()){
                return "AJAX";
            }
            return "HTTP";
        }

PHP check whether property exists in object or class

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

if (isset($ob->a))

isset() will return false if property is null

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
   public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

I was also getting exact same error and using AsyncTask :

`java.lang.IllegalStateException:` The content of the adapter has changed but ListView  did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. [in ListView(2131296334, class android.widget.ListView) with Adapter... etc

I solved it by puttingadapter.notifyDataSetChanged(); at the bottom of my UI thread, that is my AsyncTask onPostExecute method. Like this :

 protected void onPostExecute(Void aVoid) {

 all my other stuff etc...
    all my other stuff etc...

           adapter.notifyDataSetChanged();

                }

            });
        }

Now my app works.

EDIT : In fact, my app still crashed about every 1 in 10 times, giving the same error.

Eventually I came across runOnUiThread on a previous post, which I thought could be useful. So I put it in my doInBackground method, like this :

@Override
protected Void doInBackground(Void... voids) {

    runOnUiThread(new Runnable() {
                      public void run() { etc... etc...

And I removed the adapter.notifyDataSetChanged(); method. Now, my app never crashes.

List directory in Go

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }
 
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

Generating a drop down list of timezones with PHP

You can create very easy a dropdown from this array (It was a time-consuming task to put this together and test it). We already use this list in some of our apps.

It is very important to store timezone identifiers in your database and not just the timezone offset like "GMT+2", because of Daylight Saving Times.

UPDATE

I updated/corrected the timezones list (also checkout: https://github.com/paptamas/timezones):

<?php
$timezones = array (
'(GMT-11:00) Midway Island' => 'Pacific/Midway',
'(GMT-11:00) Samoa' => 'Pacific/Samoa',
'(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
'(GMT-09:00) Alaska' => 'US/Alaska',
'(GMT-08:00) Pacific Time (US &amp; Canada)' => 'America/Los_Angeles',
'(GMT-08:00) Tijuana' => 'America/Tijuana',
'(GMT-07:00) Arizona' => 'US/Arizona',
'(GMT-07:00) Chihuahua' => 'America/Chihuahua',
'(GMT-07:00) La Paz' => 'America/Chihuahua',
'(GMT-07:00) Mazatlan' => 'America/Mazatlan',
'(GMT-07:00) Mountain Time (US &amp; Canada)' => 'US/Mountain',
'(GMT-06:00) Central America' => 'America/Managua',
'(GMT-06:00) Central Time (US &amp; Canada)' => 'US/Central',
'(GMT-06:00) Guadalajara' => 'America/Mexico_City',
'(GMT-06:00) Mexico City' => 'America/Mexico_City',
'(GMT-06:00) Monterrey' => 'America/Monterrey',
'(GMT-06:00) Saskatchewan' => 'Canada/Saskatchewan',
'(GMT-05:00) Bogota' => 'America/Bogota',
'(GMT-05:00) Eastern Time (US &amp; Canada)' => 'US/Eastern',
'(GMT-05:00) Indiana (East)' => 'US/East-Indiana',
'(GMT-05:00) Lima' => 'America/Lima',
'(GMT-05:00) Quito' => 'America/Bogota',
'(GMT-04:00) Atlantic Time (Canada)' => 'Canada/Atlantic',
'(GMT-04:30) Caracas' => 'America/Caracas',
'(GMT-04:00) La Paz' => 'America/La_Paz',
'(GMT-04:00) Santiago' => 'America/Santiago',
'(GMT-03:30) Newfoundland' => 'Canada/Newfoundland',
'(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
'(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Greenland' => 'America/Godthab',
'(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
'(GMT-01:00) Azores' => 'Atlantic/Azores',
'(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
'(GMT+00:00) Casablanca' => 'Africa/Casablanca',
'(GMT+00:00) Edinburgh' => 'Europe/London',
'(GMT+00:00) Greenwich Mean Time : Dublin' => 'Etc/Greenwich',
'(GMT+00:00) Lisbon' => 'Europe/Lisbon',
'(GMT+00:00) London' => 'Europe/London',
'(GMT+00:00) Monrovia' => 'Africa/Monrovia',
'(GMT+00:00) UTC' => 'UTC',
'(GMT+01:00) Amsterdam' => 'Europe/Amsterdam',
'(GMT+01:00) Belgrade' => 'Europe/Belgrade',
'(GMT+01:00) Berlin' => 'Europe/Berlin',
'(GMT+01:00) Bern' => 'Europe/Berlin',
'(GMT+01:00) Bratislava' => 'Europe/Bratislava',
'(GMT+01:00) Brussels' => 'Europe/Brussels',
'(GMT+01:00) Budapest' => 'Europe/Budapest',
'(GMT+01:00) Copenhagen' => 'Europe/Copenhagen',
'(GMT+01:00) Ljubljana' => 'Europe/Ljubljana',
'(GMT+01:00) Madrid' => 'Europe/Madrid',
'(GMT+01:00) Paris' => 'Europe/Paris',
'(GMT+01:00) Prague' => 'Europe/Prague',
'(GMT+01:00) Rome' => 'Europe/Rome',
'(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
'(GMT+01:00) Skopje' => 'Europe/Skopje',
'(GMT+01:00) Stockholm' => 'Europe/Stockholm',
'(GMT+01:00) Vienna' => 'Europe/Vienna',
'(GMT+01:00) Warsaw' => 'Europe/Warsaw',
'(GMT+01:00) West Central Africa' => 'Africa/Lagos',
'(GMT+01:00) Zagreb' => 'Europe/Zagreb',
'(GMT+02:00) Athens' => 'Europe/Athens',
'(GMT+02:00) Bucharest' => 'Europe/Bucharest',
'(GMT+02:00) Cairo' => 'Africa/Cairo',
'(GMT+02:00) Harare' => 'Africa/Harare',
'(GMT+02:00) Helsinki' => 'Europe/Helsinki',
'(GMT+02:00) Istanbul' => 'Europe/Istanbul',
'(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
'(GMT+02:00) Kyiv' => 'Europe/Helsinki',
'(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
'(GMT+02:00) Riga' => 'Europe/Riga',
'(GMT+02:00) Sofia' => 'Europe/Sofia',
'(GMT+02:00) Tallinn' => 'Europe/Tallinn',
'(GMT+02:00) Vilnius' => 'Europe/Vilnius',
'(GMT+03:00) Baghdad' => 'Asia/Baghdad',
'(GMT+03:00) Kuwait' => 'Asia/Kuwait',
'(GMT+03:00) Minsk' => 'Europe/Minsk',
'(GMT+03:00) Nairobi' => 'Africa/Nairobi',
'(GMT+03:00) Riyadh' => 'Asia/Riyadh',
'(GMT+03:00) Volgograd' => 'Europe/Volgograd',
'(GMT+03:30) Tehran' => 'Asia/Tehran',
'(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
'(GMT+04:00) Baku' => 'Asia/Baku',
'(GMT+04:00) Moscow' => 'Europe/Moscow',
'(GMT+04:00) Muscat' => 'Asia/Muscat',
'(GMT+04:00) St. Petersburg' => 'Europe/Moscow',
'(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
'(GMT+04:00) Yerevan' => 'Asia/Yerevan',
'(GMT+04:30) Kabul' => 'Asia/Kabul',
'(GMT+05:00) Islamabad' => 'Asia/Karachi',
'(GMT+05:00) Karachi' => 'Asia/Karachi',
'(GMT+05:00) Tashkent' => 'Asia/Tashkent',
'(GMT+05:30) Chennai' => 'Asia/Calcutta',
'(GMT+05:30) Kolkata' => 'Asia/Kolkata',
'(GMT+05:30) Mumbai' => 'Asia/Calcutta',
'(GMT+05:30) New Delhi' => 'Asia/Calcutta',
'(GMT+05:30) Sri Jayawardenepura' => 'Asia/Calcutta',
'(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
'(GMT+06:00) Almaty' => 'Asia/Almaty',
'(GMT+06:00) Astana' => 'Asia/Dhaka',
'(GMT+06:00) Dhaka' => 'Asia/Dhaka',
'(GMT+06:00) Ekaterinburg' => 'Asia/Yekaterinburg',
'(GMT+06:30) Rangoon' => 'Asia/Rangoon',
'(GMT+07:00) Bangkok' => 'Asia/Bangkok',
'(GMT+07:00) Hanoi' => 'Asia/Bangkok',
'(GMT+07:00) Jakarta' => 'Asia/Jakarta',
'(GMT+07:00) Novosibirsk' => 'Asia/Novosibirsk',
'(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
'(GMT+08:00) Chongqing' => 'Asia/Chongqing',
'(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
'(GMT+08:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
'(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
'(GMT+08:00) Perth' => 'Australia/Perth',
'(GMT+08:00) Singapore' => 'Asia/Singapore',
'(GMT+08:00) Taipei' => 'Asia/Taipei',
'(GMT+08:00) Ulaan Bataar' => 'Asia/Ulan_Bator',
'(GMT+08:00) Urumqi' => 'Asia/Urumqi',
'(GMT+09:00) Irkutsk' => 'Asia/Irkutsk',
'(GMT+09:00) Osaka' => 'Asia/Tokyo',
'(GMT+09:00) Sapporo' => 'Asia/Tokyo',
'(GMT+09:00) Seoul' => 'Asia/Seoul',
'(GMT+09:00) Tokyo' => 'Asia/Tokyo',
'(GMT+09:30) Adelaide' => 'Australia/Adelaide',
'(GMT+09:30) Darwin' => 'Australia/Darwin',
'(GMT+10:00) Brisbane' => 'Australia/Brisbane',
'(GMT+10:00) Canberra' => 'Australia/Canberra',
'(GMT+10:00) Guam' => 'Pacific/Guam',
'(GMT+10:00) Hobart' => 'Australia/Hobart',
'(GMT+10:00) Melbourne' => 'Australia/Melbourne',
'(GMT+10:00) Port Moresby' => 'Pacific/Port_Moresby',
'(GMT+10:00) Sydney' => 'Australia/Sydney',
'(GMT+10:00) Yakutsk' => 'Asia/Yakutsk',
'(GMT+11:00) Vladivostok' => 'Asia/Vladivostok',
'(GMT+12:00) Auckland' => 'Pacific/Auckland',
'(GMT+12:00) Fiji' => 'Pacific/Fiji',
'(GMT+12:00) International Date Line West' => 'Pacific/Kwajalein',
'(GMT+12:00) Kamchatka' => 'Asia/Kamchatka',
'(GMT+12:00) Magadan' => 'Asia/Magadan',
'(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
'(GMT+12:00) New Caledonia' => 'Asia/Magadan',
'(GMT+12:00) Solomon Is.' => 'Asia/Magadan',
'(GMT+12:00) Wellington' => 'Pacific/Auckland',
'(GMT+13:00) Nuku\'alofa' => 'Pacific/Tongatapu'
);
?>   

Get mouse wheel events in jQuery?

I was stuck in this issue today and found this code is working fine for me

$('#content').on('mousewheel', function(event) {
    //console.log(event.deltaX, event.deltaY, event.deltaFactor);
    if(event.deltaY > 0) {
      console.log('scroll up');
    } else {
      console.log('scroll down');
    }
});

Difference between `Optional.orElse()` and `Optional.orElseGet()`

The following example should demonstrate the difference:

String destroyTheWorld() {
  // destroy the world logic
  return "successfully destroyed the world";
}

Optional<String> opt = Optional.of("Save the world");

// we're dead
opt.orElse(destroyTheWorld());

// we're safe    
opt.orElseGet(() -> destroyTheWorld());

The answer appears in the docs as well.

public T orElseGet(Supplier<? extends T> other):

Return the value if present, otherwise invoke other and return the result of that invocation.

The Supplier won't be invoked if the Optional presents. whereas,

public T orElse(T other):

Return the value if present, otherwise return other.

If other is a method that returns a string, it will be invoked, but it's value won't be returned in case the Optional exists.

Android replace the current fragment with another fragment

If you have a handle to an existing fragment you can just replace it with the fragment's ID.

Example in Kotlin:

fun aTestFuction() {
   val existingFragment = MyExistingFragment() //Get it from somewhere, this is a dirty example
   val newFragment = MyNewFragment()
   replaceFragment(existingFragment, newFragment, "myTag")
}

fun replaceFragment(existing: Fragment, new: Fragment, tag: String? = null) {
    supportFragmentManager.beginTransaction().replace(existing.id, new, tag).commit()
}

await is only valid in async function

When I got this error, it turned out I had a call to the map function inside my "async" function, so this error message was actually referring to the map function not being marked as "async". I got around this issue by taking the "await" call out of the map function and coming up with some other way of getting the expected behavior.

var myfunction = async function(x,y) {
    ....
    someArray.map(someVariable => { // <- This was the function giving the error
        return await someFunction(someVariable);
    });
}

How to hide keyboard in swift on pressing return key?

To get automatic keyboard dismissal, I put this code inside one of the methods of my custom text field's class:

textField.addTarget(nil, action:"firstResponderAction:", forControlEvents:.EditingDidEndOnExit)

Substitute your outlet's name for textField.

Running Command Line in Java

Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

How to get a unix script to run every 15 seconds?

Since my previous answer I came up with another solution that is different and perhaps better. This code allows processes to be run more than 60 times a minute with microsecond precision. You need the usleep program to make this work. Should be good to up to 50 times a second.

#! /bin/sh

# Microsecond Cron
# Usage: cron-ms start
# Copyright 2014 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution

basedir=/etc/cron-ms

if [ $# -eq 0 ]
then
   echo
   echo "cron-ms by Marc Perkel"
   echo
   echo "This program is used to run all programs in a directory in parallel every X times per minute."
   echo "Think of this program as cron with microseconds resolution."
   echo
   echo "Usage: cron-ms start"
   echo
   echo "The scheduling is done by creating directories with the number of"
   echo "executions per minute as part of the directory name."
   echo
   echo "Examples:"
   echo "  /etc/cron-ms/7      # Executes everything in that directory  7 times a minute"
   echo "  /etc/cron-ms/30     # Executes everything in that directory 30 times a minute"
   echo "  /etc/cron-ms/600    # Executes everything in that directory 10 times a second"
   echo "  /etc/cron-ms/2400   # Executes everything in that directory 40 times a second"
   echo
   exit
fi

# If "start" is passed as a parameter then run all the loops in parallel
# The number of the directory is the number of executions per minute
# Since cron isn't accurate we need to start at top of next minute

if [ $1 = start ]
then
   for dir in $basedir/* ; do
      $0 ${dir##*/} 60000000 &
   done
   exit
fi

# Loops per minute and the next interval are passed on the command line with each loop

loops=$1
next_interval=$2

# Sleeps until a specific part of a minute with microsecond resolution. 60000000 is full minute

usleep $(( $next_interval - 10#$(date +%S%N) / 1000 ))

# Run all the programs in the directory in parallel

for program in $basedir/$loops/* ; do
   if [ -x $program ] 
   then
      $program &> /dev/null &
   fi
done

# Calculate next_interval

next_interval=$(($next_interval % 60000000 + (60000000 / $loops) ))

# If minute is not up - call self recursively

if [ $next_interval -lt $(( 60000000 / $loops * $loops)) ]
then
   . $0 $loops $next_interval &
fi

# Otherwise we're done

Running bash script from within python

Making sleep.sh executable and adding shell=True to the parameter list (as suggested in previous answers) works ok. Depending on the search path, you may also need to add ./ or some other appropriate path. (Ie, change "sleep.sh" to "./sleep.sh".)

The shell=True parameter is not needed (under a Posix system like Linux) if the first line of the bash script is a path to a shell; for example, #!/bin/bash.

Automated Python to Java translation

Yes Jython does this, but it may or may not be what you want

Send email by using codeigniter library via localhost

Please check my working code.

function sendMail()
{
    $config = Array(
  'protocol' => 'smtp',
  'smtp_host' => 'ssl://smtp.googlemail.com',
  'smtp_port' => 465,
  'smtp_user' => '[email protected]', // change it to yours
  'smtp_pass' => 'xxx', // change it to yours
  'mailtype' => 'html',
  'charset' => 'iso-8859-1',
  'wordwrap' => TRUE
);

        $message = '';
        $this->load->library('email', $config);
      $this->email->set_newline("\r\n");
      $this->email->from('[email protected]'); // change it to yours
      $this->email->to('[email protected]');// change it to yours
      $this->email->subject('Resume from JobsBuddy for your Job posting');
      $this->email->message($message);
      if($this->email->send())
     {
      echo 'Email sent.';
     }
     else
    {
     show_error($this->email->print_debugger());
    }

}

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

Deleting old version of %USERPROFILE%\AppData\Local\SourceTree\app-x.x.x worked for me. Not sure how it was connected to command line git...

Do you need to dispose of objects and set them to null?

Objects will be cleaned up when they are no longer being used and when the garbage collector sees fit. Sometimes, you may need to set an object to null in order to make it go out of scope (such as a static field whose value you no longer need), but overall there is usually no need to set to null.

Regarding disposing objects, I agree with @Andre. If the object is IDisposable it is a good idea to dispose it when you no longer need it, especially if the object uses unmanaged resources. Not disposing unmanaged resources will lead to memory leaks.

You can use the using statement to automatically dispose an object once your program leaves the scope of the using statement.

using (MyIDisposableObject obj = new MyIDisposableObject())
{
    // use the object here
} // the object is disposed here

Which is functionally equivalent to:

MyIDisposableObject obj;
try
{
    obj = new MyIDisposableObject();
}
finally
{
    if (obj != null)
    {
        ((IDisposable)obj).Dispose();
    }
}

Amazon Linux: apt-get: command not found

If you're using Amazon Linux it's CentOS-based, which is RedHat-based. RH-based installs use yum not apt-get. Something like yum search httpd should show you the available Apache packages - you likely want yum install httpd24.

Note: Amazon Linux 2 has diverged from CentOS since the writing of this answer, but still uses yum.

How to tell if JRE or JDK is installed

@maciej-cygan described the process well, however in order to find your java path:

$ which java

it gives you the path of java binary file which is a linked file in /usr/bin directory. next:

$ cd /usr/bin/ && ls -la | grep java

find the pointed location which is something as follows (for me):

enter image description here then cd to the pointed directory to find the real home directory for Java. next:

$ ls -la | grep java

which is as follows in this case:

enter image description here

so as it's obvious in the screenshot, my Java home directory is /usr/lib/jvm/java-11-openjdk-amd64. So accordingly I need to add JAVA_HOME to my bash profile (.bashrc, .bash_profile, etc. depending on your OS) like below:

JAVA_HOME="/usr/lib/jvm/java-11-openjdk-amd64"

Here you go!

Can we create an instance of an interface in Java?

Yes we can, "Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name"->>Java Doc

How to create an array containing 1...N

Use the very popular Underscore _.range method

// _.range([start], stop, [step])

_.range(10); // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
_.range(1, 11); // => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
_.range(0, 30, 5); // => [0, 5, 10, 15, 20, 25]
_.range(0, -10, -1); //  => [0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
_.range(0); // => []

Adding new column to existing DataFrame in Python pandas

If we want to assign a scaler value eg: 10 to all rows of a new column in a df:

df = df.assign(new_col=lambda x:10)  # x is each row passed in to the lambda func

df will now have new column 'new_col' with value=10 in all rows.

Display HTML snippets in HTML

This is how I did it:

$str = file_get_contents("my-code-file.php");
echo "<textarea disabled='true' style='border: none;background-color:white;'>";
echo $str;
echo "</textarea>";

Inserting image into IPython notebook markdown

[Obsolete]

IPython/Jupyter now has support for an extension modules that can insert images via copy and paste or drag & drop.

https://github.com/ipython-contrib/IPython-notebook-extensions

The drag & drop extension seems to work in most browsers

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

But copy and paste only works in Chrome.

How to draw a graph in PHP?

<?
# ------- The graph values in the form of associative array
$values=array(
    "Jan" => 110,
    "Feb" => 130,
    "Mar" => 215,
    "Apr" => 81,
    "May" => 310,
    "Jun" => 110,
    "Jul" => 190,
    "Aug" => 175,
    "Sep" => 390,
    "Oct" => 286,
    "Nov" => 150,
    "Dec" => 196
);


$img_width=450;
$img_height=300; 
$margins=20;


# ---- Find the size of graph by substracting the size of borders
$graph_width=$img_width - $margins * 2;
$graph_height=$img_height - $margins * 2; 
$img=imagecreate($img_width,$img_height);


$bar_width=20;
$total_bars=count($values);
$gap= ($graph_width- $total_bars * $bar_width ) / ($total_bars +1);


# -------  Define Colors ----------------
$bar_color=imagecolorallocate($img,0,64,128);
$background_color=imagecolorallocate($img,240,240,255);
$border_color=imagecolorallocate($img,200,200,200);
$line_color=imagecolorallocate($img,220,220,220);

# ------ Create the border around the graph ------

imagefilledrectangle($img,1,1,$img_width-2,$img_height-2,$border_color);
imagefilledrectangle($img,$margins,$margins,$img_width-1-$margins,$img_height-1-$margins,$background_color);


# ------- Max value is required to adjust the scale -------
$max_value=max($values);
$ratio= $graph_height/$max_value;


# -------- Create scale and draw horizontal lines  --------
$horizontal_lines=20;
$horizontal_gap=$graph_height/$horizontal_lines;

for($i=1;$i<=$horizontal_lines;$i++){
    $y=$img_height - $margins - $horizontal_gap * $i ;
    imageline($img,$margins,$y,$img_width-$margins,$y,$line_color);
    $v=intval($horizontal_gap * $i /$ratio);
    imagestring($img,0,5,$y-5,$v,$bar_color);

}


# ----------- Draw the bars here ------
for($i=0;$i< $total_bars; $i++){ 
    # ------ Extract key and value pair from the current pointer position
    list($key,$value)=each($values); 
    $x1= $margins + $gap + $i * ($gap+$bar_width) ;
    $x2= $x1 + $bar_width; 
    $y1=$margins +$graph_height- intval($value * $ratio) ;
    $y2=$img_height-$margins;
    imagestring($img,0,$x1+3,$y1-10,$value,$bar_color);imagestring($img,0,$x1+3,$img_height-15,$key,$bar_color);        
    imagefilledrectangle($img,$x1,$y1,$x2,$y2,$bar_color);
}
header("Content-type:image/png");
imagepng($img);
$_REQUEST['asdfad']=234234;

?>

How can bcrypt have built-in salts?

This is from PasswordEncoder interface documentation from Spring Security,

 * @param rawPassword the raw password to encode and match
 * @param encodedPassword the encoded password from storage to compare with
 * @return true if the raw password, after encoding, matches the encoded password from
 * storage
 */
boolean matches(CharSequence rawPassword, String encodedPassword);

Which means, one will need to match rawPassword that user will enter again upon next login and matches it with Bcrypt encoded password that's stores in database during previous login/registration.

How to create a generic array?

You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.

Arrays are covariant, Generics are not:

What that means? You must be knowing by now that the following assignment is valid:

Object[] arr = new String[10];

Basically, an Object[] is a super type of String[], because Object is a super type of String. This is not true with generics. So, the following declaration is not valid, and won't compile:

List<Object> list = new ArrayList<String>(); // Will not compile.

Reason being, generics are invariant.

Enforcing Type Check:

Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String> has a static type of List<String> but a dynamic type of List.

However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:

Object[] arr = new String[10];
arr[0] = new Integer(10);

will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.

So, what's the issue with Generic Array Creation?

Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.

Consider the code as below:

public <T> T[] getArray(int size) {
    T[] arr = new T[size];  // Suppose this was allowed for the time being.
    return arr;
}

Since the type of T is not known at runtime, the array created is actually an Object[]. So the above method at runtime will look like:

public Object[] getArray(int size) {
    Object[] arr = new Object[size];
    return arr;
}

Now, suppose you call this method as:

Integer[] arr = getArray(10);

Here's the problem. You have just assigned an Object[] to a reference of Integer[]. The above code will compile fine, but will fail at runtime.

That is why generic array creation is forbidden.

Why typecasting new Object[10] to E[] works?

Now your last doubt, why the below code works:

E[] elements = (E[]) new Object[10];

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

public <T> T[] getArray(int size) {
    T[] arr = (T[])new Object[size];        
    return arr;
}

and you call invoke it like this:

String[] arr = getArray(10);

this will fail at runtime with a ClassCastException. So, no this way will not work always.

What about creating an array of type List<String>[]?

The issue is the same. Due to type erasure, a List<String>[] is nothing but a List[]. So, had the creation of such arrays allowed, let's see what could happen:

List<String>[] strlistarr = new List<String>[10];  // Won't compile. but just consider it
Object[] objarr = strlistarr;    // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.

Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[] and List<Integer>[] are compiled to List[] at runtime.

So can we create array of unbounded wildcard parameterized types?

Yes. The reason being, a List<?> is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.

List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>();  // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine

Both the above case is fine, because List<?> is super type of all the instantiation of the generic type List<E>. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[].

So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null (Ignoring the unbounded types).

Is there any workaround for E[]?

Yes, you can create the array using Array#newInstance() method:

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Typecast is needed because that method returns an Object. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.

Can comments be used in JSON?

You can't. At least that's my experience from a quick glance at json.org.

JSON has its syntax visualized on that page. There isn't any note about comments.

Have log4net use application config file for configuration data

All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref .. section it is named as ConsoleAppender. They need to match.

You can add multiple appenders to your log config but you need to register each of them in the <root> section.

<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />

You can also refer to the apache documentation on configuring log4net.

How to check whether a string contains a substring in JavaScript?

There is a String.prototype.includes in ES6:

"potato".includes("to");
> true

Note that this does not work in Internet Explorer or some other old browsers with no or incomplete ES6 support. To make it work in old browsers, you may wish to use a transpiler like Babel, a shim library like es6-shim, or this polyfill from MDN:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

I don't have "Dynamic Web Project" option in Eclipse new Project wizard

Go to Eclipse --> Help

and click--->Install new software

then you can see a window ...There a click add

Then put below url in url box: http://download.eclipse.org/webtools/repository/juno/

i am having juno

if u have any other means put that name . then click ok.

413 Request Entity Too Large - File Upload Issue

Use:

php -i

command or add:

phpinfo();

to get the location of configuration file.

Update these variables according to your need and server

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

On Linux you will need to restart nginx / apache and phpfpm service so the new ini settings are loaded. On xampp, ammps you can restart these from control panel that comes with such applications.

Select specific row from mysql table

SQL tables are not ordered by default, and asking for the n-th row from a non ordered set of rows has no meaning as it could potentially return a different row each time unless you specify an ORDER BY:

select * from customer order by id where row_number() = 3

(sometimes MySQL tables are shown with an internal order but you cannot rely on this behaviour). Then you can use LIMIT offset, row_count, with a 0-based offset so row number 3 becomes offset 2:

select * from customer order by id
limit 2, 1

or you can use LIMIT row_count OFFSET offset:

select * from customer order by id
limit 1 offset 2

Node.js server that accepts POST requests

The following code shows how to read values from an HTML form. As @pimvdb said you need to use the request.on('data'...) to capture the contents of the body.

const http = require('http')

const server = http.createServer(function(request, response) {
  console.dir(request.param)

  if (request.method == 'POST') {
    console.log('POST')
    var body = ''
    request.on('data', function(data) {
      body += data
      console.log('Partial body: ' + body)
    })
    request.on('end', function() {
      console.log('Body: ' + body)
      response.writeHead(200, {'Content-Type': 'text/html'})
      response.end('post received')
    })
  } else {
    console.log('GET')
    var html = `
            <html>
                <body>
                    <form method="post" action="http://localhost:3000">Name: 
                        <input type="text" name="name" />
                        <input type="submit" value="Submit" />
                    </form>
                </body>
            </html>`
    response.writeHead(200, {'Content-Type': 'text/html'})
    response.end(html)
  }
})

const port = 3000
const host = '127.0.0.1'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)


If you use something like Express.js and Bodyparser then it would look like this since Express will handle the request.body concatenation

var express = require('express')
var fs = require('fs')
var app = express()

app.use(express.bodyParser())

app.get('/', function(request, response) {
  console.log('GET /')
  var html = `
    <html>
        <body>
            <form method="post" action="http://localhost:3000">Name: 
                <input type="text" name="name" />
                <input type="submit" value="Submit" />
            </form>
        </body>
    </html>`
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end(html)
})

app.post('/', function(request, response) {
  console.log('POST /')
  console.dir(request.body)
  response.writeHead(200, {'Content-Type': 'text/html'})
  response.end('thanks')
})

port = 3000
app.listen(port)
console.log(`Listening at http://localhost:${port}`)

How to change the order of DataFrame columns?

import numpy as np
import pandas as pd
df = pd.DataFrame()
column_names = ['x','y','z','mean']
for col in column_names: 
    df[col] = np.random.randint(0,100, size=10000)

You can try out the following solutions :

Solution 1:

df = df[ ['mean'] + [ col for col in df.columns if col != 'mean' ] ]

Solution 2:


df = df[['mean', 'x', 'y', 'z']]

Solution 3:

col = df.pop("mean")
df = df.insert(0, col.name, col)

Solution 4:

df.set_index(df.columns[-1], inplace=True)
df.reset_index(inplace=True)

Solution 5:

cols = list(df)
cols = [cols[-1]] + cols[:-1]
df = df[cols]

solution 6:

order = [1,2,3,0] # setting column's order
df = df[[df.columns[i] for i in order]]

Time Comparison:

Solution 1:

CPU times: user 1.05 ms, sys: 35 µs, total: 1.08 ms Wall time: 995 µs

Solution 2:

CPU times: user 933 µs, sys: 0 ns, total: 933 µs Wall time: 800 µs

Solution 3:

CPU times: user 0 ns, sys: 1.35 ms, total: 1.35 ms Wall time: 1.08 ms

Solution 4:

CPU times: user 1.23 ms, sys: 45 µs, total: 1.27 ms Wall time: 986 µs

Solution 5:

CPU times: user 1.09 ms, sys: 19 µs, total: 1.11 ms Wall time: 949 µs

Solution 6:

CPU times: user 955 µs, sys: 34 µs, total: 989 µs Wall time: 859 µs

Determine the type of an object?

You can use type() or isinstance().

>>> type([]) is list
True

Be warned that you can clobber list or any other type by assigning a variable in the current scope of the same name.

>>> the_d = {}
>>> t = lambda x: "aight" if type(x) is dict else "NOPE"
>>> t(the_d) 'aight'
>>> dict = "dude."
>>> t(the_d) 'NOPE'

Above we see that dict gets reassigned to a string, therefore the test:

type({}) is dict

...fails.

To get around this and use type() more cautiously:

>>> import __builtin__
>>> the_d = {}
>>> type({}) is dict
True
>>> dict =""
>>> type({}) is dict
False
>>> type({}) is __builtin__.dict
True

Change icon-bar (?) color in bootstrap

I am using Bootstrap & HTML5. I wanted to override the look of the toggle button.

.navbar-toggle{
    background-color: #5DADB0;
    color: #F3DBAA;
    border:none;        
}

.navbar-toggle.but-menu:link {
    color: #F00;
    background-color: #CF995F;
}

.navbar-toggle.but-menu:visited {
    color: #FFF;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:hover {
    color: #FFF0C9;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:active {
    color: #FFF;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:focus {
    color: #FFF;
    background-color: #CF995F;
}

cannot make a static reference to the non-static field

The static calls to withdraw and deposit are your problem. account.withdraw(balance, 2500); This line can't work , since "balance" is an instance variable of Account. The code doesn't make much sense anyway, wouldn't withdraw/deposit be encapsulated inside the Account object itself? so the withdraw should be more like

public void withdraw(double withdrawAmount)
{
    balance -= withdrawAmount;
}

Of course depending on your problem you could do additional validation here to prevent negative balance etc.

How To: Execute command line in C#, get STD OUT results

 System.Diagnostics.ProcessStartInfo psi =
   new System.Diagnostics.ProcessStartInfo(@"program_to_call.exe");
 psi.RedirectStandardOutput = true;
 psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
 psi.UseShellExecute = false;
 System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi); ////
 System.IO.StreamReader myOutput = proc.StandardOutput;
 proc.WaitForExit(2000);
 if (proc.HasExited)
  {
      string output = myOutput.ReadToEnd();
 }

How do I get the project basepath in CodeIgniter

Codeigniter has a function that retrieves your base path which is:

FCPATH and BASEPATH i recommand use FCPATH.

for your base url use:

<?=base_url()?>

if your php short tag is off

<?php echo base_url(); ?>

for example: if you want to link you css files which is in your base path

<script src='<?=base_url()?>js/jquery.js' type='text/javascript' />

What permission do I need to access Internet from an Android application?

I had the same problem even use <uses-permission android:name="android.permission.INTERNET" />

If you want connect web api using http not https. Maybe you use android device using Android 9 (Pie) or API level 28 or higher . android:usesCleartextTraffic default value is false. You have to set be

<?xml version="1.0" encoding="utf-8"?>
<manifest ...>
    <uses-permission android:name="android.permission.INTERNET" />
    <application
        ...
        android:usesCleartextTraffic="true" <!-- this line -->
        ...>
           ...
    </application>
</manifest>

Finally, should be https

https://developer.android.com/guide/topics/manifest/application-element#usesCleartextTraffic

./configure : /bin/sh^M : bad interpreter

When you write your script on windows environment and you want to run it on unix environnement you need to be careful about the encodage :

dos2unix $filePath

Java Replace Line In Text File

just how to replace strings :) as i do first arg will be filename second target string third one the string to be replaced instead of targe

public class ReplaceString{
      public static void main(String[] args)throws Exception {
        if(args.length<3)System.exit(0);
        String targetStr = args[1];
        String altStr = args[2];
        java.io.File file = new java.io.File(args[0]);
        java.util.Scanner scanner = new java.util.Scanner(file);
        StringBuilder buffer = new StringBuilder();
        while(scanner.hasNext()){
          buffer.append(scanner.nextLine().replaceAll(targetStr, altStr));
          if(scanner.hasNext())buffer.append("\n");
        }
        scanner.close();
        java.io.PrintWriter printer = new java.io.PrintWriter(file);
        printer.print(buffer);
        printer.close();
      }
    }

How to get HttpClient to pass credentials along with the request?

It worked for me after I set up a user with internet access in the Windows service.

In my code:

HttpClientHandler handler = new HttpClientHandler();
handler.Proxy = System.Net.WebRequest.DefaultWebProxy;
handler.Proxy.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
.....
HttpClient httpClient = new HttpClient(handler)
.... 

Unable to connect with remote debugger

In my case, selecting Debug JS Remotely launched Chrome, but did not connect with the android device. Normally, the new Chrome tab/window would have the debugging URL pre-populated in the address bar, but in this case the address bar was blank. After the timeout period, the "Unable to connect with remote debugger" error message was displayed. I fixed this with the following procedure:

  • Run adb reverse tcp:8081 tcp:8081
  • Paste http://localhost:8081/debugger-ui into the address field of my Chrome browser. You should see the normal debugging screen but your app will still not be connected.

That should fix the problem. If not, you may need to take the following additional steps:

  • Close and uninstall the app from your Android device
  • Reinstall the app with react-native run-android
  • Enable remote debugging on your app.
  • Your app should now be connected to the debugger.

Renaming files in a folder to sequential numbers

Pero's answer got me here :)

I wanted to rename files relative to time as the image viewers did not display images in time order.

ls -tr *.jpg | # list jpegs relative to time
gawk 'BEGIN{ a=1 }{ printf "mv %s %04d.jpg\n", $0, a++ }' | # build mv command
bash # run that command

Mysql where id is in array

Your query translates to:

SELECT name FROM users WHERE id IN ('Array');

Or something to that affect.

Try using prepared queries instead, something like:

$numbers = explode(',', $string);
$prepare = array_map(function(){ return '?'; }, $numbers);
$statement = mysqli_prepare($link , "SELECT name FROM users WHERE id IN ('".implode(',', $prepare)."')");
if($statement) {
   $ints = array_map(function(){ return 'i'; }, $numbers);
   call_user_func_array("mysqli_stmt_bind_param", array_merge(
      array($statement, implode('', $ints)), $numbers
   ));
   $results = mysqli_stmt_execute($statement);
   // do something with results 
   // ...
}

How do I sort a Set to a List in Java?

You can convert a set into an ArrayList, where you can sort the ArrayList using Collections.sort(List).

Here is the code:

keySet = (Set) map.keySet();
ArrayList list = new ArrayList(keySet);     
Collections.sort(list);

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

sql: check if entry in table A exists in table B

This also works

SELECT *
FROM tableB
WHERE ID NOT IN (
  SELECT ID FROM tableA
);

Optimal number of threads per core

I agree with @Gonzalo's answer. I have a process that doesn't do I/O, and here is what I've found:

enter image description here

Note that all threads work on one array but different ranges (two threads do not access the same index), so the results may differ if they've worked on different arrays.

The 1.86 machine is a macbook air with an SSD. The other mac is an iMac with a normal HDD (I think it's 7200 rpm). The windows machine also has a 7200 rpm HDD.

In this test, the optimal number was equal to the number of cores in the machine.

C# 4.0 optional out/ref arguments

What about like this?

public bool OptionalOutParamMethod([Optional] ref string pOutParam)
{
    return true;
}

You still have to pass a value to the parameter from C# but it is an optional ref param.

C# Call a method in a new thread

If you actually start a new thread, that thread will terminate when the method finishes:

Thread thread = new Thread(SecondFoo);
thread.Start();

Now SecondFoo will be called in the new thread, and the thread will terminate when it completes.

Did you actually mean that you wanted the thread to terminate when the method in the calling thread completes?

EDIT: Note that starting a thread is a reasonably expensive operation. Do you definitely need a brand new thread rather than using a threadpool thread? Consider using ThreadPool.QueueUserWorkItem or (preferrably, if you're using .NET 4) TaskFactory.StartNew.

How to change the color of progressbar in C# .NET 3.5?

????: Quote: Usually the progress bar is either themed or honors the user's color preferences. So for changing the color you either need to turn off visual styles and set ForeColor or draw the control yourself.

As for the continuous style instead of blocks you can set the Style property:

pBar.Style = ProgressBarStyle.Continuous;

ProgressBarStyle.Continuous versus Blocks is useless with VistualStyles enabled...

Block(s) will only work with visual styles disabled ... which renders all of this a moot point (with regards to custom progress color) With vistual styles disabled ... the progress bar should be colored based on the forecolor.

I used a combination of William Daniel's answer (with visual styles enabled, so the ForeColor will not just be flat with no style) and Barry's answer (to custom text on the progress bar) from: How do I put text on ProgressBar?

What are App Domains in Facebook Apps?

If you don't specify the platform for the app you won't able to add app domain correctly.

Here is an example -- validate that its a type a website platform. enter image description here

How do I detect IE 8 with jQuery?

You can use $.browser to detect the browser name. possible values are :

  • webkit (as of jQuery 1.4)
  • safari (deprecated)
  • opera
  • msie
  • mozilla

or get a boolean flag: $.browser.msie will be true if the browser is MSIE.

as for the version number, if you are only interested in the major release number - you can use parseInt($.browser.version, 10). no need to parse the $.browser.version string yourself.

Anyway, The $.support property is available for detection of support for particular features rather than relying on $.browser.

Where do I get servlet-api.jar from?

You may want to consider using Java EE, which includes the javax.servlet.* packages. If you require a specific version of the servlet api, for instance to target a specific web application server, you will probably want the Java EE version which matches, see this version table.

how to empty recyclebin through command prompt?

while

rd /s /q %systemdrive%\$RECYCLE.BIN

will delete the $RECYCLE.BIN folder from the system drive, which is usually c:, one should consider deleting it from any other available partitions since there's an hidden $RECYCLE.BIN folder in any partition in local and external drives (but not in removable drives, like USB flash drive, which don't have a $RECYCLE.BIN folder). For example, I installed a program in d:, in order to delete the files it moved to the Recycle Bin I should run:

rd /s /q d:\$RECYCLE.BIN

More information available at Super User at Empty recycling bin from command line

Insert Update trigger how to determine if insert or update

I've used those exists (select * from inserted/deleted) queries for a long time, but it's still not enough for empty CRUD operations (when there're no records in inserted and deleted tables). So after researching this topic a little bit I've found more precise solution:

declare
    @columns_count int = ?? -- number of columns in the table,
    @columns_updated_count int = 0

-- this is kind of long way to get number of actually updated columns
-- from columns_updated() mask, it's better to create helper table
-- or at least function in the real system
with cte_columns as (
    select @columns_count as n
    union all
    select n - 1 from cte_columns where n > 1
), cte_bitmasks as (
    select
        n,
        (n - 1) / 8 + 1 as byte_number,
        power(2, (n - 1) % 8) as bit_mask
    from cte_columns
)
select
    @columns_updated_count = count(*)
from cte_bitmasks as c
where
    convert(varbinary(1), substring(@columns_updated_mask, c.byte_number, 1)) & c.bit_mask > 0

-- actual check
if exists (select * from inserted)
    if exists (select * from deleted)
        select @operation = 'U'
    else
        select @operation = 'I'
else if exists (select * from deleted)
    select @operation = 'D'
else if @columns_updated_count = @columns_count
    select @operation = 'I'
else if @columns_updated_count > 0
    select @operation = 'U'
else
    select @operation = 'D'

It's also possible to use columns_updated() & power(2, column_id - 1) > 0 to see if the column is updated, but it's not safe for tables with big number of columns. I've used a bit complex way of calculating (see helpful article below).

Also, this approach will still incorrectly classifies some updates as inserts (if every column in the table is affected by update), and probably it will classifies inserts where there only default values are inserted as deletes, but those are king of rare operations (at lease in my system they are). Besides that, I don't know how to improve this solution at the moment.

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

How to change port for jenkins window service when 8080 is being used

In linux,

sudo vi /etc/sysconfig/jenkins

set following configuration with any available port

JENKINS_PORT="8082"

'Incorrect SET Options' Error When Building Database Project

I found the solution for this problem:

  1. Go to the Server Properties.
  2. Select the Connections tab.
  3. Check if the ansi_padding option is unchecked.

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Set color of TextView span in Android

Set Color on Text by passing String and color:

private String getColoredSpanned(String text, String color) {
  String input = "<font color=" + color + ">" + text + "</font>";
  return input;
}

Set text on TextView / Button / EditText etc by calling below code:

TextView:

TextView txtView = (TextView)findViewById(R.id.txtView);

Get Colored String:

String name = getColoredSpanned("Hiren", "#800000");

Set Text on TextView:

txtView.setText(Html.fromHtml(name));

Done

How do the post increment (i++) and pre increment (++i) operators work in Java?

Does this help?

a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8)

a = 5;
i=a++ + ++a + ++a; =>
i=5 + 7 + 8; (a=8)

The main point is that ++a increments the value and immediately returns it.

a++ also increments the value (in the background) but returns unchanged value of the variable - what looks like it is executed later.

How to get URI from an asset File?

enter image description here

Be sure ,your assets folder put in correct position.

Disabled href tag

You can disable anchor tags by returning false. In my case Im using angular and ng-disabled for a Jquery accordion and I need to disable the sections.

So I created a little js snippet to fix this.

       <a class="opener" data-toggle="collapse"
                   data-parent="#shipping-detail"
                   id="shipping-detail-section"
                   href="#shipping-address"
                   aria-expanded="true"
                   ng-disabled="checkoutState.addressSec">
                   Shipping Address</a>
     <script>
          $("a.opener").on("click", function () {
           var disabled = $(this).attr("disabled");
           if (disabled === 'disabled') {
            return false;
           }
           });
     </script>

Converting any string into camel case

I know this is an old answer, but this handles both whitespace and _ (lodash)

function toCamelCase(s){
    return s
          .replace(/_/g, " ")
          .replace(/\s(.)/g, function($1) { return $1.toUpperCase(); })
          .replace(/\s/g, '')
          .replace(/^(.)/, function($1) { return $1.toLowerCase(); });
}

console.log(toCamelCase("Hello world");
console.log(toCamelCase("Hello_world");

// Both print "helloWorld"

Why can't static methods be abstract in Java?

You can do this with interfaces in Java 8.

This is the official documentation about it:

https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

List tables in a PostgreSQL schema

In all schemas:

=> \dt *.*

In a particular schema:

=> \dt public.*

It is possible to use regular expressions with some restrictions

\dt (public|s).(s|t)
       List of relations
 Schema | Name | Type  | Owner 
--------+------+-------+-------
 public | s    | table | cpn
 public | t    | table | cpn
 s      | t    | table | cpn

Advanced users can use regular-expression notations such as character classes, for example [0-9] to match any digit. All regular expression special characters work as specified in Section 9.7.3, except for . which is taken as a separator as mentioned above, * which is translated to the regular-expression notation .*, ? which is translated to ., and $ which is matched literally. You can emulate these pattern characters at need by writing ? for ., (R+|) for R*, or (R|) for R?. $ is not needed as a regular-expression character since the pattern must match the whole name, unlike the usual interpretation of regular expressions (in other words, $ is automatically appended to your pattern). Write * at the beginning and/or end if you don't wish the pattern to be anchored. Note that within double quotes, all regular expression special characters lose their special meanings and are matched literally. Also, the regular expression special characters are matched literally in operator name patterns (i.e., the argument of \do).

Pass Method as Parameter using C#

From OP's example:

 public static int Method1(string mystring)
 {
      return 1;
 }

 public static int Method2(string mystring)
 {
     return 2;
 }

You can try Action Delegate! And then call your method using

 public bool RunTheMethod(Action myMethodName)
 {
      myMethodName();   // note: the return value got discarded
      return true;
 }

RunTheMethod(() => Method1("MyString1"));

Or

public static object InvokeMethod(Delegate method, params object[] args)
{
     return method.DynamicInvoke(args);
}

Then simply call method

Console.WriteLine(InvokeMethod(new Func<string,int>(Method1), "MyString1"));

Console.WriteLine(InvokeMethod(new Func<string, int>(Method2), "MyString2"));

running a command as a super user from a python script

I used this for python 3.5. I did it using subprocess module.Using the password like this is very insecure.

The subprocess module takes command as a list of strings so either create a list beforehand using split() or pass the whole list later. Read the documentation for more information.

What we are doing here is echoing the password and then using pipe we pass it on to the sudo through '-S' argument.

#!/usr/bin/env python
import subprocess

sudo_password = 'mysecretpass'
command = 'apach2ctl restart'
command = command.split()

cmd1 = subprocess.Popen(['echo',sudo_password], stdout=subprocess.PIPE)
cmd2 = subprocess.Popen(['sudo','-S'] + command, stdin=cmd1.stdout, stdout=subprocess.PIPE)

output = cmd2.stdout.read().decode() 

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Agreed with jcadcell comments, but had to use JDK 1.8 because my eclipse need that. So I just copied the MSVCR71.DLL from jdk1.6 and pasted into jdk1.8 in both the folder jdk1.8.0_121\bin and jdk1.8.0_121\jre\bin

and it Worked .... Wow... Thanks :)

All ASP.NET Web API controllers return 404

One thing I ran into was having my configurations registered in the wrong order in my GLobal.asax file for instance:

Right Order:

AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);

Wrong Order:

AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);

Just saying, this was my problem and changing the order is obvious, but sometimes overlooked and can cause much frustration.

Compare cell contents against string in Excel

If a case-insensitive comparison is acceptable, just use =:

=IF(A1="ENG",1,0)

Convert string to datetime

I have had success with:

require 'time'
t = Time.parse(some_string)

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

What I have done in the past is declare my inner class collections using IList<Class>, ICollection<Class>or IEnumerable<Class> (if static list) depending on whether or not I will have to do any number of the following in a method in my repository: enumerate, sort/order or modify. When I just need to enumerate (and maybe sort) over objects then I create a temp List<Class>to work with the collection within an IEnumerable method. I think this practice would only be effective if the collection is relatively small, but it may be good practice in general, idk. Please correct me if there is evidence as to why this would not good practice.

How can I get Apache gzip compression to work?

Ran into this problem using the same .htaccess configuration. I realized that my server was serving javascript files as text/javascript instead of application/javascript. Once I added text/javascript to the AddOutputFilterByType declaration, gzip started working.

As to why javascript was being served as text/javascript: there was an AddType 'text/javascript' js declaration at the top of my root .htaccess file. After removing it (it had been added in error), javascript starting serving as application/javascript.

How to select only the first rows for each unique value of a column?

In SQL 2k5+, you can do something like:

;with cte as (
  select CName, AddressLine,
  rank() over (partition by CName order by AddressLine) as [r]
  from MyTable
)
select CName, AddressLine
from cte
where [r] = 1

What is the difference between Multiple R-squared and Adjusted R-squared in a single-variate least squares regression?

The Adjusted R-squared is close to, but different from, the value of R2. Instead of being based on the explained sum of squares SSR and the total sum of squares SSY, it is based on the overall variance (a quantity we do not typically calculate), s2T = SSY/(n - 1) and the error variance MSE (from the ANOVA table) and is worked out like this: adjusted R-squared = (s2T - MSE) / s2T.

This approach provides a better basis for judging the improvement in a fit due to adding an explanatory variable, but it does not have the simple summarizing interpretation that R2 has.

If I haven't made a mistake, you should verify the values of adjusted R-squared and R-squared as follows:

s2T <- sum(anova(v.lm)[[2]]) / sum(anova(v.lm)[[1]])
MSE <- anova(v.lm)[[3]][2]
adj.R2 <- (s2T - MSE) / s2T

On the other side, R2 is: SSR/SSY, where SSR = SSY - SSE

attach(v)
SSE <- deviance(v.lm) # or SSE <- sum((epm - predict(v.lm,list(n_days)))^2)
SSY <- deviance(lm(epm ~ 1)) # or SSY <- sum((epm-mean(epm))^2)
SSR <- (SSY - SSE) # or SSR <- sum((predict(v.lm,list(n_days)) - mean(epm))^2)
R2 <- SSR / SSY 

PowerShell - Start-Process and Cmdline Switches

Using explicit parameters, it would be:

$msbuild = 'C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe'
start-Process -FilePath $msbuild -ArgumentList '/v:q','/nologo'

EDIT: quotes.

In java how to get substring from a string till a character c?

If your project already uses commons-lang, StringUtils provide a nice method for this purpose:

String filename = "abc.def.ghi";

String start = StringUtils.substringBefore(filename, "."); // returns "abc"

see javadoc [2.6] [3.1]

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

It can be done with the regular JavaScript function replace().

value.replace(".", ":");

Move an array element from one array position to another

Here is my one liner ES6 solution with an optional parameter on.

if (typeof Array.prototype.move === "undefined") {
  Array.prototype.move = function(from, to, on = 1) {
    this.splice(to, 0, ...this.splice(from, on))
  }
}

Adaptation of the first solution proposed by digiguru

The parameter on is the number of element starting from from you want to move.

Modify request parameter with servlet filter

You can use Regular Expression for Sanitization. Inside filter before calling chain.doFilter(request, response) method, call this code. Here is Sample Code:

for (Enumeration en = request.getParameterNames(); en.hasMoreElements(); ) {
String name = (String)en.nextElement();
String values[] = request.getParameterValues(name);
int n = values.length;
    for(int i=0; i < n; i++) {
     values[i] = values[i].replaceAll("[^\\dA-Za-z ]","").replaceAll("\\s+","+").trim();   
    }
}

Hibernate Criteria for Dates

try this,

    String dateStr = "17-April-2011 19:20:23.707000000 ";
    Date dateForm = new SimpleDateFormat("dd-MMMM-yyyy HH:mm:ss").parse(dateStr);
    SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");  

    String newDate = format.format(dateForm);  

    Calendar today = Calendar.getInstance();
    Date fromDate = format.parse(newDate);
    today.setTime(fromDate);
    today.add(Calendar.DAY_OF_YEAR, 1);
    Date toDate= new SimpleDateFormat("dd-MM-yyyy").parse(format.format(today.getTime()));

    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Model.class);
    crit.add(Restrictions.ge("dateFieldName", fromDate));
    crit.add(Restrictions.le("dateFieldName", toDate));
    return crit.list();

How to get all registered routes in Express?

I was inspired by Labithiotis's express-list-routes, but I wanted an overview of all my routes and brute urls in one go, and not specify a router, and figure out the prefix each time. Something I came up with was to simply replace the app.use function with my own function which stores the baseUrl and given router. From there I can print any table of all my routes.

NOTE this works for me because I declare my routes in a specific routes file (function) which gets passed in the app object, like this:

// index.js
[...]
var app = Express();
require(./config/routes)(app);

// ./config/routes.js
module.exports = function(app) {
    // Some static routes
    app.use('/users', [middleware], UsersRouter);
    app.use('/users/:user_id/items', [middleware], ItemsRouter);
    app.use('/otherResource', [middleware], OtherResourceRouter);
}

This allows me to pass in another 'app' object with a fake use function, and I can get ALL the routes. This works for me (removed some error checking for clarity, but still works for the example):

// In printRoutes.js (or a gulp task, or whatever)
var Express = require('express')
  , app     = Express()
  , _       = require('lodash')

// Global array to store all relevant args of calls to app.use
var APP_USED = []

// Replace the `use` function to store the routers and the urls they operate on
app.use = function() {
  var urlBase = arguments[0];

  // Find the router in the args list
  _.forEach(arguments, function(arg) {
    if (arg.name == 'router') {
      APP_USED.push({
        urlBase: urlBase,
        router: arg
      });
    }
  });
};

// Let the routes function run with the stubbed app object.
require('./config/routes')(app);

// GRAB all the routes from our saved routers:
_.each(APP_USED, function(used) {
  // On each route of the router
  _.each(used.router.stack, function(stackElement) {
    if (stackElement.route) {
      var path = stackElement.route.path;
      var method = stackElement.route.stack[0].method.toUpperCase();

      // Do whatever you want with the data. I like to make a nice table :)
      console.log(method + " -> " + used.urlBase + path);
    }
  });
});

This full example (with some basic CRUD routers) was just tested and printed out:

GET -> /users/users
GET -> /users/users/:user_id
POST -> /users/users
DELETE -> /users/users/:user_id
GET -> /users/:user_id/items/
GET -> /users/:user_id/items/:item_id
PUT -> /users/:user_id/items/:item_id
POST -> /users/:user_id/items/
DELETE -> /users/:user_id/items/:item_id
GET -> /otherResource/
GET -> /otherResource/:other_resource_id
POST -> /otherResource/
DELETE -> /otherResource/:other_resource_id

Using cli-table I got something like this:

+--------------------------------+
¦        ¦ => Users              ¦
+--------+-----------------------¦
¦ GET    ¦ /users/users          ¦
+--------+-----------------------¦
¦ GET    ¦ /users/users/:user_id ¦
+--------+-----------------------¦
¦ POST   ¦ /users/users          ¦
+--------+-----------------------¦
¦ DELETE ¦ /users/users/:user_id ¦
+--------------------------------+
+-----------------------------------------+
¦        ¦ => Items                       ¦
+--------+--------------------------------¦
¦ GET    ¦ /users/:user_id/items/         ¦
+--------+--------------------------------¦
¦ GET    ¦ /users/:user_id/items/:item_id ¦
+--------+--------------------------------¦
¦ PUT    ¦ /users/:user_id/items/:item_id ¦
+--------+--------------------------------¦
¦ POST   ¦ /users/:user_id/items/         ¦
+--------+--------------------------------¦
¦ DELETE ¦ /users/:user_id/items/:item_id ¦
+-----------------------------------------+
+--------------------------------------------+
¦        ¦ => OtherResources                 ¦
+--------+-----------------------------------¦
¦ GET    ¦ /otherResource/                   ¦
+--------+-----------------------------------¦
¦ GET    ¦ /otherResource/:other_resource_id ¦
+--------+-----------------------------------¦
¦ POST   ¦ /otherResource/                   ¦
+--------+-----------------------------------¦
¦ DELETE ¦ /otherResource/:other_resource_id ¦
+--------------------------------------------+

Which kicks ass.

How do I edit a file after I shell to a Docker container?

You can use cat if installed, with the > caracter. Here is the manipulation :

cat > file_to_edit
#1 Write or Paste you text
#2 don't forget to leave a blank line at the end of file
#3 Ctrl + C to apply configuration

Now you can see the result with the command

cat file

Javascript String to int conversion

Convert by Number Class:-

Eg:

var n = Number("103");
console.log(n+1)

Output: 104

Note:- Number is class. When we pass string, then constructor of Number class will convert it.

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

Mongodb: failed to connect to server on first connect

I was trying to connect mlab with my company wifi connection and it was giving this error. But when I switched to personal network it worked and got connected.

PIL image to array (numpy array to array) - Python

Based on zenpoy's answer:

import Image
import numpy

def image2pixelarray(filepath):
    """
    Parameters
    ----------
    filepath : str
        Path to an image file

    Returns
    -------
    list
        A list of lists which make it simple to access the greyscale value by
        im[y][x]
    """
    im = Image.open(filepath).convert('L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map

Easy way to print Perl array? (with a little formatting)

For inspection/debugging check the Data::Printer module. It is meant to do one thing and one thing only:

display Perl variables and objects on screen, properly formatted (to be inspected by a human)

Example usage:

use Data::Printer;  
p @array;  # no need to pass references

The code above might output something like this (with colors!):

   [
       [0] "a",
       [1] "b",
       [2] undef,
       [3] "c",
   ]

Create directory if it does not exist

Try the -Force parameter:

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist

You can use Test-Path -PathType Container to check first.

See the New-Item MSDN help article for more details.

Pandas - Compute z-score for all columns

The almost one-liner solution:

df2 = (df.ix[:,1:] - df.ix[:,1:].mean()) / df.ix[:,1:].std()
df2['ID'] = df['ID']

How to get started with Windows 7 gadgets

Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.

Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.

Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.

Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.

Click outside menu to close in jquery

Use the ':visible' selector. Where .menuitem is the to-hide element(s) ...

$('body').click(function(){
  $('.menuitem:visible').hide('fast');
});

Or if you already have the .menuitem element(s) in a var ...

var menitems = $('.menuitem');
$('body').click(function(){
  menuitems.filter(':visible').hide('fast');
});