Programs & Examples On #Fixture

How to resolve the error on 'react-native start'

All mentioned comments above are great, sharing the path that worked with me for this Blacklist file that need to be edited:

"Your project name\node_modules\metro-bundler\src" File name "blacklist.js"

What are the "spec.ts" files generated by Angular CLI for?

The spec files are unit tests for your source files. The convention for Angular applications is to have a .spec.ts file for each .ts file. They are run using the Jasmine javascript test framework through the Karma test runner (https://karma-runner.github.io/) when you use the ng test command.

You can use this for some further reading:

https://angular.io/guide/testing

How can I pass variable to ansible playbook in the command line?

ansible-playbok -i <inventory> <playbook-name> -e "proc_name=sshd"

You can use the above command in below playbooks.

---
- name: Service Status
gather_facts: False
tasks:
- name: Check Service Status (Linux)
shell: pgrep "{{ proc_name }}"
register: service_status
ignore_errors: yes
debug: var=service_status.rc`

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

For Spring 5.2+ this works for me:

@PostMapping("/foo")
ResponseEntity<Void> foo(@PathVariable UUID fooId) {
    return fooService.findExam(fooId)
            .map(uri -> ResponseEntity.noContent().<Void>build())
            .orElse(ResponseEntity.notFound().build());
}

Django: OperationalError No Such Table

I'm using Django CMS 3.4 with Django 1.8. I stepped through the root cause in the Django CMS code. Root cause is the Django CMS is not changing directory to the directory with file containing the SQLite3 database before making database calls. The error message is spurious. The underlying problem is that a SQLite database call is made in the wrong directory.

The workaround is to ensure all your Django applications change directory back to the Django Project root directory when changing to working directories.

laravel compact() and ->with()

Route::get('/', function () {
    return view('greeting', ['name' => 'James']);
});
<html>
    <body>
        <h1>Hello, {{ $name }}</h1>
    </body>
</html>

or

public function index($id)
{
    $category = Category::find($id);
    $topics = $category->getTopicPaginator();
    $message = Message::find(1);

    // here I would just use "->with([$category, $topics, $message])"
    return View::make('category.index')->with(compact('category', 'topics', 'message'));
}

Running Composer returns: "Could not open input file: composer.phar"

Command like this :

composer.phar require intervention/image

error: composer.phar: command not found

I solved the problem by following this process

i set the composer globally and renamed composer.phar to composer then run this command composer require intervention/image . and now it's working fine

How to update a single library with Composer?

Difference between install, update and require

Assume the following scenario:

composer.json

"parsecsv/php-parsecsv": "0.*"

composer.lock file

  "name": "parsecsv/php-parsecsv",
            "version": "0.1.4",

Latest release is 1.1.0. The latest 0.* release is 0.3.2

install: composer install parsecsv/php-parsecsv

This will install version 0.1.4 as specified in the lock file

update: composer update parsecsv/php-parsecsv

This will update the package to 0.3.2. The highest version with respect to your composer.json. The entry in composer.lock will be updated.

require: composer require parsecsv/php-parsecsv

This will update or install the newest version 1.1.0. Your composer.lock file and composer.json file will be updated as well.

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

Maven Java EE Configuration Marker with Java Server Faces 1.2

I had a similar problem. I was working on a project where I did not control the web.xml configuration file, so I could not use the changes suggested about altering the version. Of course the project was not using JSF so this was especially annoying for me.

I found that there is a really simple fix. Go to Preferences > Maven > Java EE Itegration and uncheck the "JSF Configurator" box.

I did this in a fresh workspace before importing the project again, but it may work equally as well on an existing project ... not sure.

Android, How to limit width of TextView (and add three dots at the end of text)?

Simple for three dots

android:layout_width="100dp" <!--your dp or match_parent or 0dp>
android:maxLines="2" <!--count your line>
android:ellipsize="end"

how to remove untracked files in Git?

While git clean works well, I still find it useful to use my own script to clean the git repo, it has some advantages.

This shows a list of files to be cleaned, then interactively prompts to clean or not. This is nearly always what I want since interactively prompting per file gets tedious.

It also allows manual filtering of the list which comes in handy when there are file types you don't want to clean (and have reason not to commit).


git_clean.sh


#!/bin/bash
readarray -t -d '' FILES < <(
    git ls-files -z --other --directory |
        grep --null-data --null -v '.bin$\|Cargo.lock$'
)
if [ "$FILES" = "" ]; then
    echo  "Nothing to clean!"
    exit 0
fi

echo "Dirty files:"
printf '  %s\n' "${FILES[@]}"

DO_REMOVE=0
while true; do
    echo ""
    read -p "Remove ${#FILES[@]} files? [y/n]: " choice
    case "$choice" in
        y|Y )
            DO_REMOVE=1
            break ;;
        n|N )
            echo "Exiting!"
            break ;;
        * ) echo "Invalid input, expected [Y/y/N/n]"
            continue ;;
    esac
done

if [ "$DO_REMOVE" -eq 1 ];then
    echo "Removing!"
    for f in "${FILES[@]}"; do
       rm -rfv "$f"
    done
fi

How to output in CLI during execution of PHP Unit tests?

I output my Testresults HTML based, in this case it was helpfull to flush the content:

var_dump($array);
ob_flush();

There is a second PHP Method

flush() 

which i not has tried.

Automatic HTTPS connection/redirect with node.js/express

With Nginx you can take advantage of the "x-forwarded-proto" header:

function ensureSec(req, res, next){
    if (req.headers["x-forwarded-proto"] === "https"){
       return next();
    }
    res.redirect("https://" + req.headers.host + req.url);  
}

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

Updating since these answers are slightly outdated (although some still apply).

Simple feature added in rails 2.3.4, db/seeds.rb

Provides a new rake task

rake db:seed

Good for populating common static records like states, countries, etc...

http://railscasts.com/episodes/179-seed-data

*Note that you can use fixtures if you had already created them to also populate with the db:seed task by putting the following in your seeds.rb file (from the railscast episode):

require 'active_record/fixtures'
Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "operating_systems")

For Rails 3.x use 'ActiveRecord::Fixtures' instead of 'Fixtures' constant

require 'active_record/fixtures'
ActiveRecord::Fixtures.create_fixtures("#{Rails.root}/test/fixtures", "fixtures_file_name")

Could not load type from assembly error

I experienced the same as above after removing signing of assemblies in the solution. The projects would not build.

I found that one of the projects referenced the StrongNamer NuGet package, which modifies the build process and tries to sign non-signed Nuget packages.

After removing the StrongNamer package I was able to build the project again without signing/strong-naming the assemblies.

adding child nodes in treeview

Guys use this code for adding nodes and childnodes for TreeView from C# code. *

KISS (Keep It Simple & Stupid :)*

protected void Button1_Click(object sender, EventArgs e)

{

        TreeNode a1 = new TreeNode("Apple");

        TreeNode b1 = new TreeNode("Banana");
        TreeNode a2 = new TreeNode("gree apple");
        TreeView2.Nodes.Add(a1);
        TreeView2.Nodes.Add(b1);
        a1.ChildNodes.Add(a2);

}

ComboBox: Adding Text and Value to an Item (no Binding Source)

This is one of the ways that just came to mind:

combo1.Items.Add(new ListItem("Text", "Value"))

And to change text of or value of an item, you can do it like this:

combo1.Items[0].Text = 'new Text';

combo1.Items[0].Value = 'new Value';

There is no class called ListItem in Windows Forms. It only exists in ASP.NET, so you will need to write your own class before using it, the same as @Adam Markowitz did in his answer.

Also check these pages, they may help:

How to discover number of *logical* cores on Mac OS X?

On a MacBook Pro running Mavericks, sysctl -a | grep hw.cpu will only return some cryptic details. Much more detailed and accessible information is revealed in the machdep.cpu section, ie:

sysctl -a | grep machdep.cpu

In particular, for processors with HyperThreading (HT), you'll see the total enumerated CPU count (logical_per_package) as double that of the physical core count (cores_per_package).

sysctl -a | grep machdep.cpu  | grep per_package

mysqli_select_db() expects parameter 1 to be mysqli, string given

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error($connection));
}

You got the order of the arguments to mysqli_select_db() backwards. And mysqli_error() requires you to provide a connection argument. mysqli_XXX is not like mysql_XXX, these arguments are no longer optional.

Note also that with mysqli you can specify the DB in mysqli_connect():

$connection = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$connection) {
  die("Database connection failed: " . mysqli_connect_error();
}

You must use mysqli_connect_error(), not mysqli_error(), to get the error from mysqli_connect(), since the latter requires you to supply a valid connection.

Is there a way to catch the back button event in javascript?

I did a fun hack to solve this issue to my satisfaction. I've got an AJAX site that loads content dynamically, then modifies the window.location.hash, and I had code to run upon $(document).ready() to parse the hash and load the appropriate section. The thing is that I was perfectly happy with my section loading code for navigation, but wanted to add a way to intercept the browser back and forward buttons, which change the window location, but not interfere with my current page loading routines where I manipulate the window.location, and polling the window.location at constant intervals was out of the question.

What I ended up doing was creating an object as such:

var pageload = {
    ignorehashchange: false,
    loadUrl: function(){
        if (pageload.ignorehashchange == false){
            //code to parse window.location.hash and load content
        };
    }
};

Then, I added a line to my site script to run the pageload.loadUrl function upon the hashchange event, as such:

window.addEventListener("hashchange", pageload.loadUrl, false);

Then, any time I want to modify the window.location.hash without triggering this page loading routine, I simply add the following line before each window.location.hash = line:

pageload.ignorehashchange = true;

and then the following line after each hash modification line:

setTimeout(function(){pageload.ignorehashchange = false;}, 100);

So now my section loading routines are usually running, but if the user hits the 'back' or 'forward' buttons, the new location is parsed and the appropriate section loaded.

Adding up BigDecimals using Streams

Use this approach to sum the list of BigDecimal:

List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce((x, y) -> x.add(y)).get();

This approach maps each BigDecimal as a BigDecimal only and reduces them by summing them, which is then returned using the get() method.

Here's another simple way to do the same summing:

List<BigDecimal> values = ... // List of BigDecimal objects
BigDecimal sum = values.stream().reduce(BigDecimal::add).get();

Update

If I were to write the class and lambda expression in the edited question, I would have written it as follows:

import java.math.BigDecimal;
import java.util.LinkedList;

public class Demo
{
  public static void main(String[] args)
  {
    LinkedList<Invoice> invoices = new LinkedList<>();
    invoices.add(new Invoice("C1", "I-001", BigDecimal.valueOf(.1), BigDecimal.valueOf(10)));
    invoices.add(new Invoice("C2", "I-002", BigDecimal.valueOf(.7), BigDecimal.valueOf(13)));
    invoices.add(new Invoice("C3", "I-003", BigDecimal.valueOf(2.3), BigDecimal.valueOf(8)));
    invoices.add(new Invoice("C4", "I-004", BigDecimal.valueOf(1.2), BigDecimal.valueOf(7)));

    // Java 8 approach, using Method Reference for mapping purposes.
    invoices.stream().map(Invoice::total).forEach(System.out::println);
    System.out.println("Sum = " + invoices.stream().map(Invoice::total).reduce((x, y) -> x.add(y)).get());
  }

  // This is just my style of writing classes. Yours can differ.
  static class Invoice
  {
    private String company;
    private String number;
    private BigDecimal unitPrice;
    private BigDecimal quantity;

    public Invoice()
    {
      unitPrice = quantity = BigDecimal.ZERO;
    }

    public Invoice(String company, String number, BigDecimal unitPrice, BigDecimal quantity)
    {
      setCompany(company);
      setNumber(number);
      setUnitPrice(unitPrice);
      setQuantity(quantity);
    }

    public BigDecimal total()
    {
      return unitPrice.multiply(quantity);
    }

    public String getCompany()
    {
      return company;
    }

    public void setCompany(String company)
    {
      this.company = company;
    }

    public String getNumber()
    {
      return number;
    }

    public void setNumber(String number)
    {
      this.number = number;
    }

    public BigDecimal getUnitPrice()
    {
      return unitPrice;
    }

    public void setUnitPrice(BigDecimal unitPrice)
    {
      this.unitPrice = unitPrice;
    }

    public BigDecimal getQuantity()
    {
      return quantity;
    }

    public void setQuantity(BigDecimal quantity)
    {
      this.quantity = quantity;
    }
  }
}

How do I set up DNS for an apex domain (no www) pointing to a Heroku app?

(Note: root, base, apex domains are all the same thing. Using interchangeably for google-foo.)

Traditionally, to point your apex domain you'd use an A record pointing to your server's IP. This solution doesn't scale and isn't viable for a cloud platform like Heroku, where multiple and frequently changing backends are responsible for responding to requests.

For subdomains (like www.example.com) you can use CNAME records pointing to your-app-name.herokuapp.com. From there on, Heroku manages the dynamic A records behind your-app-name.herokuapp.com so that they're always up-to-date. Unfortunately, the DNS specification does not allow CNAME records on the zone apex (the base domain). (For example, MX records would break as the CNAME would be followed to its target first.)

Back to root domains, the simple and generic solution is to not use them at all. As a fallback measure, some DNS providers offer to setup an HTTP redirect for you. In that case, set it up so that example.com is an HTTP redirect to www.example.com.

Some DNS providers have come forward with custom solutions that allow CNAME-like behavior on the zone apex. To my knowledge, we have DNSimple's ALIAS record and DNS Made Easy's ANAME record; both behave similarly.

Using those, you could setup your records as (using zonefile notation, even tho you'll probably do this on their web user interface):

@   IN ALIAS your-app-name.herokuapp.com.
www IN CNAME your-app-name.herokuapp.com.

Remember @ here is a shorthand for the root domain (example.com). Also mind you that the trailing dots are important, both in zonefiles, and some web user interfaces.

See also:

Remarks:

  • Amazon's Route 53 also has an ALIAS record type, but it's somewhat limited, in that it only works to point within AWS. At the moment I would not recommend using this for a Heroku setup.

  • Some people confuse DNS providers with domain name registrars, as there's a bit of overlap with companies offering both. Mind you that to switch your DNS over to one of the aforementioned providers, you only need to update your nameserver records with your current domain registrar. You do not need to transfer your domain registration.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

How do I check (at runtime) if one class is a subclass of another?

#issubclass(child,parent)

class a:
    pass
class b(a):
    pass
class c(b):
    pass

print(issubclass(c,b))#it returns true

How to get base url with jquery or javascript?

I've run into this need on several Joomla project. The simplest way I've found to address is to add a hidden input field to my template:

<input type="hidden" id="baseurl" name="baseurl" value="<?php echo $this->baseurl; ?>" />

When I need the value in JavaScript:

var baseurl = document.getElementById('baseurl').value;

Not as fancy as using pure JavaScript but simple and gets the job done.

How to copy selected files from Android with adb pull

Pull multiple files using regex:

Create pullFiles.sh:

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION=".jpg"

for file in $(adb shell ls $DEVICE_DIR | grep $EXTENSION'$')
do
    file=$(echo -e $file | tr -d "\r\n"); # EOL fix
    adb pull $DEVICE_DIR/$file $HOST_DIR/$file;
done

Run it:

Make it executable: chmod +x pullFiles.sh

Run it: ./pullFiles.sh

Notes:

  • as is, won't work when filenames have spaces
  • includes a fix for end-of-line (EOL) on Android, which is a "\r\n"

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of <, the XML parser is implicitly looking for the tag name and the end tag >. However, in your particular case, you were using < as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The content of elements must consist of well-formed character data or markup.

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The < must be escaped as &lt;.

So, essentially, the

for (var i = 0; i < length; i++) {

must become

for (var i = 0; i &lt; length; i++) {

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="functions.js" target="head" />

This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.

See also:

add Shadow on UIView using swift 3

I will suggest you to use below the library because it allows you to set default values in one file and you can use it everywhere in the project without making one line of change. https://github.com/Shahbaz89khan/ShadowView

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!

SELECT list is not in GROUP BY clause and contains nonaggregated column

country.code is not in your group by statement, and is not an aggregate (wrapped in an aggregate function).

https://www.w3schools.com/sql/sql_ref_sqlserver.asp

How do I kill all the processes in Mysql "show processlist"?

Sometimes I have some zombies mysql processes that can't be killed (using MAMP Pro).

First get a list of all mysql processes:

ps -ax | grep mysql

Next kill every one of them with (replace processId with the first column in previous command result):

kill -9 processId

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Declare password like DB_PASSWORD="2o0@#5TGR1NG" in .env file

If # sign include in your password then password will declare in between " ".

How to select all rows which have same value in some column

You can do this without a JOIN:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

Demo: SQL Fiddle

Access cell value of datatable

string abc= dt.Rows[0]["column name"].ToString();

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

Visual Studio Code open tab in new window

If you are using the excellent

VSCode for Mac, 2020

simply tap Apple-Shift-N (as in "new window")

Drag whatever you want there.

Slack URL to open a channel from browser

You can use

slack://

in order to open the Slack desktop application. For example, on mac, I've run:

open slack://

from the terminal and it opens the Mac desktop Slack application. Still, I didn't figure out the URL that should be used for opening a certain team, channel or message.

How do you change the size of figures drawn with matplotlib?

This resizes the figure immediately even after the figure has been drawn (at least using Qt4Agg/TkAgg - but not MacOSX - with matplotlib 1.4.0):

matplotlib.pyplot.get_current_fig_manager().resize(width_px, height_px)

Auto-size dynamic text to fill fixed size container

I didn't find any of the previous solutions to be adequate enough due to bad performance, so I made my own that uses simple math instead of looping. Should work fine in all browsers as well.

According to this performance test case it is much faster then the other solutions found here.

(function($) {
    $.fn.textfill = function(maxFontSize) {
        maxFontSize = parseInt(maxFontSize, 10);
        return this.each(function(){
            var ourText = $("span", this),
                parent = ourText.parent(),
                maxHeight = parent.height(),
                maxWidth = parent.width(),
                fontSize = parseInt(ourText.css("fontSize"), 10),
                multiplier = maxWidth/ourText.width(),
                newSize = (fontSize*(multiplier-0.1));
            ourText.css(
                "fontSize", 
                (maxFontSize > 0 && newSize > maxFontSize) ? 
                    maxFontSize : 
                    newSize
            );
        });
    };
})(jQuery);

If you want to contribute I've added this to Gist.

Combining the results of two SQL queries as separate columns

how to club the 4 query's as a single query

show below query

  1. total number of cases pending + 2.cases filed during this month ( base on sysdate) + total number of cases (1+2) + no. cases disposed where nse= disposed + no. of cases pending (other than nse <> disposed)

nsc = nature of case

report is taken on 06th of every month

( monthly report will be counted from 05th previous month to 05th present of present month)

Change name of folder when cloning from GitHub?

git clone <Repo> <DestinationDirectory>

Clone the repository located at Repo into the folder called DestinationDirectory on the local machine.

javascript date + 7 days

_x000D_
_x000D_
var future = new Date(); // get today date_x000D_
future.setDate(future.getDate() + 7); // add 7 days_x000D_
var finalDate = future.getFullYear() +'-'+ ((future.getMonth() + 1) < 10 ? '0' : '') + (future.getMonth() + 1) +'-'+ future.getDate();_x000D_
console.log(finalDate);
_x000D_
_x000D_
_x000D_

Function that creates a timestamp in c#

You can also use

Stopwatch.GetTimestamp().ToString();

VBA Copy Sheet to End of Workbook (with Hidden Worksheets)

When you want to copy a sheet named "mySheet" and use .Copy After:=, Excel first names the copied sheet exactly the same and simply adds ' (2)' so that its final name is "mySheet (2)".

Hidden or Not, doesn't matter. It rocks with 2 lines of code, adding the copied sheet at the end of the Workbook!!!

Example:

Sheets("mySheet").Copy After:=Sheets(ThisWorkbook.Sheets.count)
Sheets("mySheet (2)").name = "TheNameYouWant"

Simple no!

CSS Box Shadow - Top and Bottom Only

After some experimentation I found that a fourth value in the line controls the spread (at least in FF 10). I opposed the vertical offsets and gave them a negative spread.

Here's the working pen: http://codepen.io/gillytech/pen/dlbsx

<html>
<head>
<style type="text/css">

#test {
    width: 500px;
    border: 1px  #CCC solid;
    height: 200px;

    box-shadow: 
        inset 0px 11px 8px -10px #CCC,
        inset 0px -11px 8px -10px #CCC; 
}
</style>
</head>
<body>
    <div id="test"></div>
</body>
</html>

This works perfectly for me!

How to compare two dates in php

benchmark comparison date_create, strtotime, DateTime, and direct

direct is faster

$f1="2014-12-12";
$f2="2014-12-13";
$diff=false;


$this->bench('a');
for ($i=0; $i < 20000; $i++) { 
    $date1=date_create($f1);
    $date2=date_create($f2);
    $diff=date_diff($date1,$date2);
}
$this->bench('a','b');
for ($i=0; $i < 20000; $i++) { 
     $date1=strtotime($f1);
     $date2=strtotime($f2);
     if ($date1>$date2) {
        $diff=true;
    }
}
$this->bench('b','c');
for ($i=0; $i < 20000; $i++) { 
    $date1 = new DateTime($f1);
    $date2 = new DateTime($f2);
    if ($date1>$date2) {
        $diff=true;
     }
}
$diff=false;
$this->bench('c','d');
for ($i=0; $i < 20000; $i++) { 
     if ($f1>$f2) {
        $diff=true;
     }
}
$this->bench('d','e');
var_dump($diff);

$this->dumpr($this->benchs);

results:

    [a] => 1610415241.4687
    [b] => 1610415242.8759
    [a-b] => 1.407194852829
    [c] => 1610415243.5672
    [b-c] => 0.69137716293335
    [d] => 1610415244.7036
    [c-d] => 1.1363649368286
    [e] => 1610415244.7109
    [d-e] => 0.0073208808898926

How to draw rounded rectangle in Android UI?

Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.

HTML image not showing in Gmail

You might have them turned off in your gmail settings, heres the link to change them https://support.google.com/mail/answer/145919?hl=en

Also gmail may be blocking the images thinking they are suspicious.

from the link above.

How Gmail makes images safe

Some senders try to use externally linked images in harmful ways, but Gmail takes action to ensure that images are loaded safely. Gmail serves all images through Google’s image proxy servers and transcodes them before delivery to protect you in the following ways:

Senders can’t use image loading to get information like your IP address or location. Senders can’t set or read cookies in your browser. Gmail checks your images for known viruses or malware. In some cases, senders may be able to know whether an individual has opened a message with unique image links. As always, Gmail scans every message for suspicious content and if Gmail considers a sender or message potentially suspicious, images won’t be displayed and you’ll be asked whether you want to see the images.

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

Just in case you want to handle the behaviour of the back button (at the bottom of the phone) and the home button (the one to the left of the action bar), this custom activity I'm using in my project may help you.

import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

/**
 * Activity where the home action bar button behaves like back by default
 */
public class BackActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setupHomeButton();
    }

    private void setupHomeButton() {
        final ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeButtonEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onMenuHomePressed();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    protected void onMenuHomePressed() {
        onBackPressed();
    }
}

Example of use in your activity:

public class SomeActivity extends BackActivity {

    // ....

    @Override
    public void onBackPressed()
    {
        // Example of logic
        if ( yourConditionToOverride ) {
            // ... do your logic ...
        } else {
            super.onBackPressed();
        }
    }    
}

How to programmatically modify WCF app.config endpoint address setting?

this short code worked for me:

Configuration wConfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ServiceModelSectionGroup wServiceSection = ServiceModelSectionGroup.GetSectionGroup(wConfig);

ClientSection wClientSection = wServiceSection.Client;
wClientSection.Endpoints[0].Address = <your address>;
wConfig.Save();

Of course you have to create the ServiceClient proxy AFTER the config has changed. You also need to reference the System.Configuration and System.ServiceModel assemblies to make this work.

Cheers

Web Reference vs. Service Reference

In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.

I find it better to use the Service Reference because it is new and will thus be better maintained.

how to select first N rows from a table in T-SQL?

Try this:

SELECT * FROM USERS LIMIT 10;

How to read a single character from the user?

This might be a use case for a context manager. Leaving aside allowances for Windows OS, here's my suggestion:

#!/usr/bin/env python3
# file: 'readchar.py'
"""
Implementation of a way to get a single character of input
without waiting for the user to hit <Enter>.
(OS is Linux, Ubuntu 14.04)
"""

import tty, sys, termios

class ReadChar():
    def __enter__(self):
        self.fd = sys.stdin.fileno()
        self.old_settings = termios.tcgetattr(self.fd)
        tty.setraw(sys.stdin.fileno())
        return sys.stdin.read(1)
    def __exit__(self, type, value, traceback):
        termios.tcsetattr(self.fd, termios.TCSADRAIN, self.old_settings)

def test():
    while True:
        with ReadChar() as rc:
            char = rc
        if ord(char) <= 32:
            print("You entered character with ordinal {}."\
                        .format(ord(char)))
        else:
            print("You entered character '{}'."\
                        .format(char))
        if char in "^C^D":
            sys.exit()

if __name__ == "__main__":
    test()

MYSQL import data from csv using LOAD DATA INFILE

You can load data from a csv or text file. If you have a text file with records from a table, you can load those records within the table. For example if you have a text file, where each row is a record with the values for each column, you can load the records this way.

table.sql

id //field 1

name //field2

table.txt

1,peter

2,daniel

...

--example on windows

LOAD DATA LOCAL INFILE 'C:\\directory_example\\table.txt'
INTO TABLE Table
CHARACTER SET UTF8
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'; 

Android Animation Alpha

<ImageView
    android:id="@+id/listViewIcon"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/settings"/>  

Remove android:alpha=0.2 from XML-> ImageView.

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

How to permanently export a variable in Linux?

You have to edit three files to set a permanent environment variable as follow:

  • ~/.bashrc

    When you open any terminal window this file will be run. Therefore, if you wish to have a permanent environment variable in all of your terminal windows you have to add the following line at the end of this file:

    export DISPLAY=0
    
  • ~/.profile

    Same as bashrc you have to put the mentioned command line at the end of this file to have your environment variable in every login of your OS.

  • /etc/environment

    If you want your environment variable in every window or application (not just terminal window) you have to edit this file. Add the following command at the end of this file:

    DISPLAY=0
    

    Note that in this file you do not have to write export command

Normally you have to restart your computer to apply these changes. But you can apply changes in bashrc and profile by these commands:

$ source ~/.bashrc
$ source ~/.profile

But for /etc/environment you have no choice but restarting (as far as I know)

A Simple Solution

I've written a simple script for these procedures to do all those work. You just have to set the name and value of your environment variable.

#!/bin/bash
echo "Enter variable name: "
read variable_name
echo "Enter variable value: "
read variable_value
echo "adding " $variable_name " to environment variables: " $variable_value
echo "export "$variable_name"="$variable_value>>~/.bashrc
echo $variable_name"="$variable_value>>~/.profile
echo $variable_name"="$variable_value>>/etc/environment
source ~/.bashrc
source ~/.profile
echo "do you want to restart your computer to apply changes in /etc/environment file? yes(y)no(n)"
read restart
case $restart in
    y) sudo shutdown -r 0;;
    n) echo "don't forget to restart your computer manually";;
esac
exit

Save these lines in a shfile then make it executable and just run it!

How to check if a process is running via a batch script

You should check the parent process name, see The Code Project article about a .NET based solution**.

A non-programmatic way to check:

  1. Launch Cmd.exe
  2. Launch an application (for instance, c:\windows\notepad.exe)
  3. Check properties of the Notepad.exe process in Process Explorer
  4. Check for parent process (This shows cmd.exe)

The same can be checked by getting the parent process name.

Switch tabs using Selenium WebDriver with Java

Simple Answer which worked for me:

for (String handle1 : driver1.getWindowHandles()) {
        System.out.println(handle1); 
        driver1.switchTo().window(handle1);     
}

Get all parameters from JSP page

localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3

    <%@page import="java.util.Enumeration"%>

    <%
    Enumeration in = request.getParameterNames();
    while(in.hasMoreElements()) {
     String paramName = in.nextElement().toString();
     out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
    }
    %>

    key = datr
    key2 = datr2
    key3 = datr3

Always show vertical scrollbar in <select>

I guess you cant, this maybe a limitation or not included in the IE browser. I have tried your jsfiddle with IE6-8 and all of it doesn't show the scrollbar and not sure with IE9. While in FF and chrome the scrollbar is shown. I also want to see how to do it in IE if possible.

If you really want to show the scrollbar, you can add a fake scrollbar. If you are familiar with some of the js library which use in RIA. Like in jquery/dojo some of the select is editable, because it is a combination of textbox + select or it can also be a textbox + div.

As an example, see it here a JavaScript that make select like editable.

Recursively counting files in a Linux directory

If you want to avoid error cases, don't allow wc -l to see files with newlines (which it will count as 2+ files)

e.g. Consider a case where we have a single file with a single EOL character in it

> mkdir emptydir && cd emptydir
> touch $'file with EOL(\n) character in it'
> find -type f
./file with EOL(?) character in it
> find -type f | wc -l
2

Since at least gnu wc does not appear to have an option to read/count a null terminated list (except from a file), the easiest solution would just be to not pass it filenames, but a static output each time a file is found, e.g. in the same directory as above

> find -type f -exec printf '\n' \; | wc -l
1

Or if your find supports it

> find -type f -printf '\n' | wc -l
1 

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

You have one occult directory named ".metadata" in workspace directory. Close Eclipse, delete ".metadata" and open Eclipse. When eclipse ask you about workspace make sure that ".metadata" isn't in workspace directory and click "ok" button to select default workspace.

Excel VBA Copy a Range into a New Workbook

Modify to suit your specifics, or make more generic as needed:

Private Sub CopyItOver()
  Set NewBook = Workbooks.Add
  Workbooks("Whatever.xlsx").Worksheets("output").Range("A1:K10").Copy
  NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues)
  NewBook.SaveAs FileName:=NewBook.Worksheets("Sheet1").Range("E3").Value
End Sub

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

Android Push Notifications: Icon not displaying in notification, white square shown instead

Requirements to fix this issue:

  1. Image Format: 32-bit PNG (with alpha)

  2. Image should be Transparent

  3. Transparency Color Index: White (FFFFFF)

Source: http://gr1350.blogspot.com/2017/01/problem-with-setsmallicon.html

SQL Server Group By Month

SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]

You could also try:

SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month

Add ArrayList to another ArrayList in java

Wouldn't it just be a case of:

ArrayList<ArrayList<String>> outer = new ArrayList<ArrayList<String>>();
ArrayList<String> nodeList = new ArrayList<String>();

// Fill in nodeList here...

outer.add(nodeList);

Repeat as necesary.

This should return you a list in the format you specified.

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

The first version is preferable:

  • It works for all kinds of keys, so you can, for example, say {1: 'one', 2: 'two'}. The second variant only works for (some) string keys. Using different kinds of syntax depending on the type of the keys would be an unnecessary inconsistency.
  • It is faster:

    $ python -m timeit "dict(a='value', another='value')"
    1000000 loops, best of 3: 0.79 usec per loop
    $ python -m timeit "{'a': 'value','another': 'value'}"
    1000000 loops, best of 3: 0.305 usec per loop
    
  • If the special syntax for dictionary literals wasn't intended to be used, it probably wouldn't exist.

Removing Java 8 JDK from Mac

I nuked everything Java, JDK, and oracle. I was running Java 8 on OSX El Capitan

Other answers were missing tons of stuff. This answer covers a lot more bases.

Good bye, shovelware.

sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/LaunchAgents/com.oracle.java.Java-Updater.plist
sudo rm -rf /Library/LaunchDaemons/com.oracle.java.Helper-Tool.plist
sudo rm -rf /Library/Preferences/com.oracle.java.Helper-Tool.plist
sudo rm -rf /System/Library/Frameworks/JavaVM.framework
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.bom
sudo rm -rf /var/db/receipts/com.oracle.jdk8u65.plist
sudo rm -rf /var/db/receipts/com.oracle.jre.bom
sudo rm -rf /var/db/receipts/com.oracle.jre.plist
sudo rm -rf /var/root/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/Library/Preferences/com.oracle.java.JavaAppletPlugin.plist
sudo rm -rf ~/Library/Preferences/com.oracle.javadeployment.plist
sudo rm -rf ~/.oracle_jre_usage

SyntaxError: Cannot use import statement outside a module

For those who were as confused as I was when reading the answers, in your package.json file, add "type": "module" in the upper level as show below:

{
  "name": "my-app",
  "version": "0.0.0",
  "type": "module",
  "scripts": { ...
  },
  ...
}

PostgreSQL: export resulting data from SQL query to Excel/CSV

The correct script for postgres (Ubuntu) is:

COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';

How can I show/hide a specific alert with twitter bootstrap?

JS

        function showAlert(){
         $('#alert').show();
         setTimeout(function() { 
             $('#alert').hide(); 
         }, 5000);
        }

HTML

<div class="alert alert-success" id="alert" role="alert" style="display:none;" >YOUR MESSAGE</div>

View's getWidth() and getHeight() returns 0

One liner if you are using RxJava & RxBindings. Similar approach without the boilerplate. This also solves the hack to suppress warnings as in the answer by Tim Autin.

RxView.layoutChanges(yourView).take(1)
      .subscribe(aVoid -> {
           // width and height have been calculated here
      });

This is it. No need to be unsubscribe, even if never called.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

So in Short,

vi ~/.proxy_info

export http_proxy=<username>:<password>@<proxy>:8080
export https_proxy=<username>:<password>@<proxy>:8080

source ~/.proxy_info

Hope this helps someone in hurry :)

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

low dpi is 0.75x dimensions of medium dpi

high dpi is 1.5x dimensions of medium dpi

extra high dpi is 2x dimensinons of medium dpi

It's a good practice to make all the images in vector based format so you can resize them easily using a vector design software like Illustrator etc..

Using ls to list directories and their total sizes

To display it in ls -lh format, use:

(du -sh ./*; ls -lh --color=no) | awk '{ if($1 == "total") {X = 1} else if (!X) {SIZES[$2] = $1} else { sub($5 "[ ]*", sprintf("%-7s ", SIZES["./" $9]), $0); print $0} }'

Awk code explained:

if($1 == "total") { // Set X when start of ls is detected
  X = 1 
} else if (!X) { // Until X is set, collect the sizes from `du`
  SIZES[$2] = $1
} else {
  // Replace the size on current current line (with alignment)
  sub($5 "[ ]*", sprintf("%-7s ", SIZES["./" $9]), $0); 
  print $0
}

Sample output:

drwxr-xr-x 2 root     root 4.0K    Feb 12 16:43 cgi-bin
drwxrws--- 6 root     www  20M     Feb 18 11:07 document_root
drwxr-xr-x 3 root     root 1.3M    Feb 18 00:18 icons
drwxrwsr-x 2 localusr www  8.0K    Dec 27 01:23 passwd

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

I had the same sort of need and found this to work well for me (postgres 8.4):

CAST((COALESCE(myfield,'0')) AS INTEGER)

Some test cases to demonstrate:

db=> select CAST((COALESCE(NULL,'0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('','0')) AS INTEGER);
 int4
------
    0
(1 row)

db=> select CAST((COALESCE('4','0')) AS INTEGER);
 int4
------
    4
(1 row)

db=> select CAST((COALESCE('bad','0')) AS INTEGER);
ERROR:  invalid input syntax for integer: "bad"

If you need to handle the possibility of the field having non-numeric text (such as "100bad") you can use regexp_replace to strip non-numeric characters before the cast.

CAST(REGEXP_REPLACE(COALESCE(myfield,'0'), '[^0-9]+', '', 'g') AS INTEGER)

Then text/varchar values like "b3ad5" will also give numbers

db=> select CAST(REGEXP_REPLACE(COALESCE('b3ad5','0'), '[^0-9]+', '', 'g') AS INTEGER);
 regexp_replace
----------------
             35
(1 row)

To address Chris Cogdon's concern with the solution not giving 0 for all cases, including a case such as "bad" (no digit characters at all), I made this adjusted statement:

CAST((COALESCE(NULLIF(REGEXP_REPLACE(myfield, '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);

It works similar to the simpler solutions, except will give 0 when the value to convert is non-digit characters only, such as "bad":

db=> select CAST((COALESCE(NULLIF(REGEXP_REPLACE('no longer bad!', '[^0-9]+', '', 'g'), ''), '0')) AS INTEGER);
     coalesce
----------
        0
(1 row)

ElasticSearch: Unassigned Shards, how to fix?

OK, I've solved this with some help from ES support. Issue the following command to the API on all nodes (or the nodes you believe to be the cause of the problem):

curl -XPUT 'localhost:9200/<index>/_settings' \
    -d '{"index.routing.allocation.disable_allocation": false}'

where <index> is the index you believe to be the culprit. If you have no idea, just run this on all nodes:

curl -XPUT 'localhost:9200/_settings' \
    -d '{"index.routing.allocation.disable_allocation": false}'

I also added this line to my yaml config and since then, any restarts of the server/service have been problem free. The shards re-allocated back immediately.

FWIW, to answer an oft sought after question, set MAX_HEAP_SIZE to 30G unless your machine has less than 60G RAM, in which case set it to half the available memory.

References

What's the better (cleaner) way to ignore output in PowerShell?

Personally, I use ... | Out-Null because, as others have commented, that looks like the more "PowerShellish" approach compared to ... > $null and [void] .... $null = ... is exploiting a specific automatic variable and can be easy to overlook, whereas the other methods make it obvious with additional syntax that you intend to discard the output of an expression. Because ... | Out-Null and ... > $null come at the end of the expression I think they effectively communicate "take everything we've done up to this point and throw it away", plus you can comment them out easier for debugging purposes (e.g. ... # | Out-Null), compared to putting $null = or [void] before the expression to determine what happens after executing it.

Let's look at a different benchmark, though: not the amount of time it takes to execute each option, but the amount of time it takes to figure out what each option does. Having worked in environments with colleagues who were not experienced with PowerShell or even scripting at all, I tend to try to write my scripts in a way that someone coming along years later that might not even understand the language they're looking at can have a fighting chance at figuring out what it's doing since they might be in a position of having to support or replace it. This has never occurred to me as a reason to use one method over the others until now, but imagine you're in that position and you use the help command or your favorite search engine to try to find out what Out-Null does. You get a useful result immediately, right? Now try to do the same with [void] and $null =. Not so easy, is it?

Granted, suppressing the output of a value is a pretty minor detail compared to understanding the overall logic of a script, and you can only try to "dumb down" your code so much before you're trading your ability to write good code for a novice's ability to read...not-so-good code. My point is, it's possible that some who are fluent in PowerShell aren't even familiar with [void], $null =, etc., and just because those may execute faster or take less keystrokes to type, doesn't mean they're the best way to do what you're trying to do, and just because a language gives you quirky syntax doesn't mean you should use it instead of something clearer and better-known.*

* I am presuming that Out-Null is clear and well-known, which I don't know to be $true. Whichever option you feel is clearest and most accessible to future readers and editors of your code (yourself included), regardless of time-to-type or time-to-execute, that's the option I'm recommending you use.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

I am Using Design Support Library. And just by using custom theme I achived transparent Status Bar when Opened Navigation Drawer.

enter image description here

enter image description here

<style name="NavigationStyle" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryColorDark</item>

    <!-- To Make Navigation Drawer Fill Status Bar and become Transparent Too -->
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>

</style>

Finally add theme in Manifest File

<activity
  ........
  ........
 android:theme="@style/NavigationStyle"> 
</activity>

Do not forget to use the property, android:fitsSystemWindows="true" in "DrawerLayout"

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Float vs Decimal in ActiveRecord

In Rails 4.1.0, I have faced problem with saving latitude and longitude to MySql database. It can't save large fraction number with float data type. And I change the data type to decimal and working for me.

  def change
    change_column :cities, :latitude, :decimal, :precision => 15, :scale => 13
    change_column :cities, :longitude, :decimal, :precision => 15, :scale => 13
  end

Swift 3: Display Image from URL

let url = URL(string: "http://i.imgur.com/w5rkSIj.jpg")
let data = try? Data(contentsOf: url)

if let imageData = data {
    let image = UIImage(data: imageData)
}

What is logits, softmax and softmax_cross_entropy_with_logits?

Whatever goes to softmax is logit, this is what J. Hinton repeats in coursera videos all the time.

How to implement a Map with multiple keys?

What about you declare the following "Key" class:

public class Key {
   public Object key1, key2, ..., keyN;

   public Key(Object key1, Object key2, ..., Object keyN) {
      this.key1 = key1;
      this.key2 = key2;
      ...
      this.keyN = keyN;
   }

   @Override   
   public boolean equals(Object obj) {
      if (!(obj instanceof Key))
        return false;
      Key ref = (Key) obj;
      return this.key1.equals(ref.key1) && 
          this.key2.equals(ref.key2) &&
          ...
          this.keyN.equals(ref.keyN)
   }

    @Override
    public int hashCode() {
        return key1.hashCode() ^ key2.hashCode() ^ 
            ... ^ keyN.hashCode();
    }

}

Declaring the Map

Map<Key, Double> map = new HashMap<Key,Double>();

Declaring the key object

Key key = new Key(key1, key2, ..., keyN)

Filling the map

map.put(key, new Double(0))

Getting the object from the map

Double result = map.get(key);

How do I implement a progress bar in C#?

I have not compiled this as it is meant for a proof of concept. This is how I have implemented a Progress bar for database access in the past. This example shows access to a SQLite database using the System.Data.SQLite module

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{   
    // Get the BackgroundWorker that raised this event.
    BackgroundWorker worker = sender as BackgroundWorker;
    using(SQLiteConnection cnn = new SQLiteConnection("Data Source=MyDatabase.db"))
    {
        cnn.Open();
        int TotalQuerySize = GetQueryCount("Query", cnn); // This needs to be implemented and is not shown in example
        using (SQLiteCommand cmd = cnn.CreateCommand())
        {
            cmd.CommandText = "Query is here";
            using(SQLiteDataReader reader = cmd.ExecuteReader())
            {
                int i = 0;
                while(reader.Read())
                {
                    // Access the database data using the reader[].  Each .Read() provides the next Row
                    if(worker.WorkerReportsProgress) worker.ReportProgress(++i * 100/ TotalQuerySize);
                }
            }
        }
    }
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    this.progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    // Notify someone that the database access is finished.  Do stuff to clean up if needed
    // This could be a good time to hide, clear or do somthign to the progress bar
}

public void AcessMySQLiteDatabase()
{
    BackgroundWorker backgroundWorker1 = new BackgroundWorker();
    backgroundWorker1.DoWork += 
        new DoWorkEventHandler(backgroundWorker1_DoWork);
    backgroundWorker1.RunWorkerCompleted += 
        new RunWorkerCompletedEventHandler(
    backgroundWorker1_RunWorkerCompleted);
    backgroundWorker1.ProgressChanged += 
        new ProgressChangedEventHandler(
    backgroundWorker1_ProgressChanged);
}

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

Using ORDER BY and GROUP BY together

Just you need to desc with asc. Write the query like below. It will return the values in ascending order.

SELECT * FROM table GROUP BY m_id ORDER BY m_id asc;

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

Multiple controllers with AngularJS in single page app

We can simply declare more than one Controller in the same module. Here's an example:

  <!DOCTYPE html>
    <html>

    <head>
       <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
       </script>
      <title> New Page </title>


    </head> 
    <body ng-app="mainApp"> <!-- if we remove ng-app the add book button [show/hide] will has no effect --> 
      <h2> Books </h2>

    <!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->
    <input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = "book.name"><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = "book.author"><br>


             You are entering book: {{book.bookDetails()}}
     </div>

    <script>
             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $scope.book = {
                   name: "",
                   category: "",
                   price:"",
                   author: "",


                   bookDetails: function() {
                      var bookObject;
                      bookObject = $scope.book;
                      return "Book name: " + bookObject.name +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " + bookObject.author;
                   }

                };
             });
    </script>

    <h2> Albums </h2>
    <input type = "button" value = "Add Album"ng-click="hideShow2=(hideShow2 ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "albumController" ng-if="hideShow2">
             Enter Album name: <input type = "text" ng-model = "album.name"><br>
             Enter Album category: <input type = "text" ng-model = "album.category"><br>
             Enter Album price: <input type = "text" ng-model = "album.price"><br>
             Enter Album singer: <input type = "text" ng-model = "album.singer"><br>


             You are entering Album: {{album.albumDetails()}}
     </div>

    <script>
             //no need to declare this again ;)
             //var mainApp = angular.module("mainApp", []);

             mainApp.controller('albumController', function($scope) {
                $scope.album = {
                   name: "",
                   category: "",
                   price:"",
                   singer: "",

                   albumDetails: function() {
                      var albumObject;
                      albumObject = $scope.album;
                      return "Album name: " + albumObject.name +  '\n' + "album category: " + albumObject.category + "\n" + "Book price: " + albumObject.price + "\n" + "Album Singer: " + albumObject.singer;
                   }
                };
             });
    </script>

    </body>
    </html>

SSL InsecurePlatform error when using Requests package

Use the somewhat hidden security feature:

pip install requests[security] or pip install pyOpenSSL ndg-httpsclient pyasn1

Both commands install following extra packages:

  • pyOpenSSL
  • cryptography
  • idna

Please note that this is not required for python-2.7.9+.

If pip install fails with errors, check whether you have required development packages for libffi, libssl and python installed in your system using distribution's package manager:

  • Debian/Ubuntu - python-dev libffi-dev libssl-dev packages.

  • Fedora - openssl-devel python-devel libffi-devel packages.

Distro list above is incomplete.

Workaround (see the original answer by @TomDotTom):

In case you cannot install some of the required development packages, there's also an option to disable that warning:

import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

If your pip itself is affected by InsecurePlatformWarning and cannot install anything from PyPI, it can be fixed with this step-by-step guide to deploy extra python packages manually.

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

How to remove specific substrings from a set of strings in Python?

I did the test (but it is not your example) and the data does not return them orderly or complete

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}

I proved that this works:

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']

or

>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
...     newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']

How to parse the AndroidManifest.xml file inside an .apk package

Use android-apktool

There is an application that reads apk files and decodes XMLs to nearly original form.

Usage:

apktool d Gmail.apk && cat Gmail/AndroidManifest.xml

Check android-apktool for more information

Java: JSON -> Protobuf & back conversion

Adding to Ophirs answer, JsonFormat is available even before protobuf 3.0. However, the way to do it differs a little bit.

In Protobuf 3.0+, the JsonFormat class is a singleton and therefore do something like the below

String jsonString = "";
JsonFormat.parser().ignoringUnknownFields().merge(jsonString,yourObjectBuilder);

In Protobuf 2.5+, the below should work

String jsonString = "";
JsonFormat jsonFormat = new JsonFormat();
jsonString = jsonFormat.printToString(yourProtobufMessage);

Here is a link to a tutorial I wrote that uses the JsonFormat class in a TypeAdapter that can be registered to a GsonBuilder object. You can then use Gson's toJson and fromJson methods to convert the proto data to Java and back.

Replying to jean . If we have the protobuf data in a file and want to parse it into a protobuf message object, use the merge method TextFormat class. See the below snippet:

// Let your proto text data be in a file MessageDataAsProto.prototxt
// Read it into string  
String protoDataAsString = FileUtils.readFileToString(new File("MessageDataAsProto.prototxt"));

// Create an object of the message builder
MyMessage.Builder myMsgBuilder = MyMessage.newBuilder();

// Use text format to parse the data into the message builder
TextFormat.merge(protoDataAsString, ExtensionRegistry.getEmptyRegistry(), myMsgBuilder);

// Build the message and return
return myMsgBuilder.build();

Yahoo Finance API

IMHO the best place to find this information is: http://code.google.com/p/yahoo-finance-managed/

I used to use the "gummy-stuff" too but then I found this page which is far more organized and full of easy to use examples. I am using it now to get the data in CSV files and use the files in my C++/Qt project.

Datatable vs Dataset

When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

do <something> N times (declarative syntax)

Assuming we can use some ES6 syntax like the spread operator, we'll want to do something as many times as the sum of all numbers in the collection.

In this case if times is equal to [1,2,3], the total number of times will be 6, i.e. 1+2+3.

/**
 * @param {number[]} times
 * @param {cb} function
 */
function doTimes(times, cb) {
  // Get the sum of all the times
  const totalTimes = times.reduce((acc, time) => acc + time);
  // Call the callback as many times as the sum
  [...Array(totalTimes)].map(cb);
}

doTimes([1,2,3], () => console.log('something'));
// => Prints 'something' 6 times

This post should be helpful if the logic behind constructing and spreading an array isn't apparent.

How to select into a variable in PL/SQL when the result might be null?

I use this syntax for flexibility and speed -

    begin
    --
    with KLUJ as
    ( select 0 ROES from dual
       union 
      select count(*) from MY_TABLE where rownum = 1
    ) select max(ROES) into has_rows from KLUJ;
    --
    end;

Dual returns 1 row, rownum adds 0 or 1 rows, and max() groups to exactly 1. This gives 0 for no rows in a table and 1 for any other number of rows.

I extend the where clause to count rows by condition, remove rownum to count rows meeting a condition, and increase rownum to count rows meeting the condition up to a limit.

Creating a directory in /sdcard fails

Isn't it already created ? Mkdir returns false if the folder already exists too mkdir

Implement Validation for WPF TextBoxes

When it comes to Muhammad Mehdi's answer, it is better to do:

private void salary_texbox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
     Regex regex = new Regex ( "[^0-9]+" );
     if(regex.IsMatch(e.Text))
     {
         MessageBox.Show("Error");
     }
}

Because when comparing with the TextCompositionEventArgs it gets also the last character, while with the textbox.Text it does not. With textbox, the error will show after next inserted character.

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

A DateTime in C# is a value type, not a reference type, and therefore cannot be null. It can however be the constant DateTime.MinValue which is outside the range of Sql Servers DATETIME data type.

Value types are guaranteed to always have a (default) value (of zero) without always needing to be explicitly set (in this case DateTime.MinValue).

Conclusion is you probably have an unset DateTime value that you are trying to pass to the database.

DateTime.MinValue = 1/1/0001 12:00:00 AM
DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 
                    exactly one 100-nanosecond tick 
                    before 00:00:00, January 1, 10000

MSDN: DateTime.MinValue


Regarding Sql Server

datetime
Date and time data from January 1, 1753 through December 31, 9999, to an accuracy of one three-hundredth of a second (equivalent to 3.33 milliseconds or 0.00333 seconds). Values are rounded to increments of .000, .003, or .007 seconds

smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute. smalldatetime values with 29.998 seconds or lower are rounded down to the nearest minute; values with 29.999 seconds or higher are rounded up to the nearest minute.

MSDN: Sql Server DateTime and SmallDateTime


Lastly, if you find yourself passing a C# DateTime as a string to sql, you need to format it as follows to retain maximum precision and to prevent sql server from throwing a similar error.

string sqlTimeAsString = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fff");

Update (8 years later)

Consider using the sql DateTime2 datatype which aligns better with the .net DateTime with date range 0001-01-01 through 9999-12-31 and time range 00:00:00 through 23:59:59.9999999

string dateTime2String = myDateTime.ToString("yyyy-MM-ddTHH:mm:ss.fffffff");

MSDN datetime2 (Transact-SQL)

How to create full path with node's fs.mkdirSync?

Using reduce we can verify if each path exists and create it if necessary, also this way I think it is easier to follow. Edited, thanks @Arvin, we should use path.sep to get the proper platform-specific path segment separator.

const path = require('path');

// Path separators could change depending on the platform
const pathToCreate = 'path/to/dir'; 
pathToCreate
 .split(path.sep)
 .reduce((prevPath, folder) => {
   const currentPath = path.join(prevPath, folder, path.sep);
   if (!fs.existsSync(currentPath)){
     fs.mkdirSync(currentPath);
   }
   return currentPath;
 }, '');

How to get a particular date format ('dd-MMM-yyyy') in SELECT query SQL Server 2008 R2

select convert(varchar(11), transfer_date, 106)

got me my desired result of date formatted as 07 Mar 2018

My column transfer_date is a datetime type column and I am using SQL Server 2017 on azure

check if command was successful in a batch file

Goodness I had a hard time finding the answer to this... Here it is:

cd thisDoesntExist
if %errorlevel% == 0 (
  echo Oh, I guess it does
  echo Huh.
)

REST API Best practices: Where to put parameters?

As per the REST Implementation,

1) Path variables are used for the direct action on the resources, like a contact or a song ex..
GET etc /api/resource/{songid} or
GET etc /api/resource/{contactid} will return respective data.

2) Query perms/argument are used for the in-direct resources like metadata of a song ex.., GET /api/resource/{songid}?metadata=genres it will return the genres data for that particular song.

Create an empty list in python with certain size

Here's my code for 2D list in python which would read no. of rows from the input :

empty = []
row = int(input())

for i in range(row):
    temp = list(map(int, input().split()))
    empty.append(temp)

for i in empty:
    for j in i:
        print(j, end=' ')
    print('')

CSS opacity only to background color, not the text on it?

The easiest way to do this is with 2 divs, 1 with the background and 1 with the text:

_x000D_
_x000D_
#container {_x000D_
  position: relative;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
#block {_x000D_
  background: #CCC;_x000D_
  filter: alpha(opacity=60);_x000D_
  /* IE */_x000D_
  -moz-opacity: 0.6;_x000D_
  /* Mozilla */_x000D_
  opacity: 0.6;_x000D_
  /* CSS3 */_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div id="block"></div>_x000D_
  <div id="text">Test</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Ruby on Rails: how to render a string as HTML?

If you're on rails which utilizes Erubis — the coolest way to do it is

<%== @str >

Note the double equal sign. See related question on SO for more info.

How do I create a self-signed certificate for code signing on Windows?

As stated in the answer, in order to use a non deprecated way to sign your own script, one should use New-SelfSignedCertificate.

  1. Generate the key:
New-SelfSignedCertificate -DnsName [email protected] -Type CodeSigning -CertStoreLocation cert:\CurrentUser\My
  1. Export the certificate without the private key:
Export-Certificate -Cert (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)[0] -FilePath code_signing.crt

The [0] will make this work for cases when you have more than one certificate... Obviously make the index match the certificate you want to use... or use a way to filtrate (by thumprint or issuer).

  1. Import it as Trusted Publisher
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\TrustedPublisher
  1. Import it as a Root certificate authority.
Import-Certificate -FilePath .\code_signing.crt -Cert Cert:\CurrentUser\Root
  1. Sign the script (assuming here it's named script.ps1, fix the path accordingly).
Set-AuthenticodeSignature .\script.ps1 -Certificate (Get-ChildItem Cert:\CurrentUser\My -CodeSigningCert)

Obviously once you have setup the key, you can simply sign any other scripts with it.
You can get more detailed information and some troubleshooting help in this article.

How to generate JAXB classes from XSD?

In intellij click .xsd file -> WebServices ->Generate Java code from Xml Schema JAXB then give package path and package name ->ok

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

For Jackson versions < 2.0 use this annotation on the class being serialized:

@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)

Change background image opacity

You can also simply use this:

_x000D_
_x000D_
.bg_rgba {
  background: linear-gradient(0deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.9)), url('https://picsum.photos/200');
  width: 200px;
  height: 200px;
  border: 1px solid black;
}
_x000D_
<div class='bg_rgba'></div>
_x000D_
_x000D_
_x000D_

You can change the opacity of the color to your preference.

Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]

When I ran into this error the fix was simple. I was simply missing a setter for a property. Make sure you define matching getters / setters for all your properties.

Difference between "managed" and "unmanaged"

This is more general than .NET and Windows. Managed is an environment where you have automatic memory management, garbage collection, type safety, ... unmanaged is everything else. So for example .NET is a managed environment and C/C++ is unmanaged.

No Access-Control-Allow-Origin header is present on the requested resource

You are missing 'json' dataType in the $.post() method:

$.post('http://www.example.com:PORT_NUMBER/MYSERVLET',{MyParam: 'value'})
        .done(function(data){
                  alert(data);
         }, "json");
         //-^^^^^^-------here

Updates:

try with this:

response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

Is it good practice to make the constructor throw an exception?

Throwing exceptions in a constructor is not bad practice. In fact, it is the only reasonable way for a constructor to indicate that there is a problem; e.g. that the parameters are invalid.

I also think that throwing checked exceptions can be OK1, assuming that the checked exception is 1) declared, 2) specific to the problem you are reporting, and 3) it is reasonable to expect the caller to deal with a checked exception for this2.

However explicitly declaring or throwing java.lang.Exception is almost always bad practice.

You should pick an exception class that matches the exceptional condition that has occurred. If you throw Exception it is difficult for the caller to separate this exception from any number of other possible declared and undeclared exceptions. This makes error recovery difficult, and if the caller chooses to propagate the Exception, the problem just spreads.


1 - Some people may disagree, but IMO there is no substantive difference between this case and the case of throwing exceptions in methods. The standard checked vs unchecked advice applies equally to both cases.

2 - For example, the existing FileInputStream constructors will throw FileNotFoundException if you try to open a file that does not exist. Assuming that it is reasonable for FileNotFoundException to be a checked exception3, then the constructor is the most appropriate place for that exception to be thrown. If we threw the FileNotFoundException the first time that (say) a read or write call was made, that is liable to make application logic more complicated.

3 - Given that this is one of the motivating examples for checked exceptions, if you don't accept this you are basically saying that all exceptions should be unchecked. That is not practical ... if you are going to use Java.


Someone suggested using assert for checking arguments. The problem with this is that checking of assert assertions can be turned on and off via a JVM command-line setting. Using assertions to check internal invariants is OK, but using them to implement argument checking that is specified in your javadoc is not a good idea ... because it means your method will only strictly implement the specification when assertion checking is enabled.

The second problem with assert is that if an assertion fails, then AssertionError will be thrown, and received wisdom is that it is a bad idea to attempt to catch Error and any of its subtypes.

Get all directories within directory nodejs

CoffeeScript version of this answer, with proper error handling:

fs = require "fs"
{join} = require "path"
async = require "async"

get_subdirs = (root, callback)->
    fs.readdir root, (err, files)->
        return callback err if err
        subdirs = []
        async.each files,
            (file, callback)->
                fs.stat join(root, file), (err, stats)->
                    return callback err if err
                    subdirs.push file if stats.isDirectory()
                    callback null
            (err)->
                return callback err if err
                callback null, subdirs

Depends on async

Alternatively, use a module for this! (There are modules for everything. [citation needed])

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

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

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

C# ListView Column Width Auto

There is another useful method called AutoResizeColumn which allows you to auto size a specific column with the required parameter.

You can call it like this:

listview1.AutoResizeColumn(1, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(2, ColumnHeaderAutoResizeStyle.ColumnContent);
listview1.AutoResizeColumn(3, ColumnHeaderAutoResizeStyle.HeaderSize);
listview1.AutoResizeColumn(4, ColumnHeaderAutoResizeStyle.HeaderSize);

Plotting categorical data with pandas and matplotlib

like this :

df.groupby('colour').size().plot(kind='bar')

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

I write one with js and python, used in two projects, very nice and simple: a simple library (less then 2kb) used to format date with *** time ago statement.

simple, small, easy used, and well tested.

  1. npm install timeago.js

  2. import timeago from 'timeago.js'; // or use script tag

  3. use api format.

Sample:

var timeagoIns  = timeago();
timeagoIns .format('2016-06-12');

Also you can render in real-time.

var timeagoIns = timeago();
timeagoIns.render(document.querySelectorAll('time'));

Automatically deleting related rows in Laravel (Eloquent ORM)

You can use this method as an alternative.

What will happen is that we take all the tables associated with the users table and delete the related data using looping

$tables = DB::select("
    SELECT
        TABLE_NAME,
        COLUMN_NAME,
        CONSTRAINT_NAME,
        REFERENCED_TABLE_NAME,
        REFERENCED_COLUMN_NAME
    FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
    WHERE REFERENCED_TABLE_NAME = 'users'
");

foreach($tables as $table){
    $table_name =  $table->TABLE_NAME;
    $column_name = $table->COLUMN_NAME;

    DB::delete("delete from $table_name where $column_name = ?", [$id]);
}

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

How to compare two dates to find time difference in SQL Server 2005, date manipulation

Below code gives in hh:mm format.

select RIGHT(LEFT(job_end- job_start,17),5)

How do I display a text file content in CMD?

We can use the 'type' command to see file contents in cmd.

Example -

type abc.txt

More information can be found HERE.

fatal: early EOF fatal: index-pack failed

As @ingyhere said:

Shallow Clone

First, turn off compression:

git config --global core.compression 0

Next, let's do a partial clone to truncate the amount of info coming down:

git clone --depth 1 <repo_URI>

When that works, go into the new directory and retrieve the rest of the clone:

git fetch --unshallow

or, alternately,

git fetch --depth=2147483647

Now, do a pull:

git pull --all

Then to solve the problem of your local branch only tracking master

open your git config file (.git/config) in the editor of your choice

where it says:

[remote "origin"]
    url=<git repo url>
    fetch = +refs/heads/master:refs/remotes/origin/master

change the line

fetch = +refs/heads/master:refs/remotes/origin/master

to

fetch = +refs/heads/*:refs/remotes/origin/*

Do a git fetch and git will pull all your remote branches now

Getting a directory name from a filename

Using Boost.Filesystem:

boost::filesystem::path p("C:\\folder\\foo.txt");
boost::filesystem::path dir = p.parent_path();

Allowed memory size of X bytes exhausted

The memory must be configured in several places.
Set memory_limit to 512M:

sudo vi /etc/php5/cgi/php.ini
sudo vi /etc/php5/cli/php.ini
sudo vi /etc/php5/apache2/php.ini Or /etc/php5/fpm/php.ini

Restart service:

sudo service service php5-fpm restart
sudo service service nginx restart

or

sudo service apache2 restart

Finally it should solve the problem of the memory_limit

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

How to put multiple statements in one line?

Its acctualy possible ;-)

# not pep8 compatible^
sam = ['Sam',]
try: print('hello',sam) if sam[0] != 'harry' else rais
except: pass

You can do very ugly stuff in python like:

def o(s):return''.join([chr(ord(n)+(13if'Z'<n<'n'or'N'>n else-13))if n.isalpha()else n for n in s])

which is function for rot13/cesa encryption in one line with 99 characters.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Comparing HTTP and FTP for transferring files

Here's a performance comparison of the two. HTTP is more responsive for request-response of small files, but FTP may be better for large files if tuned properly. FTP used to be generally considered faster. FTP requires a control channel and state be maintained besides the TCP state but HTTP does not. There are 6 packet transfers before data starts transferring in FTP but only 4 in HTTP.

I think a properly tuned TCP layer would have more effect on speed than the difference between application layer protocols. The Sun Blueprint Understanding Tuning TCP has details.

Heres another good comparison of individual characteristics of each protocol.

What is the difference between ( for... in ) and ( for... of ) statements?

Everybody did explain why this problem occurs, but it's still very easy to forget about it and then scratching your head why you got wrong results. Especially when you're working on big sets of data when the results seem to be fine at first glance.

Using Object.entries you ensure to go trough all properties:

var arr = [3, 5, 7];
arr.foo = "hello";

for ( var [key, val] of Object.entries( arr ) ) {
   console.log( val );
}

/* Result:

3
5
7
hello

*/

Calculate the date yesterday in JavaScript

new Date(new Date().setDate(new Date().getDate()-1))

How do I clear all options in a dropdown box?

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}

Hope, this code will helps you

Excel doesn't update value unless I hit Enter

I ran into this exact problem too. In my case, adding parenthesis around any internal functions (to get them to evaluate first) seemed to do the trick:

Changed

=SUM(A1, SUBSTITUTE(A2,"x","3",1), A3) 

to

=SUM(A1, (SUBSTITUTE(A2,"x","3",1)), A3) 

PHP - Merging two arrays into one array (also Remove Duplicates)

It will merger two array and remove duplicate

<?php
 $first = 'your first array';
 $second = 'your second array';
 $result = array_merge($first,$second);
 print_r($result);
 $result1= array_unique($result);
 print_r($result1);
 ?>

Try this link link1

Insert line at middle of file with Python?

This is a way of doing the trick.

f = open("path_to_file", "r")
contents = f.readlines()
f.close()

contents.insert(index, value)

f = open("path_to_file", "w")
contents = "".join(contents)
f.write(contents)
f.close()

"index" and "value" are the line and value of your choice, lines starting from 0.

Clear text input on click with AngularJS

Just clear the scope model value on click event and it should do the trick for you.

<input type="text" ng-model="searchAll" />
<a class="clear" ng-click="searchAll = null">
    <span class="glyphicon glyphicon-remove"></span>
</a>

Or if you keep your controller's $scope function and clear it from there. Make sure you've set your controller correctly.

$scope.clearSearch = function() {
    $scope.searchAll = null;
}

SSL Error: unable to get local issuer certificate

jww is right — you're referencing the wrong intermediate certificate.

As you have been issued with a SHA256 certificate, you will need the SHA256 intermediate. You can grab it from here: http://secure2.alphassl.com/cacert/gsalphasha2g2r1.crt

How long do browsers cache HTTP 301s?

There is a very simple way to remove browser cache for http redirects e.g. 301, 307 etc.

You can open network panel in developer console in chrome. Select the network call. Right click on it and then click on Clear Browser Cache to remove the cached redirection.

network call context menu

Git push failed, "Non-fast forward updates were rejected"

Before pushing, do a git pull with rebase option. This will get the changes that you made online (in your origin) and apply them locally, then add your local changes on top of it.

git pull --rebase

Now, you can push to remote

git push 

For more information take a look at Git rebase explained and Chapter 3.6 Git Branching - Rebasing.

npm install from Git in a specific version

If by version you mean a tag or a release, then github provides download links for those. For example, if I want to install fetch version 0.3.2 (it is not available on npm), then I add to my package.json under dependencies:

"fetch": "https://github.com/github/fetch/archive/v0.3.2.tar.gz",

The only disadvantage when compared with the commit hash approach is that a hash is guaranteed not to represent changed code, whereas a tag could be replaced. Thankfully this rarely happens.

Update:

These days the approach I use is the compact notation for a GitHub served dependency:

"dependencies": {
  "package": "github:username/package#commit"
}

Where commit can be anything commitish, like a tag. In the case of GitHub you can even drop the initial github: since it's the default.

img tag displays wrong orientation

I found part of the solution. Images now have metadata that specify the orientation of the photo. There is a new CSS spec for image-orientation.

Just add this to your CSS:

img {
    image-orientation: from-image;
}

According to the spec as of Jan 25 2016, Firefox and iOS Safari (behind a prefix) are the only browsers that support this. I'm seeing issues with Safari and Chrome still. However, mobile Safari seems to natively support orientation without the CSS tag.

I suppose we'll have to wait and see if browsers wills start supporting image-orientation.

What are the file limits in Git (number and size)?

There is no real limit -- everything is named with a 160-bit name. The size of the file must be representable in a 64 bit number so no real limit there either.

There is a practical limit, though. I have a repository that's ~8GB with >880,000 files and git gc takes a while. The working tree is rather large so operations that inspect the entire working directory take quite a while. This repo is only used for data storage, though, so it's just a bunch of automated tools that handle it. Pulling changes from the repo is much, much faster than rsyncing the same data.

%find . -type f | wc -l
791887
%time git add .
git add .  6.48s user 13.53s system 55% cpu 36.121 total
%time git status
# On branch master
nothing to commit (working directory clean)
git status  0.00s user 0.01s system 0% cpu 47.169 total
%du -sh .
29G     .
%cd .git
%du -sh .
7.9G    .

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

I have been getting similar error, and just want to share with you. maybe it will help someone.

If you want to use EntityManagerFactory to get an EntityManager, make sure that you will use:

<persistence-unit name="name" transaction-type="RESOURCE_LOCAL">

and not:

<persistence-unit name="name" transaction-type="JPA">

in persistance.xml

clean and rebuild project, it should help.

What are good ways to prevent SQL injection?

By using the SqlCommand and its child collection of parameters all the pain of checking for sql injection is taken away from you and will be handled by these classes.

Here is an example, taken from one of the articles above:

private static void UpdateDemographics(Int32 customerID,
    string demoXml, string connectionString)
{
    // Update the demographics for a store, which is stored  
    // in an xml column.  
    string commandText = "UPDATE Sales.Store SET Demographics = @demographics "
        + "WHERE CustomerID = @ID;";

    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(commandText, connection);
        command.Parameters.Add("@ID", SqlDbType.Int);
        command.Parameters["@ID"].Value = customerID;

        // Use AddWithValue to assign Demographics. 
        // SQL Server will implicitly convert strings into XML.
        command.Parameters.AddWithValue("@demographics", demoXml);

        try
        {
            connection.Open();
            Int32 rowsAffected = command.ExecuteNonQuery();
            Console.WriteLine("RowsAffected: {0}", rowsAffected);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

Create a temporary table in MySQL with an index from a select

CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
select_statement

Example :

CREATE TEMPORARY TABLE IF NOT EXISTS mytable
(id int(11) NOT NULL, PRIMARY KEY (id)) ENGINE=MyISAM;
INSERT IGNORE INTO mytable SELECT id FROM table WHERE xyz;

Convert command line argument to string

It's simple. Just do this:

#include <iostream>
#include <vector>
#include <string.h>

int main(int argc, char *argv[])
{
    std::vector<std::string> argList;
    for(int i=0;i<argc;i++)
        argList.push_back(argv[i]);
    //now you can access argList[n]
}

@Benjamin Lindley You are right. This is not a good solution. Please read the one answered by juanchopanza.

How to print a two dimensional array?

How about trying this?

public static void main (String [] args)
{
   int [] [] listTwo = new int [5][5];
    // 2 Dimensional array 
    int x = 0;
    int y = 0;
    while (x < 5) {
        listTwo[x][y] = (int)(Math.random()*10);

        while (y <5){
            listTwo [x] [y] = (int)(Math.random()*10);
            System.out.print(listTwo[x][y]+" | ");
            y++;                
        }
        System.out.println("");
        y=0;
        x++;
    }
}

GZIPInputStream reading line by line

The basic setup of decorators is like this:

InputStream fileStream = new FileInputStream(filename);
InputStream gzipStream = new GZIPInputStream(fileStream);
Reader decoder = new InputStreamReader(gzipStream, encoding);
BufferedReader buffered = new BufferedReader(decoder);

The key issue in this snippet is the value of encoding. This is the character encoding of the text in the file. Is it "US-ASCII", "UTF-8", "SHIFT-JIS", "ISO-8859-9", …? there are hundreds of possibilities, and the correct choice usually cannot be determined from the file itself. It must be specified through some out-of-band channel.

For example, maybe it's the platform default. In a networked environment, however, this is extremely fragile. The machine that wrote the file might sit in the neighboring cubicle, but have a different default file encoding.

Most network protocols use a header or other metadata to explicitly note the character encoding.

In this case, it appears from the file extension that the content is XML. XML includes the "encoding" attribute in the XML declaration for this purpose. Furthermore, XML should really be processed with an XML parser, not as text. Reading XML line-by-line seems like a fragile, special case.

Failing to explicitly specify the encoding is against the second commandment. Use the default encoding at your peril!

Retrieve filename from file descriptor in C

In Windows, with GetFileInformationByHandleEx, passing FileNameInfo, you can retrieve the file name.

Need to ZIP an entire directory using Node.js

To pipe the result to the response object (scenarios where there is a need to download the zip rather than store locally)

 archive.pipe(res);

Sam's hints for accessing the content of the directory worked for me.

src: ["**/*"]

How to convert an enum type variable to a string?

For C99 there is P99_DECLARE_ENUM in P99 that lets you simply declare enum like this:

P99_DECLARE_ENUM(color, red, green, blue);

and then use color_getname(A) to obtain a string with the color name.

sass --watch with automatic minify?

If you are using JetBrains editors like IntelliJ IDEA, PhpStorm, WebStorm etc. Use the following settings in Settings > File Watchers. enter image description here

  1. Convert style.scss to style.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.css
    

    and output paths to refresh

    $FileNameWithoutExtension$.css
    
  2. Convert style.scss to compressed style.min.css set the arguments

    --no-cache --update $FileName$:$FileNameWithoutExtension$.min.css --style compressed
    

    and output paths to refresh

    $FileNameWithoutExtension$.min.css
    

Is it possible to change the content HTML5 alert messages?

Thank you guys for the help,

When I asked at first I didn't think it's even possible, but after your answers I googled and found this amazing tutorial:

http://blog.thomaslebrun.net/2011/11/html-5-how-to-customize-the-error-message-for-a-required-field/#.UsNN1BYrh2M

How to clear an EditText on click?

Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:

String value = "";//any text you are pre-filling in the EditText

final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (et.getCompoundDrawables()[2] == null) {
            return false;
        }
        if (event.getAction() != MotionEvent.ACTION_UP) {
            return false;
        }
        if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
            et.setText("");
            et.setCompoundDrawables(null, null, null, null);
        }
        return false;
    }
});
et.addTextChangedListener(new TextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
    }

    @Override
    public void afterTextChanged(Editable arg0) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
});

How to compare two lists in python?

If you mean lists, try ==:

l1 = [1,2,3]
l2 = [1,2,3,4]

l1 == l2 # False

If you mean array:

l1 = array('l', [1, 2, 3])
l2 = array('d', [1.0, 2.0, 3.0])
l1 == l2 # True
l2 = array('d', [1.0, 2.0, 3.0, 4.0])
l1 == l2 # False

If you want to compare strings (per your comment):

date_string  = u'Thu Sep 16 13:14:15 CDT 2010'
date_string2 = u'Thu Sep 16 14:14:15 CDT 2010'
date_string == date_string2 # False

NSCameraUsageDescription in iOS 10.0 runtime crash?

Another instance that I faced while trying to use the camera, was that it was still busy crashing giving same _CRASHING_DUE_TO_PRIVACY even after adding the "Camera Usage Description". After failing to get anything tangible from the call stack, switched to the "Organizer" and looked into the crash reports on the device. I found that it was in fact complaining about the privacy due to the missing "Microphone Usage Description". I added that and got rid of such a cryptic break down.

jQuery add class .active on menu

No other "addClass" methods worked for me when adding a class to an 'a' element on menu except this one:

$(function () {
        var url = window.location.pathname,
    urlRegExp = new RegExp(url.replace(/\/$/, '') + "$");  
        $('a').each(function () {
                            if (urlRegExp.test(this.href.replace(/\/$/, ''))) {
                $(this).addClass('active');
            }
        });
    });

This took me four hours to find it.

How do I make a branch point at a specific commit?

git branch -f <branchname> <commit>

I go with Mark Longair's solution and comments and recommend anyone reads those before acting, but I'd suggest the emphasis should be on

git branch -f <branchname> <commit>

Here is a scenario where I have needed to do this.

Scenario

Develop on the wrong branch and hence need to reset it.

Start Okay

Cleanly develop and release some software.

So far so good

Develop on wrong branch

Mistake: Accidentally stay on the release branch while developing further.

After a mistake

Realize the mistake

"OH NO! I accidentally developed on the release branch." The workspace is maybe cluttered with half changed files that represent work-in-progress and we really don't want to touch and mess with. We'd just like git to flip a few pointers to keep track of the current state and put that release branch back how it should be.

Create a branch for the development that is up to date holding the work committed so far and switch to it.

git branch development
git checkout development 

Changed to another branch

Correct the branch

Now we are in the problem situation and need its solution! Rectify the mistake (of taking the release branch forward with the development) and put the release branch back how it should be.

Correct the release branch to point back to the last real release.

git branch -f release release2

The release branch is now correct again, like this ...

Corrected

What if I pushed the mistake to a remote?

git push -f <remote> <branch> is well described in another thread, though the word "overwrite" in the title is misleading. Force "git push" to overwrite remote files

Interface or an Abstract Class: which one to use?

Best practice is to use an interface to specify the contract and an abstract class as just one implementation thereof. That abstract class can fill in a lot of the boilerplate so you can create an implementation by just overriding what you need to or want to without forcing you to use a particular implementation.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

I'll try to explain it visually:

_x000D_
_x000D_
/**_x000D_
 * explaining margins_x000D_
 */_x000D_
_x000D_
body {_x000D_
  padding: 3em 15%_x000D_
}_x000D_
_x000D_
.parent {_x000D_
  width: 50%;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  position: relative;_x000D_
  background: lemonchiffon;_x000D_
}_x000D_
_x000D_
.parent:before,_x000D_
.parent:after {_x000D_
  position: absolute;_x000D_
  content: "";_x000D_
}_x000D_
_x000D_
.parent:before {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 50%;_x000D_
  border-left: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.parent:after {_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 50%;_x000D_
  border-top: dashed 1px #ccc;_x000D_
}_x000D_
_x000D_
.child {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  background: rgba(200, 198, 133, .5);_x000D_
}_x000D_
_x000D_
ul {_x000D_
  padding: 5% 20px;_x000D_
}_x000D_
_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
_x000D_
/* position absolute */_x000D_
_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
_x000D_
.set6 .child {_x000D_
  top: 50%; /* level from which margin-top starts _x000D_
 - downwards, in the case of a positive margin_x000D_
 - upwards, in the case of a negative margin _x000D_
 */_x000D_
  left: 50%; /* level from which margin-left starts _x000D_
 - towards right, in the case of a positive margin_x000D_
 - towards left, in the case of a negative margin _x000D_
 */_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}
_x000D_
<!-- content to be placed inside <body>…</body> -->_x000D_
<h2><code>position: relative;</code></h2>_x000D_
<h3>Set 1</h3>_x000D_
<div class="parent set 1">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set1 .child {_x000D_
  margin: 0;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 2</h3>_x000D_
<div class="parent set2">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set2 .child {_x000D_
  margin-left: 75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 3</h3>_x000D_
<div class="parent set3">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set3 .child {_x000D_
  margin-left: -75px;_x000D_
  position: relative;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h2><code>position: absolute;</code></h2>_x000D_
_x000D_
<h3>Set 4</h3>_x000D_
<div class="parent set4">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set4 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: 0;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 5</h3>_x000D_
<div class="parent set5">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set5 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-left: 75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<h3>Set 6</h3>_x000D_
<div class="parent set6">_x000D_
  <div class="child">_x000D_
    <pre>_x000D_
.set6 .child {_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin: -75px;_x000D_
  position: absolute;_x000D_
}_x000D_
  </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Random record from MongoDB

non of the solutions worked well for me. especially when there are many gaps and set is small. this worked very well for me(in php):

$count = $collection->count($search);
$skip = mt_rand(0, $count - 1);
$result = $collection->find($search)->skip($skip)->limit(1)->getNext();

Extension mysqli is missing, phpmyadmin doesn't work

Since I had this problem following an upgrade, I just disable Apache2-php5

a2dismod php5

and activated php7

a2enmod php7

Hope it may help anybody!

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

PostgreSQL: How to change PostgreSQL user password?

and the fully automated way with bash and expect ( in this example we provision a new postgres admin with the newly provisioned postgres pw both on OS and postgres run-time level )

  # the $postgres_usr_pw and the other bash vars MUST be defined 
  # for reference the manual way of doing things automated with expect bellow
  #echo "copy-paste: $postgres_usr_pw"
  #sudo -u postgres psql -c "\password"
  # the OS password could / should be different
  sudo -u root echo "postgres:$postgres_usr_pw" | sudo chpasswd

  expect <<- EOF_EXPECT
     set timeout -1
     spawn sudo -u postgres psql -c "\\\password"
     expect "Enter new password: "
     send -- "$postgres_usr_pw\r"
     expect "Enter it again: "
     send -- "$postgres_usr_pw\r"
     expect eof
EOF_EXPECT

  cd /tmp/
  # at this point the postgres uses the new password
  sudo -u postgres PGPASSWORD=$postgres_usr_pw psql \
    --port $postgres_db_port --host $postgres_db_host -c "
  DO \$\$DECLARE r record;
     BEGIN
        IF NOT EXISTS (
           SELECT
           FROM   pg_catalog.pg_roles
           WHERE  rolname = '"$postgres_db_useradmin"') THEN
              CREATE ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
              CREATEDB REPLICATION BYPASSRLS 
 PASSWORD '"$postgres_db_useradmin_pw"' LOGIN ;
        END IF;
     END\$\$;
  ALTER ROLE "$postgres_db_useradmin" WITH SUPERUSER CREATEROLE
  CREATEDB REPLICATION BYPASSRLS 
PASSWORD  '"$postgres_db_useradmin_pw"' LOGIN ;
 "

Create an enum with string values

Faced this issue recently with TypeScript 1.0.1, and solved this way:

enum IEvents {
        /** A click on a product or product link for one or more products. */
        CLICK,
        /** A view of product details. */
        DETAIL,
        /** Adding one or more products to a shopping cart. */
        ADD,
        /** Remove one or more products from a shopping cart. */
        REMOVE,
        /** Initiating the checkout process for one or more products. */
        CHECKOUT,
        /** Sending the option value for a given checkout step. */
        CHECKOUT_OPTION,
        /** The sale of one or more products. */
        PURCHASE,
        /** The refund of one or more products. */
        REFUND,
        /** A click on an internal promotion. */
        PROMO_CLICK
}

var Events = [
        'click',
        'detail',
        'add',
        'remove',
        'checkout',
        'checkout_option',
        'purchase',
        'refund',
        'promo_click'
];

function stuff(event: IEvents):boolean {
        // event can now be only IEvents constants
        Events[event]; // event is actually a number that matches the index of the array
}
// stuff('click') won't work, it needs to be called using stuff(IEvents.CLICK)

How can I extract audio from video with ffmpeg?

ffmpeg -i sample.avi will give you the audio/video format info for your file. Make sure you have the proper libraries configured to parse the input streams. Also, make sure that the file isn't corrupt.

Android Studio update -Error:Could not run build action using Gradle distribution

I had same issue. I have tried many things but nothing worked Until I try following:

  1. Close Android Studio
  2. Delete any directory matching gradle-[version]-all within C:\Users\<username>\.gradle\wrapper\dists\. If you encounter a "File in use" error (or similar), terminate any running Java executables.
  3. Open Android Studio as Administrator.
  4. Try to sync project files.
  5. If the above does not work, try restarting your computer and/or delete the project's .gradle directory.
  6. Open the problem project and trigger a Gradle sync.

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Get data from php array - AJAX - jQuery

When you do echo $array;, PHP will simply echo 'Array' since it can't convert an array to a string. So The 'A' that you are actually getting is the first letter of Array, which is correct.

You might actually need

echo json_encode($array);

This should get you what you want.

EDIT : And obviously, you'd need to change your JS to work with JSON instead of just text (as pointed out by @genesis)

is there any alternative for ng-disabled in angular2?

[attr.disabled]="valid == true ? true : null"

You have to use null to remove attr from html element.

How to ignore HTML element from tabindex?

You can use tabindex="-1".

The W3C HTML5 specification supports negative tabindex values:

If the value is a negative integer
The user agent must set the element's tabindex focus flag, but should not allow the element to be reached using sequential focus navigation.


Watch out though that this is a HTML5 feature and might not work with old browsers.
To be W3C HTML 4.01 standard (from 1999) compliant, tabindex would need to be positive.


Sample usage below in pure HTML.

_x000D_
_x000D_
<input />_x000D_
<input tabindex="-1" placeholder="NoTabIndex" />_x000D_
<input />
_x000D_
_x000D_
_x000D_

Best way to change font colour halfway through paragraph?

<span> will allow you to style text, but it adds no semantic content.

As you're emphasizing some text, it sounds like you'd be better served by wrapping the text in <em></em> and using CSS to change the color of the <em> element. For example:

CSS

.description {
  color: #fff;
}

.description em {
  color: #ffa500;
}

Markup

<p class="description">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat 
massa, <em>eget vulputate tellus fermentum.</em></p>

In fact, I'd go to great pains to avoid the <span> element, as it's completely meaningless to everything that doesn't render your style sheet (bots, screen readers, luddites who disable styles, parsers, etc.) or renders it in unexpected ways (personal style sheets). In many ways, it's no better than using the <font> element.

_x000D_
_x000D_
.description {_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
.description em {_x000D_
  color: #ffa500;_x000D_
}
_x000D_
<p class="description">Lorem ipsum dolor sit amet, consectetur _x000D_
adipiscing elit. Sed hendrerit mollis varius. Etiam ornare placerat _x000D_
massa, <em>eget vulputate tellus fermentum.</em></p>
_x000D_
_x000D_
_x000D_

Wait Until File Is Completely Written

There is only workaround for the issue you are facing.

Check whether file id in process before starting the process of copy. You can call the following function until you get the False value.

1st Method, copied directly from this answer:

private bool IsFileLocked(FileInfo file)
{
    FileStream stream = null;

    try
    {
        stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (IOException)
    {
        //the file is unavailable because it is:
        //still being written to
        //or being processed by another thread
        //or does not exist (has already been processed)
        return true;
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }

    //file is not locked
    return false;
}

2nd Method:

const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private bool IsFileLocked(string file)
{
    //check that problem is not in destination file
    if (File.Exists(file) == true)
    {
        FileStream stream = null;
        try
        {
            stream = File.Open(file, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
        }
        catch (Exception ex2)
        {
            //_log.WriteLog(ex2, "Error in checking whether file is locked " + file);
            int errorCode = Marshal.GetHRForException(ex2) & ((1 << 16) - 1);
            if ((ex2 is IOException) && (errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION))
            {
                return true;
            }
        }
        finally
        {
            if (stream != null)
                stream.Close();
        }
    }
    return false;
}

Color theme for VS Code integrated terminal

VSCode comes with in-built color themes which can be used to change the colors of the editor and the terminal.

  • For changing the color theme press ctrl+k+t in windows/ubuntu or cmd+k+t on mac.
  • Alternatively you can open command palette by pressing ctrl+shift+p in windows/ubuntu or cmd+shift+p on mac and type color. Select preferences: color theme from the options, to select your favourite color.
  • You can also install more themes from the extensions menu on the left bar. just search category:themes to install your favourite themes. (If you need to sort the themes by installs search category:themes @sort:installs)

Edit - for manually editing colors in terminal

VSCode team have removed customizing colors from user settings page. Currently using the themes is the only way to customize terminal colors in VSCode. For more information check out issue #6766

How to change python version in anaconda spyder

You can open the preferences (multiple options):

  • keyboard shortcut Ctrl + Alt + Shift + P
  • Tools -> Preferences

And depending on the Spyder version you can change the interpreter in the Python interpreter section (Spyder 3.x):

enter image description here

or in the advanced Console section (Spyder 2.x):

enter image description here

How to add composite primary key to table

You don't need to create the table first and then add the keys in subsequent steps. You can add both primary key and foreign key while creating the table:

This example assumes the existence of a table (Codes) that we would want to reference with our foreign key.

CREATE TABLE d (
id [numeric](1),
code [varchar](2),
PRIMARY KEY (id, code),
CONSTRAINT fk_d_codes FOREIGN KEY (code) REFERENCES Codes (code)
)

If you don't have a table that we can reference, add one like this so that the example will work:

CREATE TABLE Codes (
    Code [varchar](2) PRIMARY KEY   
    )

NOTE: you must have a table to reference before creating the foreign key.

What's the difference between import java.util.*; and import java.util.Date; ?

The toString() implementation of java.util.Date does not depend on the way the class is imported. It always returns a nice formatted date.

The toString() you see comes from another class.

Specific import have precedence over wildcard imports.

in this case

import other.Date
import java.util.*

new Date();

refers to other.Date and not java.util.Date.

The odd thing is that

import other.*
import java.util.*

Should give you a compiler error stating that the reference to Date is ambiguous because both other.Date and java.util.Date matches.

Get folder name of the file in Python

you can use pathlib

from pathlib import Path
Path(r"C:\folder1\folder2\filename.xml").parts[-2]

The output of the above was this:

'folder2'

Histogram with Logarithmic Scale and custom breaks

Here's a pretty ggplot2 solution:

library(ggplot2)
library(scales)  # makes pretty labels on the x-axis

breaks=c(0,1,2,3,4,5,25)

ggplot(mydata,aes(x = V3)) + 
  geom_histogram(breaks = log10(breaks)) + 
  scale_x_log10(
    breaks = breaks,
    labels = scales::trans_format("log10", scales::math_format(10^.x))
  )

Note that to set the breaks in geom_histogram, they had to be transformed to work with scale_x_log10

Set the space between Elements in Row Flutter

Row(
 children: <Widget>[
  Flexible(
   child: TextFormField()),
  Container(width: 20, height: 20),
  Flexible(
   child: TextFormField())
 ])

This works for me, there are 3 widgets inside row: Flexible, Container, Flexible

Return HTML from ASP.NET Web API

Starting with AspNetCore 2.0, it's recommended to use ContentResult instead of the Produce attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885

This doesn't rely on serialization nor on content negotiation.

[HttpGet]
public ContentResult Index() {
    return new ContentResult {
        ContentType = "text/html",
        StatusCode = (int)HttpStatusCode.OK,
        Content = "<html><body>Hello World</body></html>"
    };
}

Select values of checkbox group with jQuery

I'm not sure about the "@" used in the selector. At least with the latest jQuery, I had to remove the @ to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:

var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});

var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});

Now both, items and about work.

How to Copy Contents of One Canvas to Another Canvas Locally

Actually you don't have to create an image at all. drawImage() will accept a Canvas as well as an Image object.

//grab the context from your destination canvas
var destCtx = destinationCanvas.getContext('2d');

//call its drawImage() function passing it the source canvas directly
destCtx.drawImage(sourceCanvas, 0, 0);

Way faster than using an ImageData object or Image element.

Note that sourceCanvas can be a HTMLImageElement, HTMLVideoElement, or a HTMLCanvasElement. As mentioned by Dave in a comment below this answer, you cannot use a canvas drawing context as your source. If you have a canvas drawing context instead of the canvas element it was created from, there is a reference to the original canvas element on the context under context.canvas.

Here is a jsPerf to demonstrate why this is the only right way to clone a canvas: http://jsperf.com/copying-a-canvas-element

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

Python: count repeated elements in the list

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

How to increase font size in the Xcode editor?

When changing fonts in XCode from [Preferences] (after duplicating a template that matches colours close to what you want), you can select multiple entries and change the fonts all at once. Use [shift] to select a range or [cmd] to select multiple individual entries (e.g. you might select both 'comments' and 'strings' and change only their fonts).

Steve

Scroll to the top of the page using JavaScript?

Better solution with smooth animation:

// this changes the scrolling behavior to "smooth"
window.scrollTo({ top: 0, behavior: 'smooth' });

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollTo#Example

Logging levels - Logback - rule-of-thumb to assign log levels

Not different for other answers, my framework have almost the same levels:

  1. Error: critical logical errors on application, like a database connection timeout. Things that call for a bug-fix in near future
  2. Warn: not-breaking issues, but stuff to pay attention for. Like a requested page not found
  3. Info: used in functions/methods first line, to show a procedure that has been called or a step gone ok, like a insert query done
  4. log: logic information, like a result of an if statement
  5. debug: variable contents relevant to be watched permanently

Is it possible to cherry-pick a commit from another git repository?

You'll need to add the other repository as a remote, then fetch its changes. From there you see the commit and you can cherry-pick it.

Like that:

git remote add other https://example.link/repository.git
git fetch other

Now you have all the information to simply do git cherry-pick.

More info about working with remotes here: https://git-scm.com/book/en/v2/Git-Basics-Working-with-Remotes

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

Header set Access-Control-Allow-Origin in .htaccess doesn't work

I +1'd Miro's answer for the link to the header-checker site http://www.webconfs.com/http-header-check.php. It pops up an obnoxious ad every time you use it, but it is, nevertheless, very useful for verifying the presence of the Access-Control-Allow-Origin header.

I'm reading a .json file from the javascript on my web page. I found that adding the following to my .htaccess file fixed the problem when viewing my web page in IE 11 (version 11.447.14393.0):

<FilesMatch "\.(json)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

I also added the following to /etc/httpd.conf (Apache's configuration file):

AllowOverride All

The header-checker site verified that the Access-Control-Allow-Origin header is now being sent (thanks, Miro!).

However, Firefox 50.0.2, Opera 41.0.2353.69, and Edge 38.14393.0.0 all fetch the file anyhow, even without the Access-Control-Allow-Origin header. (Note: they might be checking IP addresses, since the two domains I was using are both hosted on the same server, at the same IPv4 address.)

However, Chrome 54.0.2840.99 m (64-bit) ignores the Access-Control-Allow-Origin header and fails anyhow, erroneously reporting:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '{mydomain}' is therefore not allowed access.

I think this has got to be some sort of "first." IE is working correctly; Chrome, Firefox, Opera and Edge are all buggy; and Chrome is the worst. Isn't that the exact opposite of the usual case?

css width: calc(100% -100px); alternative using jquery

Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)

function calcShim(element,property,expression){
    var calculated = 0;
    var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
    // Remove all the ( ) and spaces 
    // Now find the parts 
    var parts = freed_expression.split(/[\*+-\/]/gi);

    var units = {
        'px':function(quantity){
            var part = 0;
            part = parseFloat(quantity,10);
            return part;
        },
        '%':function(quantity){
            var part = 0,
            parentQuantity = parseFloat(element.parent().css(property));
            part = parentQuantity * ((parseFloat(quantity,10))/100);
            return part;
        } // you can always add more units here.
    }

    for( var i = 0; i < parts.length; i++ ){
        for( var unit in units ){
            if( parts[i].indexOf(unit) != -1 ){
               // replace the expression by calculated part.
               expression = expression.replace(parts[i],units[unit](parts[i]));
               break;
            }
        }
    }
    // And now compute it. though eval is evil but in some cases its a good friend.
    // Though i wish there was math. calc
    element.css(property,eval(expression));
}

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

Current best practice in CSS development is to create more general selectors with modifiers that can be applied as widely as possible throughout the web site. I would try to avoid defining separate styles for individual page elements.

If the purpose of the CSS class on the <form/> element is to control the style of elements within the form, you could add the class attribute the existing <fieldset/> element which encapsulates any form by default in web pages generated by ASP.NET MVC. A CSS class on the form is rarely necessary.

How to picture "for" loop in block representation of algorithm

The Algorithm for given flow chart :

enter image description here

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Step :01

  • Start

Step :02 [Variable initialization]

  • Set counter: i<----K [Where K:Positive Number]

Step :03[Condition Check]

  • If condition True then Do your task, set i=i+N and go to Step :03 [Where N:Positive Number]
  • If condition False then go to Step :04

Step:04

  • Stop

How can I get the current user's username in Bash?

A hack the I've used on Solaris 9 and Linux and which works fine for both of them:

ps -o user= -p $$ | awk '{print $1}'

This snippet prints the name of the user with the current EUID.

NOTE: you need Bash as the interpreter here.

On Solaris you have problems with methods, described above:

  • id does not accept the -u and -n parameters (so you will have to parse the output)
  • whoami does not exist (by default)
  • who am I prints owner of current terminal (ignores EUID)
  • $USER variable is set correctly only after reading profile files (for example, /etc/profile)

dll missing in JDBC

Alright guys, I found it out! I didn't really need to change the java.library.path but the "Native library location" of sqljdbc.jar

This is the best answer I could find: https://stackoverflow.com/a/958074/2000342

It works now, thanks for the support!

ssh "permissions are too open" error

I am using VPC on EC2 and was getting the same error messages. I noticed I was using the public DNS. I changed that to the private DNS and vola!! it worked...

Placeholder in UITextView

Simply create @IBDesignable subclass of your UITextView:

@IBDesignable class AttributedTextView: UITextView {

    private let placeholderLabel = UILabel()

    @IBInspectable var placeholder: String = "" {

        didSet {

            setupPlaceholderLabelIfNeeded()
            textViewDidChange()
        }
    }

    override var text: String! {

        didSet {
            textViewDidChange()
        }
    }

    //MARK: - Initialization

    override func awakeFromNib() {
        super.awakeFromNib()

        setupPlaceholderLabelIfNeeded()
        NotificationCenter.default.addObserver(self, selector: #selector(textViewDidChange), name: .UITextViewTextDidChange, object: nil)
    }

    //MARK: - Deinitialization

    deinit {
        NotificationCenter.default.removeObserver(self)
    }

    //MARK: - Internal

    func textViewDidChange() {

        placeholderLabel.isHidden = !text.isEmpty
        layoutIfNeeded()
    }

    //MARK: - Private

    private func setupPlaceholderLabelIfNeeded() {

        placeholderLabel.removeFromSuperview()
        placeholderLabel.frame = CGRect(x: 0, y: 8, width: frame.size.width, height: 0)
        placeholderLabel.textColor = UIColor.lightGray
        placeholderLabel.text = placeholder

        placeholderLabel.sizeToFit()

        insertSubview(placeholderLabel, at: 0)
    }
}

and then simply setup your placeholder in identity inspector:

enter image description here

Removing elements from an array in C

There are really two separate issues. The first is keeping the elements of the array in proper order so that there are no "holes" after removing an element. The second is actually resizing the array itself.

Arrays in C are allocated as a fixed number of contiguous elements. There is no way to actually remove the memory used by an individual element in the array but the elements can be shifted to fill the hole made by removing an element. For example:

void remove_element(array_type *array, int index, int array_length)
{
   int i;
   for(i = index; i < array_length - 1; i++) array[i] = array[i + 1];
}

Statically allocated arrays can not be resized. Dynamically allocated arrays can be resized with realloc(). This will potentially move the entire array to another location in memory, so all pointers to the array or to its elements will have to be updated. For example:

remove_element(array, index, array_length);  /* First shift the elements, then reallocate */
array_type *tmp = realloc(array, (array_length - 1) * sizeof(array_type) );
if (tmp == NULL && array_length > 1) {
   /* No memory available */
   exit(EXIT_FAILURE);
}
array_length = array_length - 1;
array = tmp;

realloc will return a NULL pointer if the requested size is 0, or if there is an error. Otherwise it returns a pointer to the reallocated array. The temporary pointer is used to detect errors when calling realloc because instead of exiting it is also possible to just leave the original array as it was. When realloc fails to reallocate an array it does not alter the original array.

Note that both of these operations will be fairly slow if the array is large or if a lot of elements are removed. There are other data structures like linked lists and hashes that can be used if efficient insertion and deletion is a priority.

Validate a username and password against Active Directory?

For me both of these below worked, make sure your Domain is given with LDAP:// in start

//"LDAP://" + domainName
private void btnValidate_Click(object sender, RoutedEventArgs e)
{
    try
    {
        DirectoryEntry de = new DirectoryEntry(txtDomainName.Text, txtUsername.Text, txtPassword.Text);
        DirectorySearcher dsearch = new DirectorySearcher(de);
        SearchResult results = null;

        results = dsearch.FindOne();

        MessageBox.Show("Validation Success.");
    }
    catch (LdapException ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
}

private void btnValidate2_Click(object sender, RoutedEventArgs e)
{
    try
    {
        LdapConnection lcon = new LdapConnection(new LdapDirectoryIdentifier((string)null, false, false));
        NetworkCredential nc = new NetworkCredential(txtUsername.Text,
                               txtPassword.Text, txtDomainName.Text);
        lcon.Credential = nc;
        lcon.AuthType = AuthType.Negotiate;
        lcon.Bind(nc);

        MessageBox.Show("Validation Success.");
    }
    catch (LdapException ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Validation Failure. {ex.GetBaseException().Message}");
    }
}

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound  
FROM sys.sql_modules  
WHERE object_id = OBJECT_ID('your View Name');  

C# how to use enum with switch

Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:

public double Calculate(int left, int right, Operator op) =>
            op switch 
        {
            Operator.PLUS => left + right,
            Operator.MINUS => left - right,
            Operator.MULTIPLY => left * right,
            Operator.DIVIDE => left / right,
            _    =>  0
        }

Ref. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

Hashmap holding different data types as values for instance Integer, String and Object

Do simply like below....

HashMap<String,Object> yourHash = new HashMap<String,Object>();
yourHash.put(yourKey+"message","message");
yourHash.put(yourKey+"timestamp",timestamp);
yourHash.put(yourKey+"count ",count);
yourHash.put(yourKey+"version ",version);

typecast the value while getting back. For ex:

    int count = Integer.parseInt(yourHash.get(yourKey+"count"));
//or
int count = Integer.valueOf(yourHash.get(yourKey+"count"));
//or
int count = (Integer)yourHash.get(yourKey+"count"); //or (int)

Where to change the value of lower_case_table_names=2 on windows xampp

On linux I cannot set lower_case_table_names to 2 (it reverts to 0), but I can set it to 1.

Before changing this setting, do a complete dump of all databases, and drop all databases. You won't be able to drop them after setting lower_case_table_names to 1, because any uppercase characters in database or table names will prevent them from being referenced.

Then set lower_case_table_names to 1, restart MySQL, and re-load your data, which will convert everything to lowercase, including any subsequent queries made.