Programs & Examples On #Merb

Merb, short for "Mongrel+Erb", is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins.

Flutter Countdown Timer

Here is an example using Timer.periodic :

Countdown starts from 10 to 0 on button click :

import 'dart:async';

[...]

Timer _timer;
int _start = 10;

void startTimer() {
  const oneSec = const Duration(seconds: 1);
  _timer = new Timer.periodic(
    oneSec,
    (Timer timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
        });
      } else {
        setState(() {
          _start--;
        });
      }
    },
  );
}

@override
void dispose() {
  _timer.cancel();
  super.dispose();
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_start")
      ],
    ),
  );
}

Result :

Flutter countdown timer example

You can also use the CountdownTimer class from the quiver.async library, usage is even simpler :

import 'package:quiver/async.dart';

[...]

int _start = 10;
int _current = 10;

void startTimer() {
  CountdownTimer countDownTimer = new CountdownTimer(
    new Duration(seconds: _start),
    new Duration(seconds: 1),
  );

  var sub = countDownTimer.listen(null);
  sub.onData((duration) {
    setState(() { _current = _start - duration.elapsed.inSeconds; });
  });

  sub.onDone(() {
    print("Done");
    sub.cancel();
  });
}

Widget build(BuildContext context) {
  return new Scaffold(
    appBar: AppBar(title: Text("Timer test")),
    body: Column(
      children: <Widget>[
        RaisedButton(
          onPressed: () {
            startTimer();
          },
          child: Text("start"),
        ),
        Text("$_current")
      ],
    ),
  );
}

EDIT : For the question in comments about button click behavior

With the above code which uses Timer.periodic, a new timer will indeed be started on each button click, and all these timers will update the same _start variable, resulting in a faster decreasing counter.

There are multiple solutions to change this behavior, depending on what you want to achieve :

  • disable the button once clicked so that the user could not disturb the countdown anymore (maybe enable it back once timer is cancelled)
  • wrap the Timer.periodic creation with a non null condition so that clicking the button multiple times has no effect
if (_timer != null) {
  _timer = new Timer.periodic(...);
}
  • cancel the timer and reset the countdown if you want to restart the timer on each click :
if (_timer != null) {
  _timer.cancel();
  _start = 10;
}
_timer = new Timer.periodic(...);
  • if you want the button to act like a play/pause button :
if (_timer != null) {
  _timer.cancel();
  _timer = null;
} else {
  _timer = new Timer.periodic(...);
}

You could also use this official async package which provides a RestartableTimer class which extends from Timer and adds the reset method.

So just call _timer.reset(); on each button click.

Finally, Codepen now supports Flutter ! So here is a live example so that everyone can play with it : https://codepen.io/Yann39/pen/oNjrVOb

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

Handling polymorphism is either model-bound or requires lots of code with various custom deserializers. I'm a co-author of a JSON Dynamic Deserialization Library that allows for model-independent json deserialization library. The solution to OP's problem can be found below. Note that the rules are declared in a very brief manner.

public class SOAnswer {
    @ToString @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static abstract class Animal {
        private String name;    
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Dog extends Animal {
        private String breed;
    }

    @ToString(callSuper = true) @Getter @Setter
    @AllArgsConstructor @NoArgsConstructor
    public static class Cat extends Animal {
        private String favoriteToy;
    }
    
    
    public static void main(String[] args) {
        String json = "[{"
                + "    \"name\": \"pluto\","
                + "    \"breed\": \"dalmatian\""
                + "},{"
                + "    \"name\": \"whiskers\","
                + "    \"favoriteToy\": \"mouse\""
                + "}]";
        
        // create a deserializer instance
        DynamicObjectDeserializer deserializer = new DynamicObjectDeserializer();
        
        // runtime-configure deserialization rules; 
        // condition is bound to the existence of a field, but it could be any Predicate
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("breed"),
                DeserializationActionFactory.objectToType(Dog.class)));
        
        deserializer.addRule(DeserializationRuleFactory.newRule(1, 
                (e) -> e.getJsonNode().has("favoriteToy"),
                DeserializationActionFactory.objectToType(Cat.class)));
        
        List<Animal> deserializedAnimals = deserializer.deserializeArray(json, Animal.class);
        
        for (Animal animal : deserializedAnimals) {
            System.out.println("Deserialized Animal Class: " + animal.getClass().getSimpleName()+";\t value: "+animal.toString());
        }
    }
}

Maven depenendency for pretius-jddl (check newest version at maven.org/jddl:

<dependency>
  <groupId>com.pretius</groupId>
  <artifactId>jddl</artifactId>
  <version>1.0.0</version>
</dependency>

Error: org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'text/plain;charset=UTF-8' not supported

Building on what is mentioned in the comments, the simplest solution would be:

@RequestMapping(method = RequestMethod.PUT, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public Collection<BudgetDTO> updateConsumerBudget(@RequestBody SomeDto someDto) throws GeneralException, ParseException {

    //whatever

}

class SomeDto {

   private List<WhateverBudgerPerDateDTO> budgetPerDate;


  //getters setters
}

The solution assumes that the HTTP request you are creating actually has

Content-Type:application/json instead of text/plain

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

It means your table is not mapped to the JPA. Either Name of the table is wrong (Maybe case sensitive), or you need to put an entry in the XML file.

Happy Coding :)

Get method arguments using Spring AOP?

You have a few options:

First, you can use the JoinPoint#getArgs() method which returns an Object[] containing all the arguments of the advised method. You might have to do some casting depending on what you want to do with them.

Second, you can use the args pointcut expression like so:

// use '..' in the args expression if you have zero or more parameters at that point
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..)) && args(yourString,..)")

then your method can instead be defined as

public void logBefore(JoinPoint joinPoint, String yourString) 

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

In Python, can I call the main() of an imported module?

Assuming you are trying to pass the command line arguments as well.

import sys
import myModule


def main():
    # this will just pass all of the system arguments as is
    myModule.main(*sys.argv)

    # all the argv but the script name
    myModule.main(*sys.argv[1:])

Routing with multiple Get methods in ASP.NET Web API

You might not need to make any change in the routing. Just add following four methods in your customersController.cs file:

public ActionResult Index()
{
}

public ActionResult currentMonth()
{
}

public ActionResult customerById(int id)
{
}


public ActionResult customerByUsername(string userName)
{
}

Put the relevant code in the method. With the default routing supplied, you should get appropriate action result from the controller based on the action and parameters for your given urls.

Modify your default route as:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Api", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

search in java ArrayList

Customer findCustomerByid(int id){
    for (int i=0; i<this.customers.size(); i++) {
        Customer customer = this.customers.get(i);
        if (customer.getId() == id){
             return customer;
        }
    }
    return null; // no Customer found with this ID; maybe throw an exception
}

How to force Chrome's script debugger to reload javascript?

Here's a shortcut to DevTools:

  1. F12 to open Chrome DevTools
  2. F1 to open DevTools Settings
  3. Check Disable cache (while DevTools is open) as shown below:

enter image description here

Note: Updated per Dimi's comment. They tend to move it so let me know or update the post if you notice that it's changed.

Refresh image with a new one at the same url

<img src='someurl.com/someimage.ext' onload='imageRefresh(this, 1000);'>

Then below in some javascript

<script language='javascript'>
 function imageRefresh(img, timeout) {
    setTimeout(function() {
     var d = new Date;
     var http = img.src;
     if (http.indexOf("&d=") != -1) { http = http.split("&d=")[0]; } 

     img.src = http + '&d=' + d.getTime();
    }, timeout);
  }
</script>

And so what this does is, when the image loads, schedules it to be reloaded in 1 second. I'm using this on a page with home security cameras of varying type.

Getting the exception value in Python

If you don't know the type/origin of the error, you can try:

import sys
try:
    doSomethingWrongHere()
except:
    print('Error: {}'.format(sys.exc_info()[0]))

But be aware, you'll get pep8 warning:

[W] PEP 8 (E722): do not use bare except

How to convert string to double with proper cultureinfo

You can convert the value user provides to a double and store it again as nvarchar, with the aid of FormatProviders. CultureInfo is a typical FormatProvider. Assuming you know the culture you are operating,

System.Globalization.CultureInfo EnglishCulture = new System.Globalization.CultureInfo("en-EN");
System.Globalization.CultureInfo GermanCulture = new System.Globalization.CultureInfo("de-de");

will suffice to do the neccesary transformation, like;

double val;
if(double.TryParse("65,89875", System.Globalization.NumberStyles.Float, GermanCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

if(double.TryParse("65.89875", System.Globalization.NumberStyles.Float, EnglishCulture,  out val))
{
    string valInGermanFormat = val.ToString(GermanCulture);
    string valInEnglishFormat = val.ToString(EnglishCulture);
}

How to check if current thread is not main thread

You can try Thread.currentThread().isDaemon()

How to style an asp.net menu with CSS

You can try styling with LevelSubMenuStyles

            <asp:Menu ID="mainMenu" runat="server" Orientation="Horizontal" 
                StaticEnableDefaultPopOutImage="False">
                <StaticMenuStyle CssClass="test" />
                <LevelSubMenuStyles>
                    <asp:SubMenuStyle BackColor="#33CCFF" BorderColor="#FF9999" 
                        Font-Underline="False" />
                    <asp:SubMenuStyle BackColor="#FF99FF" Font-Underline="False" />
                </LevelSubMenuStyles>
                <StaticMenuItemStyle CssClass="main-nav-item" />
            </asp:Menu>

Extending from two classes

Yes. slandau is right. Java does not allow extending from several classes.

What you want is probably public class Main extends ListActivity implements ControlMenu. I am guessing you are trying to make a list.

Hope that helps.

Date Format in Swift

Swift - 5.0

let date = Date()
let formate = date.getFormattedDate(format: "yyyy-MM-dd HH:mm:ss") // Set output formate

extension Date {
   func getFormattedDate(format: String) -> String {
        let dateformat = DateFormatter()
        dateformat.dateFormat = format
        return dateformat.string(from: self)
    }
}

Swift - 4.0

2018-02-01T19:10:04+00:00 Convert Feb 01,2018

extension Date {
    static func getFormattedDate(string: String , formatter:String) -> String{
        let dateFormatterGet = DateFormatter()
        dateFormatterGet.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

        let dateFormatterPrint = DateFormatter()
        dateFormatterPrint.dateFormat = "MMM dd,yyyy"

        let date: Date? = dateFormatterGet.date(from: "2018-02-01T19:10:04+00:00")
        print("Date",dateFormatterPrint.string(from: date!)) // Feb 01,2018
        return dateFormatterPrint.string(from: date!);
    }
}

String comparison technique used by Python

A pure Python equivalent for string comparisons would be:

def less(string1, string2):
    # Compare character by character
    for idx in range(min(len(string1), len(string2))):
        # Get the "value" of the character
        ordinal1, ordinal2 = ord(string1[idx]), ord(string2[idx])
        # If the "value" is identical check the next characters
        if ordinal1 == ordinal2:
            continue
        # It's not equal so we're finished at this index and can evaluate which is smaller.
        else:
            return ordinal1 < ordinal2
    # We're out of characters and all were equal, so the result depends on the length
    # of the strings.
    return len(string1) < len(string2)

This function does the equivalent of the real method (Python 3.6 and Python 2.7) just a lot slower. Also note that the implementation isn't exactly "pythonic" and only works for < comparisons. It's just to illustrate how it works. I haven't checked if it works like Pythons comparison for combined unicode characters.

A more general variant would be:

from operator import lt, gt

def compare(string1, string2, less=True):
    op = lt if less else gt
    for char1, char2 in zip(string1, string2):
        ordinal1, ordinal2 = ord(char1), ord(char1)
        if ordinal1 == ordinal2:
            continue
        else:
            return op(ordinal1, ordinal2)
    return op(len(string1), len(string2))

How do I use modulus for float/double?

fmod is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod function. In Java you can use the % operator on doubles the same as on integers:

int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2

Eclipse Problems View not showing Errors anymore

In my case Eclipse wasn't properly picking up a Java project that a current project was dependent on.

You can go to Project > BuildPath > Configure BuildPath and then delete and re-add the project.

'mvn' is not recognized as an internal or external command, operable program or batch file

My problem solved, path didn't resolve %M2%. When i added location of maven-bin in the path instead of %M2% after that commands works.

I would like to thanks to all those who try to solve the problem

Easiest way to convert int to string in C++

I usually use the following method:

#include <sstream>

template <typename T>
  std::string NumberToString ( T Number )
  {
     std::ostringstream ss;
     ss << Number;
     return ss.str();
  }

It is described in details here.

How to calculate the median of an array?

I faced a similar problem yesterday. I wrote a method with Java generics in order to calculate the median value of every collection of Numbers; you can apply my method to collections of Doubles, Integers, Floats and returns a double. Please consider that my method creates another collection in order to not alter the original one. I provide also a test, have fun. ;-)

public static <T extends Number & Comparable<T>> double median(Collection<T> numbers){
    if(numbers.isEmpty()){
        throw new IllegalArgumentException("Cannot compute median on empty collection of numbers");
    }
    List<T> numbersList = new ArrayList<>(numbers);
    Collections.sort(numbersList);
    int middle = numbersList.size()/2;
    if(numbersList.size() % 2 == 0){
        return 0.5 * (numbersList.get(middle).doubleValue() + numbersList.get(middle-1).doubleValue());
    } else {
        return numbersList.get(middle).doubleValue();
    }

}

JUnit test code snippet:

/**
 * Test of median method, of class Utils.
 */
@Test
public void testMedian() {
    System.out.println("median");
    Double expResult = 3.0;
    Double result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,13.0));
    assertEquals(expResult, result);
    expResult = 3.5;
    result = Utils.median(Arrays.asList(3.0,2.0,1.0,9.0,4.0,13.0));
    assertEquals(expResult, result);
}

Usage example (consider the class name is Utils):

List<Integer> intValues = ... //omitted init
Set<Float> floatValues = ... //omitted init
.....
double intListMedian = Utils.median(intValues);
double floatSetMedian = Utils.median(floatValues);

Note: my method works on collections, you can convert arrays of numbers to list of numbers as pointed here

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

I had the same issue with Xcode 10.0 beta 5 (10L221o) and a device running iOS 12.0 (16A5345f) - that's also beta.

After installing the app alert titled "App installation failed" showed up, "A valid provisioning profile for this executable was not found.".

I got rid of it by going to: ~/Library/MobileDevice/Provisioning Profiles and finding the certificate Xcode was trying to use. Then in the "Devices and Simulators" window in Xcode, I right clicked on my device, choose "Show Provisioning Profiles" and with a plus button added the provisioning profile to the device there.

I don't remember when I've done it last time, it's been years. I guess that Xcode normally does it for us but for some reason, it fails when we see that message.

Move entire line up and down in Vim

A simple solution is to put in your .vimrc these lines:

nmap <C-UP> :m-2<CR>  
nmap <C-DOWN> :m+1<CR>

jQuery AJAX cross domain

You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to * will accept cross-domain AJAX requests from any domain.

Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:

header("Access-Control-Allow-Origin: *");

Don't forget to enable mod_headers module in httpd.conf.

Left Outer Join using + sign in Oracle 11g

TableA LEFT OUTER JOIN TableB is equivalent to TableB RIGHT OUTER JOIN Table A.

In Oracle, (+) denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S. In your second query, it's S RIGHT OUTER JOIN P. They're functionally equivalent.

In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S, P will always have a record because it's on the LEFT, but S could be null.

See this example from java2s.com for additional explanation.


To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.


RIGHT vs LEFT

I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+) determines RIGHT or LEFT. (Specifically, if the (+) is on the right, it's a LEFT JOIN. If (+) is on the left, it's a RIGHT JOIN.)


Types of JOIN

The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.

See this SO question.

Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.

Implicit JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.

Explicit JOIN

SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column

These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.

Unsupported major.minor version 52.0 when rendering in Android Studio

This is bug in Android Studio. Usually you get error: Unsupported major.minor version 52.0

WORKAROUND: If you have installed Android N, change Android rendering version with older one and the problem will disappear.

SOLUTION: Install Android SDK Tools 25.1.3 (tools) or higher

enter image description here

MySQL INNER JOIN select only one row from second table

You can try this:

SELECT u.*, p.*
FROM users AS u LEFT JOIN (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY userid ORDER BY [Date] DESC) AS RowNo
    FROM payments  
) AS p ON u.userid = p.userid AND p.RowNo=1

jQuery: How can I create a simple overlay?

Here's a fully encapsulated version which adds an overlay (including a share button) to any IMG element where data-photo-overlay='true.

JSFiddle http://jsfiddle.net/wloescher/7y6UX/19/

HTML

<img id="my-photo-id" src="http://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png" alt="Photo" data-photo-overlay="true" />

CSS

#photoOverlay {
    background: #ccc;
    background: rgba(0, 0, 0, .5);
    display: none;
    height: 50px;
    left: 0;
    position: absolute;
    text-align: center;
    top: 0;
    width: 50px;
    z-index: 1000;
}

#photoOverlayShare {
    background: #fff;
    border: solid 3px #ccc;
    color: #ff6a00;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    margin-left: auto;
    margin: 15px;
    padding: 5px;
    position: absolute;
    left: calc(100% - 100px);
    text-transform: uppercase;
    width: 50px;
}

JavaScript

(function () {
    // Add photo overlay hover behavior to selected images
    $("img[data-photo-overlay='true']").mouseenter(showPhotoOverlay);

    // Create photo overlay elements
    var _isPhotoOverlayDisplayed = false;
    var _photoId;
    var _photoOverlay = $("<div id='photoOverlay'></div>");
    var _photoOverlayShareButton = $("<div id='photoOverlayShare'>Share</div>");

    // Add photo overlay events
    _photoOverlay.mouseleave(hidePhotoOverlay);
    _photoOverlayShareButton.click(sharePhoto);

    // Add photo overlay elements to document
    _photoOverlay.append(_photoOverlayShareButton);
    _photoOverlay.appendTo(document.body);

    // Show photo overlay
    function showPhotoOverlay(e) {
        // Get sender 
        var sender = $(e.target || e.srcElement);

        // Check to see if overlay is already displayed
        if (!_isPhotoOverlayDisplayed) {
            // Set overlay properties based on sender
            _photoOverlay.width(sender.width());
            _photoOverlay.height(sender.height());

            // Position overlay on top of photo
            if (sender[0].x) {
                _photoOverlay.css("left", sender[0].x + "px");
                _photoOverlay.css("top", sender[0].y) + "px";
            }
            else {
                // Handle IE incompatibility
                _photoOverlay.css("left", sender.offset().left);
                _photoOverlay.css("top", sender.offset().top);
            }

            // Get photo Id
            _photoId = sender.attr("id");

            // Show overlay
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = true;
        }
    }

    // Hide photo overlay
    function hidePhotoOverlay(e) {
        if (_isPhotoOverlayDisplayed) {
            _photoOverlay.animate({ opacity: "toggle" });
            _isPhotoOverlayDisplayed = false;
        }
    }

    // Share photo
    function sharePhoto() {
        alert("TODO: Share photo. [PhotoId = " + _photoId + "]");
        }
    }
)();

How do I apply a diff patch on Windows?

TortoiseMerge is a separate utility that comes bundled with TortoiseSVN.

It can also be can be downloaded separately in the TortoiseDiff.zip archive. This will allow you to apply unified diffs to non-versioned files.

How to get current domain name in ASP.NET

Here is a quick easy way to just get the name of the url.

            var urlHost = HttpContext.Current.Request.Url.Host;

            var xUrlHost = urlHost.Split('.');
            foreach(var thing in xUrlHost)
            {
                if(thing != "www" && thing != "com")
                {
                    urlHost = thing;
                }
            }

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

What are the differences between the urllib, urllib2, urllib3 and requests module?

To get the content of a url:

try: # Try importing requests first.
    import requests
except ImportError: 
    try: # Try importing Python3 urllib
        import urllib.request
    except AttributeError: # Now importing Python2 urllib
        import urllib


def get_content(url):
    try:  # Using requests.
        return requests.get(url).content # Returns requests.models.Response.
    except NameError:  
        try: # Using Python3 urllib.
            with urllib.request.urlopen(index_url) as response:
                return response.read() # Returns http.client.HTTPResponse.
        except AttributeError: # Using Python3 urllib.
            return urllib.urlopen(url).read() # Returns an instance.

It's hard to write Python2 and Python3 and request dependencies code for the responses because they urlopen() functions and requests.get() function return different types:

  • Python2 urllib.request.urlopen() returns a http.client.HTTPResponse
  • Python3 urllib.urlopen(url) returns an instance
  • Request request.get(url) returns a requests.models.Response

How to replace space with comma using sed?

Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

How to set an HTTP proxy in Python 2.7?

cd C:\Python34\Scripts

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

set HTTP_PROXY= DOMAIN\User_Name:Passw0rd123@PROXY_SERVER_NAME_OR_IP:PORT#

pip.exe install PackageName

Dynamically load JS inside JS

You can use jQuery's $.getScript() method to do it but if you want a more full feature one, yepnope.js is your choice. It supports conditional loading of scripts and stylesheets and it's easy to use.

When do you use map vs flatMap in RxJava?

Here is a simple thumb-rule that I use help me decide as when to use flatMap() over map() in Rx's Observable.

Once you come to a decision that you're going to employ a map transformation, you'd write your transformation code to return some Object right?

If what you're returning as end result of your transformation is:

  • a non-observable object then you'd use just map(). And map() wraps that object in an Observable and emits it.

  • an Observable object, then you'd use flatMap(). And flatMap() unwraps the Observable, picks the returned object, wraps it with its own Observable and emits it.

Say for example we've a method titleCase(String inputParam) that returns Titled Cased String object of the input param. The return type of this method can be String or Observable<String>.

  • If the return type of titleCase(..) were to be mere String, then you'd use map(s -> titleCase(s))

  • If the return type of titleCase(..) were to be Observable<String>, then you'd use flatMap(s -> titleCase(s))

Hope that clarifies.

Regex to match string containing two names in any order

You can do:

\bjack\b.*\bjames\b|\bjames\b.*\bjack\b

How to add a new column to an existing sheet and name it?

Use insert method from range, for example

Sub InsertColumn()
        Columns("C:C").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
        Range("C1").Value = "Loc"
End Sub

Convert comma separated string of ints to int array

This has been asked before. .Net has a built-in ConvertAll function for converting between an array of one type to an array of another type. You can combine this with Split to separate the string to an array of strings

Example function:

 static int[] ToIntArray(this string value, char separator)
 {
     return Array.ConvertAll(value.Split(separator), s=>int.Parse(s));
 }

Taken from here

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

Is there a cross-browser onload event when clicking the back button?

for the people who don't want to use the whole jquery library i extracted the implementation in separate code. It's only 0,4 KB big.

You can find the code, together with a german tutorial in this wiki: http://www.easy-coding.de/wiki/html-ajax-und-co/onload-event-cross-browser-kompatibler-domcontentloaded.html

Difference between add(), replace(), and addToBackStack()

Basic difference between add() and replace() can be described as:

  • add() is used for simply adding a fragment to some root element.
  • replace() behaves similarly but at first it removes previous fragments and then adds next fragment.

We can see the exact difference when we use addToBackStack() together with add() or replace().

When we press back button after in case of add()... onCreateView is never called, but in case of replace(), when we press back button ... oncreateView is called every time.

How can I clear previous output in Terminal in Mac OS X?

Typing the following in the terminal will erase your history (meaning using up arrow will get you nothing), but it will not clear the screen:

history -c

PHP 5 disable strict standards error

I didn't see an answer that's clean and suitable for production-ready software, so here it goes:

/*
 * Get current error_reporting value,
 * so that we don't lose preferences set in php.ini and .htaccess
 * and accidently reenable message types disabled in those.
 *
 * If you want to disable e.g. E_STRICT on a global level,
 * use php.ini (or .htaccess for folder-level)
 */
$old_error_reporting = error_reporting();

/*
 * Disable E_STRICT on top of current error_reporting.
 *
 * Note: do NOT use ^ for disabling error message types,
 * as ^ will re-ENABLE the message type if it happens to be disabled already!
 */
error_reporting($old_error_reporting & ~E_STRICT);


// code that should not emit E_STRICT messages goes here


/*
 * Optional, depending on if/what code comes after.
 * Restore old settings.
 */
error_reporting($old_error_reporting);

How can I generate random number in specific range in Android?

int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.

MySQL SELECT only not null values

I use the \! command within MySQL to grep out NULL values from the shell:

\! mysql -e "SELECT * FROM table WHERE column = 123456\G" | grep -v NULL

It works best with a proper .my.cnf where your database/username/password are specified. That way you just have to surround your select with \! mysql e and | grep -v NULL.

gitx How do I get my 'Detached HEAD' commits back into master

If checkout master was the last thing you did, then the reflog entry HEAD@{1} will contain your commits (otherwise use git reflog or git log -p to find them). Use git merge HEAD@{1} to fast forward them into master.

EDIT:

As noted in the comments, Git Ready has a great article on this.

git reflog and git reflog --all will give you the commit hashes of the mis-placed commits.

Git Ready: Reflog, Your Safety Net

Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html

Add a default value to a column through a migration

**Rails 4.X +**

As of Rails 4 you can't generate a migration to add a column to a table with a default value, The following steps add a new column to an existing table with default value true or false.

1. Run the migration from command line to add the new column

$ rails generate migration add_columnname_to_tablename columnname:boolean

The above command will add a new column in your table.

2. Set the new column value to TRUE/FALSE by editing the new migration file created.

class AddColumnnameToTablename < ActiveRecord::Migration
  def change
    add_column :table_name, :column_name, :boolean, default: false
  end
end

**3. To make the changes into your application database table, run the following command in terminal**

$ rake db:migrate

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

a=5; i=++a + ++a + a++;

is

i = 7 + 6 + 7

Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6 . then a=7 is provided to post increment => 7 + 6 + 7 =20 and a =8.

a=5; i=a++ + ++a + ++a;

is

i=7 + 7 + 6

Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6.then a=7 is provided to post increment => 7 + 7 + 6 =20 and a =8.

How to overlay image with color in CSS?

Use mutple backgorund on the element, and use a linear-gradient as your color overlay by declaring both start and end color-stops as the same value.

Note that layers in a multi-background declaration are read much like they are rendered, top-to-bottom, so put your overlay first, then your bg image:

#header {
  background: 
    linear-gradient(to bottom, rgba(100, 100, 0, 0.5), rgba(100, 100, 0, 0.5)) cover,
    url(../img/bg.jpg) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF
}

How can I get a channel ID from YouTube?

To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg" or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg".

UCjXfkj5iapKHJrhYfAF9ZGg will be the channel ID you are looking for.

How to extract 1 screenshot for a video with ffmpeg at a given time?

Use the -ss option:

ffmpeg -ss 01:23:45 -i input -vframes 1 -q:v 2 output.jpg
  • For JPEG output use -q:v to control output quality. Full range is a linear scale of 1-31 where a lower value results in a higher quality. 2-5 is a good range to try.

  • The select filter provides an alternative method for more complex needs such as selecting only certain frame types, or 1 per 100, etc.

  • Placing -ss before the input will be faster. See FFmpeg Wiki: Seeking and this excerpt from the ffmpeg cli tool documentation:

-ss position (input/output)

When used as an input option (before -i), seeks in this input file to position. Note the in most formats it is not possible to seek exactly, so ffmpeg will seek to the closest seek point before position. When transcoding and -accurate_seek is enabled (the default), this extra segment between the seek point and position will be decoded and discarded. When doing stream copy or when -noaccurate_seek is used, it will be preserved.

When used as an output option (before an output filename), decodes but discards input until the timestamps reach position.

position may be either in seconds or in hh:mm:ss[.xxx] form.

How to enable Auto Logon User Authentication for Google Chrome

Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.

If you are using Chrome right now, you can check your version with : chrome://version

  1. Goto: chrome://settings

  1. Scroll down to the bottom of the page and click on "Advanced" to show more settings.

OLDER VERSIONS:

Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.

  1. In the "System" section, click on "Open proxy settings".

OLDER VERSIONS:

In the "Network" section, click on "Change proxy settings...".

  1. Click on the "Security" tab, then select "Local intranet" icon and click on "Sites" button.

  1. Click on "Advanced" button.

  1. Insert your intranet local address and click on the "Add" button.

  1. Close all windows.

That's it.

Escape text for HTML

Also, you can use this if you don't want to use the System.Web assembly:

var encoded = System.Security.SecurityElement.Escape(unencoded)

Per this article, the difference between System.Security.SecurityElement.Escape() and System.Web.HttpUtility.HtmlEncode() is that the former also encodes apostrophe (') characters.

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

Check if an apt-get package is installed and then install it if it's not on Linux

$name="rsync"

[ `which $name` ] $$ echo "$name : installed" || sudo apt-get install -y $name

How can I recover a lost commit in Git?

This happened to me just today, so I am writing what came out as a lifesaver for me. My answer is very similar to @Amber 's answer.

First, I did a git reflog and searched for that particular commit's hash, then just copied that hash and did a git cherry-pick <hash> from that branch. This brought all the change from that lost commit to my current branch, and restored my faith on GIT.

Have a nice day!

how to call a onclick function in <a> tag?

Try onclick function separately it can give you access to execute your function which can be used to open up a new window, for this purpose you first need to create a javascript function there you can define it and in your anchor tag you just need to call your function.

Example:

function newwin() {              
 myWindow=window.open('lead_data.php?leadid=1','myWin','width=400,height=650')
}

See how to call it from your anchor tag

<a onclick='newwin()'>Anchor</a>

Update

Visit this jsbin

http://jsbin.com/icUTUjI/1/edit

May be this will help you a lot to understand your problem.

How do you loop in a Windows batch file?

Conditionally perform a command several times.

  • syntax-FOR-Files

    FOR %%parameter IN (set) DO command 
    
  • syntax-FOR-Files-Rooted at Path

    FOR /R [[drive:]path] %%parameter IN (set) DO command 
    
  • syntax-FOR-Folders

    FOR /D %%parameter IN (folder_set) DO command 
    
  • syntax-FOR-List of numbers

    FOR /L %%parameter IN (start,step,end) DO command 
    
  • syntax-FOR-File contents

    FOR /F ["options"] %%parameter IN (filenameset) DO command 
    

    or

    FOR /F ["options"] %%parameter IN ("Text string to process") DO command
    
  • syntax-FOR-Command Results

    FOR /F ["options"] %%parameter IN ('command to process') DO command
    

It

  • Take a set of data
  • Make a FOR Parameter %%G equal to some part of that data
  • Perform a command (optionally using the parameter as part of the command).
  • --> Repeat for each item of data

If you are using the FOR command at the command line rather than in a batch program, use just one percent sign: %G instead of %%G.

FOR Parameters

  • The first parameter has to be defined using a single character, for example the letter G.

  • FOR %%G IN ...

    In each iteration of a FOR loop, the IN ( ....) clause is evaluated and %%G set to a different value

    If this clause results in a single value then %%G is set equal to that value and the command is performed.

    If the clause results in a multiple values then extra parameters are implicitly defined to hold each. These are automatically assigned in alphabetical order %%H %%I %%J ...(implicit parameter definition)

    If the parameter refers to a file, then enhanced variable reference can be used to extract the filename/path/date/size.

    You can of course pick any letter of the alphabet other than %%G. but it is a good choice because it does not conflict with any of the pathname format letters (a, d, f, n, p, s, t, x) and provides the longest run of non-conflicting letters for use as implicit parameters.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

How to check if a value exists in an array in Ruby

Try

['Cat', 'Dog', 'Bird'].include?('Dog')

Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect)

I also ran into this error when attempting to update an existing row after creating a new one, and spent ages scratching my head, digging through transaction and version logic, until I realised that I had used the wrong type for one of my primary key columns.

I used LocalDate when I should have been using LocalDateTime – I think this was causing hibernate to not be able to distinguish entities, leading to this error.

After changing the key to be a LocalDateTime, the error went away. Also, updating individual rows began to work as well – previously it would fail to find a row for updating, and testing this separate issue was actually what led me to my conclusions regarding the primary key mapping.

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

find files by extension, *.html under a folder in nodejs

The following code does a recursive search inside ./ (change it appropriately) and returns an array of absolute file names ending with .html

var fs = require('fs');
var path = require('path');

var searchRecursive = function(dir, pattern) {
  // This is where we store pattern matches of all files inside the directory
  var results = [];

  // Read contents of directory
  fs.readdirSync(dir).forEach(function (dirInner) {
    // Obtain absolute path
    dirInner = path.resolve(dir, dirInner);

    // Get stats to determine if path is a directory or a file
    var stat = fs.statSync(dirInner);

    // If path is a directory, scan it and combine results
    if (stat.isDirectory()) {
      results = results.concat(searchRecursive(dirInner, pattern));
    }

    // If path is a file and ends with pattern then push it onto results
    if (stat.isFile() && dirInner.endsWith(pattern)) {
      results.push(dirInner);
    }
  });

  return results;
};

var files = searchRecursive('./', '.html'); // replace dir and pattern
                                                // as you seem fit

console.log(files);

How to check if running in Cygwin, Mac or Linux?

Bash sets the shell variable OSTYPE. From man bash:

Automatically set to a string that describes the operating system on which bash is executing.

This has a tiny advantage over uname in that it doesn't require launching a new process, so will be quicker to execute.

However, I'm unable to find an authoritative list of expected values. For me on Ubuntu 14.04 it is set to 'linux-gnu'. I've scraped the web for some other values. Hence:

case "$OSTYPE" in
  linux*)   echo "Linux / WSL" ;;
  darwin*)  echo "Mac OS" ;; 
  win*)     echo "Windows" ;;
  msys*)    echo "MSYS / MinGW / Git Bash" ;;
  cygwin*)  echo "Cygwin" ;;
  bsd*)     echo "BSD" ;;
  solaris*) echo "Solaris" ;;
  *)        echo "unknown: $OSTYPE" ;;
esac

The asterisks are important in some instances - for example OSX appends an OS version number after the 'darwin'. The 'win' value is actually 'win32', I'm told - maybe there is a 'win64'?

Perhaps we could work together to populate a table of verified values here:

  • Linux Ubuntu (incl. WSL): linux-gnu
  • Cygwin 64-bit: cygwin
  • Msys/MINGW (Git Bash for Windows): msys

(Please append your value if it differs from existing entries)

How to display a list of images in a ListView in Android?

We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.

public View getView(int position, View convertView, ViewGroup parent) {
 // TODO Auto-generated method stub
 LayoutInflater inflater = (LayoutInflater) context
 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 View single_row = inflater.inflate(R.layout.list_row, null,
 true);
 TextView textView = (TextView) single_row.findViewById(R.id.textView);
 ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
 textView.setText(color_names[position]);
 imageView.setImageResource(image_id[position]);
 return single_row; 
 }

Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.

Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);

Git, How to reset origin/master to a commit?

origin/xxx branches are always pointer to a remote. You cannot check them out as they're not pointer to your local repository (you only checkout the commit. That's why you won't see the name written in the command line interface branch marker, only the commit hash).

What you need to do to update the remote is to force push your local changes to master:

git checkout master
git reset --hard e3f1e37
git push --force origin master
# Then to prove it (it won't print any diff)
git diff master..origin/master

How do I copy a string to the clipboard?

import wx

def ctc(text):

    if not wx.TheClipboard.IsOpened():
        wx.TheClipboard.Open()
        data = wx.TextDataObject()
        data.SetText(text)
        wx.TheClipboard.SetData(data)
    wx.TheClipboard.Close()

ctc(text)

Make a bucket public in Amazon S3

You can set a bucket policy as detailed in this blog post:

http://ariejan.net/2010/12/24/public-readable-amazon-s3-bucket-policy/


As per @robbyt's suggestion, create a bucket policy with the following JSON:

{
  "Version": "2008-10-17",
  "Statement": [{
    "Sid": "AllowPublicRead",
    "Effect": "Allow",
    "Principal": { "AWS": "*" },
    "Action": ["s3:GetObject"],
    "Resource": ["arn:aws:s3:::bucket/*" ]
  }]
}

Important: replace bucket in the Resource line with the name of your bucket.

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

Udo G. said:

  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

He's right, but there's a way to affect the global scope from a function. Improving his example:

function include(file_) {
    with (global) {
        eval(fs.readFileSync(file_) + '');
    };
};

include('somefile_with_some_declarations.js');

// the declarations are now accessible here.

Hope, that helps.

A generic list of anonymous class

There are many ways to do this, but some of the responses here are creating a list that contains garbage elements, which requires you to clear the list.

If you are looking for an empty list of the generic type, use a Select against a List of Tuples to make the empty list. No elements will be instantiated.

Here's the one-liner to create an empty list:

 var emptyList = new List<Tuple<int, string>>()
          .Select(t => new { Id = t.Item1, Name = t.Item2 }).ToList();

Then you can add to it using your generic type:

 emptyList.Add(new { Id = 1, Name = "foo" });
 emptyList.Add(new { Id = 2, Name = "bar" });

As an alternative, you can do something like below to create the empty list (But, I prefer the first example because you can use it for a populated collection of Tuples as well) :

 var emptyList = new List<object>()
          .Select(t => new { Id = default(int), Name = default(string) }).ToList();   

What's the difference between size_t and int in C++?

It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.

How to go to a URL using jQuery?

//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";

how to hide a vertical scroll bar when not needed

overflow: auto; or overflow: hidden; should do it I think.

List of Stored Procedures/Functions Mysql Command Line

If you want to list Store Procedure for Current Selected Database,

SHOW PROCEDURE STATUS WHERE Db = DATABASE();

it will list Routines based on current selected Database

UPDATED to list out functions in your database

select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="FUNCTION";

to list out routines/store procedures in your database,

select * from information_schema.ROUTINES where ROUTINE_SCHEMA="YOUR DATABASE NAME" and ROUTINE_TYPE="PROCEDURE";

to list tables in your database,

select * from information_schema.TABLES WHERE TABLE_TYPE="BASE TABLE" AND TABLE_SCHEMA="YOUR DATABASE NAME";

to list views in your database,

method 1:

select * from information_schema.TABLES WHERE TABLE_TYPE="VIEW" AND TABLE_SCHEMA="YOUR DATABASE NAME";

method 2:

select * from information_schema.VIEWS WHERE TABLE_SCHEMA="YOUR DATABASE NAME";

http://localhost:50070 does not work HADOOP

port 50070 changed to 9870 in 3.0.0-alpha1

In fact, lots of others ports changed too. Look:

Namenode ports: 50470 --> 9871, 50070 --> 9870, 8020 --> 9820
Secondary NN ports: 50091 --> 9869, 50090 --> 9868
Datanode ports: 50020 --> 9867, 50010 --> 9866, 50475 --> 9865, 50075 --> 9864

Source

Uploading file using POST request in Node.js

You can also use the "custom options" support from the request library. This format allows you to create a multi-part form upload, but with a combined entry for both the file and extra form information, like filename or content-type. I have found that some libraries expect to receive file uploads using this format, specifically libraries like multer.

This approach is officially documented in the forms section of the request docs - https://github.com/request/request#forms

//toUpload is the name of the input file: <input type="file" name="toUpload">

let fileToUpload = req.file;

let formData = {
    toUpload: {
      value: fs.createReadStream(path.join(__dirname, '..', '..','upload', fileToUpload.filename)),
      options: {
        filename: fileToUpload.originalname,
        contentType: fileToUpload.mimeType
      }
    }
  };
let options = {
    url: url,
    method: 'POST',
    formData: formData
  }
request(options, function (err, resp, body) {
    if (err)
      cb(err);

    if (!err && resp.statusCode == 200) {
      cb(null, body);
    }
  });

Using wget to recursively fetch a directory with arbitrary files in it

Recursive wget ignoring robots (for websites)

wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'

-e robots=off causes it to ignore robots.txt for that domain

-r makes it recursive

-np = no parents, so it doesn't follow links up to the parent folder

How can I fill a div with an image while keeping it proportional?

The CSS object-fit: cover and object-position: left center property values now address this issue.

htaccess redirect all pages to single page

If your aim is to redirect all pages to a single maintenance page (as the title could suggest also this), then use:

RewriteEngine on
RewriteCond %{REQUEST_URI} !/maintenance.php$ 
RewriteCond %{REMOTE_HOST} !^000\.000\.000\.000
RewriteRule $ /maintenance.php [R=302,L] 

Where 000 000 000 000 should be replaced by your ip adress.

Source:

http://www.techiecorner.com/97/redirect-to-maintenance-page-during-upgrade-using-htaccess/

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

Solution 1 - you need to change your backend to accept your incoming requests

Solution 2 - using Angular proxy see here

Please note this is only for ng serve, you can't use proxy in ng build

Note: the reason it's working via postman is postman doesn't send preflight requests while your browser does.

How to filter a RecyclerView with a SearchView

With Android Architecture Components through the use of LiveData this can be easily implemented with any type of Adapter. You simply have to do the following steps:

1. Setup your data to return from the Room Database as LiveData as in the example below:

@Dao
public interface CustomDAO{

@Query("SELECT * FROM words_table WHERE column LIKE :searchquery")
    public LiveData<List<Word>> searchFor(String searchquery);
}

2. Create a ViewModel object to update your data live through a method that will connect your DAO and your UI

public class CustomViewModel extends AndroidViewModel {

    private final AppDatabase mAppDatabase;

    public WordListViewModel(@NonNull Application application) {
        super(application);
        this.mAppDatabase = AppDatabase.getInstance(application.getApplicationContext());
    }

    public LiveData<List<Word>> searchQuery(String query) {
        return mAppDatabase.mWordDAO().searchFor(query);
    }

}

3. Call your data from the ViewModel on the fly by passing in the query through onQueryTextListener as below:

Inside onCreateOptionsMenu set your listener as follows

searchView.setOnQueryTextListener(onQueryTextListener);

Setup your query listener somewhere in your SearchActivity class as follows

private android.support.v7.widget.SearchView.OnQueryTextListener onQueryTextListener =
            new android.support.v7.widget.SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    getResults(query);
                    return true;
                }

                @Override
                public boolean onQueryTextChange(String newText) {
                    getResults(newText);
                    return true;
                }

                private void getResults(String newText) {
                    String queryText = "%" + newText + "%";
                    mCustomViewModel.searchQuery(queryText).observe(
                            SearchResultsActivity.this, new Observer<List<Word>>() {
                                @Override
                                public void onChanged(@Nullable List<Word> words) {
                                    if (words == null) return;
                                    searchAdapter.submitList(words);
                                }
                            });
                }
            };

Note: Steps (1.) and (2.) are standard AAC ViewModel and DAO implementation, the only real "magic" going on here is in the OnQueryTextListener which will update the results of your list dynamically as the query text changes.

If you need more clarification on the matter please don't hesitate to ask. I hope this helped :).

Casting variables in Java

Actually, casting doesn't always work. If the object is not an instanceof the class you're casting it to you will get a ClassCastException at runtime.

jQuery AutoComplete Trigger Change Event

The simplest, most robust way is to use the internal ._trigger() to fire the autocomplete change event.

$("#CompanyList").autocomplete({
  source : yourSource,
  change : yourChangeHandler
})

$("#CompanyList").data("ui-autocomplete")._trigger("change");

Note, jQuery UI 1.9 changed from .data("autocomplete") to .data("ui-autocomplete"). You may also see some people using .data("uiAutocomplete") which indeed works in 1.9 and 1.10, but "ui-autocomplete" is the official preferred form. See http://jqueryui.com/upgrade-guide/1.9/#changed-naming-convention-for-data-keys for jQuery UI namespaecing on data keys.

Get values from label using jQuery

Use .attr

$("current_month").attr("month")
$("current_month").attr("year")

And change the labels id to

<label year="2010" month="6" id="current_month"> June &nbsp;2010</label>

How do I set cell value to Date and apply default Excel date format?

To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);

Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@ becomes d/m/yy h.mm;@) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

Getting the text that follows after the regex match

You can do this with "just the regular expression" as you asked for in a comment:

(?<=sentence).*

(?<=sentence) is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence without making that text itself part of the match. Consequently, (?<=sentence).* will match any text after sentence.

This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4}) is legal, but (?<=sentence\s*) isn't.

Where does Internet Explorer store saved passwords?

Short answer: in the Vault. Since Windows 7, a Vault was created for storing any sensitive data among it the credentials of Internet Explorer. The Vault is in fact a LocalSystem service - vaultsvc.dll.

Long answer: Internet Explorer allows two methods of credentials storage: web sites credentials (for example: your Facebook user and password) and autocomplete data. Since version 10, instead of using the Registry a new term was introduced: Windows Vault. Windows Vault is the default storage vault for the credential manager information.

You need to check which OS is running. If its Windows 8 or greater, you call VaultGetItemW8. If its isn't, you call VaultGetItemW7.

To use the "Vault", you load a DLL named "vaultcli.dll" and access its functions as needed.

A typical C++ code will be:

hVaultLib = LoadLibrary(L"vaultcli.dll");

if (hVaultLib != NULL) 
{
    pVaultEnumerateItems = (VaultEnumerateItems)GetProcAddress(hVaultLib, "VaultEnumerateItems");
    pVaultEnumerateVaults = (VaultEnumerateVaults)GetProcAddress(hVaultLib, "VaultEnumerateVaults");
    pVaultFree = (VaultFree)GetProcAddress(hVaultLib, "VaultFree");
    pVaultGetItemW7 = (VaultGetItemW7)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultGetItemW8 = (VaultGetItemW8)GetProcAddress(hVaultLib, "VaultGetItem");
    pVaultOpenVault = (VaultOpenVault)GetProcAddress(hVaultLib, "VaultOpenVault");
    pVaultCloseVault = (VaultCloseVault)GetProcAddress(hVaultLib, "VaultCloseVault");

    bStatus = (pVaultEnumerateVaults != NULL)
        && (pVaultFree != NULL)
        && (pVaultGetItemW7 != NULL)
        && (pVaultGetItemW8 != NULL)
        && (pVaultOpenVault != NULL)
        && (pVaultCloseVault != NULL)
        && (pVaultEnumerateItems != NULL);
}

Then you enumerate all stored credentials by calling

VaultEnumerateVaults

Then you go over the results.

What is the difference between Java RMI and RPC?

1. Approach:

RMI uses an object-oriented paradigm where the user needs to know the object and the method of the object he needs to invoke.

RPC doesn't deal with objects. Rather, it calls specific subroutines that are already established.

2. Working:

With RPC, you get a procedure call that looks pretty much like a local call. RPC handles the complexities involved with passing the call from local to the remote computer.

RMI does the very same thing, but RMI passes a reference to the object and the method that is being called.

RMI = RPC + Object-orientation

3. Better one:

RMI is a better approach compared to RPC, especially with larger programs as it provides a cleaner code that is easier to identify if something goes wrong.

4. System Examples:

RPC Systems: SUN RPC, DCE RPC

RMI Systems: Java RMI, CORBA, Microsoft DCOM/COM+, SOAP(Simple Object Access Protocol)

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

How can I make my custom objects Parcelable?

You can find some examples of this here, here (code is taken here), and here.

You can create a POJO class for this, but you need to add some extra code to make it Parcelable. Have a look at the implementation.

public class Student implements Parcelable{
        private String id;
        private String name;
        private String grade;

        // Constructor
        public Student(String id, String name, String grade){
            this.id = id;
            this.name = name;
            this.grade = grade;
       }
       // Getter and setter methods
       .........
       .........

       // Parcelling part
       public Student(Parcel in){
           String[] data = new String[3];

           in.readStringArray(data);
           // the order needs to be the same as in writeToParcel() method
           this.id = data[0];
           this.name = data[1];
           this.grade = data[2];
       }

       @?verride
       public int describeContents(){
           return 0;
       }

       @Override
       public void writeToParcel(Parcel dest, int flags) {
           dest.writeStringArray(new String[] {this.id,
                                               this.name,
                                               this.grade});
       }
       public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
           public Student createFromParcel(Parcel in) {
               return new Student(in); 
           }

           public Student[] newArray(int size) {
               return new Student[size];
           }
       };
   }

Once you have created this class, you can easily pass objects of this class through the Intent like this, and recover this object in the target activity.

intent.putExtra("student", new Student("1","Mike","6"));

Here, the student is the key which you would require to unparcel the data from the bundle.

Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");

This example shows only String types. But, you can parcel any kind of data you want. Try it out.

EDIT: Another example, suggested by Rukmal Dias.

Upper memory limit?

No, there's no Python-specific limit on the memory usage of a Python application. I regularly work with Python applications that may use several gigabytes of memory. Most likely, your script actually uses more memory than available on the machine you're running on.

In that case, the solution is to rewrite the script to be more memory efficient, or to add more physical memory if the script is already optimized to minimize memory usage.

Edit:

Your script reads the entire contents of your files into memory at once (line = u.readlines()). Since you're processing files up to 20 GB in size, you're going to get memory errors with that approach unless you have huge amounts of memory in your machine.

A better approach would be to read the files one line at a time:

for u in files:
     for line in u: # This will iterate over each line in the file
         # Read values from the line, do necessary calculations

Why has it failed to load main-class manifest attribute from a JAR file?

I got this error, and it was because I had the arguments in the wrong order:

CORRECT

java maui.main.Examples tagging -jar maui-1.0.jar 

WRONG

java -jar maui-1.0.jar maui.main.Examples tagging 

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

What are unit tests, integration tests, smoke tests, and regression tests?

  • Unit test: an automatic test to test the internal workings of a class. It should be a stand-alone test which is not related to other resources.
  • Integration test: an automatic test that is done on an environment, so similar to unit tests but with external resources (db, disk access)
  • Regression test: after implementing new features or bug fixes, you re-test scenarios which worked in the past. Here you cover the possibility in which your new features break existing features.
  • Smoke testing: first tests on which testers can conclude if they will continue testing.

/etc/apt/sources.list" E212: Can't open file for writing

for me worked changing the filesystem from Read-Only before running vim:

bash-3.2# mount -o remount rw /

return string with first match Regex

Maybe this would perform a bit better in case greater amount of input data does not contain your wanted piece because except has greater cost.

def return_first_match(text):
    result = re.findall('\d+',text)
    result = result[0] if result else ""
    return result

offsetting an html anchor to adjust for fixed header

I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:

<div id="c1234" class="contentElement">...</div>

and i changed the rendering so it renders like this:

<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>

And this CSS:

.anchor{
    position: relative;
    top: -50px;
}

The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.

Only drawback of this technique is you can no longer use :target.

Easiest way to loop through a filtered list with VBA?

One way assuming filtered data in A1 downwards;

dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng 
   ...     

Why does the preflight OPTIONS request of an authenticated CORS request work in Chrome but not Firefox?

This is an old post but maybe this could help people to complete the CORS problem. To complete the basic authorization problem you should avoid authorization for OPTIONS requests in your server. This is an Apache configuration example. Just add something like this in your VirtualHost or Location.

<LimitExcept OPTIONS>
    AuthType Basic
    AuthName <AUTH_NAME>
    Require valid-user
    AuthUserFile <FILE_PATH>
</LimitExcept>

Get DOM content of cross-domain iframe

You can't. XSS protection. Cross site contents can not be read by javascript. No major browser will allow you that. I'm sorry, but this is a design flaw, you should drop the idea.

EDIT

Note that if you have editing access to the website loaded into the iframe, you can use postMessage (also see the browser compatibility)

How do I check if the mouse is over an element in jQuery?

WARNING: is(':hover') is deprecated in jquery 1.8+. See this post for a solution.

You can also use this answer : https://stackoverflow.com/a/6035278/8843 to test if the mouse is hover an element :

$('#test').click(function() {
    if ($('#hello').is(':hover')) {
        alert('hello');
    }
});

How to make Java work with SQL Server?

Maybe a little late, but using different drivers altogether is overkill for a case of user error:

db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );

should be either one of these:

db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );

(using named pipe) or:

db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );

using port number directly; you can leave out 1433 because it's the default port, leaving:

db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );

what's the differences between r and rb in fopen

This makes a difference on Windows, at least. See that link for details.

Adding a newline into a string in C#

A simple string replace will do the job. Take a look at the example program below:

using System;

namespace NewLineThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "fkdfdsfdflkdkfk@dfsdfjk72388389@kdkfkdfkkl@jkdjkfjd@jjjk@";
            str = str.Replace("@", "@" + Environment.NewLine);
            Console.WriteLine(str);
            Console.ReadKey();
        }
    }
}

Installing Bootstrap 3 on Rails App

As many know, there is no need for a gem.

Steps to take:

  1. Download Bootstrap
  2. Copy

    bootstrap/dist/css/bootstrap.css
    bootstrap/dist/css/bootstrap.min.css 
    

    to: app/assets/stylesheets

  3. Copy

    bootstrap/dist/js/bootstrap.js
    bootstrap/dist/js/bootstrap.min.js 
    

    to: app/assets/javascripts

  4. Append to: app/assets/stylesheets/application.css

    *= require bootstrap

  5. Append to: app/assets/javascripts/application.js

    //= require bootstrap

That is all. You are ready to add a new cool Bootstrap template.


Why app/ instead of vendor/?

It is important to add the files to app/assets, so in the future you'll be able to overwrite Bootstrap styles.

If later you want to add a custom.css.scss file with custom styles. You'll have something similar to this in application.css:

 *= require bootstrap                                                            
 *= require custom  

If you placed the bootstrap files in app/assets, everything works as expected. But, if you placed them in vendor/assets, the Bootstrap files will be loaded last. Like this:

<link href="/assets/custom.css?body=1" media="screen" rel="stylesheet">
<link href="/assets/bootstrap.css?body=1" media="screen" rel="stylesheet">

So, some of your customizations won't be used as the Bootstrap styles will override them.

Reason behind this

Rails will search for assets in many locations; to get a list of this locations you can do this:

$ rails console
> Rails.application.config.assets.paths

In the output you'll see that app/assets takes precedence, thus loading it first.

How to pause a vbscript execution?

You can use a WScript object and call the Sleep method on it:

Set WScript = CreateObject("WScript.Shell")
WScript.Sleep 2000 'Sleeps for 2 seconds

Another option is to import and use the WinAPI function directly (only works in VBA, thanks @Helen):

Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Sleep 2000

Convert data.frame column to a vector?

You could use $ extraction:

class(aframe$a1)
[1] "numeric"

or the double square bracket:

class(aframe[["a1"]])
[1] "numeric"

Compare a date string to datetime in SQL Server?

SELECT  *
FROM    table1
WHERE   CONVERT(varchar(10),columnDatetime,121) = 
        CONVERT(varchar(10),CONVERT('14 AUG 2008' ,smalldatetime),121)

This will convert the datatime and the string into varchars of the format "YYYY-MM-DD".

This is very ugly, but should work

Android Linear Layout - How to Keep Element At Bottom Of View?

You will have to expand one of your upper views to fill the remaining space by setting android:layout_weight="1" on it. This will push your last view down to the bottom.

Here is a brief sketch of what I mean:

<LinearLayout android:orientation="vertical">
    <View/>
    <View android:layout_weight="1"/>
    <View/>
    <View android:id="@+id/bottom"/>
</LinearLayout>

where each of the child view heights is "wrap_content" and everything else is "fill_parent".

How to find a string inside a entire database?

Here is an easy and convenient cursor based solution

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT name, object_id FROM sys.objects WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

How to change the color of a CheckBox?

You can change the color directly in XML. Use buttonTint for the box: (as of API level 23)

<CheckBox
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:buttonTint="@color/CHECK_COLOR" />

You can also do this using appCompatCheckbox v7 for older API levels:

<android.support.v7.widget.AppCompatCheckBox 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    app:buttonTint="@color/COLOR_HERE" /> 

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

What is the difference between class and instance methods?

CLASS METHODS


A class method typically either creates a new instance of the class or retrieves some global properties of the class. Class methods do not operate on an instance or have any access to instance variable.


INSTANCE METHODS


An instance method operates on a particular instance of the class. For example, the accessors method that you implemented are all instance methods. You use them to set or get the instance variables of a particular object.


INVOKE


To invoke an instance method, you send the message to an instance of the class.

To invoke a class method, you send the message to the class directly.


Source: IOS - Objective-C - Class Methods And Instance Methods

Is there a Subversion command to reset the working copy?

To revert tracked files

svn revert . -R

To clean untracked files

svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

The -rf may/should look scary at first, but once understood it will not be for these reasons:

  1. Only wholly-untracked directories will match the pattern passed to rm
  2. The -rf is required, else these directories will not be removed

To revert then clean (the OP question)

svn revert . -R && svn status | rm -rf $(awk '/^?/{$1 = ""; print $0}')

For consistent ease of use

Add permanent alias to your .bash_aliases

alias svn.HardReset='read -p "destroy all local changes?[y/N]" && [[ $REPLY =~ ^[yY] ]] && svn revert . -R && rm -rf $(awk -f <(echo "/^?/{print \$2}") <(svn status) ;)'

How to add default value for html <textarea>?

If you want to bring information from a database into a textarea tag for editing: The input tag not to display data that occupy several lines: rows no work, tag input is one line.

<!--input class="article-input" id="article-input" type="text" rows="5" value="{{article}}" /-->

The textarea tag has no value, but work fine with handlebars

<textarea class="article-input" id="article-input" type="text" rows="9" >{{article}}</textarea> 

How do you transfer or export SQL Server 2005 data to Excel

SSIS is a no-brainer for doing stuff like this and is very straight forward (and this is just the kind of thing it is for).

  1. Right-click the database in SQL Management Studio
  2. Go to Tasks and then Export data, you'll then see an easy to use wizard.
  3. Your database will be the source, you can enter your SQL query
  4. Choose Excel as the target
  5. Run it at end of wizard

If you wanted, you could save the SSIS package as well (there's an option at the end of the wizard) so that you can do it on a schedule or something (and even open and modify to add more functionality if needed).

MySQL: How to set the Primary Key on phpMyAdmin?

You can't set the field having data-type "text". Only because of that thing you are getting this error. Try to change the data-type with int

Enable/Disable a dropdownbox in jquery

Try -

$('#chkdwn2').change(function(){
    if($(this).is(':checked'))
        $('#dropdown').removeAttr('disabled');
    else
        $('#dropdown').attr("disabled","disabled");
})

How to convert list to string

L = ['L','O','L']
makeitastring = ''.join(map(str, L))

How can I pass a member function where a free function is expected?

You can stop banging your heads now. Here is the wrapper for the member function to support existing functions taking in plain C functions as arguments. thread_local directive is the key here.

http://cpp.sh/9jhk3

// Example program
#include <iostream>
#include <string>

using namespace std;

typedef int FooCooker_ (int);

// Existing function
extern "C" void cook_10_foo (FooCooker_ FooCooker) {
    cout << "Cooking 10 Foo ..." << endl;
    cout << "FooCooker:" << endl;
    FooCooker (10);
}

struct Bar_ {
    Bar_ (int Foo = 0) : Foo (Foo) {};
    int cook (int Foo) {
        cout << "This Bar got " << this->Foo << endl;
        if (this->Foo >= Foo) {
            this->Foo -= Foo;
            cout << Foo << " cooked" << endl;
            return Foo;
        } else {
            cout << "Can't cook " <<  Foo << endl;
            return 0;
        }
    }
    int Foo = 0;
};

// Each Bar_ object and a member function need to define
// their own wrapper with a global thread_local object ptr
// to be called as a plain C function.
thread_local static Bar_* BarPtr = NULL;
static int cook_in_Bar (int Foo) {
    return BarPtr->cook (Foo);
}

thread_local static Bar_* Bar2Ptr = NULL;
static int cook_in_Bar2 (int Foo) {
    return Bar2Ptr->cook (Foo);
}

int main () {
  BarPtr = new Bar_ (20);
  cook_10_foo (cook_in_Bar);

  Bar2Ptr = new Bar_ (40);
  cook_10_foo (cook_in_Bar2);

  delete BarPtr;
  delete Bar2Ptr;
  return 0;
}

Please comment on any issues with this approach.

Other answers fail to call existing plain C functions: http://cpp.sh/8exun

Display HTML form values in same page after submit using Ajax

Try this one:

onsubmit="return f(this.'yourfieldname'.value);"

I hope this will help you.

Ubuntu: Using curl to download an image

If you want to keep the original name — use uppercase -O

curl -O https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

If you want to save remote file with a different name — use lowercase -o

curl -o myPic.png https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

Is there any free OCR library for Android?

OCR can be pretty CPU intensive, you might want to reconsider doing it on a smart phone.

That aside, to my knowledge the popular OCR libraries are Aspire and Tesseract. Neither are straight up Java, so you're not going to get a drop-in Android OCR library.

However, Tesseract is open source (GitHub hosted infact); so you can throw some time at porting the subset you need to Java. My understanding is its not insane C++, so depending on how badly you need OCR it might be worth the time.

So short answer: No.

Long answer: if you're willing to work for it.

Python Pandas counting and summing specific conditions

You didn't mention the fancy indexing capabilities of dataframes, e.g.:

>>> df = pd.DataFrame({"class":[1,1,1,2,2], "value":[1,2,3,4,5]})
>>> df[df["class"]==1].sum()
class    3
value    6
dtype: int64
>>> df[df["class"]==1].sum()["value"]
6
>>> df[df["class"]==1].count()["value"]
3

You could replace df["class"]==1by another condition.

Writing to a new file if it doesn't exist, and appending to a file if it does

Have you tried mode 'a+'?

with open(filename, 'a+') as f:
    f.write(...)

Note however that f.tell() will return 0 in Python 2.x. See https://bugs.python.org/issue22651 for details.

Scroll Element into View with Selenium

If you think other answers were too hacky, this one is too, but there is no JavaScript injection involved.

When the button is off the screen, it breaks and scrolls to it, so retry it... ¯\_(?)_/¯

try
{
    element.Click();
}
catch {
    element.Click();
}

How to check if function exists in JavaScript?

I have tried the accepted answer; however:

console.log(typeof me.onChange);

returns 'undefined'. I've noticed that the specification states an event called 'onchange' instead of 'onChange' (notice the camelCase).

Changing the original accepted answer to the following worked for me:

if (typeof me.onchange === "function") { 
  // safe to use the function
}

How to Execute a Python File in Notepad ++?

In case someone is interested in passing arguments to cmd.exe and running the python script in a Virtual Environment, these are the steps I used:

On the Notepad++ -> Run -> Run , I enter the following:

cmd /C cd $(CURRENT_DIRECTORY) && "PATH_to_.bat_file" $(FULL_CURRENT_PATH)

Here I cd into the directory in which the .py file exists, so that it enables accessing any other relevant files which are in the directory of the .py code.

And on the .bat file I have:

@ECHO off
set File_Path=%1

call activate Venv
python %File_Path%
pause

Parsing query strings on Android

If you have jetty (server or client) libs on your classpath you can use the jetty util classes (see javadoc), e.g.:

import org.eclipse.jetty.util.*;
URL url = new URL("www.example.com/index.php?foo=bar&bla=blub");
MultiMap<String> params = new MultiMap<String>();
UrlEncoded.decodeTo(url.getQuery(), params, "UTF-8");

assert params.getString("foo").equals("bar");
assert params.getString("bla").equals("blub");

CSS: 100% width or height while keeping aspect ratio?

Simple elegant working solution:

img {
  width: 600px;  /*width of parent container*/
  height: 350px; /*height of parent container*/
  object-fit: contain;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

CSS table td width - fixed, not flexible

The above suggestions trashed the layout of my table so I ended up using:

td {
  min-width: 30px;
  max-width: 30px;
  overflow: hidden;
}

This is horrible to maintain but was easier than re-doing all the existing css for the site. Hope it helps someone else.

turn typescript object into json string

Be careful when using these JSON.(parse/stringify) methods. I did the same with complex objects and it turned out that an embedded array with some more objects had the same values for all other entities in the object tree I was serializing.

const temp = [];
const t = {
    name: "name",
    etc: [
        {
            a: 0,
        },
    ],
};
for (let i = 0; i < 3; i++) {
    const bla = Object.assign({}, t);
    bla.name = bla.name + i;
    bla.etc[0].a = i;
    temp.push(bla);
}

console.log(JSON.stringify(temp));

How to create a jar with external libraries included in Eclipse?

To generate jar file in eclipse right click on the project for which you want to generate, Select Export>Java>Runnable Jar File,

enter image description here

enter image description here

Its create jar which includes all the dependencies from Pom.xml, But please make sure license issue if you are using third-party dependency for your application.

How do I filter ForeignKey choices in a Django ModelForm?

This is simple, and works with Django 1.4:

class ClientAdminForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(ClientAdminForm, self).__init__(*args, **kwargs)
        # access object through self.instance...
        self.fields['base_rate'].queryset = Rate.objects.filter(company=self.instance.company)

class ClientAdmin(admin.ModelAdmin):
    form = ClientAdminForm
    ....

You don't need to specify this in a form class, but can do it directly in the ModelAdmin, as Django already includes this built-in method on the ModelAdmin (from the docs):

ModelAdmin.formfield_for_foreignkey(self, db_field, request, **kwargs)¶
'''The formfield_for_foreignkey method on a ModelAdmin allows you to 
   override the default formfield for a foreign keys field. For example, 
   to return a subset of objects for this foreign key field based on the
   user:'''

class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if db_field.name == "car":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
        return super(MyModelAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

An even niftier way to do this (for example in creating a front-end admin interface that users can access) is to subclass the ModelAdmin and then alter the methods below. The net result is a user interface that ONLY shows them content that is related to them, while allowing you (a super-user) to see everything.

I've overridden four methods, the first two make it impossible for a user to delete anything, and it also removes the delete buttons from the admin site.

The third override filters any query that contains a reference to (in the example 'user' or 'porcupine' (just as an illustration).

The last override filters any foreignkey field in the model to filter the choices available the same as the basic queryset.

In this way, you can present an easy to manage front-facing admin site that allows users to mess with their own objects, and you don't have to remember to type in the specific ModelAdmin filters we talked about above.

class FrontEndAdmin(models.ModelAdmin):
    def __init__(self, model, admin_site):
        self.model = model
        self.opts = model._meta
        self.admin_site = admin_site
        super(FrontEndAdmin, self).__init__(model, admin_site)

remove 'delete' buttons:

    def get_actions(self, request):
        actions = super(FrontEndAdmin, self).get_actions(request)
        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

prevents delete permission

    def has_delete_permission(self, request, obj=None):
        return False

filters objects that can be viewed on the admin site:

    def get_queryset(self, request):
        if request.user.is_superuser:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()
            return qs

        else:
            try:
                qs = self.model.objects.all()
            except AttributeError:
                qs = self.model._default_manager.get_queryset()

            if hasattr(self.model, ‘user’):
                return qs.filter(user=request.user)
            if hasattr(self.model, ‘porcupine’):
                return qs.filter(porcupine=request.user.porcupine)
            else:
                return qs

filters choices for all foreignkey fields on the admin site:

    def formfield_for_foreignkey(self, db_field, request, **kwargs):
        if request.employee.is_superuser:
            return super(FrontEndAdmin, self).formfield_for_foreignkey(db_field, request, **kwargs)

        else:
            if hasattr(db_field.rel.to, 'user'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(user=request.user)
            if hasattr(db_field.rel.to, 'porcupine'):
                kwargs["queryset"] = db_field.rel.to.objects.filter(porcupine=request.user.porcupine)
            return super(ModelAdminFront, self).formfield_for_foreignkey(db_field, request, **kwargs)

CSS, Images, JS not loading in IIS

I added app.UseStaticFiles(); this code in starup.cs of Configure method, than it is fixed.

And Check your permission on this folder.

git stash changes apply to new branch?

Is the standard procedure not working?

  • make changes
  • git stash save
  • git branch xxx HEAD
  • git checkout xxx
  • git stash pop

Shorter:

  • make changes
  • git stash
  • git checkout -b xxx
  • git stash pop

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

What is the difference between Google App Engine and Google Compute Engine?

Google Compute Engine (GCE)

Virtual Machines (VMs) hosted in the cloud. Before the cloud, these were often called Virtual Private Servers (VPS). You'd use these the same way you'd use a physical server, where you install and configure the operating system, install your application, install the database, keep the OS up-to-date, etc. This is known as Infrastructure-as-a-Service (IaaS).

VMs are most useful when you have an existing application running on a VM or server in your datacenter, and want to easily migrate it to GCP.

Google App Engine

App Engine hosts and runs your code, without requiring you to deal with the operating system, networking, and many of the other things you'd have to manage with a physical server or VM. Think of it as a runtime, which can automatically deploy, version, and scale your application. This is called Platform-as-a-Service (PaaS).

App Engine is most useful when you want automated deployment and automated scaling of your application. Unless your application requires custom OS configuration, App Engine is often advantageous over configuring and managing VMs by hand.

ANTLR: Is there a simple example?

version 4.7.1 was slightly different : for import:

import org.antlr.v4.runtime.*;

for the main segment - note the CharStreams:

CharStream in = CharStreams.fromString("12*(5-6)");
ExpLexer lexer = new ExpLexer(in);
CommonTokenStream tokens = new CommonTokenStream(lexer);
ExpParser parser = new ExpParser(tokens);

Memcached vs. Redis?

Another bonus is that it can be very clear how memcache is going to behave in a caching scenario, while redis is generally used as a persistent datastore, though it can be configured to behave just like memcached aka evicting Least Recently Used items when it reaches max capacity.

Some apps I've worked on use both just to make it clear how we intend the data to behave - stuff in memcache, we write code to handle the cases where it isn't there - stuff in redis, we rely on it being there.

Other than that Redis is generally regarded as superior for most use cases being more feature-rich and thus flexible.

How to use PHP's password_hash to hash and verify passwords

Yes, it's true. Why do you doubt the php faq on the function? :)

The result of running password_hash() has has four parts:

  1. the algorithm used
  2. parameters
  3. salt
  4. actual password hash

So as you can see, the hash is a part of it.

Sure, you could have an additional salt for an added layer of security, but I honestly think that's overkill in a regular php application. The default bcrypt algorithm is good, and the optional blowfish one is arguably even better.

Pause Console in C++ program

Late response, but I think it will help others.

Part of imitating system("pause") is imitating what it asks the user to do: "Press any key to continue . . . " So, we need something that does not wait for simply a return as std::cin.get() would do. Even getch() has its problems when used twice (the second time call has been noticed to skip pausing generally if it's immediately paused again afterwards on the same key press). I think it has to do with the input buffer. System("pause") is usually not recommended, but we still need something to imitate what users might already expect. I prefer getch() because it doesn't echo to the screen, and it works dynamically.

The solution is to do the following using a do-while loop:

void Console::pause()
{ 
    int ch = 0;

    std::cout << "\nPress any key to continue . . . ";

    do {
        ch = getch();
    } while (ch != 0);

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

Now it waits for the user to press any key. If it's used twice, it waits for the user again instead of skipping.

Difference between try-catch and throw in java

Others have already given thorough answers, but if you're looking for even more information, the Oracle Java tutorials are always a good resource. Here's the Java tutorial for Exceptions, which covers all of your questions in great detail; https://docs.oracle.com/javase/tutorial/essential/exceptions/index.html

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

getting the ng-object selected with ng-change

You can also directly get selected value using following code

 <select ng-options='t.name for t in templates'
                  ng-change='selectedTemplate(t.url)'></select>

script.js

 $scope.selectedTemplate = function(pTemplate) {
    //Your logic
    alert('Template Url is : '+pTemplate);
}

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective.

models.py

class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=255)

admin.py (Incorrect Way) - you think it would work by using 'model__field' to reference, but it doesn't

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'author__name', ]

admin.site.register(Book, BookAdmin)

admin.py (Correct Way) - this is how you reference a foreign key name the Django way

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'get_name', ]

    def get_name(self, obj):
        return obj.author.name
    get_name.admin_order_field  = 'author'  #Allows column order sorting
    get_name.short_description = 'Author Name'  #Renames column head

    #Filtering on side - for some reason, this works
    #list_filter = ['title', 'author__name']

admin.site.register(Book, BookAdmin)

For additional reference, see the Django model link here

Combine two ActiveRecord::Relation objects

If you want to combine using AND (intersection), use merge:

first_name_relation.merge(last_name_relation)

If you want to combine using OR (union), use or:

first_name_relation.or(last_name_relation)

Only in ActiveRecord 5+; for 4.2 install the where-or backport.

(grep) Regex to match non-ASCII characters?

I use [^\t\r\n\x20-\x7E]+ and that seems to be working fine.

How do I validate a date in this format (yyyy-mm-dd) using jquery?

You can use this one it's for YYYY-MM-DD. It checks if it's a valid date and that the value is not NULL. It returns TRUE if everythings check out to be correct or FALSE if anything is invalid. It doesn't get easier then this!

function validateDate(date) {
    var matches = /^(\d{4})[-\/](\d{2})[-\/](\d{2})$/.exec(date);
    if (matches == null) return false;
    var d = matches[3];
    var m = matches[2] - 1;
    var y = matches[1] ;
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
            composedDate.getMonth() == m &&
            composedDate.getFullYear() == y;
}

Be aware that months need to be subtracted like this: var m = matches[2] - 1; else the new Date() instance won't be properly made.

Hiding the address bar of a browser (popup)

Looking for the same, the only thing I'm able to do is

Launch Google Chrome in app mode

Chrome.exe --app="<address>"

From the run prompt. Example:

Chrome.exe --app="http://www.google.com"

Hide the address bar in Mozilla Firefox

Type about:config in the address bar, the search for:

dom.disable_window_open_feature.location

And set it to false

So, when you open a popup window, it will launch with the address bar hidden. For example:

window.open("http://www.google.com",'','postwindow');

Firefox without location bar

Chrome in app mode

Now, I'm looking to do something similar with Microsoft Edge, I have not found anything yet for this browser.

Store output of sed into a variable

line=`sed -n 2p myfile`
echo $line

Check if a string matches a regex in Bash script

A good way to test if a string is a correct date is to use the command date:

if date -d "${DATE}" >/dev/null 2>&1
then
  # do what you need to do with your date
else
  echo "${DATE} incorrect date" >&2
  exit 1
fi

from comment: one can use formatting

if [ "2017-01-14" == $(date -d "2017-01-14" '+%Y-%m-%d') ] 

Winforms TableLayoutPanel adding rows programmatically

It's a weird design, but the TableLayoutPanel.RowCount property doesn't reflect the count of the RowStyles collection, and similarly for the ColumnCount property and the ColumnStyles collection.

What I've found I needed in my code was to manually update RowCount/ColumnCount after making changes to RowStyles/ColumnStyles.

Here's an example of code I've used:

    /// <summary>
    /// Add a new row to our grid.
    /// </summary>
    /// The row should autosize to match whatever is placed within.
    /// <returns>Index of new row.</returns>
    public int AddAutoSizeRow()
    {
        Panel.RowStyles.Add(new RowStyle(SizeType.AutoSize));
        Panel.RowCount = Panel.RowStyles.Count;
        mCurrentRow = Panel.RowCount - 1;
        return mCurrentRow;
    }

Other thoughts

  • I've never used DockStyle.Fill to make a control fill a cell in the Grid; I've done this by setting the Anchors property of the control.

  • If you're adding a lot of controls, make sure you call SuspendLayout and ResumeLayout around the process, else things will run slow as the entire form is relaid after each control is added.

How to allow only numeric (0-9) in HTML inputbox using jQuery?

You could just use a simple JavaScript regular expression to test for purely numeric characters:

/^[0-9]+$/.test(input);

This returns true if the input is numeric or false if not.

or for event keycode, simple use below :

     // Allow: backspace, delete, tab, escape, enter, ctrl+A and .
    if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
         // Allow: Ctrl+A
        (e.keyCode == 65 && e.ctrlKey === true) || 
         // Allow: home, end, left, right
        (e.keyCode >= 35 && e.keyCode <= 39)) {
             // let it happen, don't do anything
             return;
    }

    var charValue = String.fromCharCode(e.keyCode)
        , valid = /^[0-9]+$/.test(charValue);

    if (!valid) {
        e.preventDefault();
    }

Using filesystem in node.js with async / await

You can use the simple and lightweight module https://github.com/nacholibre/nwc-l it supports both async and sync methods.

Note: this module was created by me.

matplotlib: colorbars and its text labels

To add to tacaswell's answer, the colorbar() function has an optional cax input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable

fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')

cax.set_xlabel('data label')  # cax == cb.ax

Android: How to get a custom View's height and width?

I was also lost around getMeasuredWidth() and getMeasuredHeight() getHeight() and getWidth() for a long time.......... later i found onSizeChanged() method to be REALLY helpful.

New Blog Post: how to get width and height dimensions of a customView (extends View) in Android http://syedrakibalhasan.blogspot.com/2011/02/how-to-get-width-and-height-dimensions.html

How to set page content to the middle of screen?

If you want to center the content horizontally and vertically, but don't know in prior how high your page will be, you have to you use JavaScript.

HTML:

<body>
    <div id="content">...</div>
</body>

CSS:

#content {
    max-width: 1000px;
    margin: auto;
    left: 1%;
    right: 1%;
    position: absolute;
}

JavaScript (using jQuery):

$(function() {
    $(window).on('resize', function resize()  {
        $(window).off('resize', resize);
        setTimeout(function () {
            var content = $('#content');
            var top = (window.innerHeight - content.height()) / 2;
            content.css('top', Math.max(0, top) + 'px');
            $(window).on('resize', resize);
        }, 50);
    }).resize();
});

Centered horizontally and vertically

Demo: http://jsfiddle.net/nBzcb/

How do I resolve a TesseractNotFoundError?

You are probably missing tesseract-ocr from your machine. Check the installation instructions here: https://github.com/tesseract-ocr/tesseract/wiki

On a Mac, you can just install using homebrew:

brew install tesseract

It should run fine after that

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

I have resolved it by adding below line in my context:

modelBuilder.Entity<YourObject>().Property(e => e.YourColumn).HasMaxLength(4000);

Somehow, [MaxLength] didn't work for me.

How do you properly determine the current script directory?

Hopefully this helps:- If you run a script/module from anywhere you'll be able to access the __file__ variable which is a module variable representing the location of the script.

On the other hand, if you're using the interpreter you don't have access to that variable, where you'll get a name NameError and os.getcwd() will give you the incorrect directory if you're running the file from somewhere else.

This solution should give you what you're looking for in all cases:

from inspect import getsourcefile
from os.path import abspath
abspath(getsourcefile(lambda:0))

I haven't thoroughly tested it but it solved my problem.

MySQL match() against() - order by relevance and column?

Just adding for who might need.. Don't forget to alter the table!

ALTER TABLE table_name ADD FULLTEXT(column_name);

Create list or arrays in Windows Batch

Array type does not exist

There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.

Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.

  • As for echoing to a file echo variable >> filepath works for echoing the contents of a variable to a file,
  • and echo. (the period is not a typo) works for echoing a newline character.

I think that these two together should work to accomplish what you need.

Further reading

How to pass a function as a parameter in Java?

I used the command pattern that @jk. mentioned, adding a return type:

public interface Callable<I, O> {

    public O call(I input);   
}

Get unique values from a list in python

set - unordered collection of unique elements. List of elements can be passed to set's constructor. So, pass list with duplicate elements, we get set with unique elements and transform it back to list then get list with unique elements. I can say nothing about performance and memory overhead, but I hope, it's not so important with small lists.

list(set(my_not_unique_list))

Simply and short.

Running multiple async tasks and waiting for them all to complete

This is how I do it with an array Func<>:

var tasks = new Func<Task>[]
{
   () => myAsyncWork1(),
   () => myAsyncWork2(),
   () => myAsyncWork3()
};

await Task.WhenAll(tasks.Select(task => task()).ToArray()); //Async    
Task.WaitAll(tasks.Select(task => task()).ToArray()); //Or use WaitAll for Sync

Measuring function execution time in R

You can use MATLAB-style tic-toc functions, if you prefer. See this other SO question

Stopwatch function in R

How to add a changed file to an older (not last) commit in Git

Use git rebase. Specifically:

  1. Use git stash to store the changes you want to add.
  2. Use git rebase -i HEAD~10 (or however many commits back you want to see).
  3. Mark the commit in question (a0865...) for edit by changing the word pick at the start of the line into edit. Don't delete the other lines as that would delete the commits.[^vimnote]
  4. Save the rebase file, and git will drop back to the shell and wait for you to fix that commit.
  5. Pop the stash by using git stash pop
  6. Add your file with git add <file>.
  7. Amend the commit with git commit --amend --no-edit.
  8. Do a git rebase --continue which will rewrite the rest of your commits against the new one.
  9. Repeat from step 2 onwards if you have marked more than one commit for edit.

[^vimnote]: If you are using vim then you will have to hit the Insert key to edit, then Esc and type in :wq to save the file, quit the editor, and apply the changes. Alternatively, you can configure a user-friendly git commit editor with git config --global core.editor "nano".

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

The warning comes up because Tomcat scans all Jars for TLDs (Tagging Library Definitions).

Step1: To see which JARs are throwing up this warning, insert he following line to tomcat/conf/logging.properties

org.apache.jasper.servlet.TldScanner.level = FINE

Now you should be able to see warnings with a detail of which JARs are causing the intial warning

Step2 Since skipping unneeded JARs during scanning can improve startup time and JSP compilation time, we will skip un-needed JARS in the catalina.properties file. You have two options here -

  1. List all the JARs under the tomcat.util.scan.StandardJarScanFilter.jarsToSkip. But this can get cumbersome if you have a lot jars or if the jars keep changing.
  2. Alternatively, Insert tomcat.util.scan.StandardJarScanFilter.jarsToSkip=* to skip all the jars

You should now not see the above warnings and if you have a considerably large application, it should save you significant time in deploying an application.

Note: Tested in Tomcat8

check if array is empty (vba excel)

@jeminar has the best solution above.

I cleaned it up a bit though.

I recommend adding this to a FunctionsArray module

  • isInitialised=false is not needed because Booleans are false when created
  • On Error GoTo 0 wrap and indent code inside error blocks similar to with blocks for visibility. these methods should be avoided as much as possible but ... VBA ...
Function isInitialised(ByRef a() As Variant) As Boolean
    On Error Resume Next
    isInitialised = IsNumeric(UBound(a))
    On Error GoTo 0
End Function

How do you revert to a specific tag in Git?

Use git reset:

git reset --hard "Version 1.0 Revision 1.5"

(assuming that the specified string is the tag).

jQuery ajax error function

From jquery.com:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete()
callback methods introduced injQuery 1.5 are deprecated
as of jQuery 1.8. To prepare your code for their eventual 
removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

If you want global handlers you can use:

.ajaxStart(), .ajaxStop(),
.ajaxComplete(), .ajaxError(),
.ajaxSuccess(), .ajaxSend()

Check which element has been clicked with jQuery

Another option can be to utilize the tagName property of the e.target. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
  }
});

How to set image in imageview in android?

1> You can add image from layout itself:

<ImageView
                android:id="@+id/iv_your_image"
                android:layout_width="wrap_content"
                android:layout_height="25dp"
                android:background="@mipmap/your_image"
                android:padding="2dp" />

OR

2> Programmatically in java class:

ImageView ivYouImage= (ImageView)findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

OR for fragments:

View rowView= inflater.inflate(R.layout.your_layout, null, true);

ImageView ivYouImage= (ImageView) rowView.findViewById(R.id.iv_your_image);
        ivYouImage.setImageResource(R.mipmap.ic_changeImage);

MySQl Error #1064

maybe you forgot to add ";" after this line of code:

`quantity` INT NOT NULL)

Bootstrap: change background color

You could hard code it.

<div class="col-md-6" style="background-color:blue;">
</div>

<div class="col-md-6" style="background-color:white;">
</div>

Seaborn Barplot - Displaying Values

A simple way to do so is to add the below code (for Seaborn):

for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points') 

Example :

splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')    
plt.show()

JTable won't show column headers

The main difference between this answer and the accepted answer is the use of setViewportView() instead of add().

How to put JTable in JScrollPane using Eclipse IDE:

  1. Create JScrollPane container via Design tab.
  2. Stretch JScrollPane to desired size (applies to Absolute Layout).
  3. Drag and drop JTable component on top of JScrollPane (Viewport area).

In Structure > Components, table should be a child of scrollPane. enter image description here

The generated code would be something like this:

JScrollPane scrollPane = new JScrollPane();
...

JTable table = new JTable();
scrollPane.setViewportView(table);

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

how to run mysql in ubuntu through terminal

You seem to just have begun using mysql.

Simple answer: for now use

mysql -u root -p password

Password is usually root by default. You may use other usernames if you have created other user using create user in mysql. For details use "help, help manage accounts, help create users" etc. If you dont want your password to be shown in open just press return key after "-p" and you will be prompted for password next. Hope this resolves the issue.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

How stable is the git plugin for eclipse?

You can integrate Git-GUI with Eclipse as an alternative to EGit.

See this two part YouTube tutorial specific to Windows:
http://www.youtube.com/watch?v=DcM1xOiaidk
http://www.youtube.com/watch?v=1OrPJClD92s

Implementing IDisposable correctly

First of all, you don't need to "clean up" strings and ints - they will be taken care of automatically by the garbage collector. The only thing that needs to be cleaned up in Dispose are unmanaged resources or managed recources that implement IDisposable.

However, assuming this is just a learning exercise, the recommended way to implement IDisposable is to add a "safety catch" to ensure that any resources aren't disposed of twice:

public void Dispose()
{
    Dispose(true);

    // Use SupressFinalize in case a subclass 
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);   
}
protected virtual void Dispose(bool disposing)
{
    if (!_disposed)
    {
        if (disposing) 
        {
            // Clear all property values that maybe have been set
            // when the class was instantiated
            id = 0;
            name = String.Empty;
            pass = String.Empty;
        }

        // Indicate that the instance has been disposed.
        _disposed = true;   
    }
}

zsh compinit: insecure directories

This fixed it for me:

$ sudo chmod -R 755 /usr/local/share/zsh/site-functions

Credit: a post on zsh mailing list


EDIT: As pointed out by @biocyberman in the comments. You may need to update the owner of site-functions as well:

$ sudo chown -R root:root /usr/local/share/zsh/site-functions

On my machine (OSX 10.9), I do not need to do this but YMMV.

EDIT2: On OSX 10.11, only this worked:

$ sudo chmod -R 755 /usr/local/share/zsh
$ sudo chown -R root:staff /usr/local/share/zsh

Also user:staff is the correct default permission on OSX.

How can I kill a process by name instead of PID?

You can kill processes by name with killall <name>

killall sends a signal to all processes running any of the specified commands. If no signal name is specified, SIGTERM is sent.

Signals can be specified either by name (e.g. -HUP or -SIGHUP ) or by number (e.g. -1) or by option -s.

If the command name is not regular expression (option -r) and contains a slash (/), processes executing that particular file will be selected for killing, independent of their name.

But if you don't see the process with ps aux, you probably won't have the right to kill it ...

Replace missing values with column mean

# Lets say I have a dataframe , df as following -
df <- data.frame(a=c(2,3,4,NA,5,NA),b=c(1,2,3,4,NA,NA))

# create a custom function
fillNAwithMean <- function(x){
    na_index <- which(is.na(x))        
    mean_x <- mean(x, na.rm=T)
    x[na_index] <- mean_x
    return(x)
}

(df <- apply(df,2,fillNAwithMean))
   a   b
2.0 1.0
3.0 2.0
4.0 3.0
3.5 4.0
5.0 2.5
3.5 2.5

Can I execute a function after setState is finished updating?

when new props or states being received (like you call setState here), React will invoked some functions, which are called componentWillUpdate and componentDidUpdate

in your case, just simply add a componentDidUpdate function to call this.drawGrid()

here is working code in JS Bin

as I mentioned, in the code, componentDidUpdate will be invoked after this.setState(...)

then componentDidUpdate inside is going to call this.drawGrid()

read more about component Lifecycle in React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate

jquery can't get data attribute value

Use plain javascript methods

$x10Device = this.dataset("x10");

Avoid line break between html elements

In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:

_x000D_
_x000D_
.wrapper{_x000D_
  width: 290px;   _x000D_
  white-space: no-wrap;_x000D_
  resize:both;_x000D_
  overflow:auto; _x000D_
  border: 1px solid gray;_x000D_
}_x000D_
_x000D_
.breakable-text{_x000D_
  display: inline;_x000D_
  white-space: no-wrap;_x000D_
}_x000D_
_x000D_
.no-break-before {_x000D_
  padding-left: 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>&#8205;<span class="no-break-before">TOGETHER</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
else
  echo "Intalled"
fi

How to use Google fonts in React.js?

In some cases your font resource maybe somewhere in your project directory. So you can load it like this using SCSS

 $list: (
      "Black",
      "BlackItalic",
      "Bold",
      "BoldItalic",
      "Italic",
      "Light",
      "LightItalic",
      "Medium",
      "MediumItalic",
      "Regular",
      "Thin",
      "ThinItalic"
    );
    
    @mixin setRobotoFonts {
      @each $var in $list {
        @font-face {
          font-family: "Roboto-#{$var}";
          src: url("../fonts/Roboto-#{$var}.ttf") format("ttf");
        }
      }
    }
@include setRobotoFonts();

Determine if string is in list in JavaScript

RegExp is universal, but I understand that you're working with arrays. So, check out this approach. I use to use it, and it's very effective and blazing fast!

var str = 'some string with a';
var list = ['a', 'b', 'c'];
var rx = new RegExp(list.join('|'));

rx.test(str);

You can also apply some modifications, i.e.:

One-liner

new RegExp(list.join('|')).test(str);

Case insensitive

var rx = new RegExp(list.join('|').concat('/i'));


And many others!

could not access the package manager. is the system running while installing android application

Once you see this error, wait for emulator to show lock screen. And then relaunch the app in your IDE and check the emulator again. It works for me always.

In Android studio, you can relaunch by clicking the green play button or ctrl + r.

Keyboard shortcut to comment lines in Sublime Text 2

By default on Linux/Windows for an English keyboard the shortcut is Ctrl+Shift+/ to toggle a block comment, and Ctrl+/ to toggle a line comment.

If you go into Preferences->Key Bindings - Default, you can find all the shortcuts, below are the lines for commenting.

{ "keys": ["ctrl+/"], "command": "toggle_comment", "args": { "block": false } },
{ "keys": ["ctrl+shift+/"], "command": "toggle_comment", "args": { "block": true } },

Is there a way to access an iteration-counter in Java's for-each loop?

The easiest solution is to just run your own counter thus:

int i = 0;
for (String s : stringArray) {
    doSomethingWith(s, i);
    i++;
}

The reason for this is because there's no actual guarantee that items in a collection (which that variant of for iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).

See for example, the following code:

import java.util.*;

public class TestApp {
  public static void AddAndDump(AbstractSet<String> set, String str) {
    System.out.println("Adding [" + str + "]");
    set.add(str);
    int i = 0;
    for(String s : set) {
        System.out.println("   " + i + ": " + s);
        i++;
    }
  }

  public static void main(String[] args) {
    AbstractSet<String> coll = new HashSet<String>();
    AddAndDump(coll, "Hello");
    AddAndDump(coll, "My");
    AddAndDump(coll, "Name");
    AddAndDump(coll, "Is");
    AddAndDump(coll, "Pax");
  }
}

When you run that, you can see something like:

Adding [Hello]
   0: Hello
Adding [My]
   0: Hello
   1: My
Adding [Name]
   0: Hello
   1: My
   2: Name
Adding [Is]
   0: Hello
   1: Is
   2: My
   3: Name
Adding [Pax]
   0: Hello
   1: Pax
   2: Is
   3: My
   4: Name

indicating that, rightly so, order is not considered a salient feature of a set.

There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.

How can I delete derived data in Xcode 8?

I've created a bash command. Configure it with 3 simple steps. then in the terminal just type cleandd https://github.com/Salarsoleimani/Usefulscripts

What are the benefits of learning Vim?

Personally,

I find many of these terminal text editors incapable at times. Would I invest time picking one up? Absolutely! I would continue to learning one along side a IDE. Of course in the end, it really comes down to preference.

Pull new updates from original GitHub repository into forked GitHub repository

This video shows how to update a fork directly from GitHub

Steps:

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.
  4. Click on switching the base. Now GitHub will compare your fork with the original, and you should see all the latest changes.
  5. Click on Create a pull request for this comparison and assign a predictable name to your pull request (e.g., Update from original).
  6. Click on Create pull request.
  7. Scroll down and click Merge pull request and finally Confirm merge. If your fork didn’t have any changes, you will be able to merge it automatically.

restrict edittext to single line

You must add this line in your EditText

android:maxLines="1"

and another thing, don't forget set android:inputType (whatever you want, text, phone .., but you must set it)

Error - "UNION operator must have an equal number of expressions" when using CTE for recursive selection

The problem lays here:

--This result set has 3 columns
select LOC_id,LOC_locatie,LOC_deelVan_LOC_id from tblLocatie t
where t.LOC_id = 1 -- 1 represents an example

union all

--This result set has 1 columns   
select t.LOC_locatie + '>' from tblLocatie t
inner join q parent on parent.LOC_id = t.LOC_deelVan_LOC_id

In order to use union or union all number of columns and their types should be identical cross all result sets.

I guess you should just add the column LOC_deelVan_LOC_id to your second result set

How to add 20 minutes to a current date?

you have a lot of answers in the post

var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );

Windows 7 environment variable not working in path

If the PATH value would be too long after your user's PATH variable has been concatenated onto the environment PATH variable, Windows will silently fail to concatenate the user PATH variable.

This can easily happen after new software is installed and adds something to PATH, thereby breaking existing installed software. Windows fail!

The best fix is to edit one of the PATH variables in the Control Panel and remove entries you don't need. Then open a new CMD window and see if all entries are shown in "echo %PATH%".

How to create a sub array from another array in Java?

int newArrayLength = 30; 

int[] newArray = new int[newArrayLength];

System.arrayCopy(oldArray, 0, newArray, 0, newArray.length);