Programs & Examples On #Subscript

Python slice first and last element in list

This isn't a "slice", but it is a general solution that doesn't use explicit indexing, and works for the scenario where the sequence in question is anonymous (so you can create and "slice" on the same line, without creating twice and indexing twice): operator.itemgetter

import operator

# Done once and reused
first_and_last = operator.itemgetter(0, -1)

...

first, last = first_and_last(some_list)

You could just inline it as (after from operator import itemgetter for brevity at time of use):

first, last = itemgetter(0, -1)(some_list)

but if you'll be reusing the getter a lot, you can save the work of recreating it (and give it a useful, self-documenting name) by creating it once ahead of time.

Thus, for your specific use case, you can replace:

x, y = a.split("-")[0], a.split("-")[-1]

with:

x, y = itemgetter(0, -1)(a.split("-"))

and split only once without storing the complete list in a persistent name for len checking or double-indexing or the like.

Note that itemgetter for multiple items returns a tuple, not a list, so if you're not just unpacking it to specific names, and need a true list, you'd have to wrap the call in the list constructor.

HTML <sup /> tag affecting line height, how to make it consistent?

keep it easy:

sup { vertical-align: text-top; }

[font-size dependent on your individual type-face]

Subscripts in plots in R

See ?expression

plot(1:10,main=expression("This is a subscript "[2]))

enter image description here

Get everything after and before certain character in SQL Server

I know this has been a while.. but here is an idea

declare @test varchar(25) = 'images/test.jpg'

select
 @test as column_name
 , parsename(replace(@test,'/','.'),1) as jpg
 ,parsename(replace(@test,'/','.'),2) as test
  ,parsename(replace(@test,'/','.'),3) as images

Placing/Overlapping(z-index) a view above another view in android

If you are adding the View programmatically, you can use yourLayout.addView(view, 1);

where 1 is the index.

Execute action when back bar button of UINavigationController is pressed

When back button is pressed, ignore interactive pop with screen edge gesture.

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    
    if isMovingFromParent, transitionCoordinator?.isInteractive == false {
      // code here
    }
  }

Converting PKCS#12 certificate into PEM using OpenSSL

I had a PFX file and needed to create KEY file for NGINX, so I did this:

openssl pkcs12 -in file.pfx -out file.key -nocerts -nodes

Then I had to edit the KEY file and remove all content up to -----BEGIN PRIVATE KEY-----. After that NGINX accepted the KEY file.

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

Java Wait for thread to finish

Thread has a method that does that for you join which will block until the thread has finished executing.

How do I add a reference to the MySQL connector for .NET?

In Visual Studio you can use nuget to download the latest version. Just right click on the project and click 'Manage NuGet Packages' then search online for MySql.Data and install.

How to prevent IFRAME from redirecting top-level window

Since the page you load inside the iframe can execute the "break out" code with a setInterval, onbeforeunload might not be that practical, since it could flud the user with 'Are you sure you want to leave?' dialogs.

There is also the iframe security attribute which only works on IE & Opera

:(

How to restart ADB manually from Android Studio

Open task manager and kill adb.exe, now adb will start normally

Hidden Features of C#?

Some ?? weirdness :)

Delegate target =
  (target0 = target as CallTargetWithContext0) ??
  (target1 = target as CallTargetWithContext1) ??
  (target2 = target as CallTargetWithContext2) ??
  (target3 = target as CallTargetWithContext3) ??
  (target4 = target as CallTargetWithContext4) ??
  (target5 = target as CallTargetWithContext5) ??
  ((Delegate)(targetN = target as CallTargetWithContextN));

Interesting to note the last cast that is needed for some reason. Bug or by design?

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

Using regular expression in css?

An ID is meant to identify the element uniquely. Any styles applied to it should also be unique to that element. If you have styles you want to apply to many elements, you should add a class to them all, rather than relying on ID selectors...

<div id="sections">
   <div id="s1" class="sec">...</div>
   <div id="s2" class="sec">...</div>
   ...
</div>

and

.sec {
    ...
}

Or in your specific case you could select all divisions inside your parent container, if nothing else is inside it, like so:

#sections > div {
    ...
}

Rails create or update magic?

You can do it in one statement like this:

CachedObject.where(key: "the given key").first_or_create! do |cached|
   cached.attribute1 = 'attribute value'
   cached.attribute2 = 'attribute value'
end

Can I have multiple background images using CSS?

The easiest way I have found to use two different background images in one div is with this line of code:

body {
    background:url(image1.png) repeat-x, url(image2.png) repeat;
}

Obviously, that does not have to be for only the body of the website, you can use that for any div you want.

Hope that helps! There is a post on my blog that talks about this a little more in depth if anyone needs further instructions or help - http://blog.thelibzter.com/css-tricks-use-two-background-images-for-one-div.

SQL Query for Student mark functionality

I will try to get the answer with one query using CTE and window function rank()

create the tables

create table Students 
(student_id int,
Name varchar(255),
details varchar(255));

create table Subject(
Sub_id int,
name varchar(255));

create table marks
(student_id int,
subject_id int,
mark int);

the answer should be a table with the below fields

student_name | subject_name | mark

plan the execution steps

  1. Create a CTE
  • join the tables;
  • rank the subjects, order them by mark descending
  1. Select the output fields from the CTE
with CTE as (select s.name, sb.name as subject_name, m.mark, rank() over(partition by sb.name order by m.mark desc) as rn 
from Students s
join marks m on s.student_id = m.student_id
join subject sb
on sb.Sub_id = m.subject_id)
select name , subject_name, mark
from CTE
where rn = 1

How do I print out the contents of a vector?

You can print containers as well as ranges and tuples using the {fmt} library. For example:

#include <vector>
#include <fmt/ranges.h>

int main() {
  auto v = std::vector<int>{1, 2, 3};
  fmt::print("{}", v);
}

prints

{1, 2, 3}

to stdout (godbolt).

I wouldn't recommend overloading operator<< for standard containers because it may introduce ODR violations.

Disclaimer: I'm the author of {fmt}.

Iframe transparent background

Set the background color of the src to none and allow transparencey.

[WITHIN SCR PAGE STYLE]
<style type="text/css">
    body
    {
        background:none transparent;
    }
</style>

[IFRAME]
<iframe src="#" allowtransparency="true">Error, iFrame failed to load.</iframe>

NOTE: I code my CSS a little different to how everyone else does.

How do I revert an SVN commit?

First, revert the working copy to 1943.

> svn merge -c -1943 .

Second, check what is about to be commited.

> svn status

Third, commit version 1945.

> svn commit -m "Fix bad commit."

Fourth, look at the new log.

> svn log -l 4

------------------------------------------------------------------------
1945 | myname | 2015-04-20 19:20:51 -0700 (Mon, 20 Apr 2015) | 1 line

Fix bad commit.
------------------------------------------------------------------------
1944 | myname | 2015-04-20 19:09:58 -0700 (Mon, 20 Apr 2015) | 1 line

This is the bad commit that I made.
------------------------------------------------------------------------
1943 | myname | 2015-04-20 18:36:45 -0700 (Mon, 20 Apr 2015) | 1 line

This was a good commit.
------------------------------------------------------------------------

Test if numpy array contains only zeros

The other answers posted here will work, but the clearest and most efficient function to use is numpy.any():

>>> all_zeros = not np.any(a)

or

>>> all_zeros = not a.any()
  • This is preferred over numpy.all(a==0) because it uses less RAM. (It does not require the temporary array created by the a==0 term.)
  • Also, it is faster than numpy.count_nonzero(a) because it can return immediately when the first nonzero element has been found.
    • Edit: As @Rachel pointed out in the comments, np.any() no longer uses "short-circuit" logic, so you won't see a speed benefit for small arrays.

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

got it solved by first creating new "Path" variable under User variables (note that after fresh windows install Path variable is not created as User variable, only as system) after that, I appended %M2% (pointing to maven dir/bin) to (freshly created) user Path variable. after that restarted cmd window and it worked like a charm.

PHP is_numeric or preg_match 0-9 validation

is_numeric checks more:

Finds whether the given variable is numeric. Numeric strings consist of optional sign, any number of digits, optional decimal part and optional exponential part. Thus +0123.45e6 is a valid numeric value. Hexadecimal notation (0xFF) is allowed too but only without sign, decimal and exponential part.

Find document with array that contains a specific value

Incase of lookup_food_array is array.

match_stage["favoriteFoods"] = {'$elemMatch': {'$in': lookup_food_array}}

Incase of lookup_food_array is string.

match_stage["favoriteFoods"] = {'$elemMatch': lookup_food_string}

jQuery add class .active on menu

this work for me :D

    function setActive() {
      aObj = document.getElementById('menu').getElementsByTagName('a');
      for(i=0;i<aObj.length;i++) {
        if(document.location.href.indexOf(aObj[i].href)>=0) {
          var activeurl = window.location;
          $('a[href="'+activeurl+'"]').parent('li').addClass('active');
        }
      }
    }

    window.onload = setActive;

Getting request payload from POST request in Java servlet

String payloadRequest = getBody(request);

Using this method

public static String getBody(HttpServletRequest request) throws IOException {

    String body = null;
    StringBuilder stringBuilder = new StringBuilder();
    BufferedReader bufferedReader = null;

    try {
        InputStream inputStream = request.getInputStream();
        if (inputStream != null) {
            bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            char[] charBuffer = new char[128];
            int bytesRead = -1;
            while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                stringBuilder.append(charBuffer, 0, bytesRead);
            }
        } else {
            stringBuilder.append("");
        }
    } catch (IOException ex) {
        throw ex;
    } finally {
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException ex) {
                throw ex;
            }
        }
    }

    body = stringBuilder.toString();
    return body;
}

MySQL: Can't create table (errno: 150)

If you re-create a table that was dropped, it must have a definition that conforms to the foreign key constraints referencing it. It must have the correct column names and types, and it must have indexes on the referenced keys, as stated earlier. If these are not satisfied, MySQL returns Error 1005 and refers to Error 150 in the error message, which means that a foreign key constraint was not correctly formed. Similarly, if an ALTER TABLE fails due to Error 150, this means that a foreign key definition would be incorrectly formed for the altered table.

Use jquery click to handle anchor onClick()

The HTML should look like:

<div class="solTitle"> <a href="#"  id="solution0">Solution0 </a></div>
<div class="solTitle"> <a href="#"  id="solution1">Solution1 </a></div>

<div id="summary_solution0" style="display:none" class="summary">Summary solution0</div>
<div id="summary_solution1" style="display:none" class="summary">Summary solution1</div>

And the javascript:

$(document).ready(function(){
    $(".solTitle a").live('click',function(e){
        var contentId = "summary_" + $(this).attr('id');
        $(".summary").hide();
        $("#" + contentId).show();
    });
});

See the Example: http://jsfiddle.net/kmendes/4G9UF/

Check if a varchar is a number (TSQL)

Using SQL Server 2012+, you can use the TRY_* functions if you have specific needs. For example,

-- will fail for decimal values, but allow negative values
TRY_CAST(@value AS INT) IS NOT NULL 

-- will fail for non-positive integers; can be used with other examples below as well, or reversed if only negative desired
TRY_CAST(@value AS INT) > 0

-- will fail if a $ is used, but allow decimals to the specified precision
TRY_CAST(@value AS DECIMAL(10,2)) IS NOT NULL 

-- will allow valid currency
TRY_CAST(@value AS MONEY) IS NOT NULL  

-- will allow scientific notation to be used like 1.7E+3
TRY_CAST(@value AS FLOAT) IS NOT NULL 

C# - insert values from file into two arrays

string[] lines = File.ReadAllLines("sample.txt"); List<string> list1 = new List<string>(); List<string> list2 = new List<string>();  foreach (var line in lines) {     string[] values = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);     list1.Add(values[0]);     list2.Add(values[1]);  } 

Parser Error: '_Default' is not allowed here because it does not extend class 'System.Web.UI.Page' & MasterType declaration

I had this issue, as I had copied a (fairly generic) webpage from one of my ASP.Net applications into a new application.

I changed the relevant namespace commands, to reflect the new location of the file... but... I had forgotten to change the Inherits parameter in the aspx page itself.

<%@ Page MasterPageFile="" StylesheetTheme="" Language="C#"
    AutoEventWireup="true" CodeBehind="MikesReports.aspx.cs" 
    Inherits="MikesCompany.MikesProject.MikesReports" %>

Once I had changed the Inherits parameter, the error went away.

How do you get the current time of day?

Another option using String.Format()

string.Format("{0:HH:mm:ss tt}", DateTime.Now)

Select option padding not working in chrome

Arbitrary Indentation of any Option

If you just want to indent random, arbitrary <option /> elements, you can use &nbsp;, which has the greatest cross-browser compatibility of the solutions posted here...

_x000D_
_x000D_
.optionGroup {
  font-weight: bold;
  font-style: italic;
}
_x000D_
<select>
    <option class="optionGroup" selected disabled>Choose one</option>
    <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
    <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
    <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
    <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_

Ordered Indentation of Options

But if you have some sorted, ordered structure to your data, then it is recommended that you use the <optgroup/> syntax....

The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>)

_x000D_
_x000D_
<select>
    <optgroup label="Australia" default selected>
        <option value="sydney">Sydney</option>
        <option value="melbourne">Melbourne</option>
    </optgroup>
    <optgroup label="United Kingdom">
        <option value="london">London</option>
        <option value="glasgow">Glasgow</option>
    </optgroup>
</select>
_x000D_
_x000D_
_x000D_

Unfortunately, only one <optgroup /> level is allowed and currently supported by browsers today. (Source: w3.org.) Personally, I would consider that part of the spec broken, but you can always extend to third, fourth, etc., levels of indentation with using the &nbsp; trick up above.

Node.js ES6 classes with require

The ES6 way of require is import. You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.

import fs from 'fs';
export default class Animal {

  constructor(name){
    this.name = name ;
  }

  print(){
    console.log('Name is :'+ this.name);
  }
}

import Animal from 'path/to/Animal.js';

How to change a <select> value from JavaScript

 <script language="javascript" type="text/javascript">
        function selectFunction() {
             var printStr = document.getElementById("select").options[0].value
            alert(printStr);
            document.getElementById("select").selectedIndex = 0;
        }
    </script>

FlutterError: Unable to load asset

My issue was nested folders.

I had my image in assets/images/logo/xyz.png and thought that - assets/images/ would catch all subfolders.

You have to explicitly add each nested subfolder

Solution: - assets/images/logo/ etc.

Download File Using Javascript/jQuery

To improve Imagine Breaker 's answer, this is supported on FF & IE :

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

function downloadURI(uri, name) {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.dispatchEvent(evt);
}

In other words, just use a dispatchEvent function instead of click();

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

CSS Select box arrow style

Try to replace the

padding: 2px 30px 2px 2px;

with

padding: 2px 2px 2px 2px;

It should work.

how to show alternate image if source image is not found? (onerror working in IE but not in mozilla)

If you're open to a PHP solution:

<td><img src='<?PHP
  $path1 = "path/to/your/image.jpg";
  $path2 = "alternate/path/to/another/image.jpg";

  echo file_exists($path1) ? $path1 : $path2; 
  ?>' alt='' />
</td>

////EDIT OK, here's a JS version:

<table><tr>
<td><img src='' id='myImage' /></td>
</tr></table>

<script type='text/javascript'>
  document.getElementById('myImage').src = "newImage.png";

  document.getElementById('myImage').onload = function() { 
    alert("done"); 
  }

  document.getElementById('myImage').onerror = function() { 
    alert("Inserting alternate");
    document.getElementById('myImage').src = "alternate.png"; 
  }
</script>

Searching a list of objects in Python

You can use in to look for an item in a collection, and a list comprehension to extract the field you are interested in. This (works for lists, sets, tuples, and anything that defines __contains__ or __getitem__).

if 5 in [data.n for data in myList]:
    print "Found it"

See also:

How to run a stored procedure in oracle sql developer?

Try to execute the procedure like this,

var c refcursor;
execute pkg_name.get_user('14232', '15', 'TDWL', 'SA', 1, :c);
print c;

Declare global variables in Visual Studio 2010 and VB.NET

You could just add a new Variable under the properties of your project Each time you want to get that variable you just have to use

My.Settings.(Name of variable)

That'll work for the entire Project in all forms

Partition Function COUNT() OVER possible using DISTINCT

I use a solution that is similar to that of David above, but with an additional twist if some rows should be excluded from the count. This assumes that [UserAccountKey] is never null.

-- subtract an extra 1 if null was ranked within the partition,
-- which only happens if there were rows where [Include] <> 'Y'
dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end asc
) 
+ dense_rank() over (
  partition by [Mth] 
  order by case when [Include] = 'Y' then [UserAccountKey] else null end desc
)
- max(case when [Include] = 'Y' then 0 else 1 end) over (partition by [Mth])
- 1

An SQL Fiddle with an extended example can be found here.

Preloading @font-face fonts?

Your head should include the preload rel as follows:

<head>
    ...
    <link rel="preload" as="font" href="/somefolder/font-one.woff2">
    <link rel="preload" as="font" href="/somefolder/font-two.woff2">
</head>

This way woff2 will be preloaded by browsers that support preload, and all the fallback formats will load as they normally do.
And your css font face should look similar to to this

@font-face {
    font-family: FontOne;
    src: url(../somefolder/font-one.eot);
    src: url(../somefolder/font-one.eot?#iefix) format('embedded-opentype'),
    url(../somefolder/font-one.woff2) format('woff2'), //Will be preloaded
    url(../somefolder/font-one.woff) format('woff'),
    url(../somefolder/font-one.ttf)  format('truetype'),
    url(../somefolder/font-one.svg#svgFontName) format('svg'); 
}
@font-face {
    font-family: FontTwo;
    src: url(../somefolder/font-two.eot);
    src: url(../somefolder/font-two.eot?#iefix) format('embedded-opentype'),
    url(../somefolder/font-two.woff2) format('woff2'), //Will be preloaded
    url(../somefolder/font-two.woff) format('woff'),
    url(../somefolder/font-two.ttf)  format('truetype'),
    url(../somefolder/font-two.svg#svgFontName) format('svg');
}

How to differ sessions in browser-tabs?

You can use link-rewriting to append a unique identifier to all your URLs when starting at a single page (e.g. index.html/jsp/whatever). The browser will use the same cookies for all your tabs so everything you put in cookies will not be unique.

Disabling Controls in Bootstrap

also you can use "readonly"

<select id="xxx" name="xxx" class="input-medium" readonly>

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I've the same problem and solved with this code. I put this code before the first call to my webservices.

javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
  new javax.net.ssl.HostnameVerifier(){

      public boolean verify(String hostname,
             javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost"); // or return true
      }
  });

It's simple and works fine.

Here is the original source.

Set field value with reflection

It's worth reading Oracle Java Tutorial - Getting and Setting Field Values

Field#set(Object object, Object value) sets the field represented by this Field object on the specified object argument to the specified new value.

It should be like this

f.set(objectOfTheClass, new ConcurrentHashMap<>());

You can't set any value in null Object If tried then it will result in NullPointerException


Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.

How can I alias a default import in JavaScript?

defaultMember already is an alias - it doesn't need to be the name of the exported function/thing. Just do

import alias from 'my-module';

Alternatively you can do

import {default as alias} from 'my-module';

but that's rather esoteric.

How to find the sum of an array of numbers

    <!DOCTYPE html>
    <html>
    <body>

      <p>Click the button to join two arrays.</p>
      <button onclick="myFunction()">Try it</button>
      <p id="demo"></p>
    <script>
var hege = [1, 2,4,6,7,8,8];
var stale = [1, 2,4,5];
function myFunction() {
    console.log((hege.length > stale.length))    
    var children  = (hege.length > stale.length)? abc1() :abc2();       document.getElementById("demo").innerHTML = children;
}
function abc1(){
    console.log(hege,"Abc1")    
    var abcd=hege.map(function (num, idx) {
        console.log(hege.length , idx)
        return stale.length>idx?num + stale[idx]:num;
    })
    return abcd;
}

function abc2(){

    console.log(hege,"Abc2",stale)    
    var abcd=stale.map(function (num, idx) {
        console.log(hege.length , idx)
        return hege.length>idx?num + hege[idx]:num;
    })
    return abcd;
}
</script>

</body>
</html>

How to increment a pointer address and pointer's value?

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

Maven 3 Archetype for Project With Spring, Spring MVC, Hibernate, JPA

A great Spring MVC quickstart archetype is available on GitHub, courtesy of kolorobot. Good instructions are provided on how to install it to your local Maven repo and use it to create a new Spring MVC project. He’s even helpfully included the Tomcat 7 Maven plugin in the archetypical project so that the newly created Spring MVC can be run from the command line without having to manually deploy it to an application server.

Kolorobot’s example application includes the following:

  • No-xml Spring MVC 3.2 web application for Servlet 3.0 environment
  • Apache Tiles with configuration in place,
  • Bootstrap
  • JPA 2.0 (Hibernate/HSQLDB)
  • JUnit/Mockito
  • Spring Security 3.1

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

Get keys of a Typescript interface as array of strings

I had a similar problem that I had a giant list of properties that I wanted to have both an interface, and an object out of it.

NOTE: I didn't want to write (type with keyboard) the properties twice! Just DRY.


One thing to note here is, interfaces are enforced types at compile-time, while objects are mostly run-time. (Source)

As @derek mentioned in another answer, the common denominator of interface and object can be a class that serves both a type and a value.

So, TL;DR, the following piece of code should satisfy the needs:

class MyTableClass {
    // list the propeties here, ONLY WRITTEN ONCE
    id = "";
    title = "";
    isDeleted = false;
}

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// This is the pure interface version, to be used/exported
interface IMyTable extends MyTableClass { };

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Props type as an array, to be exported
type MyTablePropsArray = Array<keyof IMyTable>;

// Props array itself!
const propsArray: MyTablePropsArray =
    Object.keys(new MyTableClass()) as MyTablePropsArray;

console.log(propsArray); // prints out  ["id", "title", "isDeleted"]


// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

// Example of creating a pure instance as an object
const tableInstance: MyTableClass = { // works properly!
    id: "3",
    title: "hi",
    isDeleted: false,
};

(Here is the above code in Typescript Playground to play more)

PS. If you don't want to assign initial values to the properties in the class, and stay with the type, you can do the constructor trick:

class MyTableClass {
    // list the propeties here, ONLY WRITTEN ONCE
    constructor(
        readonly id?: string,
        readonly title?: string,
        readonly isDeleted?: boolean,
    ) {}
}

console.log(Object.keys(new MyTableClass()));  // prints out  ["id", "title", "isDeleted"] 

Constructor Trick in TypeScript Playground.

Capturing image from webcam in java?

This kind of goes off of gt_ebuddy's answer using JavaCV, but my video output is at a much higher quality then his answer. I've also added some other random improvements (such as closing down the program when ESC and CTRL+C are pressed, and making sure to close down the resources the program uses properly).

import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;

import javax.swing.AbstractAction;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.KeyStroke;

import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.OpenCVFrameGrabber;
import com.googlecode.javacv.cpp.opencv_core.IplImage;

public class HighRes extends JComponent implements Runnable {
    private static final long serialVersionUID = 1L;

    private static CanvasFrame frame = new CanvasFrame("Web Cam");
    private static boolean running = false;
    private static int frameWidth = 800;
    private static int frameHeight = 600;
    private static OpenCVFrameGrabber grabber = new OpenCVFrameGrabber(0);
    private static BufferedImage bufImg;

    public HighRes()
    {
        // setup key bindings
        ActionMap actionMap = frame.getRootPane().getActionMap();
        InputMap inputMap = frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);

        for (Keys direction : Keys.values())
        {
            actionMap.put(direction.getText(), new KeyBinding(direction.getText()));
            inputMap.put(direction.getKeyStroke(), direction.getText());
        }

        frame.getRootPane().setActionMap(actionMap);
        frame.getRootPane().setInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);

        // setup window listener for close action
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                stop();
            }
        });
    }

    public static void main(String... args)
    {
        HighRes webcam = new HighRes();
        webcam.start();
    }

    @Override
    public void run()
    {
        try
        {

            grabber.setImageWidth(frameWidth);
            grabber.setImageHeight(frameHeight);
            grabber.start();
            while (running)
            {

                final IplImage cvimg = grabber.grab();
                if (cvimg != null)
                {

                    // cvFlip(cvimg, cvimg, 1); // mirror

                    // show image on window
                    bufImg = cvimg.getBufferedImage();
                    frame.showImage(bufImg);
                }
            }
            grabber.stop();
            grabber.release();
            frame.dispose();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    public void start()
    {
        new Thread(this).start();
        running = true;
    }

    public void stop()
    {
        running = false;
    }

    private class KeyBinding extends AbstractAction {

        private static final long serialVersionUID = 1L;

        public KeyBinding(String text)
        {
            super(text);
            putValue(ACTION_COMMAND_KEY, text);
        }

        @Override
        public void actionPerformed(ActionEvent e)
        {
            String action = e.getActionCommand();
            if (action.equals(Keys.ESCAPE.toString()) || action.equals(Keys.CTRLC.toString())) stop();
            else System.out.println("Key Binding: " + action);
        }
    }
}

enum Keys
{
    ESCAPE("Escape", KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0)),
    CTRLC("Control-C", KeyStroke.getKeyStroke(KeyEvent.VK_C, KeyEvent.CTRL_DOWN_MASK)),
    UP("Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
    DOWN("Down", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
    LEFT("Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),
    RIGHT("Right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));

    private String text;
    private KeyStroke keyStroke;

    Keys(String text, KeyStroke keyStroke)
    {
        this.text = text;
        this.keyStroke = keyStroke;
    }

    public String getText()
    {
        return text;
    }

    public KeyStroke getKeyStroke()
    {
        return keyStroke;
    }

    @Override
    public String toString()
    {
        return text;
    }
}

SQLite in Android How to update a specific row

  1. I personally prefere .update for its convenience. But execsql will work same.
  2. You are right with your guess that the problem is your content values. You should create a ContentValue Object and put the values for your database row there.

This code should fix your example:

 ContentValues data=new ContentValues();
 data.put("Field1","bob");
 data.put("Field2",19);
 data.put("Field3","male");
 DB.update(Tablename, data, "_id=" + id, null);

Blur or dim background when Android PopupWindow active

findViewById(R.id.drawer_layout).setAlpha((float) 0.7);

R.id.drawer_layout is the id of the layout of which you want to dim the brightness.

In a URL, should spaces be encoded using %20 or +?

It shouldn't matter, any more than if you encoded the letter A as %41.

However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.

How to target the href to div

Try this code in jquery

$(document).ready(function(){
  $("a").click(function(){
  var id=$(this).attr('href');
  var value=$(id).text();
  $(".target").text(value);
  });
});

NuGet: 'X' already has a dependency defined for 'Y'

I fixed a similar issue in my solution by:

  1. Opening up a command prompt
  2. Navigating to the .nuget folder in my solution
  3. Running nuget update -self

This upgraded the copy of NuGet.exe that was in my solution from 2.8.0 to 3.4.4, which fixed the 'X' already has a dependency defined for 'Y' error that was stopping it from downloading SSH.NET automatically before building.

(If your solution doesn't have a copy of NuGet.exe in it - and it might not - then you should try the solution in TN's answer instead)

Use of PUT vs PATCH methods in REST API real life scenarios

The difference between PUT and PATCH is that:

  1. PUT is required to be idempotent. In order to achieve that, you have to put the entire complete resource in the request body.
  2. PATCH can be non-idempotent. Which implies it can also be idempotent in some cases, such as the cases you described.

PATCH requires some "patch language" to tell the server how to modify the resource. The caller and the server need to define some "operations" such as "add", "replace", "delete". For example:

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "zip": "10001"
}

PATCH /contacts/1
{
 [{"operation": "add", "field": "address", "value": "123 main street"},
  {"operation": "replace", "field": "email", "value": "[email protected]"},
  {"operation": "delete", "field": "zip"}]
}

GET /contacts/1
{
  "id": 1,
  "name": "Sam Kwee",
  "email": "[email protected]",
  "state": "NY",
  "address": "123 main street",
}

Instead of using explicit "operation" fields, the patch language can make it implicit by defining conventions like:

in the PATCH request body:

  1. The existence of a field means "replace" or "add" that field.
  2. If the value of a field is null, it means delete that field.

With the above convention, the PATCH in the example can take the following form:

PATCH /contacts/1
{
  "address": "123 main street",
  "email": "[email protected]",
  "zip":
}

Which looks more concise and user-friendly. But the users need to be aware of the underlying convention.

With the operations I mentioned above, the PATCH is still idempotent. But if you define operations like: "increment" or "append", you can easily see it won't be idempotent anymore.

Import data into Google Colaboratory

An official example notebook demonstrating local file upload/download and integration with Drive and sheets is available here: https://colab.research.google.com/notebooks/io.ipynb

The simplest way to share files is to mount your Google Drive.

To do this, run the following in a code cell:

from google.colab import drive
drive.mount('/content/drive')

It will ask you to visit a link to ALLOW "Google Files Stream" to access your drive. After that a long alphanumeric auth code will be shown that needs to be entered in your Colab's notebook.

Afterward, your Drive files will be mounted and you can browse them with the file browser in the side panel.

enter image description here

Here's a full example notebook

JavaScript Nested function

Functions are another type of variable in JavaScript (with some nuances of course). Creating a function within another function changes the scope of the function in the same way it would change the scope of a variable. This is especially important for use with closures to reduce total global namespace pollution.

The functions defined within another function won't be accessible outside the function unless they have been attached to an object that is accessible outside the function:

function foo(doBar)
{
  function bar()
  {
    console.log( 'bar' );
  }

  function baz()
  {
    console.log( 'baz' );
  }

  window.baz = baz;
  if ( doBar ) bar();
}

In this example, the baz function will be available for use after the foo function has been run, as it's overridden window.baz. The bar function will not be available to any context other than scopes contained within the foo function.

as a different example:

function Fizz(qux)
{
  this.buzz = function(){
    console.log( qux );
  };
}

The Fizz function is designed as a constructor so that, when run, it assigns a buzz function to the newly created object.

How do I create variable variables?

Whenever you want to use variable variables, it's probably better to use a dictionary. So instead of writing

$foo = "bar"
$$foo = "baz"

you write

mydict = {}
foo = "bar"
mydict[foo] = "baz"

This way you won't accidentally overwrite previously existing variables (which is the security aspect) and you can have different "namespaces".

S3 - Access-Control-Allow-Origin Header

@jordanstephens said this in a comment, but it kind of gets lost and was a really easy fix for me.

I simply added HEAD method and clicked saved and it started working.

_x000D_
_x000D_
<CORSConfiguration>_x000D_
 <CORSRule>_x000D_
  <AllowedOrigin>*</AllowedOrigin>_x000D_
  <AllowedMethod>GET</AllowedMethod>_x000D_
  <AllowedMethod>HEAD</AllowedMethod> <!-- Add this -->_x000D_
  <MaxAgeSeconds>3000</MaxAgeSeconds>_x000D_
  <AllowedHeader>Authorization</AllowedHeader>_x000D_
 </CORSRule>_x000D_
</CORSConfiguration>
_x000D_
_x000D_
_x000D_

How to capture the android device screen content?

According to this link, it is possible to use ddms in the tools directory of the android sdk to take screen captures.

To do this within an application (and not during development), there are also applications to do so. But as @zed_0xff points out it certainly requires root.

How to delete a folder with files using Java

As mentioned, Java isn't able to delete a folder that contains files, so first delete the files and then the folder.

Here's a simple example to do this:

import org.apache.commons.io.FileUtils;



// First, remove files from into the folder 
FileUtils.cleanDirectory(folder/path);

// Then, remove the folder
FileUtils.deleteDirectory(folder/path);

Or:

FileUtils.forceDelete(new File(destination));

'Use of Unresolved Identifier' in Swift

One possible issue is that your new class has a different Target or different Targets from the other one.

For example, it might have a testing target while the other one doesn't. For this specific case, you have to include all of your classes in the testing target or none of them.

Targets

Replacing all non-alphanumeric characters with empty strings

I made this method for creating filenames:

public static String safeChar(String input)
{
    char[] allowed = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_".toCharArray();
    char[] charArray = input.toString().toCharArray();
    StringBuilder result = new StringBuilder();
    for (char c : charArray)
    {
        for (char a : allowed)
        {
            if(c==a) result.append(a);
        }
    }
    return result.toString();
}

What are some good Python ORM solutions?

SQLAlchemy's declarative extension, which is becoming standard in 0.5, provides an all in one interface very much like that of Django or Storm. It also integrates seamlessly with classes/tables configured using the datamapper style:

Base = declarative_base()

class Foo(Base):
    __tablename__ = 'foos'
    id = Column(Integer, primary_key=True)

class Thing(Base):
    __tablename__ = 'things'

    id = Column(Integer, primary_key=True)
    name = Column(Unicode)
    description = Column(Unicode)
    foo_id = Column(Integer, ForeignKey('foos.id'))
    foo = relation(Foo)

engine = create_engine('sqlite://')

Base.metadata.create_all(engine)  # issues DDL to create tables

session = sessionmaker(bind=engine)()

foo = Foo()
session.add(foo)
thing = Thing(name='thing1', description='some thing')
thing.foo = foo  # also adds Thing to session
session.commit()

Test file upload using HTTP PUT method

For curl, how about using the -d switch? Like: curl -X PUT "localhost:8080/urlstuffhere" -d "@filename"?

How do I detect whether 32-bit Java is installed on x64 Windows, only looking at the filesystem and registry?

If it is not Oracle's Java, you may not be able to tell. When I install Oracle Java 64-bit, the files go into C:\Program Files\Java, but when I install a 32-bit version, they default to C:\Program Files (x86)\Java instead. Of course, the person who installed Java could have overridden those defaults.

Splitting dataframe into multiple dataframes

The method based on list comprehension and groupby- Which stores all the split dataframe in list variable and can be accessed using the index.

Example

ans = [pd.DataFrame(y) for x, y in DF.groupby('column_name', as_index=False)]

ans[0]
ans[0].column_name

Create a new database with MySQL Workbench

In MySQL Work bench 6.0 CE.

  1. You launch MySQL Workbench.
  2. From Menu Bar click on Database and then select "Connect to Database"
  3. It by default showing you default settings other wise you choose you host name, user name and password. and click to ok.
  4. As in above define that you should click write on existing database but if you don't have existing new database then you may choose the option from the icon menu that is provided on below the menu bar. Now keep the name as you want and enjoy ....

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

maybe useful for somebody, I got next problem on windows 8, apache 2.4, php 7+.

php.ini conf>

extension_dir="C:/Server/PHP7/ext"

php on apache works ok but on cli problem with libs loading, as a result, I changed to

extension_dir="C:/server/PHP7/ext"

What is the proper declaration of main in C++?

From Standard docs., 3.6.1.2 Main Function,

It shall have a return type of type int, but otherwise its type is implementation-defined. All implementations shall allow both of the following definitions of main:

int main() { / ... / } and int main(int argc, char* argv[]) { / ... / }

In the latter form argc shall be the number of arguments passed to the program from the environment in which the program is run.If argc is nonzero these arguments shall be supplied in argv[0] through argv[argc-1] as pointers to the initial characters of null-terminated multibyte strings.....

Hope that helps..

How to check if a file exists in Ansible?

Discovered that calling stat is slow and collects a lot of info that is not required for file existence check.
After spending some time searching for solution, i discovered following solution, which works much faster:

- raw: test -e /path/to/something && echo true || echo false
  register: file_exists

- debug: msg="Path exists"
  when: file_exists == true

getContext is not a function

I got the same error because I had accidentally used <div> instead of <canvas> as the element on which I attempt to call getContext.

How to make a form close when pressing the escape key?

The best way i found is to override the "ProcessDialogKey" function. This way canceling a open control is still possible because the function is only called when no other control uses the pressed Key.

This is the same behaviour as when setting a CancelButton. Using the KeyDown Event fires always and thus the form would close even when it should cancel the edit of an open editor.

protected override bool ProcessDialogKey(Keys keyData)
{
    if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
    {
        this.Close();
        return true;
    }
    return base.ProcessDialogKey(keyData);
}

How can I make XSLT work in chrome?

As close as I can tell, Chrome is looking for the header

Content-Type: text/xml

Then it works --- other iterations have failed.

Make sure your web server is providing this. It also explains why it fails for file://URI xml files.

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

IF Statement multiple conditions, same statement

if (columnname != a && columnname != b && columnname != c 
        && (columnname != A2 || checkbox.checked))
    {
      "statement 1"
    }

Reading RFID with Android phones

First is understanding that RFID is very generic term. NFC is subset of RFID technology. NFC is used for prox card, credit cards, tap and go payment system. Your phones can read and emulate NFC (Apple pay, Google pay, etc.), if they support NFC. NFC is very short distance and low power - which is why you see tap and go type usage.

The more common RFID are the tags you see here and there. They come in a wide ranges of styles, uses and frequency.

HF - high frequency tags are what they use for "chipping" animals - cattle, dogs, cats. Read range is about 12 inches and requires an external antenna that is powered the bigger the antenna the more power it needs and the further it can read.

UFH tags look similar to HF tags but have a read range of several feet.

Also HF tags come single read and multi read. UFH is exclusviely multi read.

Mutiread means when a reader is active, you can litterally read about 1700 tags in under 10 seconds.

But this is a function of the size of the antenna and how much power you can push through the reader.

As to the direct question about Android and RFID - the best way to go is to get an external handheld reader that connects to your mobile device via Bluetooth. Bluetooth libraries exist for all mobile devices - Android, Apple, Windows. From there its just a matter of the manufacturer documentation about how to open a socket to the reader and how to decode the serial information.

The TSL line of readers is very popular because you don't have to deal with reading bytes and all that low level serial jazz that other manufactures do. They have a nice set of commands that are easy to use to control the reader.

Other manufactures are basic in that you open a serial socket and then read the output like you would see in terminal app like PuTTY.

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

How to remove class from all elements jquery

$(".edgetoedge>li").removeClass("highlight");

How to run multiple SQL commands in a single SQL connection?

The following should work. Keep single connection open all time, and just create new commands and execute them.

using (SqlConnection connection = new SqlConnection(connectionString))
{
    connection.Open();
    using (SqlCommand command1 = new SqlCommand(commandText1, connection))
    {
    }
    using (SqlCommand command2 = new SqlCommand(commandText2, connection))
    {
    }
    // etc
}

Setting DataContext in XAML in WPF

This code will always fail.

As written, it says: "Look for a property named "Employee" on my DataContext property, and set it to the DataContext property". Clearly that isn't right.

To get your code to work, as is, change your window declaration to:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SampleApplication"
    Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
   <local:Employee/>
</Window.DataContext>

This declares a new XAML namespace (local) and sets the DataContext to an instance of the Employee class. This will cause your bindings to display the default data (from your constructor).

However, it is highly unlikely this is actually what you want. Instead, you should have a new class (call it MainViewModel) with an Employee property that you then bind to, like this:

public class MainViewModel
{
   public Employee MyEmployee { get; set; } //In reality this should utilize INotifyPropertyChanged!
}

Now your XAML becomes:

<Window x:Class="SampleApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SampleApplication"
        Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
       <local:MainViewModel/>
    </Window.DataContext>
    ...
    <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding MyEmployee.EmpID}" />
    <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding MyEmployee.EmpName}" />

Now you can add other properties (of other types, names), etc. For more information, see Implementing the Model-View-ViewModel Pattern

How to execute .sql script file using JDBC

You should be able to parse the SQL file into statements. And run a single statement a time. If you know that your file consists of simple insert/update/delete statements you can use a semicolon as statement delimiter. In common case you have a task to create your specific SQL-dialect parser.

How do I repair an InnoDB table?

stop your application...or stop your slave so no new rows are being added

create table <new table> like <old table>;
insert <new table> select * from <old table>;
truncate table  <old table>;
insert <old table> select * from <new table>;

restart your server or slave

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

SLF4J: Class path contains multiple SLF4J bindings

Sbt version:

Append exclude("org.slf4j", "slf4j-log4j12") to the dependency that transitively includes slf4j-log4j12. For example, when using Spark with Log4j 2.6:

libraryDependencies ++= Seq(
  // One SLF4J implementation (log4j-slf4j-impl) is here:
  "org.apache.logging.log4j" % "log4j-api" % "2.6.1",
  "org.apache.logging.log4j" % "log4j-core" % "2.6.1",
  "org.apache.logging.log4j" % "log4j-slf4j-impl" % "2.6.1",
  // The other implementation (slf4j-log4j12) would be transitively
  // included by Spark. Prevent that with exclude().
  "org.apache.spark" %% "spark-core" % "1.5.1" exclude("org.slf4j", "slf4j-log4j12")
)

How to convert HTML to PDF using iTextSharp

As of 2018, there is also iText7 (A next iteration of old iTextSharp library) and its HTML to PDF package available: itext7.pdfhtml

Usage is straightforward:

HtmlConverter.ConvertToPdf(
    new FileInfo(@"Path\to\Html\File.html"),
    new FileInfo(@"Path\to\Pdf\File.pdf")
);

Method has many more overloads.

Update: iText* family of products has dual licensing model: free for open source, paid for commercial use.

Visual Studio can't build due to rc.exe

From what I have found, if you have a windows 7 OS, doing the following steps will fix the problem:

1) go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A\Bin

2) then copy RC.exe and RcDll from this file

3) go to C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\bin and paste the two files you have copied into it.

I had the same problem, and the above posted solution did not work. My solution was derived from it, and it worked for me, if the ones above do not work you can give this one a try.

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

What's your most controversial programming opinion?

The best code is often the code you don't write. As programmers we want to solve every problem by writing some cool method. Anytime we can solve a problem and still give the users 80% of what they want without introducing more code to maintain and test we have provided waaaay more value.

Dynamically changing font size of UILabel

Here's a Swift extension for UILabel. It runs a binary search algorithm to resize the font based off the width and height of the label's bounds. Tested to work with iOS 9 and autolayout.

USAGE: Where <label> is your pre-defined UILabel that needs font resizing

<label>.fitFontForSize()

By Default, this function searches in within the range of 5pt and 300pt font sizes and sets the font to fit its text "perfectly" within the bounds (accurate within 1.0pt). You could define the parameters so that it, for example, searches between 1pt and the label's current font size accurately within 0.1pts in the following way:

<label>.fitFontForSize(1.0, maxFontSize: <label>.font.pointSize, accuracy:0.1)

Copy/Paste the following code into your file

extension UILabel {

    func fitFontForSize(var minFontSize : CGFloat = 5.0, var maxFontSize : CGFloat = 300.0, accuracy : CGFloat = 1.0) {
        assert(maxFontSize > minFontSize)
        layoutIfNeeded() // Can be removed at your own discretion
        let constrainedSize = bounds.size
        while maxFontSize - minFontSize > accuracy {
            let midFontSize : CGFloat = ((minFontSize + maxFontSize) / 2)
            font = font.fontWithSize(midFontSize)
            sizeToFit()
            let checkSize : CGSize = bounds.size
            if  checkSize.height < constrainedSize.height && checkSize.width < constrainedSize.width {
                minFontSize = midFontSize
            } else {
                maxFontSize = midFontSize
            }
        }
        font = font.fontWithSize(minFontSize)
        sizeToFit()
        layoutIfNeeded() // Can be removed at your own discretion
    }

}

NOTE: Each of the layoutIfNeeded() calls can be removed at your own discretion

Git: which is the default configured remote for branch?

For the sake of completeness: the previous answers tell how to set the upstream branch, but not how to see it.

There are a few ways to do this:

git branch -vv shows that info for all branches. (formatted in blue in most terminals)

cat .git/config shows this also.

For reference:

What to return if Spring MVC controller method doesn't return value?

There is nothing wrong with returning a void @ResponseBody and you should for POST requests.

Use HTTP status codes to define errors within exception handler routines instead as others are mentioning success status. A normal method as you have will return a response code of 200 which is what you want, any exception handler can then return an error object and a different code (i.e. 500).

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

Convert StreamReader to byte[]

Just throw everything you read into a MemoryStream and get the byte array in the end. As noted, you should be reading from the underlying stream to get the raw bytes.

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    var buffer = new byte[512];
    var bytesRead = default(int);
    while ((bytesRead = reader.BaseStream.Read(buffer, 0, buffer.Length)) > 0)
        memstream.Write(buffer, 0, bytesRead);
    bytes = memstream.ToArray();
}

Or if you don't want to manage the buffers:

var bytes = default(byte[]);
using (var memstream = new MemoryStream())
{
    reader.BaseStream.CopyTo(memstream);
    bytes = memstream.ToArray();
}

Return from a promise then()

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://web.dev/promises/#queuing-asynchronous-actions

Switch statement fall-through...should it be allowed?

I don't like my switch statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case statements all do exactly the same thing.

If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.

How to launch jQuery Fancybox on page load?

Fancybox currently does not directly support a way to automatically launch. The work around I was able to get working is creating a hidden anchor tag and triggering it's click event. Make sure your call to trigger the click event is included after the jQuery and Fancybox JS files are included. The code I used is as follows:

This sample script is embedded directly in the HTML, but it could also be included in a JS file.

<script type="text/javascript">
    $(document).ready(function() {
        $("#hidden_link").fancybox().trigger('click');
    });
</script>

Remove Top Line of Text File with PowerShell

Inspired by AASoft's answer, I went out to improve it a bit more:

  1. Avoid the loop variable $i and the comparison with 0 in every loop
  2. Wrap the execution into a try..finally block to always close the files in use
  3. Make the solution work for an arbitrary number of lines to remove from the beginning of the file
  4. Use a variable $p to reference the current directory

These changes lead to the following code:

$p = (Get-Location).Path

(Measure-Command {
    # Number of lines to skip
    $skip = 1
    $ins = New-Object System.IO.StreamReader ($p + "\test.log")
    $outs = New-Object System.IO.StreamWriter ($p + "\test-1.log")
    try {
        # Skip the first N lines, but allow for fewer than N, as well
        for( $s = 1; $s -le $skip -and !$ins.EndOfStream; $s++ ) {
            $ins.ReadLine()
        }
        while( !$ins.EndOfStream ) {
            $outs.WriteLine( $ins.ReadLine() )
        }
    }
    finally {
        $outs.Close()
        $ins.Close()
    }
}).TotalSeconds

The first change brought the processing time for my 60 MB file down from 5.3s to 4s. The rest of the changes is more cosmetic.

How to get diff between all files inside 2 folders that are on the web?

Once you have the source trees, e.g.

diff -ENwbur repos1/ repos2/ 

Even better

diff -ENwbur repos1/ repos2/  | kompare -o -

and have a crack at it in a good gui tool :)

  • -Ewb ignore the bulk of whitespace changes
  • -N detect new files
  • -u unified
  • -r recurse

Installing Google Protocol Buffers on mac

For v3 users.

http://google.github.io/proto-lens/installing-protoc.html

PROTOC_ZIP=protoc-3.7.1-osx-x86_64.zip
curl -OL https://github.com/protocolbuffers/protobuf/releases/download/v3.7.1/$PROTOC_ZIP
sudo unzip -o $PROTOC_ZIP -d /usr/local bin/protoc
sudo unzip -o $PROTOC_ZIP -d /usr/local 'include/*'
rm -f $PROTOC_ZIP

.gitignore exclude folder but include specific subfolder

There are a bunch of similar questions about this, so I'll post what I wrote before:

The only way I got this to work on my machine was to do it this way:

# Ignore all directories, and all sub-directories, and it's contents:
*/*

#Now ignore all files in the current directory 
#(This fails to ignore files without a ".", for example 
#'file.txt' works, but 
#'file' doesn't):
*.*

#Only Include these specific directories and subdirectories:
!wordpress/
!wordpress/*/
!wordpress/*/wp-content/
!wordpress/*/wp-content/themes/
!wordpress/*/wp-content/themes/*
!wordpress/*/wp-content/themes/*/*
!wordpress/*/wp-content/themes/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*
!wordpress/*/wp-content/themes/*/*/*/*/*

Notice how you have to explicitly allow content for each level you want to include. So if I have subdirectories 5 deep under themes, I still need to spell that out.

This is from @Yarin's comment here: https://stackoverflow.com/a/5250314/1696153

These were useful topics:

I also tried

*
*/*
**/**

and **/wp-content/themes/**

or /wp-content/themes/**/*

None of that worked for me, either. Lots of trial and error!

Check if at least two out of three booleans are true

Taking the answers (so far) here:

public class X
{
    static boolean a(final boolean a, final boolean b, final boolean c)
    {
    return ((a && b) || (b && c) || (a && c));
    }

    static boolean b(final boolean a, final boolean b, final boolean c)
    {
    return a ? (b || c) : (b && c);
    }

    static boolean c(final boolean a, final boolean b, final boolean c)
    {
    return ((a & b) | (b & c) | (c & a));
    }

    static boolean d(final boolean a, final boolean b, final boolean c)
    {
    return ((a?1:0)+(b?1:0)+(c?1:0) >= 2);
    }
}

and running them through the decompiler (javap -c X > results.txt):

Compiled from "X.java"
public class X extends java.lang.Object{
public X();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

static boolean a(boolean, boolean, boolean);
  Code:
   0:   iload_0
   1:   ifeq    8
   4:   iload_1
   5:   ifne    24
   8:   iload_1
   9:   ifeq    16
   12:  iload_2
   13:  ifne    24
   16:  iload_0
   17:  ifeq    28
   20:  iload_2
   21:  ifeq    28
   24:  iconst_1
   25:  goto    29
   28:  iconst_0
   29:  ireturn

static boolean b(boolean, boolean, boolean);
  Code:
   0:   iload_0
   1:   ifeq    20
   4:   iload_1
   5:   ifne    12
   8:   iload_2
   9:   ifeq    16
   12:  iconst_1
   13:  goto    33
   16:  iconst_0
   17:  goto    33
   20:  iload_1
   21:  ifeq    32
   24:  iload_2
   25:  ifeq    32
   28:  iconst_1
   29:  goto    33
   32:  iconst_0
   33:  ireturn

static boolean c(boolean, boolean, boolean);
  Code:
   0:   iload_0
   1:   iload_1
   2:   iand
   3:   iload_1
   4:   iload_2
   5:   iand
   6:   ior
   7:   iload_2
   8:   iload_0
   9:   iand
   10:  ior
   11:  ireturn

static boolean d(boolean, boolean, boolean);
  Code:
   0:   iload_0
   1:   ifeq    8
   4:   iconst_1
   5:   goto    9
   8:   iconst_0
   9:   iload_1
   10:  ifeq    17
   13:  iconst_1
   14:  goto    18
   17:  iconst_0
   18:  iadd
   19:  iload_2
   20:  ifeq    27
   23:  iconst_1
   24:  goto    28
   27:  iconst_0
   28:  iadd
   29:  iconst_2
   30:  if_icmplt   37
   33:  iconst_1
   34:  goto    38
   37:  iconst_0
   38:  ireturn
}

You can see that the ?: ones are slightly better then the fixed up version of your original. The one that is the best is the one that avoids branching altogether. That is good from the point of view of fewer instructions (in most cases) and better for branch prediction parts of the CPU, since a wrong guess in the branch prediction can cause CPU stalling.

I'd say the most efficient one is the one from moonshadow overall. It uses the fewest instructions on average and reduces the chance for pipeline stalls in the CPU.

To be 100% sure you would need to find out the cost (in CPU cycles) for each instruction, which, unfortunately isn't readily available (you would have to look at the source for hotspot and then the CPU vendors specs for the time taken for each generated instruction).

See the updated answer by Rotsor for a runtime analysis of the code.

Is it possible that one domain name has multiple corresponding IP addresses?

This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

If you are looking for TypeScript working functions then follow

public numericValue = (alphaChar: any) => alphaChar.toUpperCase().charCodeAt(0) - 64;

public alphaValue = (numericDigit: any) => 
   String.fromCharCode(64 + numericDigit) : '';

You can make several checks like (numericDigit >= 1 && numericDigit <= 26) ? inside function body as per the requirements.

Use space as a delimiter with cut command

I have an answer (I admit somewhat confusing answer) that involvessed, regular expressions and capture groups:

  • \S* - first word
  • \s* - delimiter
  • (\S*) - second word - captured
  • .* - rest of the line

As a sed expression, the capture group needs to be escaped, i.e. \( and \).

The \1 returns a copy of the captured group, i.e. the second word.

$ echo "alpha beta gamma delta" | sed 's/\S*\s*\(\S*\).*/\1/'
beta

When you look at this answer, its somewhat confusing, and, you may think, why bother? Well, I'm hoping that some, may go "Aha!" and will use this pattern to solve some complex text extraction problems with a single sed expression.

Most efficient way to concatenate strings?

It really depends on your usage pattern. A detailed benchmark between string.Join, string,Concat and string.Format can be found here: String.Format Isn't Suitable for Intensive Logging

(This is actually the same answer I gave to this question)

How to run a cron job on every Monday, Wednesday and Friday?

Use this command to add job

crontab -e

In this format:

0 19 * * 1,3,5 /path to your file/file.php

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

When the plugin detects that you're using an API that's no longer supported, it can now provide more-detailed information to help you determine where that API is being used. To see the additional info, you need to include the following in your project's gradle.properties file:

android.debug.obsoleteApi=true

iPhone system font

UIFont *systemFont = [UIFont systemFontOfSize:[UIFont systemFontSize]];

This will give you the system font with the default system font size applied for the label texts by default.

Select method of Range class failed via VBA

This is how you get around that in an easy non-complicated way.
Instead of using sheet(x).range use Activesheet.range("range").select

How to add shortcut keys for java code in eclipse

Type syso and ctrl + space for System.out.println()

Java out.println() how is this possible?

Well, you would typically use

System.out.println("print something");

which doesn't require any imports. However, since out is a static field inside of System, you could write use a static import like this:

import static java.lang.System.*;

class Test {
    public static void main(String[] args) {
        out.println("print something");
    }
}

Take a look at this link. Typically you would only do this if you are using a lot of static methods from a particular class, like I use it all the time for junit asserts, and easymock.

Convert Json Array to normal Java list

Maybe it's only a workaround (not very efficient) but you could do something like this:

String[] resultingArray = yourJSONarray.join(",").split(",");

Obviously you can change the ',' separator with anything you like (I had a JSONArray of email addresses)

Seeing the console's output in Visual Studio 2010?

You can use the System.Diagnostics.Debug.Write or System.Runtime.InteropServices method to write messages to the Output Window.

Android Studio - local path doesn't exist

Just Close The Android Studio and Restart it and Sysnc. Gradle Files Again......And Run The Project Again

Why do we have to normalize the input for an artificial neural network?

Looking at the neural network from the outside, it is just a function that takes some arguments and produces a result. As with all functions, it has a domain (i.e. a set of legal arguments). You have to normalize the values that you want to pass to the neural net in order to make sure it is in the domain. As with all functions, if the arguments are not in the domain, the result is not guaranteed to be appropriate.

The exact behavior of the neural net on arguments outside of the domain depends on the implementation of the neural net. But overall, the result is useless if the arguments are not within the domain.

How to return a string value from a Bash function

You could also capture the function output:

#!/bin/bash
function getSomeString() {
     echo "tadaa!"
}

return_var=$(getSomeString)
echo $return_var
# Alternative syntax:
return_var=`getSomeString`
echo $return_var

Looks weird, but is better than using global variables IMHO. Passing parameters works as usual, just put them inside the braces or backticks.

How to set the max value and min value of <input> in html5 by javascript or jquery?

Try this:

<input type="number" max="???" min="???" step="0.5" id="myInput"/>

$("#myInput").attr({
   "max" : 10,
   "min" : 2
});

Note:This will set max and min value only to single input

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Send a file via HTTP POST with C#

To send the raw file only:

using(WebClient client = new WebClient()) {
    client.UploadFile(address, filePath);
}

If you want to emulate a browser form with an <input type="file"/>, then that is harder. See this answer for a multipart/form-data answer.

Nginx not picking up site in sites-enabled?

Include sites-available/default in sites-enabled/default. It requires only one line.

In sites-enabled/default (new config version?):

It seems that the include path is relative to the file that included it

include sites-available/default;

See the include documentation.


I believe that certain versions of nginx allows including/linking to other files purely by having a single line with the relative path to the included file. (At least that's what it looked like in some "inherited" config files I've been using, until a new nginx version broke them.)

In sites-enabled/default (old config version?):

It seems that the include path is relative to the current file

../sites-available/default

How to convert UTF8 string to byte array?

The logic of encoding Unicode in UTF-8 is basically:

  • Up to 4 bytes per character can be used. The fewest number of bytes possible is used.
  • Characters up to U+007F are encoded with a single byte.
  • For multibyte sequences, the number of leading 1 bits in the first byte gives the number of bytes for the character. The rest of the bits of the first byte can be used to encode bits of the character.
  • The continuation bytes begin with 10, and the other 6 bits encode bits of the character.

Here's a function I wrote a while back for encoding a JavaScript UTF-16 string in UTF-8:

function toUTF8Array(str) {
    var utf8 = [];
    for (var i=0; i < str.length; i++) {
        var charcode = str.charCodeAt(i);
        if (charcode < 0x80) utf8.push(charcode);
        else if (charcode < 0x800) {
            utf8.push(0xc0 | (charcode >> 6), 
                      0x80 | (charcode & 0x3f));
        }
        else if (charcode < 0xd800 || charcode >= 0xe000) {
            utf8.push(0xe0 | (charcode >> 12), 
                      0x80 | ((charcode>>6) & 0x3f), 
                      0x80 | (charcode & 0x3f));
        }
        // surrogate pair
        else {
            i++;
            // UTF-16 encodes 0x10000-0x10FFFF by
            // subtracting 0x10000 and splitting the
            // 20 bits of 0x0-0xFFFFF into two halves
            charcode = 0x10000 + (((charcode & 0x3ff)<<10)
                      | (str.charCodeAt(i) & 0x3ff));
            utf8.push(0xf0 | (charcode >>18), 
                      0x80 | ((charcode>>12) & 0x3f), 
                      0x80 | ((charcode>>6) & 0x3f), 
                      0x80 | (charcode & 0x3f));
        }
    }
    return utf8;
}

Best way to retrieve variable values from a text file?

Use ConfigParser.

Your config:

[myvars]
var_a: 'home'
var_b: 'car'
var_c: 15.5

Your python code:

import ConfigParser

config = ConfigParser.ConfigParser()
config.read("config.ini")
var_a = config.get("myvars", "var_a")
var_b = config.get("myvars", "var_b")
var_c = config.get("myvars", "var_c")

commons httpclient - Adding query string parameters to GET/POST request

If you want to add a query parameter after you have created the request, try casting the HttpRequest to a HttpBaseRequest. Then you can change the URI of the casted request:

HttpGet someHttpGet = new HttpGet("http://google.de");

URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
        "That was easy!").build();

((HttpRequestBase) someHttpGet).setURI(uri);

How to remove all whitespace from a string?

I just learned about the "stringr" package to remove white space from the beginning and end of a string with str_trim( , side="both") but it also has a replacement function so that:

a <- " xx yy 11 22 33 " 
str_replace_all(string=a, pattern=" ", repl="")

[1] "xxyy112233"

Pycharm: run only part of my Python file

Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e

For this to work properly, you'll have to run everything this way.

enter image description here

Difference between Date(dateString) and new Date(dateString)

Correct ways to use Date : https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

Also, the following piece of code shows how, with a single definition of the function "Animal", it can be a) called directly and b) instantiated by treating it as a constructor function

function Animal(){
    this.abc = 1;
    return 1234; 
}

var x = new Animal();
var y = Animal();

console.log(x); //prints object containing property abc set to value 1
console.log(y); // prints 1234

Objective-C : BOOL vs bool

The accepted answer has been edited and its explanation become a bit incorrect. Code sample has been refreshed, but the text below stays the same. You cannot assume that BOOL is a char for now since it depends on architecture and platform. Thus, if you run you code at 32bit platform(for example iPhone 5) and print @encode(BOOL) you will see "c". It corresponds to a char type. But if you run you code at iPhone 5s(64 bit) you will see "B". It corresponds to a bool type.

Creating a jQuery object from a big HTML-string

Update:

From jQuery 1.8, we can use $.parseHTML, which will parse the HTML string to an array of DOM nodes. eg:

var dom_nodes = $($.parseHTML('<div><input type="text" value="val" /></div>'));

alert( dom_nodes.find('input').val() );

DEMO


var string = '<div><input type="text" value="val" /></div>';

$('<div/>').html(string).contents();

DEMO

What's happening in this code:

  • $('<div/>') is a fake <div> that does not exist in the DOM
  • $('<div/>').html(string) appends string within that fake <div> as children
  • .contents() retrieves the children of that fake <div> as a jQuery object

If you want to make .find() work then try this:

var string = '<div><input type="text" value="val" /></div>',
    object = $('<div/>').html(string).contents();

alert( object.find('input').val() );

DEMO

Does PHP have threading?

If anyone cares, I have revived php_threading (not the same as threads, but similar) and I actually have it to the point where it works (somewhat) well!

Project page

Download (for Windows PHP 5.3 VC9 TS)

Examples

README

mysql: SOURCE error 2?

The solution for me was file permissions in Windows. Just give full control in the file to all users and it will work. After the import, get the permissions back to what it was before.

How to keep footer at bottom of screen

You could use position:fixed; to bottom.

eg:

#footer{
 position:fixed;
 bottom:0;
 left:0;
}

Cannot connect to local SQL Server with Management Studio

I was having this problem on a Windows 7 (64 bit) after a power outage. The SQLEXPRESS service was not started even though is status was set to 'Automatic' and the mahine had been rebooted several times. Had to start the service manually.

Asynchronous Requests with Python requests

If you want to use asyncio, then requests-async provides async/await functionality for requests - https://github.com/encode/requests-async

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

It would be interesting to know the values supplied for the two ? placeholders.

how to call an ASP.NET c# method using javascript

PageMethod an easier and faster approach for Asp.Net AJAX We can easily improve user experience and performance of web applications by unleashing the power of AJAX. One of the best things which I like in AJAX is PageMethod.

PageMethod is a way through which we can expose server side page's method in java script. This brings so many opportunities we can perform lots of operations without using slow and annoying post backs.

In this post I am showing the basic use of ScriptManager and PageMethod. In this example I am creating a User Registration form, in which user can register against his email address and password. Here is the markup of the page which I am going to develop:

<body>
    <form id="form1" runat="server">
    <div>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup"  />
    </div>
    </form>
</body>
</html>

To setup page method, first you have to drag a script manager on your page.

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>

Also notice that I have changed EnablePageMethods="true".
This will tell ScriptManager that I am going to call PageMethods from client side.

Now next step is to create a Server Side function.
Here is the function which I created, this function validates user's input:

[WebMethod]
public static string RegisterUser(string email, string password)
{
    string result = "Congratulations!!! your account has been created.";
    if (email.Length == 0)//Zero length check
    {
        result = "Email Address cannot be blank";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }
    else if (!email.Contains(".") || !email.Contains("@")) //some other basic checks
    {
        result = "Not a valid email address";
    }

    else if (password.Length == 0)
    {
        result = "Password cannot be blank";
    }
    else if (password.Length < 5)
    {
        result = "Password cannot be less than 5 chars";
    }

    return result;
}

To tell script manager that this method is accessible through javascript we need to ensure two things:
First: This method should be 'public static'.
Second: There should be a [WebMethod] tag above method as written in above code.

Now I have created server side function which creates account. Now we have to call it from client side. Here is how we can call that function from client side:

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

To call my server side method Register user, ScriptManager generates a proxy function which is available in PageMethods.
My server side function has two paramaters i.e. email and password, after that parameters we have to give two more function names which will be run if method is successfully executed (first parameter i.e. onSucess) or method is failed (second parameter i.e. result).

Now every thing seems ready, and now I have added OnClientClick="Signup();return false;" on my Signup button. So here complete code of my aspx page :

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
        </asp:ScriptManager>
        <fieldset style="width: 200px;">
            <asp:Label ID="lblEmailAddress" runat="server" Text="Email Address"></asp:Label>
            <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
            <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>
            <asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
        </fieldset>
        <div>
        </div>
        <asp:Button ID="btnCreateAccount" runat="server" Text="Signup" OnClientClick="Signup();return false;" />
    </div>
    </form>
</body>
</html>

<script type="text/javascript">
    function Signup() {
        var email = document.getElementById('<%=txtEmail.ClientID %>').value;
        var password = document.getElementById('<%=txtPassword.ClientID %>').value;

        PageMethods.RegisterUser(email, password, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Cannot process your request at the moment, please try later.');
        }
    }
</script>

Specific Time Range Query in SQL Server

select * from table where 
(dtColumn between #3/1/2009# and #3/31/2009#) and 
(hour(dtColumn) between 6 and 22) and 
(weekday(dtColumn, 1) between 2 and 4) 

Is it possible to use an input value attribute as a CSS selector?

Dynamic Values (oh no! D;)

As npup explains in his answer, a simple css rule will only target the attribute value which means that this doesn't cover the actual value of the html node.

JAVASCRIPT TO THE RESCUE!


Original Answer

Yes it's very possible, using css attribute selectors you can reference input's by their value in this sort of fashion:

input[value="United States"] { color: #F90; }?

• jsFiddle example

from the reference

  • [att] Match when the element sets the "att" attribute, whatever the value of the attribute.

  • [att=val] Match when the element's "att" attribute value is exactly "val".

  • [att~=val] Represents an element with the att attribute whose value is a white space-separated list of words, one of which is exactly "val". If "val" contains white space, it will never represent anything (since the words are separated by spaces). If "val" is the empty string, it will never represent anything either.

  • [att|=val] Represents an element with the att attribute, its value either being exactly "val" or beginning with "val" immediately followed by "-" (U+002D). This is primarily intended to allow language subcode matches (e.g., the hreflang attribute on the a element in HTML) as described in BCP 47 ([BCP47]) or its successor. For lang (or xml:lang) language subcode matching, please see the :lang pseudo-class.

How to make Regular expression into non-greedy?

The non-greedy regex modifiers are like their greedy counter-parts but with a ? immediately following them:

*  - zero or more
*? - zero or more (non-greedy)
+  - one or more
+? - one or more (non-greedy)
?  - zero or one
?? - zero or one (non-greedy)

How to tag docker image with docker-compose

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This results in an image named webapp and tagged tag, built from ./dir.

https://docs.docker.com/compose/compose-file/#build

Module not found: Error: Can't resolve 'core-js/es6'

Just change "target": "es2015" to "target": "es5" in your tsconfig.json.

Work for me with Angular 8.2.XX

Tested on IE11 and Edge

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

From the v3 documentation (Developer's Guide > Concepts > Developing for Mobile Devices):

Android and iOS devices respect the following <meta> tag:

<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

This setting specifies that the map should be displayed full-screen and should not be resizable by the user. Note that the iPhone's Safari browser requires this <meta> tag be included within the page's <head> element.

How to convert JSON data into a Python object

dacite may also be a solution for you, it supports following features:

  • nested structures
  • (basic) types checking
  • optional fields (i.e. typing.Optional)
  • unions
  • forward references
  • collections
  • custom type hooks

https://pypi.org/project/dacite/

from dataclasses import dataclass
from dacite import from_dict


@dataclass
class User:
    name: str
    age: int
    is_active: bool


data = {
    'name': 'John',
    'age': 30,
    'is_active': True,
}

user = from_dict(data_class=User, data=data)

assert user == User(name='John', age=30, is_active=True)

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • Add Bootstrap Glyphicon to Input Box

    Here is a non-bootstrap solution that keeps your markup simple by embedding the image representation of the glyphicon directly in the CSS using base64 URI encoding.

    _x000D_
    _x000D_
    input {_x000D_
      border:solid 1px #ddd;_x000D_
    }_x000D_
    input.search {_x000D_
     padding-left:20px;_x000D_
     background-repeat: no-repeat;_x000D_
     background-position-y: 1px;_x000D_
     background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAASCAYAAABb0P4QAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAADbSURBVDhP5ZI9C4MwEIb7//+BEDgICA6C4OQgBJy6dRIEB6EgCNkEJ4e3iT2oHzH9wHbpAwfyJvfkJDnhYH4kHDVKlSAigSAQoCiBKjVGXvaxFXZnxBQYkSlBICII+22K4jM63rbHSthCSdsskVX9Y6KxR5XJSSpVy6GbpbBKp6aw0BzM0ShCe1iKihMXC6EuQtMQwukzPFu3fFd4+C+/cimUNxy6WQkNnmdzL3NYPfDmLVuhZf2wZYz80qDkKX1St3CXAfVMqq4cz3hTaGEpmctxDPmB0M/fCYEbAwZYyVKYcroAAAAASUVORK5CYII=);_x000D_
    }
    _x000D_
    <input class="search">
    _x000D_
    _x000D_
    _x000D_

    Event on a disabled input

    suggestion here looks like a good candidate for this question as well

    Performing click event on a disabled element? Javascript jQuery

    jQuery('input#submit').click(function(e) {
        if ( something ) {        
            return false;
        } 
    });
    

    Setting an image button in CSS - image:active

    Check this link . You were missing . before myButton. It was a small error. :)

    .myButton{
        background:url(./images/but.png) no-repeat;
        cursor:pointer;
        border:none;
        width:100px;
        height:100px;
    }
    
    .myButton:active  /* use Dot here */
    {   
        background:url(./images/but2.png) no-repeat;
    }
    

    How to fix/convert space indentation in Sublime Text?

    I actually found it's better for my sanity to have user preferences to be defined like so:

    "translate_tabs_to_spaces": true,
    "tab_size": 2,
    "indent_to_bracket": true,
    "detect_indentation": false
    

    The detect_indentation: false is especially important, as it forces Sublime to honor these settings in every file, as opposed to the View -> Indentation settings.

    If you want to get fancy, you can also define a keyboard shortcut to automatically re-indent your code (YMMV) by pasting the following in Sublime -> Preferences -> Key Binding - User:

    [
      { "keys": ["ctrl+i"], "command": "reindent" }
    ]
    

    and to visualize the whitespace:

    "indent_guide_options": ["draw_active"],
    "trim_trailing_white_space_on_save": true,
    "ensure_newline_at_eof_on_save": true,
    "draw_white_space": "all",
    "rulers": [120],
    

    Assets file project.assets.json not found. Run a NuGet package restore

    Very weird experience I have encountered!

    I had cloned with GIT bash and GIT cmd-Line earlier, I encountered the above issues.

    Later, I cloned with Tortoise-GIT and everything worked as expected.

    May be this is a crazy answer, but trying with this once may save your time!

    typeof operator in C

    It is a C extension from the GCC compiler , see http://gcc.gnu.org/onlinedocs/gcc/Typeof.html

    Default values and initialization in Java

    These are the main factors involved:

    1. member variable (default OK)
    2. static variable (default OK)
    3. final member variable (not initialized, must set on constructor)
    4. final static variable (not initialized, must set on a static block {})
    5. local variable (not initialized)

    Note 1: you must initialize final member variables on every implemented constructor!

    Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:

    private final int memberVar;
    
    public Foo() {
        // Invalid initialization of a final member
        init();
    }
    
    private void init() {
        memberVar = 10;
    }
    

    Note 3: arrays are Objects in Java, even if they store primitives.

    Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.

    I am attaching a code example, presenting the aforementioned cases:

    public class Foo {
        // Static and member variables are initialized to default values
    
        // Primitives
        private int a; // Default 0
        private static int b; // Default 0
    
        // Objects
        private Object c; // Default NULL
        private static Object d; // Default NULL
    
        // Arrays (note: they are objects too, even if they store primitives)
        private int[] e; // Default NULL
        private static int[] f; // Default NULL
    
        // What if declared as final?
    
        // Primitives
        private final int g; // Not initialized. MUST set in the constructor
        private final static int h; // Not initialized. MUST set in a static {}
    
        // Objects
        private final Object i; // Not initialized. MUST set in constructor
        private final static Object j; // Not initialized. MUST set in a static {}
    
        // Arrays
        private final int[] k; // Not initialized. MUST set in constructor
        private final static int[] l; // Not initialized. MUST set in a static {}
    
        // Initialize final statics
        static {
            h = 5;
            j = new Object();
            l = new int[5]; // Elements of l are initialized to 0
        }
    
        // Initialize final member variables
        public Foo() {
            g = 10;
            i = new Object();
            k = new int[10]; // Elements of k are initialized to 0
        }
    
        // A second example constructor
        // You have to initialize final member variables to every constructor!
        public Foo(boolean aBoolean) {
            g = 15;
            i = new Object();
            k = new int[15]; // Elements of k are initialized to 0
        }
    
        public static void main(String[] args) {
            // Local variables are not initialized
            int m; // Not initialized
            Object n; // Not initialized
            int[] o; // Not initialized
    
            // We must initialize them before use
            m = 20;
            n = new Object();
            o = new int[20]; // Elements of o are initialized to 0
        }
    }
    

    Partly JSON unmarshal into a map in Go

    Further to Stephen Weinberg's answer, I have since implemented a handy tool called iojson, which helps to populate data to an existing object easily as well as encoding the existing object to a JSON string. A iojson middleware is also provided to work with other middlewares. More examples can be found at https://github.com/junhsieh/iojson

    Example:

    func main() {
        jsonStr := `{"Status":true,"ErrArr":[],"ObjArr":[{"Name":"My luxury car","ItemArr":[{"Name":"Bag"},{"Name":"Pen"}]}],"ObjMap":{}}`
    
        car := NewCar()
    
        i := iojson.NewIOJSON()
    
        if err := i.Decode(strings.NewReader(jsonStr)); err != nil {
            fmt.Printf("err: %s\n", err.Error())
        }
    
        // populating data to a live car object.
        if v, err := i.GetObjFromArr(0, car); err != nil {
            fmt.Printf("err: %s\n", err.Error())
        } else {
            fmt.Printf("car (original): %s\n", car.GetName())
            fmt.Printf("car (returned): %s\n", v.(*Car).GetName())
    
            for k, item := range car.ItemArr {
                fmt.Printf("ItemArr[%d] of car (original): %s\n", k, item.GetName())
            }
    
            for k, item := range v.(*Car).ItemArr {
                fmt.Printf("ItemArr[%d] of car (returned): %s\n", k, item.GetName())
            }
        }
    }
    

    Sample output:

    car (original): My luxury car
    car (returned): My luxury car
    ItemArr[0] of car (original): Bag
    ItemArr[1] of car (original): Pen
    ItemArr[0] of car (returned): Bag
    ItemArr[1] of car (returned): Pen
    

    Using std::max_element on a vector<double>

    min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

    cLower = *min_element(C.begin(), C.end());
    

    How to vertically center an image inside of a div element in HTML using CSS?

    If you want content to be what ever you need to have inside a div, this did the job for me:

    <div style="
      display: table-cell;
      vertical-align: middle;
      background-color: blue;
      width: ...px;
      height: ...px;
    ">
        <div style="
          margin: auto;
          display: block;
          width: fit-content;
        ">
            <!-- CONTENT -->
            <img src="...">
            <p> some text </p>
        </div>
     </div>
    

    How to determine if a list of polygon points are in clockwise order?

    An implementation of Sean's answer in JavaScript:

    _x000D_
    _x000D_
    function calcArea(poly) {_x000D_
        if(!poly || poly.length < 3) return null;_x000D_
        let end = poly.length - 1;_x000D_
        let sum = poly[end][0]*poly[0][1] - poly[0][0]*poly[end][1];_x000D_
        for(let i=0; i<end; ++i) {_x000D_
            const n=i+1;_x000D_
            sum += poly[i][0]*poly[n][1] - poly[n][0]*poly[i][1];_x000D_
        }_x000D_
        return sum;_x000D_
    }_x000D_
    _x000D_
    function isClockwise(poly) {_x000D_
        return calcArea(poly) > 0;_x000D_
    }_x000D_
    _x000D_
    let poly = [[352,168],[305,208],[312,256],[366,287],[434,248],[416,186]];_x000D_
    _x000D_
    console.log(isClockwise(poly));_x000D_
    _x000D_
    let poly2 = [[618,186],[650,170],[701,179],[716,207],[708,247],[666,259],[637,246],[615,219]];_x000D_
    _x000D_
    console.log(isClockwise(poly2));
    _x000D_
    _x000D_
    _x000D_

    Pretty sure this is right. It seems to be working :-)

    Those polygons look like this, if you're wondering:

    python requests file upload

    In Ubuntu you can apply this way,

    to save file at some location (temporary) and then open and send it to API

          path = default_storage.save('static/tmp/' + f1.name, ContentFile(f1.read()))
          path12 = os.path.join(os.getcwd(), "static/tmp/" + f1.name)
          data={} #can be anything u want to pass along with File
          file1 = open(path12, 'rb')
          header = {"Content-Disposition": "attachment; filename=" + f1.name, "Authorization": "JWT " + token}
           res= requests.post(url,data,header)
    

    How to emulate GPS location in the Android Emulator?

    I was trying to set the geo fix through adb for many points and could not get my app to see any GPS data. But when I tried opening DDMS, selecting my app's process and sending coordinates through the emulator control tab it worked right away.

    Using routes in Express-js

    You could also organise them into modules. So it would be something like.

    ./
    controllers
        index.js
        indexController.js
    app.js
    

    and then in the indexController.js of the controllers export your controllers.

    //indexController.js
    module.exports = function(){
    //do some set up
    
    var self = {
         indexAction : function (req,res){
           //do your thing
    }
    return self;
    };
    

    then in index.js of controllers dir

    exports.indexController = require("./indexController");
    

    and finally in app.js

    var controllers = require("./controllers");
    
    app.get("/",controllers.indexController().indexAction);
    

    I think this approach allows for clearer seperation and also you can configure your controllers by passing perhaps a db connection in.

    Spring Data JPA findOne() change to Optional how to use this?

    Optional api provides methods for getting the values. You can check isPresent() for the presence of the value and then make a call to get() or you can make a call to get() chained with orElse() and provide a default value.

    The last thing you can try doing is using @Query() over a custom method.

    Upload artifacts to Nexus, without Maven

    for those who need it in Java, using apache httpcomponents 4.0:

    public class PostFile {
        protected HttpPost httppost ;
        protected MultipartEntity mpEntity; 
        protected File filePath;
    
        public PostFile(final String fullUrl, final String filePath){
            this.httppost = new HttpPost(fullUrl);
            this.filePath = new File(filePath);        
            this.mpEntity = new MultipartEntity();
        }
    
        public void authenticate(String user, String password){
            String encoding = new String(Base64.encodeBase64((user+":"+password).getBytes()));
            httppost.setHeader("Authorization", "Basic " + encoding);
        }
        private void addParts() throws UnsupportedEncodingException{
            mpEntity.addPart("r", new StringBody("repository id"));
            mpEntity.addPart("g", new StringBody("group id"));
            mpEntity.addPart("a", new StringBody("artifact id"));
            mpEntity.addPart("v", new StringBody("version"));
            mpEntity.addPart("p", new StringBody("packaging"));
            mpEntity.addPart("e", new StringBody("extension"));
    
            mpEntity.addPart("file", new FileBody(this.filePath));
    
        }
    
        public String post() throws ClientProtocolException, IOException {
            HttpClient httpclient = new DefaultHttpClient();
            httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
            addParts();
            httppost.setEntity(mpEntity);
            HttpResponse response = httpclient.execute(httppost);
    
            System.out.println("executing request " + httppost.getRequestLine());
            System.out.println(httppost.getEntity().getContentLength());
    
            HttpEntity resEntity = response.getEntity();
    
            String statusLine = response.getStatusLine().toString();
            System.out.println(statusLine);
            if (resEntity != null) {
                System.out.println(EntityUtils.toString(resEntity));
            }
            if (resEntity != null) {
                resEntity.consumeContent();
            }
            return statusLine;
        }
    }
    

    How to use ArgumentCaptor for stubbing?

    Hypothetically, if search landed you on this question then you probably want this:

    doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));
    

    Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

    And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

    How do I add a newline using printf?

    Try this:

    printf '\n%s\n' 'I want this on a new line!'
    

    That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

    quantity=38; price=142.15; description='advanced widget'
    $ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
          38    142.15  advanced widget
    

    How to make an array of arrays in Java

    try

    String[][] arrays = new String[5][];
    

    AngularJS - Building a dynamic table based on a json

    <table class="table table-striped table-condensed table-hover">
        <thead>
        <tr>
            <th ng-repeat="header in headers | filter:headerFilter | orderBy:headerOrder" width="{{header.width}}">{{header.label}}</th>
        </tr>
        </thead>
        <tbody>
        <tr ng-repeat="user in users" ng-class-odd="'trOdd'" ng-class-even="'trEven'" ng-dblclick="rowDoubleClicked(user)">
            <td ng-repeat="(key,val) in user | orderBy:userOrder(key)">{{val}}</td>
        </tr>
        </tbody>
        <tfoot>
    
        </tfoot>
    </table>
    

    refer this https://gist.github.com/ebellinger/4399082

    How to write dynamic variable in Ansible playbook

    I would first suggest that you step back and look at organizing your plays to not require such complexity, but if you really really do, use the following:

       vars:
        myvariable: "{{[param1|default(''), param2|default(''), param3|default('')]|join(',')}}"
    

    Display tooltip on Label's hover?

    You don't have to use hidden field. Use "title" property. It will show browser default tooltip. You can then use jQuery plugin (like before mentioned bootstrap tooltip) to show custom formatted tooltip.

    <label for="male" title="Hello This Will Have Some Value">Hello ...</label>
    

    Hint: you can also use css to trim text, that does not fit into the box (text-overflow property). See http://jsfiddle.net/8eeHs/

    Bash script - variable content as a command to run

    You just need to do:

    #!/bin/bash
    count=$(cat last_queries.txt | wc -l)
    $(perl test.pl test2 $count)
    

    However, if you want to call your Perl command later, and that's why you want to assign it to a variable, then:

    #!/bin/bash
    count=$(cat last_queries.txt | wc -l)
    var="perl test.pl test2 $count" # You need double quotes to get your $count value substituted.
    
    ...stuff...
    
    eval $var
    

    As per Bash's help:

    ~$ help eval
    eval: eval [arg ...]
        Execute arguments as a shell command.
    
        Combine ARGs into a single string, use the result as input to the shell,
        and execute the resulting commands.
    
        Exit Status:
        Returns exit status of command or success if command is null.
    

    Split string into array

    You can try this way:

    let entry = prompt("Enter your name") 
    let entryArray = entry.split('')
    console.log(entryArray)
    

    here is fiddle https://jsfiddle.net/swapanil/Lp1arvqc/17/

    JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

    No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

    In other words, your code only works by accident, and probably not in all browsers.

    Is this what you're trying to do?

    <a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>
    

    Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

    I needed a package from github that was written in typscript. I did a git pull of the most recent version from the master branch into the root of my main project. I then went into the directory and did an npm install so that the gulp commands would work that generates ES5 modules. Anyway, to make the long story short, my build process was trying to build files from this new folder so I had to move it out of my root. This was causing these same errors.

    Error: No default engine was specified and no extension was provided

    Comment out the res.render lines in your code and add in next(err); instead. If you're not using a view engine, the res.render stuff will throw an error.

    Sorry, you'll have to comment out this line as well:

    app.set('view engine', 'html');
    

    My solution would result in not using a view engine though. You don't need a view engine, but if that's the goal, try this:

    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    //swap jade for ejs etc
    

    You'll need the res.render lines when using a view engine as well. Something like this:

    // error handlers
    // development error handler
    // will print stacktrace
    if (app.get('env') === 'development') {
      app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
        message: err.message,
        error: err
        });
      });
    }
    // production error handler
    // no stacktraces leaked to user
    app.use(function(err, req, res, next) {
      res.status(err.status || 500);
      next(err);
      res.render('error', {
      message: err.message,
      error: {}
      });
    });
    

    How to extract numbers from string in c?

    A possible solution using sscanf() and scan sets:

    const char* s = "ab234cid*(s349*(20kd";
    int i1, i2, i3;
    if (3 == sscanf(s,
                    "%*[^0123456789]%d%*[^0123456789]%d%*[^0123456789]%d",
                    &i1,
                    &i2,
                    &i3))
    {
        printf("%d %d %d\n", i1, i2, i3);
    }
    

    where %*[^0123456789] means ignore input until a digit is found. See demo at http://ideone.com/2hB4UW .

    Or, if the number of numbers is unknown you can use %n specifier to record the last position read in the buffer:

    const char* s = "ab234cid*(s349*(20kd";
    int total_n = 0;
    int n;
    int i;
    while (1 == sscanf(s + total_n, "%*[^0123456789]%d%n", &i, &n))
    {
        total_n += n;
        printf("%d\n", i);
    }
    

    Entity framework left join

    It might be a bit of an overkill, but I wrote an extension method, so you can do a LeftJoin using the Join syntax (at least in method call notation):

    persons.LeftJoin(
        phoneNumbers,
        person => person.Id,
        phoneNumber => phoneNumber.PersonId,
        (person, phoneNumber) => new
            {
                Person = person,
                PhoneNumber = phoneNumber?.Number
            }
    );
    

    My code does nothing more than adding a GroupJoin and a SelectMany call to the current expression tree. Nevertheless, it looks pretty complicated because I have to build the expressions myself and modify the expression tree specified by the user in the resultSelector parameter to keep the whole tree translatable by LINQ-to-Entities.

    public static class LeftJoinExtension
    {
        public static IQueryable<TResult> LeftJoin<TOuter, TInner, TKey, TResult>(
            this IQueryable<TOuter> outer,
            IQueryable<TInner> inner,
            Expression<Func<TOuter, TKey>> outerKeySelector,
            Expression<Func<TInner, TKey>> innerKeySelector,
            Expression<Func<TOuter, TInner, TResult>> resultSelector)
        {
            MethodInfo groupJoin = typeof (Queryable).GetMethods()
                                                     .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] GroupJoin[TOuter,TInner,TKey,TResult](System.Linq.IQueryable`1[TOuter], System.Collections.Generic.IEnumerable`1[TInner], System.Linq.Expressions.Expression`1[System.Func`2[TOuter,TKey]], System.Linq.Expressions.Expression`1[System.Func`2[TInner,TKey]], System.Linq.Expressions.Expression`1[System.Func`3[TOuter,System.Collections.Generic.IEnumerable`1[TInner],TResult]])")
                                                     .MakeGenericMethod(typeof (TOuter), typeof (TInner), typeof (TKey), typeof (LeftJoinIntermediate<TOuter, TInner>));
            MethodInfo selectMany = typeof (Queryable).GetMethods()
                                                      .Single(m => m.ToString() == "System.Linq.IQueryable`1[TResult] SelectMany[TSource,TCollection,TResult](System.Linq.IQueryable`1[TSource], System.Linq.Expressions.Expression`1[System.Func`2[TSource,System.Collections.Generic.IEnumerable`1[TCollection]]], System.Linq.Expressions.Expression`1[System.Func`3[TSource,TCollection,TResult]])")
                                                      .MakeGenericMethod(typeof (LeftJoinIntermediate<TOuter, TInner>), typeof (TInner), typeof (TResult));
    
            var groupJoinResultSelector = (Expression<Func<TOuter, IEnumerable<TInner>, LeftJoinIntermediate<TOuter, TInner>>>)
                                          ((oneOuter, manyInners) => new LeftJoinIntermediate<TOuter, TInner> {OneOuter = oneOuter, ManyInners = manyInners});
    
            MethodCallExpression exprGroupJoin = Expression.Call(groupJoin, outer.Expression, inner.Expression, outerKeySelector, innerKeySelector, groupJoinResultSelector);
    
            var selectManyCollectionSelector = (Expression<Func<LeftJoinIntermediate<TOuter, TInner>, IEnumerable<TInner>>>)
                                               (t => t.ManyInners.DefaultIfEmpty());
    
            ParameterExpression paramUser = resultSelector.Parameters.First();
    
            ParameterExpression paramNew = Expression.Parameter(typeof (LeftJoinIntermediate<TOuter, TInner>), "t");
            MemberExpression propExpr = Expression.Property(paramNew, "OneOuter");
    
            LambdaExpression selectManyResultSelector = Expression.Lambda(new Replacer(paramUser, propExpr).Visit(resultSelector.Body), paramNew, resultSelector.Parameters.Skip(1).First());
    
            MethodCallExpression exprSelectMany = Expression.Call(selectMany, exprGroupJoin, selectManyCollectionSelector, selectManyResultSelector);
    
            return outer.Provider.CreateQuery<TResult>(exprSelectMany);
        }
    
        private class LeftJoinIntermediate<TOuter, TInner>
        {
            public TOuter OneOuter { get; set; }
            public IEnumerable<TInner> ManyInners { get; set; }
        }
    
        private class Replacer : ExpressionVisitor
        {
            private readonly ParameterExpression _oldParam;
            private readonly Expression _replacement;
    
            public Replacer(ParameterExpression oldParam, Expression replacement)
            {
                _oldParam = oldParam;
                _replacement = replacement;
            }
    
            public override Expression Visit(Expression exp)
            {
                if (exp == _oldParam)
                {
                    return _replacement;
                }
    
                return base.Visit(exp);
            }
        }
    }
    

    Angular: How to update queryParams without changing route

    @Radoslaw Roszkowiak's answer is almost right except that relativeTo: this.route is required as below:

    constructor(
      private router: Router,
      private route: ActivatedRoute,
    ) {}
    
    changeQuery() {
      this.router.navigate(['.'], { relativeTo: this.route, queryParams: { ... }});
    }
    

    Java Returning method which returns arraylist?

    MyClass obj = new MyClass();
    ArrayList<Integer> numbers = obj.myNumbers();
    

    How do I write a RGB color value in JavaScript?

    I am showing with an example of adding random color. You can write this way

    var r = Math.floor(Math.random() * 255);
    var g = Math.floor(Math.random() * 255);
    var b = Math.floor(Math.random() * 255);
    var col = "rgb(" + r + "," + g + "," + b + ")";
    parent.childNodes[1].style.color = col;
    

    The property is expected as a string

    MySQL INNER JOIN Alias

    You'll need to join twice:

    SELECT home.*, away.*, g.network, g.date_start 
    FROM game AS g
    INNER JOIN team AS home
      ON home.importid = g.home
    INNER JOIN team AS away
      ON away.importid = g.away
    ORDER BY g.date_start DESC 
    LIMIT 7
    

    mssql '5 (Access is denied.)' error during restoring database

    I found this, and it worked for me:

    CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
    GO
    CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
    GO
    EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
    GO
    EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
    GO
    

    Regular expression for checking if capital letters are found consecutively in a string?

    ^([A-Z][a-z]+)+$
    

    This looks for sequences of an uppercase letter followed by one or more lowercase letters. Consecutive uppercase letters will not match, as only one is allowed at a time, and it must be followed by a lowercase one.

    Should I always use a parallel stream when possible?

    Never parallelize an infinite stream with a limit. Here is what happens:

        public static void main(String[] args) {
            // let's count to 1 in parallel
            System.out.println(
                IntStream.iterate(0, i -> i + 1)
                    .parallel()
                    .skip(1)
                    .findFirst()
                    .getAsInt());
        }
    

    Result

        Exception in thread "main" java.lang.OutOfMemoryError
            at ...
            at java.base/java.util.stream.IntPipeline.findFirst(IntPipeline.java:528)
            at InfiniteTest.main(InfiniteTest.java:24)
        Caused by: java.lang.OutOfMemoryError: Java heap space
            at java.base/java.util.stream.SpinedBuffer$OfInt.newArray(SpinedBuffer.java:750)
            at ...
    

    Same if you use .limit(...)

    Explanation here: Java 8, using .parallel in a stream causes OOM error

    Similarly, don't use parallel if the stream is ordered and has much more elements than you want to process, e.g.

    public static void main(String[] args) {
        // let's count to 1 in parallel
        System.out.println(
                IntStream.range(1, 1000_000_000)
                        .parallel()
                        .skip(100)
                        .findFirst()
                        .getAsInt());
    }
    

    This may run much longer because the parallel threads may work on plenty of number ranges instead of the crucial one 0-100, causing this to take very long time.

    Find CRLF in Notepad++

    Assuming it has a "regular expressions" search, look for \r\n. I prefer \r?\n, because some files don't use carriage returns.

    EDIT: Thanks for the feedback, whoever voted this down. I have learned that... well, nothing, because you provided no feedback. Why is this wrong?

    What is Python Whitespace and how does it work?

    Whitespace is used to denote blocks. In other languages curly brackets ({ and }) are common. When you indent, it becomes a child of the previous line. In addition to the indentation, the parent also has a colon following it.

    im_a_parent:
        im_a_child:
            im_a_grandchild
        im_another_child:
            im_another_grand_child
    

    Off the top of my head, def, if, elif, else, try, except, finally, with, for, while, and class all start blocks. To end a block, you simple outdent, and you will have siblings. In the above im_a_child and im_another_child are siblings.

    Why is &#65279; appearing in my HTML?

    yeah, its so simple to fix that, just open that file by notepad++ and step follow --> Encoding\ encoding UTF-8 without BOM. then save that. It work for me as well!

    How do I add a .click() event to an image?

    Enclose <img> in <a> tag.

    <a href="http://www.google.com.pk"><img src="smiley.gif"></a>
    

    it will open link on same tab, and if you want to open link on new tab then use target="_blank"

    <a href="http://www.google.com.pk" target="_blank"><img src="smiley.gif"></a>
    

    Generating an array of letters in the alphabet

    C# 3.0 :

    char[] az = Enumerable.Range('a', 'z' - 'a' + 1).Select(i => (Char)i).ToArray();
    foreach (var c in az)
    {
        Console.WriteLine(c);
    }
    

    yes it does work even if the only overload of Enumerable.Range accepts int parameters ;-)

    TERM environment variable not set

    You can see if it's really not set. Run the command set | grep TERM.

    If not, you can set it like that: export TERM=xterm

    How to sort with a lambda?

    Got it.

    sort(mMyClassVector.begin(), mMyClassVector.end(), 
        [](const MyClass & a, const MyClass & b) -> bool
    { 
        return a.mProperty > b.mProperty; 
    });
    

    I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

    Use Conditional formatting to turn a cell Red, yellow or green depending on 3 values in another sheet

    1. Highlight the range in question.
    2. On the Home tab, in the Styles Group, Click "Conditional Formatting".
    3. Click "Highlight cell rules"

    For the first rule,

    Click "greater than", then in the value option box, click on the cell criteria you want it to be less than, than use the format drop-down to select your color.

    For the second,

    Click "less than", then in the value option box, type "=.9*" and then click the cell criteria, then use the formatting just like step 1.

    For the third,

    Same as the second, except your formula is =".8*" rather than .9.

    Writing to an Excel spreadsheet

    import xlsxwriter
    
    
    # Create an new Excel file and add a worksheet.
    workbook = xlsxwriter.Workbook('demo.xlsx')
    worksheet = workbook.add_worksheet()
    
    # Widen the first column to make the text clearer.
    worksheet.set_column('A:A', 20)
    
    # Add a bold format to use to highlight cells.
    bold = workbook.add_format({'bold': True})
    
    # Write some simple text.
    worksheet.write('A1', 'Hello')
    
    # Text with formatting.
    worksheet.write('A2', 'World', bold)
    
    # Write some numbers, with row/column notation.
    worksheet.write(2, 0, 123)
    worksheet.write(3, 0, 123.456)
    
    # Insert an image.
    worksheet.insert_image('B5', 'logo.png')
    
    workbook.close()
    

    How do I convert a double into a string in C++?

    Heh, I just wrote this (unrelated to this question):

    string temp = "";
    stringstream outStream;
    double ratio = (currentImage->width*1.0f)/currentImage->height;
    outStream << " R: " << ratio;
    temp = outStream.str();
    
    /* rest of the code */
    

    Oracle PL/SQL string compare issue

    Only change the line str1:=''; to str1:=' ';