Programs & Examples On #Diskimage

How do I get an object's unqualified (short) class name?

$shortClassName = join('',array_slice(explode('\\', $longClassName), -1));

What's NSLocalizedString equivalent in Swift?

By using this way its possible to create a different implementation for different types (i.e. Int or custom classes like CurrencyUnit, ...). Its also possible to scan for this method invoke using the genstrings utility. Simply add the routine flag to the command

genstrings MyCoolApp/Views/SomeView.swift -s localize -o .

extension:

import UIKit

extension String {
    public static func localize(key: String, comment: String) -> String {
        return NSLocalizedString(key, comment: comment)
    }
}

usage:

String.localize("foo.bar", comment: "Foo Bar Comment :)")

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

Horizontal scroll css?

Just set your width to auto:

#myWorkContent{
    width: auto;
    height:210px;
    border: 13px solid #bed5cd;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}

This way your div can be as wide as possible, so you can add as many kitty images as possible ;3

Your div's width will expand based on the child elements it contains.

jsFiddle

Read an Excel file directly from a R script

And now there is readxl:

The readxl package makes it easy to get data out of Excel and into R. Compared to the existing packages (e.g. gdata, xlsx, xlsReadWrite etc) readxl has no external dependencies so it's easy to install and use on all operating systems. It is designed to work with tabular data stored in a single sheet.

readxl is built on top of the libxls C library, which abstracts away many of the complexities of the underlying binary format.

It supports both the legacy .xls format and .xlsx

readxl is available from CRAN, or you can install it from github with:

# install.packages("devtools")
devtools::install_github("hadley/readxl")

Usage

library(readxl)

# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")

# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)

# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")

Note that while the description says 'no external dependencies', it does require the Rcpp package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. Though many people have them installed for other reasons.

how to place last div into right top corner of parent div? (css)

If you can add another wrapping div "block3" you could do something like this.

 <html>
      <head>
      <style type="text/css">
      .block1 {color:red;width:120px;border:1px solid green; height: 100px;}
      .block3 {float:left; width:10px;}
      .block2 {color:blue;width:70px;border:2px solid black;position:relative;float:right;}
      </style>
      </head>

    <body>
    <div class='block1'>

        <div class='block3'>
            <p>text1</p>
            <p>text2</p>
        </div>

        <div class='block2'>block2</DIV>

    </div>

    </body>
    </html>

How do I install cURL on Windows?

I agree with Erroid, you must add PHP directory into PATH environment.

PATH=%PATH%;<Your_PHP_Path>

Example

PATH=%PATH%;C:\php

It worked for me. Thank you.

TypeError: expected a character buffer object - while trying to save integer to textfile

from __future__ import with_statement
with open('file.txt','r+') as f:
    counter = str(int(f.read().strip())+1)
    f.seek(0)
    f.write(counter)

Delete files in subfolder using batch script

Moved from the closed topic

del /s d:\test\archive*.txt

This should get you all of your text files

Alternatively,

I modified a script I already wrote to look for certain files to move them, this one should go and find files and delete them. It allows you to just choose to which folder by a selection screen.

Please test this on your system before using it though.

@echo off
Title DeleteFilesInSubfolderList
color 0A
SETLOCAL ENABLEDELAYEDEXPANSION

REM ---------------------------
REM   *** EDIT VARIABLES BELOW ***
REM ---------------------------

set targetFolder=
REM targetFolder is the location you want to delete from    
REM ---------------------------
REM  *** DO NOT EDIT BELOW ***
REM ---------------------------

IF NOT DEFINED targetFolder echo.Please type in the full BASE Symform Offline Folder (I.E. U:\targetFolder)
IF NOT DEFINED targetFolder set /p targetFolder=:
cls
echo.Listing folders for: %targetFolder%\^*
echo.-------------------------------
set Index=1
for /d %%D in (%targetFolder%\*) do (
  set "Subfolders[!Index!]=%%D"
  set /a Index+=1
)
set /a UBound=Index-1
for /l %%i in (1,1,%UBound%) do echo. %%i. !Subfolders[%%i]!

:choiceloop
echo.-------------------------------
set /p Choice=Search for ERRORS in: 
if "%Choice%"=="" goto chioceloop
if %Choice% LSS 1 goto choiceloop
if %Choice% GTR %UBound% goto choiceloop
set Subfolder=!Subfolders[%Choice%]!
goto start

:start
TITLE Delete Text Files - %Subfolder%
IF NOT EXIST %ERRPATH% goto notExist
IF EXIST %ERRPATH% echo.%ERRPATH% Exists - Beginning to test-delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
echo "%%a" "%Subfolder%\%%~nxa"
)
popd
echo.
echo.
verIFy >nul
echo.Execute^?
choice /C:YNX /N /M "(Y)Yes or (N)No:"
IF '%ERRORLEVEL%'=='1' set question1=Y
IF '%ERRORLEVEL%'=='2' set question1=N
IF /I '%question1%'=='Y' goto execute
IF /I '%question1%'=='N' goto end

:execute
echo.%ERRPATH% Exists - Beginning to delete files...
echo.Searching for .txt files...
pushd %ERRPATH%
for /r %%a in (*.txt) do (
del "%%a" "%Subfolder%\%%~nxa"
)
popd
goto end

:end
echo.
echo.
echo.Finished deleting files from %subfolder%
pause
goto choiceloop
ENDLOCAL
exit


REM Created by Trevor Giannetti
REM An unpublished work
REM (October 2012)

If you change the

set targetFolder= 

to the folder you want you won't get prompted for the folder. *Remember when putting the base path in, the format does not include a '\' on the end. e.g. d:\test c:\temp

Hope this helps

New xampp security concept: Access Forbidden Error 403 - Windows 7 - phpMyAdmin

Comment out the line Require local in httpd-xampp.conf.
Restart Apache.
Worked for me connecting my mobile phone to my test web-site on my PC. No idea of the security implications.

Disable time in bootstrap date time picker

Not as put off time and language at a time I put this and not work

$(function () {
    $('#datetimepicker2').datetimepicker({
              locale: 'es',
              pickTime: false
          });
});

How do I implement JQuery.noConflict() ?

Today i have this issue because i have implemented "bootstrap menu" that uses a jQuery version along with "fancybox image gallery". Of course one plugin works and the other not due to jQuery conflict but i have overcome it as follow:

First i have added the "bootstrap menu" Js in the script footer as the menu is presented allover the website pages:

<!-- Top Menu Javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript">
var jq171 = jQuery.noConflict(true);
</script>

And in the "fancybox" image gallery page as follow:

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script>window.jQuery || document.write('<script src="fancybox/js/libs/jquery-1.7.1.min.js"><\/script>')</script>

And the good thing is both working like a charm :)

Give it a try :)

What does "for" attribute do in HTML <label> tag?

The <label> tag allows you to click on the label, and it will be treated like clicking on the associated input element. There are two ways to create this association:

One way is to wrap the label element around the input element:

<label>Input here:
    <input type='text' name='theinput' id='theinput'>
</label>

The other way is to use the for attribute, giving it the ID of the associated input:

<label for="theinput">Input here:</label>
<input type='text' name='whatever' id='theinput'>

This is especially useful for use with checkboxes and buttons, since it means you can check the box by clicking on the associated text instead of having to hit the box itself.

Read more about this element in MDN.

How to use conditional breakpoint in Eclipse?

A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.

if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
-->    int noop = 0; //don't do anything
}

(the breakpoint is represented by the arrow)

This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.

Using grep and sed to find and replace a string

I think that without using -exec you can simply provide /dev/null as at least one argument in case nothing is found:

grep -rl oldstr path | xargs sed -i 's/oldstr/newstr/g' /dev/null

Mysql database sync between two databases

Have a look at Schema and Data Comparison tools in dbForge Studio for MySQL. These tool will help you to compare, to see the differences, generate a synchronization script and synchronize two databases.

Add two textbox values and display the sum in a third textbox automatically

Since eval("3+2")=5 ,you can use it as following :

byId=(id)=>document.getElementById(id); 
byId('txt3').value=eval(`${byId('txt1').value}+${byId('txt2').value}`)

By that, you don't need parseInt

How to make spring inject value into a static field

You have two possibilities:

  1. non-static setter for static property/field;
  2. using org.springframework.beans.factory.config.MethodInvokingFactoryBean to invoke a static setter.

In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.

public void setTheProperty(Object value) {
    foo.bar.Class.STATIC_VALUE = value;
}

but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).

In the second case it would be done as follows:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Class.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

On you case you will add a new setter on the Utils class:

public static setDataBaseAttr(Properties p)

and in your context you will configure it with the approach exemplified above, more or less like:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/>
    <property name="arguments">
        <list>
            <ref bean="dataBaseAttr"/>
        </list>
   </property>
</bean>

How to draw a custom UIView that is just a circle - iPhone app

Swift 3 - custom class, easy to reuse. It uses backgroundColor set in UI builder

import UIKit

@IBDesignable
class CircleBackgroundView: UIView {

    override func layoutSubviews() {
        super.layoutSubviews()
        layer.cornerRadius = bounds.size.width / 2
        layer.masksToBounds = true
    }

}

Execute curl command within a Python script

You could use urllib as @roippi said:

import urllib2
data = '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}'
url = 'http://localhost:8080/firewall/rules/0000000000000001'
req = urllib2.Request(url, data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
for x in f:
    print(x)
f.close()

How can I create a blank/hardcoded column in a sql query?

This should work on most databases. You can also select a blank string as your extra column like so:

Select
  Hat, Show, Boat, '' as SomeValue
From
  Objects

Basic http file downloading and saving to disk in python?

For text files, you can use:

import requests

url = 'https://WEBSITE.com'
req = requests.get(url)
path = "C:\\YOUR\\FILE.html"

with open(path, 'wb') as f:
    f.write(req.content)

What is a magic number, and why is it bad?

Magic Number Vs. Symbolic Constant: When to replace?

Magic: Unknown semantic

Symbolic Constant -> Provides both correct semantic and correct context for use

Semantic: The meaning or purpose of a thing.

"Create a constant, name it after the meaning, and replace the number with it." -- Martin Fowler

First, magic numbers are not just numbers. Any basic value can be "magic". Basic values are manifest entities such as integers, reals, doubles, floats, dates, strings, booleans, characters, and so on. The issue is not the data type, but the "magic" aspect of the value as it appears in our code text.

What do we mean by "magic"? To be precise: By "magic", we intend to point to the semantics (meaning or purpose) of the value in the context of our code; that it is unknown, unknowable, unclear, or confusing. This is the notion of "magic". A basic value is not magic when its semantic meaning or purpose-of-being-there is quickly and easily known, clear, and understood (not confusing) from the surround context without special helper words (e.g. symbolic constant).

Therefore, we identify magic numbers by measuring the ability of a code reader to know, be clear, and understand the meaning and purpose of a basic value from its surrounding context. The less known, less clear, and more confused the reader is, the more "magic" the basic value is.

Helpful Definitions

  • confuse: cause (someone) to become bewildered or perplexed.
  • bewildered: cause (someone) to become perplexed and confused.
  • perplexed: completely baffled; very puzzled.
  • baffled: totally bewilder or perplex.
  • puzzled: unable to understand; perplexed.
  • understand: perceive the intended meaning of (words, a language, or speaker).
  • meaning: what is meant by a word, text, concept, or action.
  • meant: intend to convey, indicate, or refer to (a particular thing or notion); signify.
  • signify: be an indication of.
  • indication: a sign or piece of information that indicates something.
  • indicate: point out; show.
  • sign: an object, quality, or event whose presence or occurrence indicates the probable presence or occurrence of something else.

Basics

We have two scenarios for our magic basic values. Only the second is of primary importance for programmers and code:

  1. A lone basic value (e.g. number) from which its meaning is unknown, unknowable, unclear or confusing.
  2. A basic value (e.g. number) in context, but its meaning remains unknown, unknowable, unclear or confusing.

An overarching dependency of "magic" is how the lone basic value (e.g. number) has no commonly known semantic (like Pi), but has a locally known semantic (e.g. your program), which is not entirely clear from context or could be abused in good or bad context(s).

The semantics of most programming languages will not allow us to use lone basic values, except (perhaps) as data (i.e. tables of data). When we encounter "magic numbers", we generally do so in a context. Therefore, the answer to

"Do I replace this magic number with a symbolic constant?"

is:

"How quickly can you assess and understand the semantic meaning of the number (its purpose for being there) in its context?"

Kind of Magic, but not quite

With this thought in mind, we can quickly see how a number like Pi (3.14159) is not a "magic number" when placed in proper context (e.g. 2 x 3.14159 x radius or 2*Pi*r). Here, the number 3.14159 is mentally recognized Pi without the symbolic constant identifier.

Still, we generally replace 3.14159 with a symbolic constant identifier like Pi because of the length and complexity of the number. The aspects of length and complexity of Pi (coupled with a need for accuracy) usually means the symbolic identifier or constant is less prone to error. Recognition of "Pi" as a name is a simply a convenient bonus, but is not the primary reason for having the constant.

Meanwhile: Back at the Ranch

Laying aside common constants like Pi, let's focus primarily on numbers with special meanings, but which those meanings are constrained to the universe of our software system. Such a number might be "2" (as a basic integer value).

If I use the number 2 by itself, my first question might be: What does "2" mean? The meaning of "2" by itself is unknown and unknowable without context, leaving its use unclear and confusing. Even though having just "2" in our software will not happen because of language semantics, we do want to see that "2" by itself carries no special semantics or obvious purpose being alone.

Let's put our lone "2" in a context of: padding := 2, where the context is a "GUI Container". In this context the meaning of 2 (as pixels or other graphical unit) offers us a quick guess of its semantics (meaning and purpose). We might stop here and say that 2 is okay in this context and there is nothing else we need to know. However, perhaps in our software universe this is not the whole story. There is more to it, but "padding = 2" as a context cannot reveal it.

Let's further pretend that 2 as pixel padding in our program is of the "default_padding" variety throughout our system. Therefore, writing the instruction padding = 2 is not good enough. The notion of "default" is not revealed. Only when I write: padding = default_padding as a context and then elsewhere: default_padding = 2 do I fully realize a better and fuller meaning (semantic and purpose) of 2 in our system.

The example above is pretty good because "2" by itself could be anything. Only when we limit the range and domain of understanding to "my program" where 2 is the default_padding in the GUI UX parts of "my program", do we finally make sense of "2" in its proper context. Here "2" is a "magic" number, which is factored out to a symbolic constant default_padding within the context of the GUI UX of "my program" in order to make it use as default_padding quickly understood in the greater context of the enclosing code.

Thus, any basic value, whose meaning (semantic and purpose) cannot be sufficiently and quickly understood is a good candidate for a symbolic constant in the place of the basic value (e.g. magic number).

Going Further

Numbers on a scale might have semantics as well. For example, pretend we are making a D&D game, where we have the notion of a monster. Our monster object has a feature called life_force, which is an integer. The numbers have meanings that are not knowable or clear without words to supply meaning. Thus, we begin by arbitrarily saying:

  • full_life_force: INTEGER = 10 -- Very alive (and unhurt)
  • minimum_life_force: INTEGER = 1 -- Barely alive (very hurt)
  • dead: INTEGER = 0 -- Dead
  • undead: INTEGER = -1 -- Min undead (almost dead)
  • zombie: INTEGER = -10 -- Max undead (very undead)

From the symbolic constants above, we start to get a mental picture of the aliveness, deadness, and "undeadness" (and possible ramifications or consequences) for our monsters in our D&D game. Without these words (symbolic constants), we are left with just the numbers ranging from -10 .. 10. Just the range without the words leaves us in a place of possibly great confusion and potentially with errors in our game if different parts of the game have dependencies on what that range of numbers means to various operations like attack_elves or seek_magic_healing_potion.

Therefore, when searching for and considering replacement of "magic numbers" we want to ask very purpose-filled questions about the numbers within the context of our software and even how the numbers interact semantically with each other.

Conclusion

Let's review what questions we ought to ask:

You might have a magic number if ...

  1. Can the basic value have a special meaning or purpose in your softwares universe?
  2. Can the special meaning or purpose likely be unknown, unknowable, unclear, or confusing, even in its proper context?
  3. Can a proper basic value be improperly used with bad consequences in the wrong context?
  4. Can an improper basic value be properly used with bad consequences in the right context?
  5. Does the basic value have a semantic or purpose relationships with other basic values in specific contexts?
  6. Can a basic value exist in more than one place in our code with different semantics in each, thereby causing our reader a confusion?

Examine stand-alone manifest constant basic values in your code text. Ask each question slowly and thoughtfully about each instance of such a value. Consider the strength of your answer. Many times, the answer is not black and white, but has shades of misunderstood meaning and purpose, speed of learning, and speed of comprehension. There is also a need to see how it connects to the software machine around it.

In the end, the answer to replacement is answer the measure (in your mind) of the strength or weakness of the reader to make the connection (e.g. "get it"). The more quickly they understand meaning and purpose, the less "magic" you have.

CONCLUSION: Replace basic values with symbolic constants only when the magic is large enough to cause difficult to detect bugs arising from confusions.

CSS :not(:last-child):after selector

You can try this, I know is not the answers you are looking for but the concept is the same.

Where you are setting the styles for all the children and then removing it from the last child.

Code Snippet

li
  margin-right: 10px

  &:last-child
    margin-right: 0

Image

enter image description here

jQuery Ajax POST example with PHP

HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

How many threads is too many?

I think this is a bit of a dodge to your question, but why not fork them into processes? My understanding of networking (from the hazy days of yore, I don't really code networks at all) was that each incoming connection can be handled as a separate process, because then if someone does something nasty in your process, it doesn't nuke the entire program.

How to create virtual column using MySQL SELECT?

You could use a CASE statement, like

SELECT name
       ,address
       ,CASE WHEN a < b THEN '1' 
             ELSE '2' END AS one_or_two
FROM ...

How to open a new HTML page using jQuery?

If you want to use jQuery, the .load() function is the correct function you are after;

But you are missing the # from the div1 id selector in the example 2)

This should work:

$("#div1").load("file2.html");

Can I pass parameters by reference in Java?

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

Remove whitespaces inside a string in javascript

For space-character removal use

"hello world".replace(/\s/g, "");

for all white space use the suggestion by Rocket in the comments below!

Setting maxlength of textbox with JavaScript or jQuery

You can make it like this:

$('#inputID').keypress(function () {
    var maxLength = $(this).val().length;
    if (maxLength >= 5) {
        alert('You cannot enter more than ' + maxLength + ' chars');
        return false;
    }
});

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

Add image in title bar

you should be searching about how to add favicon.ico . You can try adding favicon.ico directly in your html pages like this

<link rel="shortcut icon" href="/favicon.png" type="image/png">
<link rel="shortcut icon" type="image/png" href="http://www.example.com/favicon.png" />

Or you can update that in your webserver. It is advised to add in your webserver as you don't need to add this in each of your html pages (assuming no includes).

To add in your apache place the favicon.ico in your root website director and add this in httpd.conf

AddType image/x-icon .ico

How can I build for release/distribution on the Xcode 4?

The short answer is:

  1. choose the iOS scheme from the drop-down near the run button from the menu bar
  2. choose product > archive in the window that pops-up
  3. click 'validate'
  4. upon successful validation, click 'submit'

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

how to access downloads folder in android?

You should add next permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)

Python string.replace regular expression

re.sub is definitely what you are looking for. And so you know, you don't need the anchors and the wildcards.

re.sub(r"(?i)interfaceOpDataFile", "interfaceOpDataFile %s" % filein, line)

will do the same thing--matching the first substring that looks like "interfaceOpDataFile" and replacing it.

Convert Java string to Time, NOT Date

You might consider Joda Time or Java 8, which has a type called LocalTime specifically for a time of day without a date component.

Example code in Joda-Time 2.7/Java 8.

LocalTime t = LocalTime.parse( "17:40" ) ;

Start/Stop and Restart Jenkins service on Windows

Step 01: You need to add jenkins for environment variables, Then you can use jenkins commands

Step 02: Go to "C:\Program Files (x86)\Jenkins" with admin prompt

Step 03: Choose your option: jenkins.exe stop / jenkins.exe start / jenkins.exe restart

Troubleshooting "Illegal mix of collations" error in mysql

Very interesting... Now, be ready. I looked at all of the "add collate" solutions and to me, those are band aid fixes. The reality is the database design was "bad". Yes, standard changes and new things gets added, blah blah, but it does not change the bad database design fact. I refuse to go with the route of adding "collate" all over the SQL statements just to get my query to work. The only solution that works for me and will virtually eliminate the need to tweak my code in the future is to re-design the database/tables to match the character set that I will live with and embrace for the long term future. In this case, I choose to go with the character set "utf8mb4".

So the solution here when you encounter that "illegal" error message is to re-design your database and tables. It is much easier and quicker then it sounds. Exporting your data and re-importing it from a CSV may not even be required. Change the character set of the database and make sure all the character set of your tables matches.

Use these commands to guide you:

SHOW VARIABLES LIKE "collation_database";
SHOW TABLE STATUS;

Now, if you enjoy adding "collate" here and there and beef up your code with forces fulls "overrides", be my guess.

C# getting its own class name

Get Current class name of Asp.net

string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <body>
        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
    
            <script>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
                </script>
        </body>
    
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "
      </div>
    

What is the best way to manage a user's session in React?

I would avoid using component state since this could be difficult to manage and prone to issues that can be difficult to troubleshoot.

You should use either cookies or localStorage for persisting a user's session data. You can also use a closure as a wrapper around your cookie or localStorage data.

Here is a simple example of a UserProfile closure that will hold the user's name.

var UserProfile = (function() {
  var full_name = "";

  var getName = function() {
    return full_name;    // Or pull this from cookie/localStorage
  };

  var setName = function(name) {
    full_name = name;     
    // Also set this in cookie/localStorage
  };

  return {
    getName: getName,
    setName: setName
  }

})();

export default UserProfile;

When a user logs in, you can populate this object with user name, email address etc.

import UserProfile from './UserProfile';

UserProfile.setName("Some Guy");

Then you can get this data from any component in your app when needed.

import UserProfile from './UserProfile';

UserProfile.getName();

Using a closure will keep data outside of the global namespace, and make it is easily accessible from anywhere in your app.

Checkout subdirectories in Git?

git clone --filter from git 2.19 now works on GitHub (tested 2020-09-18, git 2.25.1)

This option was added together with an update to the remote protocol, and it truly prevents objects from being downloaded from the server.

To clone only objects required for d1 of this repository: https://github.com/cirosantilli/test-git-partial-clone I can do:

git clone \
  --depth 1 \
  --filter=blob:none \
  --no-checkout \
  https://github.com/cirosantilli/test-git-partial-clone \
;
cd test-git-partial-clone
git checkout master -- d1

I have covered this in more detail at: Git: How do I clone a subdirectory only of a Git repository?

It is more efficient to use if-return-return or if-else-return?

This is a question of style (or preference) since the interpreter does not care. Personally I would try not to make the final statement of a function which returns a value at an indent level other than the function base. The else in example 1 obscures, if only slightly, where the end of the function is.

By preference I use:

return A+1 if (A > B) else A-1

As it obeys both the good convention of having a single return statement as the last statement in the function (as already mentioned) and the good functional programming paradigm of avoiding imperative style intermediate results.

For more complex functions I prefer to break the function into multiple sub-functions to avoid premature returns if possible. Otherwise I revert to using an imperative style variable called rval. I try not to use multiple return statements unless the function is trivial or the return statement before the end is as a result of an error. Returning prematurely highlights the fact that you cannot go on. For complex functions that are designed to branch off into multiple subfunctions I try to code them as case statements (driven by a dict for instance).

Some posters have mentioned speed of operation. Speed of Run-time is secondary for me since if you need speed of execution Python is not the best language to use. I use Python as its the efficiency of coding (i.e. writing error free code) that matters to me.

Error checking for NULL in VBScript

I see lots of confusion in the comments. Null, IsNull() and vbNull are mainly used for database handling and normally not used in VBScript. If it is not explicitly stated in the documentation of the calling object/data, do not use it.

To test if a variable is uninitialized, use IsEmpty(). To test if a variable is uninitialized or contains "", test on "" or Empty. To test if a variable is an object, use IsObject and to see if this object has no reference test on Is Nothing.

In your case, you first want to test if the variable is an object, and then see if that variable is Nothing, because if it isn't an object, you get the "Object Required" error when you test on Nothing.

snippet to mix and match in your code:

If IsObject(provider) Then
    If Not provider Is Nothing Then
        ' Code to handle a NOT empty object / valid reference
    Else
        ' Code to handle an empty object / null reference
    End If
Else
    If IsEmpty(provider) Then
        ' Code to handle a not initialized variable or a variable explicitly set to empty
    ElseIf provider = "" Then
        ' Code to handle an empty variable (but initialized and set to "")
    Else
        ' Code to handle handle a filled variable
    End If
End If

Simple and fast method to compare images for similarity

If you can be sure to have precise alignment of your template (the icon) to the testing region, then any old sum of pixel differences will work.

If the alignment is only going to be a tiny bit off, then you can low-pass both images with cv::GaussianBlur before finding the sum of pixel differences.

If the quality of the alignment is potentially poor then I would recommend either a Histogram of Oriented Gradients or one of OpenCV's convenient keypoint detection/descriptor algorithms (such as SIFT or SURF).

Scroll to a div using jquery

you can try :

$("#MediaPlayer").ready(function(){
    $("html, body").delay(2000).animate({
        scrollTop: $('#MediaPlayer').offset().top 
    }, 2000);
});

Undo a particular commit in Git that's been pushed to remote repos

If the commit you want to revert is a merged commit (has been merged already), then you should either -m 1 or -m 2 option as shown below. This will let git know which parent commit of the merged commit to use. More details can be found HERE.

  • git revert <commit> -m 1
  • git revert <commit> -m 2

Java function for arrays like PHP's join()?

A little mod instead of using substring():

//join(String array,delimiter)
public static String join(String r[],String d)
{
        if (r.length == 0) return "";
        StringBuilder sb = new StringBuilder();
        int i;
        for(i=0;i<r.length-1;i++){
            sb.append(r[i]);
            sb.append(d);
        }
        sb.append(r[i]);
        return sb.toString();
}

How to add double quotes to a string that is inside a variable?

in C# if we use "\" means that will indicate following symbol is not c# inbuild symbol that will use by developer. so in string we need double quotes means we can put "\" symbol before double quotes. string s = "\"Hi\""

Cannot make a static reference to the non-static method

There are some good answers already with explanations of why the mixture of the non-static Context method getText() can't be used with your static final String.

A good question to ask is: why do you want to do this? You are attempting to load a String from your strings resource, and populate its value into a public static field. I assume that this is so that some of your other classes can access it? If so, there is no need to do this. Instead pass a Context into your other classes and call context.getText(R.string.TTT) from within them.

public class NonActivity {

    public static void doStuff(Context context) {
        String TTT = context.getText(R.string.TTT);
        ...
    }
}

And to call this from your Activity:

NonActivity.doStuff(this);

This will allow you to access your String resource without needing to use a public static field.

Difference between RUN and CMD in a Dockerfile

RUN Command: RUN command will basically, execute the default command, when we are building the image. It also will commit the image changes for next step.

There can be more than 1 RUN command, to aid in process of building a new image.

CMD Command: CMD commands will just set the default command for the new container. This will not be executed at build time.

If a docker file has more than 1 CMD commands then all of them are ignored except the last one. As this command will not execute anything but just set the default command.

enable/disable zoom in Android WebView

The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:

User Pinch Zooms and controls appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP

User Pinch Zoom and Controls don't appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP

Can you shed more light on your solution?

Remove Fragment Page from ViewPager in Android

I added a function "clearFragments" and I used that function to clear adapter before setting the new fragments. This calls the proper remove actions of Fragments. My pagerAdapter class:

private class ChartPagerAdapter extends FragmentPagerAdapter{
    private ArrayList<Fragment> fragmentList;

    ChartPagerAdapter(FragmentManager fm){
        super(fm);
        fragmentList = new ArrayList<>();
    }

    void setFragments(ArrayList<? extends Fragment> fragments){
        fragmentList.addAll(fragments);
    }

    void clearFragments(){
        for(Fragment fragment:fragmentList)
            getChildFragmentManager().beginTransaction().remove(fragment).commit();
        fragmentList.clear();
    }

    @Override
    public Fragment getItem(int i) {
        return fragmentList.get(i);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

}

How to compile and run C files from within Notepad++ using NppExec plugin?

You can actually compile and run C code even without the use of nppexec plugins. If you use MingW32 C compiler, use g++ for C++ language and gcc for C language.

Paste this code into the notepad++ run section

cmd /k cd $(CURRENT_DIRECTORY) && gcc $(FILE_NAME) -o $(NAME_PART).exe  && $(NAME_PART).exe && pause

It will compile your C code into exe and run it immediately. It's like a build and run feature in CodeBlock. All these are done with some cmd knowledge.

Explanation:

  1. cmd /k is used for testing.
  2. cd $(CURRENT_DIRECTORY)
    • change directory to where file is located
  3. && operators
    • to chain your commands in a single line
  4. gcc $(FILE_NAME)
    • use GCC to compile File with its file extension.
  5. -o $(NAME_PART).exe
    • this flag allow you to choose your output filename. $(NAME_PART) does not include file extension.
  6. $(NAME_PART).exe
    • this alone runs your program
  7. pause
    • this command is used to keep your console open after file has been executed.

For more info on notepad++ commands, go to

http://docs.notepad-plus-plus.org/index.php/External_Programs

What is mapDispatchToProps?

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)

The split() method in Java does not work on a dot (.)

The method takes a regular expression, not a string, and the dot has a special meaning in regular expressions. Escape it like so split("\\."). You need a double backslash, the second one escapes the first.

mysql update column with value from another table

Second possibility is,

UPDATE TableB 
SET TableB.value = (
    SELECT TableA.value 
    FROM TableA
    WHERE TableA.name = TableB.name
);

concatenate char array in C

You can concatenate strings by using the sprintf() function. In your case, for example:

char file[80];
sprintf(file,"%s%s",name,extension);

And you'll end having the concatenated string in "file".

How generate unique Integers based on GUIDs

Here is the simplest way:

Guid guid = Guid.NewGuid();
Random random = new Random();
int i = random.Next();

You'll notice that guid is not actually used here, mainly because there would be no point in using it. Microsoft's GUID algorithm does not use the computer's MAC address any more - GUID's are actually generated using a pseudo-random generator (based on time values), so if you want a random integer it makes more sense to use the Random class for this.

Update: actually, using a GUID to generate an int would probably be worse than just using Random ("worse" in the sense that this would be more likely to generate collisions). This is because not all 128 bits in a GUID are random. Ideally, you would want to exclude the non-varying bits from a hashing function, although it would be a lot easier to just generate a random number, as I think I mentioned before. :)

Use <Image> with a local file

It works exactly as you expect it to work. There's a bug https://github.com/facebook/react-native/issues/282 that prevents it from working correctly.

If you have node_modules (with react_native) in the same folder as the xcode project, you can edit node_modules/react-native/packager/packager.js and make this change: https://github.com/facebook/react-native/pull/286/files . It'll work magically :)

If your react_native is installed somewhere else and the patch doesn't work, comment on https://github.com/facebook/react-native/issues/282 to let them know about your setup.

Renaming files using node.js

You'll need to use fs for that: http://nodejs.org/api/fs.html

And in particular the fs.rename() function:

var fs = require('fs');
fs.rename('/path/to/Afghanistan.png', '/path/to/AF.png', function(err) {
    if ( err ) console.log('ERROR: ' + err);
});

Put that in a loop over your freshly-read JSON object's keys and values, and you've got a batch renaming script.

fs.readFile('/path/to/countries.json', function(error, data) {
    if (error) {
        console.log(error);
        return;
    }

    var obj = JSON.parse(data);
    for(var p in obj) {
        fs.rename('/path/to/' + obj[p] + '.png', '/path/to/' + p + '.png', function(err) {
            if ( err ) console.log('ERROR: ' + err);
        });
    }
});

(This assumes here that your .json file is trustworthy and that it's safe to use its keys and values directly in filenames. If that's not the case, be sure to escape those properly!)

How to stop default link click behavior with jQuery

I've just wasted an hour on this. I tried everything - it turned out (and I can hardly believe this) that giving my cancel button and element id of cancel meant that any attempt to prevent event propagation would fail! I guess an HTML page must treat this as someone pressing ESC?

Quickest way to convert a base 10 number to any base in .NET?

I had a similar need, except I needed to do math on the "numbers" as well. I took some of the suggestions here and created a class that will do all this fun stuff. It allows for any unicode character to be used to represent a number and it works with decimals too.

This class is pretty easy to use. Just create a number as a type of New BaseNumber, set a few properties, and your off. The routines take care of switching between base 10 and base x automatically and the value you set is preserved in the base you set it in, so no accuracy is lost (until conversion that is, but even then precision loss should be very minimal since this routine uses Double and Long where ever possible).

I can't command on the speed of this routine. It is probably quite slow, so I'm not sure if it will suit the needs of the one who asked the question, but it certain is flexible, so hopefully someone else can use this.

For anyone else that may need this code for calculating the next column in Excel, I will include the looping code I used that leverages this class.

Public Class BaseNumber

    Private _CharacterArray As List(Of Char)

    Private _BaseXNumber As String
    Private _Base10Number As Double?

    Private NumberBaseLow As Integer
    Private NumberBaseHigh As Integer

    Private DecimalSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator
    Private GroupSeparator As Char = System.Globalization.CultureInfo.CurrentCulture.NumberFormat.NumberGroupSeparator

    Public Sub UseCapsLetters()
        'http://unicodelookup.com
        TrySetBaseSet(65, 90)
    End Sub

    Public Function GetCharacterArray() As List(Of Char)
        Return _CharacterArray
    End Function

    Public Sub SetCharacterArray(CharacterArray As String)
        _CharacterArray = New List(Of Char)
        _CharacterArray.AddRange(CharacterArray.ToList)

        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetCharacterArray(CharacterArray As List(Of Char))
        _CharacterArray = CharacterArray
        TrySetBaseSet(_CharacterArray)
    End Sub

    Public Sub SetNumber(Value As String)
        _BaseXNumber = Value
        _Base10Number = Nothing
    End Sub

    Public Sub SetNumber(Value As Double)
        _Base10Number = Value
        _BaseXNumber = Nothing
    End Sub

    Public Function GetBaseXNumber() As String
        If _BaseXNumber IsNot Nothing Then
            Return _BaseXNumber
        Else
            Return ToBaseString()
        End If
    End Function

    Public Function GetBase10Number() As Double
        If _Base10Number IsNot Nothing Then
            Return _Base10Number
        Else
            Return ToBase10()
        End If
    End Function

    Private Sub TrySetBaseSet(Values As List(Of Char))
        For Each value As Char In _BaseXNumber
            If Not Values.Contains(value) Then
                Throw New ArgumentOutOfRangeException("The string has a value, " & value & ", not contained in the selected 'base' set.")
                _CharacterArray.Clear()
                DetermineNumberBase()
            End If
        Next

        _CharacterArray = Values

    End Sub

    Private Sub TrySetBaseSet(LowValue As Integer, HighValue As Integer)

        Dim HighLow As KeyValuePair(Of Integer, Integer) = GetHighLow()

        If HighLow.Key < LowValue OrElse HighLow.Value > HighValue Then
            Throw New ArgumentOutOfRangeException("The string has a value not contained in the selected 'base' set.")
            _CharacterArray.Clear()
            DetermineNumberBase()
        End If

        NumberBaseLow = LowValue
        NumberBaseHigh = HighValue

    End Sub

    Private Function GetHighLow(Optional Values As List(Of Char) = Nothing) As KeyValuePair(Of Integer, Integer)
        If Values Is Nothing Then
            Values = _BaseXNumber.ToList
        End If

        Dim lowestValue As Integer = Convert.ToInt32(Values(0))
        Dim highestValue As Integer = Convert.ToInt32(Values(0))

        Dim currentValue As Integer

        For Each value As Char In Values

            If value <> DecimalSeparator AndAlso value <> GroupSeparator Then
                currentValue = Convert.ToInt32(value)
                If currentValue > highestValue Then
                    highestValue = currentValue
                End If
                If currentValue < lowestValue Then
                    currentValue = lowestValue
                End If
            End If
        Next

        Return New KeyValuePair(Of Integer, Integer)(lowestValue, highestValue)

    End Function

    Public Sub New(BaseXNumber As String)
        _BaseXNumber = BaseXNumber
        DetermineNumberBase()
    End Sub

    Public Sub New(BaseXNumber As String, NumberBase As Integer)
        Me.New(BaseXNumber, Convert.ToInt32("0"c), NumberBase)
    End Sub

    Public Sub New(BaseXNumber As String, NumberBaseLow As Integer, NumberBaseHigh As Integer)
        _BaseXNumber = BaseXNumber
        Me.NumberBaseLow = NumberBaseLow
        Me.NumberBaseHigh = NumberBaseHigh
    End Sub

    Public Sub New(Base10Number As Double)
        _Base10Number = Base10Number
    End Sub

    Private Sub DetermineNumberBase()
        Dim highestValue As Integer

        Dim currentValue As Integer

        For Each value As Char In _BaseXNumber

            currentValue = Convert.ToInt32(value)
            If currentValue > highestValue Then
                highestValue = currentValue
            End If
        Next

        NumberBaseHigh = highestValue
        NumberBaseLow = Convert.ToInt32("0"c) 'assume 0 is the lowest

    End Sub

    Private Function ToBaseString() As String
        Dim Base10Number As Double = _Base10Number

        Dim intPart As Long = Math.Truncate(Base10Number)
        Dim fracPart As Long = (Base10Number - intPart).ToString.Replace(DecimalSeparator, "")

        Dim intPartString As String = ConvertIntToString(intPart)
        Dim fracPartString As String = If(fracPart <> 0, DecimalSeparator & ConvertIntToString(fracPart), "")

        Return intPartString & fracPartString

    End Function

    Private Function ToBase10() As Double
        Dim intPartString As String = _BaseXNumber.Split(DecimalSeparator)(0).Replace(GroupSeparator, "")
        Dim fracPartString As String = If(_BaseXNumber.Contains(DecimalSeparator), _BaseXNumber.Split(DecimalSeparator)(1), "")

        Dim intPart As Long = ConvertStringToInt(intPartString)
        Dim fracPartNumerator As Long = ConvertStringToInt(fracPartString)
        Dim fracPartDenominator As Long = ConvertStringToInt(GetEncodedChar(1) & String.Join("", Enumerable.Repeat(GetEncodedChar(0), fracPartString.ToString.Length)))

        Return Convert.ToDouble(intPart + fracPartNumerator / fracPartDenominator)

    End Function

    Private Function ConvertIntToString(ValueToConvert As Long) As String
        Dim result As String = String.Empty
        Dim targetBase As Long = GetEncodingCharsLength()

        Do
            result = GetEncodedChar(ValueToConvert Mod targetBase) & result
            ValueToConvert = ValueToConvert \ targetBase
        Loop While ValueToConvert > 0

        Return result
    End Function

    Private Function ConvertStringToInt(ValueToConvert As String) As Long
        Dim result As Long
        Dim targetBase As Integer = GetEncodingCharsLength()
        Dim startBase As Integer = GetEncodingCharsStartBase()

        Dim value As Char
        For x As Integer = 0 To ValueToConvert.Length - 1
            value = ValueToConvert(x)
            result += GetDecodedChar(value) * Convert.ToInt32(Math.Pow(GetEncodingCharsLength, ValueToConvert.Length - (x + 1)))
        Next

        Return result

    End Function

    Private Function GetEncodedChar(index As Integer) As Char
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray(index)
        Else
            Return Convert.ToChar(index + NumberBaseLow)
        End If
    End Function

    Private Function GetDecodedChar(character As Char) As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.IndexOf(character)
        Else
            Return Convert.ToInt32(character) - NumberBaseLow
        End If
    End Function

    Private Function GetEncodingCharsLength() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return _CharacterArray.Count
        Else
            Return NumberBaseHigh - NumberBaseLow + 1
        End If
    End Function

    Private Function GetEncodingCharsStartBase() As Integer
        If _CharacterArray IsNot Nothing AndAlso _CharacterArray.Count > 0 Then
            Return GetHighLow.Key
        Else
            Return NumberBaseLow
        End If
    End Function
End Class

And now for the code to loop through Excel columns:

    Public Function GetColumnList(DataSheetID As String) As List(Of String)
        Dim workingColumn As New BaseNumber("A")
        workingColumn.SetCharacterArray("@ABCDEFGHIJKLMNOPQRSTUVWXYZ")

        Dim listOfPopulatedColumns As New List(Of String)
        Dim countOfEmptyColumns As Integer

        Dim colHasData As Boolean
        Dim cellHasData As Boolean

        Do
            colHasData = True
            cellHasData = False
            For r As Integer = 1 To GetMaxRow(DataSheetID)
                cellHasData = cellHasData Or XLGetCellValue(DataSheetID, workingColumn.GetBaseXNumber & r) <> ""
            Next
            colHasData = colHasData And cellHasData

            'keep trying until we get 4 empty columns in a row
            If colHasData Then
                listOfPopulatedColumns.Add(workingColumn.GetBaseXNumber)
                countOfEmptyColumns = 0
            Else
                countOfEmptyColumns += 1
            End If

            'we are already starting with column A, so increment after we check column A
            Do
                workingColumn.SetNumber(workingColumn.GetBase10Number + 1)
            Loop Until Not workingColumn.GetBaseXNumber.Contains("@")

        Loop Until countOfEmptyColumns > 3

        Return listOfPopulatedColumns

    End Function

You'll note the important part of the Excel part is that 0 is identified by a @ in the re-based number. So I just filter out all the numbers that have an @ in them and I get the proper sequence (A, B, C, ..., Z, AA, AB, AC, ...).

How to input automatically when running a shell over SSH?

Also you can pipe the answers to the script:

printf "y\npassword\n" | sh test.sh

where \n is escape-sequence

Determine if an element has a CSS class with jQuery

In my case , I used the 'is' a jQuery function, I had a HTML element with different css classes added , I was looking for a specific class in the middle of these , so I used the "is" a good alternative to check a class dynamically added to an html element , which already has other css classes, it is another good alternative.

simple example :

 <!--element html-->
 <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

 <!--jQuery "is"-->
 $('#menu').is('.cbp-spmenu-open');

advanced example :

 <!--element html-->
    <nav class="cbp-spmenu cbp-spmenu-horizontal cbp-spmenu-bottom cbp-spmenu-open" id="menu">somethings here... </nav>

   <!--jQuery "is"-->
    if($('#menu').is('.cbp-spmenu-bottom.cbp-spmenu-open')){
       $("#menu").show();
    }

Need to get a string after a "word" in a string in c#

string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);

Something like this?

Perhaps you should handle the case of missing code :...

string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);

if (ix != -1) 
{
    string code = myString.Substring(ix + toBeSearched.Length);
    // do something here
}

How to diff one file to an arbitrary version in Git?

git diff master~20 -- pom.xml

Works if you are not in master branch too.

Why do we use __init__ in Python classes?

class Dog(object):

    # Class Object Attribute
    species = 'mammal'

    def __init__(self,breed,name):
        self.breed = breed
        self.name = name

In above example we use species as a global since it will be always same(Kind of constant you can say). when you call __init__ method then all the variable inside __init__ will be initiated(eg:breed,name).

class Dog(object):
    a = '12'

    def __init__(self,breed,name,a):
        self.breed = breed
        self.name = name
        self.a= a

if you print the above example by calling below like this

Dog.a
12

Dog('Lab','Sam','10')
Dog.a
10

That means it will be only initialized during object creation. so anything which you want to declare as constant make it as global and anything which changes use __init__

SQL LEFT JOIN Subquery Alias

I recognize that the answer works and has been accepted but there is a much cleaner way to write that query. Tested on mysql and postgres.

SELECT wpoi.order_id As No_Commande
FROM  wp_woocommerce_order_items AS wpoi
LEFT JOIN wp_postmeta AS wpp ON wpoi.order_id = wpp.post_id 
                            AND wpp.meta_key = '_shipping_first_name'
WHERE  wpoi.order_id =2198 

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

loading json data from local file into React JS

  1. install json-loader:

    npm i json-loader --save

  2. create data folder in src:

    mkdir data

  3. put your file(s) there

  4. load your file

    var data = require('json!../data/yourfile.json');

Using custom fonts using CSS?

I am working on Win 8, use this code. It works for IE and FF, Opera, etc. What I understood are : woff font is light et common on Google fonts.

Go here to convert your ttf font to woff before.

@font-face
{
    font-family:'Open Sans';
    src:url('OpenSans-Regular.woff');
}

load scripts asynchronously

Here is my custom solution to eliminate render-blocking JavaScript:

// put all your JS files here, in correct order
const libs = {
  "jquery": "https://code.jquery.com/jquery-2.1.4.min.js",
  "bxSlider": "https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.5/jquery.bxslider.min.js",
  "angular": "https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular.min.js",
  "ngAnimate": "https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.0-beta.2/angular-animate.min.js"
}
const loadedLibs = {}
let counter = 0

const loadAsync = function(lib) {
  var http = new XMLHttpRequest()
  http.open("GET", libs[lib], true)
  http.onload = () => {
    loadedLibs[lib] = http.responseText
    if (++counter == Object.keys(libs).length) startScripts()
  }
  http.send()
}

const startScripts = function() {
  for (var lib in libs) eval(loadedLibs[lib])
  console.log("allLoaded")
}

for (var lib in libs) loadAsync(lib)

In short, it loads all your scripts asynchronously, and then executes them consequently.

Github repo: https://github.com/mudroljub/js-async-loader

How to draw a graph in LaTeX?

TikZ can do this.

A quick demo:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  [scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
  \node (n6) at (1,10) {6};
  \node (n4) at (4,8)  {4};
  \node (n5) at (8,9)  {5};
  \node (n1) at (11,8) {1};
  \node (n2) at (9,6)  {2};
  \node (n3) at (5,5)  {3};

  \foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
    \draw (\from) -- (\to);

\end{tikzpicture}

\end{document}

produces:

enter image description here

More examples @ http://www.texample.net/tikz/examples/tag/graphs/

More information about TikZ: http://sourceforge.net/projects/pgf/ where I guess an installation guide will also be present.

Bootstrap 3 dropdown select

The dropdown list appearing like that depends on what your browser is, as it is not possible to style this away for some. It looks like yours is IE9, but would look quite different in Chrome.

You could look to use something like this:

http://silviomoreto.github.io/bootstrap-select/

Which will make your selectboxes more consistent cross browser.

Adjust icon size of Floating action button (fab)

As FAB is like ImageView so You can use scaleType attribute to change the icon size likewise ImageView. Default scaleType for a FAB is fitCenter. You can use center and centerInside to make icon small and large respectively.

All values for scaleType attribute are - center, centerCrop, centerInside, fitCenter, fitEnd, fitStart, fitXY and matrix.

See https://developer.android.com/reference/android/widget/ImageView.ScaleType.html for more details.

How do I show a running clock in Excel?

Found the code that I referred to in my comment above. To test it, do this:

  1. In Sheet1 change the cell height and width of say A1 as shown in the snapshot below.
  2. Format the cell by right clicking on it to show time format
  3. Add two buttons (form controls) on the worksheet and name them as shown in the snapshot
  4. Paste this code in a module
  5. Right click on the Start Timer button on the sheet and click on Assign Macros. Select StartTimer macro.
  6. Right click on the End Timer button on the sheet and click on Assign Macros. Select EndTimer macro.

Now click on Start Timer button and you will see the time getting updated in cell A1. To stop time updates, Click on End Timer button.

Code (TRIED AND TESTED)

Public Declare Function SetTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long, _
ByVal uElapse As Long, ByVal lpTimerFunc As Long) As Long

Public Declare Function KillTimer Lib "user32" ( _
ByVal HWnd As Long, ByVal nIDEvent As Long) As Long

Public TimerID As Long, TimerSeconds As Single, tim As Boolean
Dim Counter As Long

'~~> Start Timer
Sub StartTimer()
    '~~ Set the timer for 1 second
    TimerSeconds = 1
    TimerID = SetTimer(0&, 0&, TimerSeconds * 1000&, AddressOf TimerProc)
End Sub

'~~> End Timer
Sub EndTimer()
    On Error Resume Next
    KillTimer 0&, TimerID
End Sub

Sub TimerProc(ByVal HWnd As Long, ByVal uMsg As Long, _
ByVal nIDEvent As Long, ByVal dwTimer As Long)
    '~~> Update value in Sheet 1
    Sheet1.Range("A1").Value = Time
End Sub

SNAPSHOT

enter image description here

How to update PATH variable permanently from Windows command line?

For reference purpose, for anyone searching how to change the path via code, I am quoting a useful post by a Delphi programmer from this web page: http://www.tek-tips.com/viewthread.cfm?qid=686382

TonHu (Programmer) 22 Oct 03 17:57 I found where I read the original posting, it's here: http://news.jrsoftware.org/news/innosetup.isx/msg02129....

The excerpt of what you would need is this:

You must specify the string "Environment" in LParam. In Delphi you'd do it this way:

 SendMessage(HWND_BROADCAST, WM_SETTINGCHANGE, 0, Integer(PChar('Environment')));

It was suggested by Jordan Russell, http://www.jrsoftware.org, the author of (a.o.) InnoSetup, ("Inno Setup is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability.") (I just would like more people to use InnoSetup )

HTH

How do I select an entire row which has the largest ID in the table?

One can always go for analytical functions as well which will give you more control

select tmp.row from ( select row, rank() over(partition by id order by id desc ) as rnk from table) tmp where tmp.rnk=1

If you face issue with rank() function depending on the type of data then one can choose from row_number() or dense_rank() too.

How to initialize a dict with keys from a list and empty value in Python?

>>> keyDict = {"a","b","c","d"}

>>> dict([(key, []) for key in keyDict])

Output:

{'a': [], 'c': [], 'b': [], 'd': []}

Anaconda-Navigator - Ubuntu16.04

Use the following command on your terminal (Ctrl + Alt + T):-

$ conda activate
$ anaconda-navigator

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

sudo -i
cd /etc/apt/sources.list.d
echo "deb http://archive.ubuntu.com/ubuntu/ precise main restricted universe multiverse" >ia32-libs-raring.list
apt-get update
apt-get install ia32-libs
rm /etc/apt/sources.list.d/ia32-libs-raring.list
apt-get update
exit

If you are in China, you can modify "raring" to "precise" (for Ubuntu 13.04 (Raring Ringtail) and Ubuntu 12.04 LTS (Precise Pangolin), respectively). I installed Beyond Compare on Ubuntu 14.04 (Trusty Tahr).

How to create a drop-down list?

You can also use AppCompatSpinner widget:

<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spinner_order_type"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:backgroundTint="@color/red"/>

Inside your Activity class:

AppCompatSpinner spinOrderType = (AppCompatSpinner) findViewById(R.id.spinner_order_type);
List<String> categories = new ArrayList<String>();
        categories.add(getString(R.string.label_table_order));
        categories.add(getString(R.string.label_take_away));

        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext,
                R.layout.layout_spinner_item, categories);
        dataAdapter.setDropDownViewResource(R.layout.layout_spinner_item);
        spinOrderType.setAdapter(dataAdapter);
        spinOrderType.setSelection(0);

        spinOrderType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                String item = parent.getItemAtPosition(position).toString();
                Log.d(TAG, item);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

layout_spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:tools="http://schemas.android.com/tools"
    android:gravity="left"
    android:textSize="@dimen/text.size.large"
    android:textColor="@color/text.link"
    android:padding="@dimen/margin.3" />

Maximum length for MD5 input/output

You can have any length, but of course, there can be a memory issue on the computer if the String input is too long. The output is always 32 characters.

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

How to get the ActionBar height?

In javafx (using Gluon), the height is set at runtime or something like it. While being able to get the width just like normal...

double width = appBar.getWidth();

You have to create a listener:

GluonApplication application = this;

application.getAppBar().heightProperty().addListener(new ChangeListener(){
    @Override
    public void changed(ObservableValue observable, Object oldValue, Object newValue) {
        // Take most recent value given here
        application.getAppBar.heightProperty.get()
    }
});

...And take the most recent value it changed to. To get the height.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.

In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name, which is the logged in user identifier as set during the ASP.NET authentication.

However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.

Example of Mapping SignalR Users to Connections using IUserIdProvider

Lets assume our application uses a userId to identify each user. Now, we need to send message to a specific user. We have userId and message, but SignalR must also know the mapping between our userId and the connection.

To achieve this, first we need to create a new class which implements IUserIdProvider:

public class CustomUserIdProvider : IUserIdProvider
{
     public string GetUserId(IRequest request)
    {
        // your logic to fetch a user identifier goes here.

        // for example:

        var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
        return userId.ToString();
    }
}

The second step is to tell SignalR to use our CustomUserIdProvider instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var idProvider = new CustomUserIdProvider();

        GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);          

        // Any connection or hub wire up and configuration should go here
        app.MapSignalR();
    }
}

Now, you can send message to a specific user using his userId as mentioned in the documentation, like:

public class MyHub : Hub
{
   public void Send(string userId, string message)
   {
      Clients.User(userId).send(message);
   }
}

Hope this helps.

get number of columns of a particular row in given excel using Java

Sometimes using row.getLastCellNum() gives you a higher value than what is actually filled in the file.
I used the method below to get the last column index that contains an actual value.

private int getLastFilledCellPosition(Row row) {
        int columnIndex = -1;

        for (int i = row.getLastCellNum() - 1; i >= 0; i--) {
            Cell cell = row.getCell(i);

            if (cell == null || CellType.BLANK.equals(cell.getCellType()) || StringUtils.isBlank(cell.getStringCellValue())) {
                continue;
            } else {
                columnIndex = cell.getColumnIndex();
                break;
            }
        }

        return columnIndex;
    }

Why use sys.path.append(path) instead of sys.path.insert(1, path)?

you are confusing the concept of appending and prepending. the following code is prepending:

sys.path.insert(1,'/thePathToYourFolder/')

it places the new information at the beginning (well, second, to be precise) of the search sequence that your interpreter will go through. sys.path.append() puts things at the very end of the search sequence.

it is advisable that you use something like virtualenv instead of manually coding your package directories into the PYTHONPATH everytime. for setting up various ecosystems that separate your site-packages and possible versions of python, read these two blogs:

  1. python ecosystems introduction

  2. bootstrapping python virtual environments

if you do decide to move down the path to environment isolation you would certainly benefit by looking into virtualenvwrapper: http://www.doughellmann.com/docs/virtualenvwrapper/

What is the equivalent of "none" in django templates?

isoperator : New in Django 1.10

{% if somevar is None %}
  This appears if somevar is None, or if somevar is not found in the context.
{% endif %}

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

Efficient way to update all rows in a table

update Hotels set Discount=30 where Hotelid >= 1 and Hotelid <= 5504

How do I convert NSInteger to NSString datatype?

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

Format cell if cell contains date less than today

Your first problem was you weren't using your compare symbols correctly.

< less than
> greater than
<= less than or equal to
>= greater than or equal to

To answer your other questions; get the condition to work on every cell in the column and what about blanks?

What about blanks?

Add an extra IF condition to check if the cell is blank or not, if it isn't blank perform the check. =IF(B2="","",B2<=TODAY())

Condition on every cell in column

enter image description here

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

Read response headers from API response - Angular 5 + TypeScript

You can get data from post response Headers in this way (Angular 6):

import { HttpClient, HttpHeaders, HttpResponse } from '@angular/common/http';

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json' }),
  observe: 'response' as 'response'
};

this.http.post(link,body,httpOptions).subscribe((res: HttpResponse<any>) => {
  console.log(res.headers.get('token-key-name'));
})

How to create a pivot query in sql server without aggregate function

SELECT *
FROM
(
SELECT [Period], [Account], [Value]
FROM TableName
) AS source
PIVOT
(
    MAX([Value])
    FOR [Period] IN ([2000], [2001], [2002])
) as pvt

Another way,

SELECT ACCOUNT,
      MAX(CASE WHEN Period = '2000' THEN Value ELSE NULL END) [2000],
      MAX(CASE WHEN Period = '2001' THEN Value ELSE NULL END) [2001],
      MAX(CASE WHEN Period = '2002' THEN Value ELSE NULL END) [2002]
FROM tableName
GROUP BY Account

Calculate correlation with cor(), only for numerical columns

I found an easier way by looking at the R script generated by Rattle. It looks like below:

correlations <- cor(mydata[,c(1,3,5:87,89:90,94:98)], use="pairwise", method="spearman")

Simple UDP example to send and receive data from same socket

(I presume you are aware that using UDP(User Datagram Protocol) does not guarantee delivery, checks for duplicates and congestion control and will just answer your question).

In your server this line:

var data = udpServer.Receive(ref groupEP);

re-assigns groupEP from what you had to a the address you receive something on.

This line:

udpServer.Send(new byte[] { 1 }, 1); 

Will not work since you have not specified who to send the data to. (It works on your client because you called connect which means send will always be sent to the end point you connected to, of course we don't want that on the server as we could have many clients). I would:

UdpClient udpServer = new UdpClient(UDP_LISTEN_PORT);

while (true)
{
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);
    udpServer.Send(new byte[] { 1 }, 1, remoteEP); // if data is received reply letting the client know that we got his data          
}

Also if you have server and client on the same machine you should have them on different ports.

Find an object in SQL Server (cross-database)

Easiest way is to hit up the information_schemas...

SELECT *
FROM information_schema.Tables
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Views
WHERE [Table_Name]='????'

SELECT *
FROM information_schema.Routines
WHERE [Routine_Name]='????'

Increase max execution time for php

well, there are two way to change max_execution_time.
1. You can directly set it in php.ini file.
2. Secondly, you can add following line in your code.

ini_set('max_execution_time', '100')

MySQL Job failed to start

In my case the problem was the /var/log disk full (check with df -h)

Just deleted some log files and mysql started, no big deal!

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

Checking if a number is a prime number in Python

This is the most efficient way to see if a number is prime, if you only have a few query. If you ask a lot of numbers if they are prime try Sieve of Eratosthenes.

import math

def is_prime(n):
    if n == 2:
        return True
    if n % 2 == 0 or n <= 1:
        return False

    sqr = int(math.sqrt(n)) + 1

    for divisor in range(3, sqr, 2):
        if n % divisor == 0:
            return False
    return True

How to execute a Python script from the Django shell?

If you want to run in in BG even better:

nohup echo 'exec(open("my_script.py").read())' | python manage.py shell &

The output will be in nohup.out

Why does HTML think “chucknorris” is a color?

The WHATWG HTML spec has the exact algorithm for parsing a legacy color value: https://html.spec.whatwg.org/multipage/infrastructure.html#rules-for-parsing-a-legacy-colour-value.

The code Netscape Classic used for parsing color strings is open source: https://dxr.mozilla.org/classic/source/lib/layout/layimage.c#155.

For example, notice that each character is parsed as a hex digit and then is shifted into a 32-bit integer without checking for overflow. Only eight hex digits fit into a 32-bit integer, which is why only the last 8 characters are considered. After parsing the hex digits into 32-bit integers, they are then truncated into 8-bit integers by dividing them by 16 until they fit into 8-bit, which is why leading zeros are ignored.

Update: This code does not exactly match what is defined in the spec, but the only difference there is a few lines of code. I think it is these lines that was added (in Netscape 4):

if (bytes_per_val > 4)
{
    bytes_per_val = 4;
}

ErrorActionPreference and ErrorAction SilentlyContinue for Get-PSSessionConfiguration

A solution for me:

$old_ErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = 'SilentlyContinue'
if((Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue) -eq $null) {
   WriteTraceForTrans "The session configuration MyShellUri is already unregistered."
}
else {        
   #Unregister-PSSessionConfiguration -Name "MyShellUri" -Force -ErrorAction Ignore
}
$ErrorActionPreference = $old_ErrorActionPreference 

Or use try-catch

try { 

(Get-PSSessionConfiguration -Name "MyShellUri" -ErrorAction SilentlyContinue)

} 
catch {

}

React fetch data in server before render

As a supplement of the answer of Michael Parker, you can make getData accept a callback function to active the setState update the data:

componentWillMount : function () {
    var data = this.getData(()=>this.setState({data : data}));
},

Clearing an HTML file upload field via JavaScript

Shorter version that works perfect for me that is as follow:

document.querySelector('#fileUpload').value = "";

How to set max_connections in MySQL Programmatically

How to change max_connections

You can change max_connections while MySQL is running via SET:

mysql> SET GLOBAL max_connections = 5000;
Query OK, 0 rows affected (0.00 sec)

mysql> SHOW VARIABLES LIKE "max_connections";
+-----------------+-------+
| Variable_name   | Value |
+-----------------+-------+
| max_connections | 5000  |
+-----------------+-------+
1 row in set (0.00 sec)

To OP

timeout related

I had never seen your error message before, so I googled. probably, you are using Connector/Net. Connector/Net Manual says there is max connection pool size. (default is 100) see table 22.21.

I suggest that you increase this value to 100k or disable connection pooling Pooling=false

UPDATED

he has two questions.

Q1 - what happens if I disable pooling Slow down making DB connection. connection pooling is a mechanism that use already made DB connection. cost of Making new connection is high. http://en.wikipedia.org/wiki/Connection_pool

Q2 - Can the value of pooling be increased or the maximum is 100?

you can increase but I'm sure what is MAX value, maybe max_connections in my.cnf

My suggestion is that do not turn off Pooling, increase value by 100 until there is no connection error.

If you have Stress Test tool like JMeter you can test youself.

How to Convert date into MM/DD/YY format in C#

Have you tried the following?:

textbox1.text = System.DateTime.Today.ToString("MM/dd/yy");

Be aware that 2 digit years could be bad in the future...

Quick easy way to migrate SQLite3 to MySQL?

This simple solution worked for me:

<?php
$sq = new SQLite3( 'sqlite3.db' );

$tables = $sq->query( 'SELECT name FROM sqlite_master WHERE type="table"' );

while ( $table = $tables->fetchArray() ) {
    $table = current( $table );
    $result = $sq->query( sprintf( 'SELECT * FROM %s', $table ) );

    if ( strpos( $table, 'sqlite' ) !== false )
        continue;

    printf( "-- %s\n", $table );
    while ( $row = $result->fetchArray( SQLITE3_ASSOC ) ) {
        $values = array_map( function( $value ) {
            return sprintf( "'%s'", mysql_real_escape_string( $value ) );
        }, array_values( $row ) );
        printf( "INSERT INTO `%s` VALUES( %s );\n", $table, implode( ', ', $values ) );
    }
}

How do I empty an input value with jQuery?

Usual way to empty textbox using jquery is:

$('#txtInput').val('');

If above code is not working than please check that you are able to get the input element.

console.log($('#txtInput')); // should return element in the console.

If still facing the same problem, please post your code.

How to specify line breaks in a multi-line flexbox layout?

@Oriol has an excellent answer, sadly as of October 2017, neither display:contents, neither page-break-after is widely supported, better said it's about Firefox which supports this but not the other players, I have come up with the following "hack" which I consider better than hard coding in a break after every 3rd element, because that will make it very difficult to make the page mobile friendly.

As said it's a hack and the drawback is that you need to add quite a lot of extra elements for nothing, but it does the trick and works cross browser even on the dated IE11.

The "hack" is to simply add an additional element after each div, which is set to display:none and then used the css nth-child to decide which one of this should be actually made visible forcing a line brake like this:

_x000D_
_x000D_
.container {
  background: tomato;
  display: flex;
  flex-flow: row wrap;
  justify-content: space-between;
}
.item {
  width: 100px;
  background: gold;
  height: 100px;
  border: 1px solid black;
  font-size: 30px;
  line-height: 100px;
  text-align: center;
  margin: 10px
}
.item:nth-child(3n-1) {
  background: silver;
}
.breaker {
  display: none;
}
.breaker:nth-child(3n) {
  display: block;
  width: 100%;
  height: 0;
}
_x000D_
<div class="container">
  <div class="item">1</div>
  <p class="breaker"></p>
  
  <div class="item">2</div>
  <p class="breaker"></p>
  
  <div class="item">3</div>
  <p class="breaker"></p>
  
  <div class="item">4</div>
  <p class="breaker"></p>
  
  <div class="item">5</div>
  <p class="breaker"></p>
  
  <div class="item">6</div>
  <p class="breaker"></p>
  
  <div class="item">7</div>
  <p class="breaker"></p>
  
  <div class="item">8</div>
  <p class="breaker"></p>
  
  <div class="item">9</div>
  <p class="breaker"></p>
  
  <div class="item">10</div>
  <p class="breaker"></p>
</div>
_x000D_
_x000D_
_x000D_

Constructor overload in TypeScript

Regarding constructor overloads one good alternative would be to implement the additional overloads as static factory methods. I think its more readable and simple than checking for all possible argument combinations at the constructor. Here is a simple example:

function calculateAge(birthday): number {
  return new Date().getFullYear() - birthday;
}

class Person {
  static fromData(data: PersonData): Person {
    const { first, last, birthday, gender = 'M' } = data;
    return new this(
      `${last}, ${first}`,
      calculateAge(birthday),
      gender,
    );
  }

  constructor(
    public fullName: string,
    public age: number,
    public gender: 'M' | 'F',
  ) {}

  toString(): string {
    return `Hello, my name is ${this.fullName} and I'm a ${this.age}yo ${this.gender}`;
  }
}

interface PersonData {
  first: string;
  last: string;
  birthday: string;
  gender?: 'M' | 'F';
}


const personA = new Person('Doe, John', 31, 'M');
console.log(personA.toString());
const personB = Person.fromData({
  first: 'Jane',
  last: 'Smith',
  birthday: '1986',
  gender: 'F',
});
console.log(personB.toString());

Method overloading in TypeScript isn't for real, let's say, as it would require too much compiler-generated code and the core team try to avoid that at all costs. Currently the main reason for method overloading to be present on the language is to provide a way to write declarations for libraries with magic arguments in their API. Since you'll need to do all the heavy-lifting by yourself to handle different sets of arguments I don't see much advantage in using overloads instead of separated methods.

After installation of Gulp: “no command 'gulp' found”

Tried with sudo and it worked !!

sudo npm install --global gulp-cli

How to get the command line args passed to a running process on unix/linux systems?

This will do the trick:

xargs -0 < /proc/<pid>/cmdline

Without the xargs, there will be no spaces between the arguments, because they have been converted to NULs.

django - get() returned more than one topic

In your Topic model you're allowing for more than one element to have the same topic field. You have created two with the same one already.

topic=models.TextField(verbose_name='Thema')

Now when trying to add a new learningObjective you seem to want to add it to only one Topic that matches what you're sending on the form. Since there's more than one with the same topic field get is finding 2, hence the exception.

You can either add the learningObjective to all Topics with that topic field:

for t in topic.objects.filter(topic=request.POST['Thema']):
    t.learningObjectivesTopic.add(neuesLernziel)

or restrict the Topic model to have a unique topic field and keep using get, but that might not be what you want.

JsonMappingException: No suitable constructor found for type [simple type, class ]: can not instantiate from JSON object

I would like to add another solution to this that does not require a dummy constructor. Since dummy constructors are a bit messy and subsequently confusing. We can provide a safe constructor and by annotating the constructor arguments we allow jackson to determine the mapping between constructor parameter and field.

so the following will also work. Note the string inside the annotation must match the field name.

import com.fasterxml.jackson.annotation.JsonProperty;
public class ApplesDO {

        private String apple;

        public String getApple() {
            return apple;
        }

        public void setApple(String apple) {
            this.apple = apple;
        }

        public ApplesDO(CustomType custom){
            //constructor Code
        }

        public ApplesDO(@JsonProperty("apple")String apple) {
        }

}

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

I thought of just adding some points missing in above answers. This diagram taken from here clearly states the what's really going on.

enter image description here

If I state again the real purpose of

  • Split: Improves the parallel processing by distributing the processing load across different nodes (Mappers), which would save the overall processing time.

  • Combine: Shrinks the output of each Mapper. It would save the time spending for moving the data from one node to another.

  • Sort (Shuffle & Sort): Makes it easy for the run-time to schedule (spawn/start) new reducers, where while going through the sorted item list, whenever the current key is different from the previous, it can spawn a new reducer.

Using Docker-Compose, how to execute multiple commands

Alpine-based images actually seem to have no bash installed, but you can use sh or ash which link to /bin/busybox.

Example docker-compose.yml:

version: "3"
services:

  api:
    restart: unless-stopped
    command: ash -c "flask models init && flask run"

Aborting a stash pop in Git

OK, I think I have managed to find a work-flow that will get you back to where you need to be (as if you had not done the pop).

TAKE A BACKUP BEFOREHAND!! I don't know whether this will work for you, so copy your whole repo just in case it doesn't work.

1) Fix the merge problems and fix all the conflict by selecting all the changes that come from the patch (in tortoisemerge, this shows up as one.REMOETE (theirs)).

git mergetool

2) Commit these changes (they will already be added via the mergetool command). Give it a commit message of "merge" or something you remember.

git commit -m "merge"

3) Now you will still have your local unstaged changes that you started originally, with a new commit from the patch (we can get rid of this later). Now commit your unstaged changes

git add .
git add -u .
git commit -m "local changes"

4) Reverse the patch. This can be done with the following command:

git stash show -p | git apply -R

5) Commit these changes:

git commit -a -m "reversed patch"

6) Get rid of the patch/unpatch commits

git rebase -i HEAD^^^

from this, remove the two lines with 'merge' and 'reversed patch' in it.

7) Get your unstanged changes back and undo the 'local changes' commit

git reset HEAD^

I've run through it with a simple example and it gets you back to where you want to be - directly before the stash was popped, with your local changes and with the stash still being available to pop.

How do I add a margin between bootstrap columns without wrapping

You should work with padding on the inner container rather than with margin. Try this!

HTML

<div class="row info-panel">
    <div class="col-md-4" id="server_1">
       <div class="server-action-menu">
           Server 1
       </div>
   </div>
</div>

CSS

.server-action-menu {
    background-color: transparent;
    background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
    background-repeat: repeat;
    border-radius:10px;
    padding: 5px;
}

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

In addition to the accepted answer, there's a third option that can be useful in some cases:

v1 with random MAC ("v1mc")

You can make a hybrid between v1 & v4 by deliberately generating v1 UUIDs with a random broadcast MAC address (this is allowed by the v1 spec). The resulting v1 UUID is time dependant (like regular v1), but lacks all host-specific information (like v4). It's also much closer to v4 in it's collision-resistance: v1mc = 60 bits of time + 61 random bits = 121 unique bits; v4 = 122 random bits.

First place I encountered this was Postgres' uuid_generate_v1mc() function. I've since used the following python equivalent:

from os import urandom
from uuid import uuid1
_int_from_bytes = int.from_bytes  # py3 only

def uuid1mc():
    # NOTE: The constant here is required by the UUIDv1 spec...
    return uuid1(_int_from_bytes(urandom(6), "big") | 0x010000000000)

(note: I've got a longer + faster version that creates the UUID object directly; can post if anyone wants)


In case of LARGE volumes of calls/second, this has the potential to exhaust system randomness. You could use the stdlib random module instead (it will probably also be faster). But BE WARNED: it only takes a few hundred UUIDs before an attacker can determine the RNG state, and thus partially predict future UUIDs.

import random
from uuid import uuid1

def uuid1mc_insecure():
    return uuid1(random.getrandbits(48) | 0x010000000000)

How do I download a file from the internet to my linux server with Bash

Using wget

wget -O /tmp/myfile 'http://www.google.com/logo.jpg'

or curl:

curl -o /tmp/myfile 'http://www.google.com/logo.jpg'

How can I perform a short delay in C# without using sleep?

Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:

You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();

textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();

Normally this will be done automatically when the thread is done. Ex, you press a button, changes are made to the text, thread dies, and then .Update() is fired and you see the changes. (I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)

In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update() is fired. This resulting in you only seeing the last change made to the text.

You would experience the same issue if you had a long execution between the text changes.

Getting a HeadlessException: No X11 DISPLAY variable was set

This appears to be a more general SWING/AWT/JDK problem that just the JBOSS installer:

The accepted answer below solved the issue for me :

Unable to run java gui programs with ubuntu

("sudo apt-get install openjdk-6-jdk")

How do I center floated elements?

Centering floats is easy. Just use the style for container:

.pagination{ display: table; margin: 0 auto; }

change the margin for floating elements:

.pagination a{ margin: 0 2px; }

or

.pagination a{ margin-left: 3px; }
.pagination a.first{ margin-left: 0; } 

and leave the rest as it is.

It's the best solution for me to display things like menus or pagination.

Strengths:

  • cross-browser for any elements (blocks, list-items etc.)

  • simplicity

Weaknesses:

  • it works only when all floating elements are in one line (which is usually ok for menus but not for galleries).

@arnaud576875 Using inline-block elements will work great (cross-browser) in this case as pagination contains just anchors (inline), no list-items or divs:

Strengths:

  • works for multiline items.

Weknesses:

  • gaps between inline-block elements - it works the same way as a space between words. It may cause some troubles calculating the width of the container and styling margins. Gaps width isn't constant but it's browser specific (4-5px). To get rid of this gaps I would add to arnaud576875 code (not fully tested):

    .pagination{ word-spacing: -1em; }

    .pagination a{ word-spacing: .1em; }

  • it won't work in IE6/7 on block and list-items elements

Restore a deleted file in the Visual Studio Code Recycle Bin

I know the OP says Recycle Bin. What I do though is recreate the file, especially if it's a single file. And when in the file, I just press CMD+Z (I'm on a Mac) and I get my file back.

  1. Recreate the file in the same directory from where it was deleted.
  2. CMD+Z inside of the newly created file.

Cast Int to enum in Java

MyEnum.values()[x] is an expensive operation. If the performance is a concern, you may want to do something like this:

public enum MyEnum {
    EnumValue1,
    EnumValue2;

    public static MyEnum fromInteger(int x) {
        switch(x) {
        case 0:
            return EnumValue1;
        case 1:
            return EnumValue2;
        }
        return null;
    }
}

Simplest way to throw an error/exception with a custom message in Swift 2?

In case you don't need to catch the error and you want to immediately stop the application you can use a fatalError: fatalError ("Custom message here")

Intersection and union of ArrayLists in Java

In Java 8, I use simple helper methods like this:

public static <T> Collection<T> getIntersection(Collection<T> coll1, Collection<T> coll2){
    return Stream.concat(coll1.stream(), coll2.stream())
            .filter(coll1::contains)
            .filter(coll2::contains)
            .collect(Collectors.toSet());
}

public static <T> Collection<T> getMinus(Collection<T> coll1, Collection<T> coll2){
    return coll1.stream().filter(not(coll2::contains)).collect(Collectors.toSet());
}

public static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
}

OS X: equivalent of Linux's wget

1) on your mac type

nano /usr/bin/wget

2) paste the following in

#!/bin/bash
curl -L $1 -o $2

3) close then make it executable

chmod 777 /usr/bin/wget

That's it.

Scroll Automatically to the Bottom of the Page

Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:

function scrollToBottom(e) {
  e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

Option 1: Have an index on a non-null column present that can be used for the scan. Or create a function-based index as:

create index idx on t(0);

this can then be scanned to give the count.

Option 2: If you have monitoring turned on then check the monitoring view USER_TAB_MODIFICATIONS and add/subtract the relevant values to the table statistics.

Option 3: For a quick estimate on large tables invoke the SAMPLE clause ... for example ...

SELECT 1000*COUNT(*) FROM sometable SAMPLE(0.1); 

Option 4: Use a materialized view to maintain the count(*). Powerful medicine though.

um ...

'System.Reflection.TargetInvocationException' occurred in PresentationFramework.dll

The event is probably raised before the elements are fully loaded or the references are still unset, hence the exceptions. Try only setting properties if the reference is not null and IsLoaded is true.

Why do we have to specify FromBody and FromUri?

Just addition to above answers ..

[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring

For Ex..

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
    [Route("{Latitude}/{Longitude}")]
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Can be called like:

http://localhost/api/values/47.678558/-122.130989

Get element inside element by class and ID - JavaScript

If this needs to work in IE 7 or lower you need to remember that getElementsByClassName does not exist in all browsers. Because of this you can create your own getElementsByClassName or you can try this.

var fooDiv = document.getElementById("foo");

for (var i = 0, childNode; i <= fooDiv.childNodes.length; i ++) {
    childNode = fooDiv.childNodes[i];
    if (/bar/.test(childNode.className)) {
        childNode.innerHTML = "Goodbye world!";
    }
}

Git submodule update

Git 1.8.2 features a new option ,--remote, that will enable exactly this behavior. Running

git submodule update --rebase --remote

will fetch the latest changes from upstream in each submodule, rebase them, and check out the latest revision of the submodule. As the documentation puts it:

--remote

This option is only valid for the update command. Instead of using the superproject’s recorded SHA-1 to update the submodule, use the status of the submodule’s remote-tracking branch.

This is equivalent to running git pull in each submodule, which is generally exactly what you want.

(This was copied from this answer.)

Push existing project into Github

Follow below gitbash commands to push the folder files on github repository :-
1.) $ git init
2.) $ git cd D:\FileFolderName
3.) $ git status
4.) If needed to switch the git branch, use this command : 
    $ git checkout -b DesiredBranch
5.) $ git add .
6.) $ git commit -m "added a new folder"
7.) $ git push -f https://github.com/username/MyTestApp.git TestBranch
    (i.e git push origin branch)

Length of string in bash

UTF-8 string length

In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen

will render:

Généralités is 11 char len, but 14 bytes len.

you could even have a look at stored chars:

myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"

will answer:

Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').

Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL along with $LANG.

Length of an argument

Argument work same as regular variables

strLen() {
    local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    printf -v sreal %q "$1"
    LANG=$oLang LC_ALL=$oLcAll
    printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}

will work as

strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'

Useful printf correction tool:

If you:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    printf " - %-14s is %2d char length\n" "'$string'"  ${#string}
done

 - 'Généralités' is 11 char length
 - 'Language'     is  8 char length
 - 'Théorème'   is  8 char length
 - 'Février'     is  7 char length
 - 'Left: ?'    is  7 char length
 - 'Yin Yang ?' is 10 char length

Not really pretty... For this, there is a little function:

strU8DiffLen () { 
    local bytlen oLang=$LANG oLcAll=$LC_ALL
    LANG=C LC_ALL=C
    bytlen=${#1}
    LANG=$oLang LC_ALL=$oLcAll
    return $(( bytlen - ${#1} ))
}

Then now:

for string in Généralités Language Théorème Février  "Left: ?" "Yin Yang ?";do
    strU8DiffLen "$string"
    printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
        "'$string'" ${#string} $((${#string}+$?))
  done 

 - 'Généralités'  is 11 chars length, but uses 14 bytes
 - 'Language'     is  8 chars length, but uses  8 bytes
 - 'Théorème'     is  8 chars length, but uses 10 bytes
 - 'Février'      is  7 chars length, but uses  8 bytes
 - 'Left: ?'      is  7 chars length, but uses  9 bytes
 - 'Yin Yang ?'   is 10 chars length, but uses 12 bytes

Unfortunely, this is not perfect!

But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...

Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.

What is the difference between require_relative and require in Ruby?

Summary

Use require for installed gems

Use require_relative for local files

require uses your $LOAD_PATH to find the files.
require_relative uses the current location of the file using the statement


require

Require relies on you having installed (e.g. gem install [package]) a package somewhere on your system for that functionality.

When using require you can use the "./" format for a file in the current directory, e.g. require "./my_file" but that is not a common or recommended practice and you should use require_relative instead.

require_relative

This simply means include the file 'relative to the location of the file with the require_relative statement'. I generally recommend that files should be "within" the current directory tree as opposed to "up", e.g. don't use

require_relative '../../../filename'

(up 3 directory levels) within the file system because that tends to create unnecessary and brittle dependencies. However in some cases if you are already 'deep' within a directory tree then "up and down" another directory tree branch may be necessary. More simply perhaps, don't use require_relative for files outside of this repository (assuming you are using git which is largely a de-facto standard at this point, late 2018).

Note that require_relative uses the current directory of the file with the require_relative statement (so not necessarily your current directory that you are using the command from). This keeps the require_relative path "stable" as it always be relative to the file requiring it in the same way.

What is an optional value in Swift?

Well...

? (Optional) indicates your variable may contain a nil value while ! (unwrapper) indicates your variable must have a memory (or value) when it is used (tried to get a value from it) at runtime.

The main difference is that optional chaining fails gracefully when the optional is nil, whereas forced unwrapping triggers a runtime error when the optional is nil.

To reflect the fact that optional chaining can be called on a nil value, the result of an optional chaining call is always an optional value, even if the property, method, or subscript you are querying returns a nonoptional value. You can use this optional return value to check whether the optional chaining call was successful (the returned optional contains a value), or did not succeed due to a nil value in the chain (the returned optional value is nil).

Specifically, the result of an optional chaining call is of the same type as the expected return value, but wrapped in an optional. A property that normally returns an Int will return an Int? when accessed through optional chaining.

var defaultNil : Int?  // declared variable with default nil value
println(defaultNil) >> nil  

var canBeNil : Int? = 4
println(canBeNil) >> optional(4)

canBeNil = nil
println(canBeNil) >> nil

println(canBeNil!) >> // Here nil optional variable is being unwrapped using ! mark (symbol), that will show runtime error. Because a nil optional is being tried to get value using unwrapper

var canNotBeNil : Int! = 4
print(canNotBeNil) >> 4

var cantBeNil : Int = 4
cantBeNil = nil // can't do this as it's not optional and show a compile time error

Here is basic tutorial in detail, by Apple Developer Committee: Optional Chaining

Font Awesome 5 font-family issue

npm i --save @fortawesome/fontawesome-free

My Sccs:

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/brands";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/v4-shims";

It worked fine for me!

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

How get total sum from input box values using Javascript?

Try this:

function add() 
{
  var sum = 0;
  var inputs = document.getElementsByTagName("input");
  for(i = 0; i <= inputs.length; i++) 
  {
   if( inputs[i].name == 'qty'+i) 
   {
     sum += parseInt(input[i].value);
   }
  }
  console.log(sum)

}

Java 8 stream map to list of keys sorted by values

You have to sort with a custom comparator based on the value of the entry. Then select all the keys before collecting

countByType.entrySet()
           .stream()
           .sorted((e1, e2) -> e1.getValue().compareTo(e2.getValue())) // custom Comparator
           .map(e -> e.getKey())
           .collect(Collectors.toList());

Iterating over a numpy array

I think you're looking for the ndenumerate.

>>> a =numpy.array([[1,2],[3,4],[5,6]])
>>> for (x,y), value in numpy.ndenumerate(a):
...  print x,y
... 
0 0
0 1
1 0
1 1
2 0
2 1

Regarding the performance. It is a bit slower than a list comprehension.

X = np.zeros((100, 100, 100))

%timeit list([((i,j,k), X[i,j,k]) for i in range(X.shape[0]) for j in range(X.shape[1]) for k in range(X.shape[2])])
1 loop, best of 3: 376 ms per loop

%timeit list(np.ndenumerate(X))
1 loop, best of 3: 570 ms per loop

If you are worried about the performance you could optimise a bit further by looking at the implementation of ndenumerate, which does 2 things, converting to an array and looping. If you know you have an array, you can call the .coords attribute of the flat iterator.

a = X.flat
%timeit list([(a.coords, x) for x in a.flat])
1 loop, best of 3: 305 ms per loop

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

Setting onSubmit in React.js

You can pass the event as argument to the function and then prevent the default behaviour.

var OnSubmitTest = React.createClass({
        render: function() {
        doSomething = function(event){
           event.preventDefault();
           alert('it works!');
        }

        return <form onSubmit={this.doSomething}>
        <button>Click me</button>
        </form>;
    }
});

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

I upgraded from 2010 to 2013 and after changing all the projects' Platform Toolset, I need to right-click on the Solution and choose Retarget... to make it work.

DropDownList's SelectedIndexChanged event not firing

try setting AutoPostBack="True" on the DropDownList.

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

Method Call Chaining; returning a pointer vs a reference?

It's canonical to use references for this; precedence: ostream::operator<<. Pointers and references here are, for all ordinary purposes, the same speed/size/safety.

How can I create a small color box using html and css?

If you want to create a small dots, just use icon from font awesome.

fa fa-circle

How to install Java SDK on CentOS?

The following command will return a list of all packages directly related to Java. They will be in the format of java-<version>.

$ yum search java | grep 'java-'

If there are no available packages, then you may need to download a new repository to search through. I suggest taking a look at Dag Wieers' repo. After downloading it, try the above command again.

You will see at least one version of Java packages available for download. Depending on when you read this, the lastest available version may be different.

java-1.7.0-openjdk.x86_64

The above package alone will only install JRE. To also install javac and JDK, the following command will do the trick:

$ yum install java-1.7.0-openjdk*

These packages will be installing (as well as their dependencies):

java-1.7.0-openjdk.x86_64
java-1.7.0-openjdk-accessibility.x86_64
java-1.7.0-openjdk-demo.x86_64
java-1.7.0-openjdk-devel.x86_64
java-1.7.0-openjdk-headless.x86_64
java-1.7.0-openjdk-javadoc.noarch
java-1.7.0-openjdk-src.x86_64

jQuery toggle animation

onmouseover="$('.play-detail').stop().animate({'height': '84px'},'300');" 

onmouseout="$('.play-detail').stop().animate({'height': '44px'},'300');"

Just put two stops -- one onmouseover and one onmouseout.

How to check if a String contains any of some strings

If you are looking for single characters, you can use String.IndexOfAny().

If you want arbitrary strings, then I'm not aware of a .NET method to achieve that "directly", although a regular expression would work.

Reading data from a website using C#

If you're downloading text then I'd recommend using the WebClient and get a streamreader to the text:

        WebClient web = new WebClient();
        System.IO.Stream stream = web.OpenRead("http://www.yoursite.com/resource.txt");
        using (System.IO.StreamReader reader = new System.IO.StreamReader(stream))
        {
            String text = reader.ReadToEnd();
        }

If this is taking a long time then it is probably a network issue or a problem on the web server. Try opening the resource in a browser and see how long that takes. If the webpage is very large, you may want to look at streaming it in chunks rather than reading all the way to the end as in that example. Look at http://msdn.microsoft.com/en-us/library/system.io.stream.read.aspx to see how to read from a stream.

Defining lists as global variables in Python

No, you can specify the list as a keyword argument to your function.

alist = []
def fn(alist=alist):
    alist.append(1)
fn()
print alist    # [1]

I'd say it's bad practice though. Kind of too hackish. If you really need to use a globally available singleton-like data structure, I'd use the module level variable approach, i.e. put 'alist' in a module and then in your other modules import that variable:

In file foomodule.py:

alist = []

In file barmodule.py:

import foomodule
def fn():
    foomodule.alist.append(1)
print foomodule.alist    # [1]

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

How to draw border on just one side of a linear layout?

To get a border on just one side of a drawable, apply a negative inset to the other 3 sides (causing those borders to be drawn off-screen).

<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
    android:insetTop="-2dp" 
    android:insetBottom="-2dp"
    android:insetLeft="-2dp">

    <shape android:shape="rectangle">
        <stroke android:width="2dp" android:color="#FF0000" />
        <solid android:color="#000000" />
    </shape>

</inset>

enter image description here

This approach is similar to naykah's answer, but without the use of a layer-list.

Highest Salary in each department

As short as the question:

SELECT DeptID, MAX(Salary) FROM EmpDetails GROUP BY DeptID

How do I horizontally center a span element inside a div

another option would be to give the span display:table; and center it via margin:0 auto;

span {
display:table;
margin:0 auto;
}

How do I execute code AFTER a form has loaded?

I know this is an old post. But here is how I have done it:

    public Form1(string myFile)
    {
        InitializeComponent();
        this.Show();
        if (myFile != null)
        {
            OpenFile(myFile);
        }
    }

    private void OpenFile(string myFile = null)
    {
            MessageBox.Show(myFile);
    }

How do I generate a stream from a string?

Use the MemoryStream class, calling Encoding.GetBytes to turn your string into an array of bytes first.

Do you subsequently need a TextReader on the stream? If so, you could supply a StringReader directly, and bypass the MemoryStream and Encoding steps.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

How do I left align these Bootstrap form items?

I was having the exact same problem. I found the issue within bootstrap.min.css. You need to change the label: label {display:inline-block;} to label {display:block;}

How to get all Errors from ASP.Net MVC modelState?

Anybody looking for asp.net core 3.1. Slightly updated than the above answer. I found that this is what [ApiController] returns

 Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

                foreach (KeyValuePair<string, ModelStateEntry> kvp in ViewData.ModelState)
                {
                    string key = kvp.Key;
                    ModelStateEntry entry = kvp.Value;

                    if (entry.Errors.Count > 0)
                    {
                        List<string> errorList = new List<string>();
                        foreach (ModelError error in entry.Errors)
                        {
                            errorList.Add(error.ErrorMessage);
                        }

                        errors[key] = errorList;
                    }
                }

                return  new JsonResult(new {Errors = errors});

Does Java have an exponential operator?

There is no operator, but there is a method.

Math.pow(2, 3) // 8.0

Math.pow(3, 2) // 9.0

FYI, a common mistake is to assume 2 ^ 3 is 2 to the 3rd power. It is not. The caret is a valid operator in Java (and similar languages), but it is binary xor.

Gradle build without tests

You should use the -x command line argument which excludes any task.

Try:

gradle build -x test 

Update:

The link in Peter's comment changed. Here is the diagram from the Gradle user's guide

What Regex would capture everything from ' mark to the end of a line?

The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:

'.*$

And if you wanted to capture everything after the ' char but not include it in the output, you would use:

(?<=').*$

This basically says give me all characters that follow the ' char until the end of the line.

Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:

'.* 

is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.

validate a dropdownlist in asp.net mvc

Example from MVC 4 for dropdownlist validation on Submit using Dataannotation and ViewBag (less line of code)

Models:

namespace Project.Models
{
    public class EmployeeReferral : Person
    {

        public int EmployeeReferralId { get; set; }


        //Company District
        //List                
        [Required(ErrorMessage = "Required.")]
        [Display(Name = "Employee District:")]
        public int? DistrictId { get; set; }

    public virtual District District { get; set; }       
}


namespace Project.Models
{
    public class District
    {
        public int? DistrictId { get; set; }

        [Display(Name = "Employee District:")]
        public string DistrictName { get; set; }
    }
}

EmployeeReferral Controller:

namespace Project.Controllers
{
    public class EmployeeReferralController : Controller
    {
        private ProjDbContext db = new ProjDbContext();

        //
        // GET: /EmployeeReferral/

        public ActionResult Index()
        {
            return View();
        }

 public ActionResult Create()
        {
            ViewBag.Districts = db.Districts;            
            return View();
        }

View:

<td>
                    <div class="editor-label">
                        @Html.LabelFor(model => model.DistrictId, "District")
                    </div>
                </td>
                <td>
                    <div class="editor-field">
                        @*@Html.DropDownList("DistrictId", "----Select ---")*@
                        @Html.DropDownListFor(model => model.DistrictId, new SelectList(ViewBag.Districts, "DistrictId", "DistrictName"), "--- Select ---")
                        @Html.ValidationMessageFor(model => model.DistrictId)                                                
                    </div>
                </td>

Why can't we use ViewBag for populating dropdownlists that can be validated with Annotations. It is less lines of code.

Easiest way to detect Internet connection on iOS?

I currently use this simple synchronous method which requires no extra files in your projects or delegates.

Import:

#import <SystemConfiguration/SCNetworkReachability.h>

Create this method:

+(bool)isNetworkAvailable
{
    SCNetworkReachabilityFlags flags;
    SCNetworkReachabilityRef address;
    address = SCNetworkReachabilityCreateWithName(NULL, "www.apple.com" );
    Boolean success = SCNetworkReachabilityGetFlags(address, &flags);
    CFRelease(address);

    bool canReach = success
                    && !(flags & kSCNetworkReachabilityFlagsConnectionRequired)
                    && (flags & kSCNetworkReachabilityFlagsReachable);

    return canReach;
}

Then, if you've put this in a MyNetworkClass:

if( [MyNetworkClass isNetworkAvailable] )
{
   // do something networky.
}

If you are testing in the simulator, turn your Mac's wifi on and off, as it appears the simulator will ignore the phone setting.

Update:

  1. In the end I used a thread/asynchronous callback to avoid blocking the main thread; and regularly re-testing so I could use a cached result - although you should avoid keeping data connections open unnecessarily.

  2. As @thunk described, there are better URLs to use, which Apple themselves use. http://cadinc.com/blog/why-your-apple-ios-7-device-wont-connect-to-the-wifi-network

css background image in a different folder from css

For mac OS you should use this :

body {
 background: url(../../img/bg.png);
}

Can't start Tomcat as Windows Service

Go to Start > Configure Tomcat >

  • Startup > Mode = Java
  • Shutdown > Mode = Java

This worked for me!

Dynamically load a JavaScript file

Something like this...

<script>
     $(document).ready(function() {
          $('body').append('<script src="https://maps.googleapis.com/maps/api/js?key=KEY&libraries=places&callback=getCurrentPickupLocation" async defer><\/script>');
     });
</script>

Move to another EditText when Soft Keyboard Next is clicked on Android

If you want to use a multiline EditText with imeOptions, try:

android:inputType="textImeMultiLine"

Split by comma and strip whitespace in Python

Split using a regular expression. Note I made the case more general with leading spaces. The list comprehension is to remove the null strings at the front and back.

>>> import re
>>> string = "  blah, lots  ,  of ,  spaces, here "
>>> pattern = re.compile("^\s+|\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['blah', 'lots', 'of', 'spaces', 'here']

This works even if ^\s+ doesn't match:

>>> string = "foo,   bar  "
>>> print([x for x in pattern.split(string) if x])
['foo', 'bar']
>>>

Here's why you need ^\s+:

>>> pattern = re.compile("\s*,\s*|\s+$")
>>> print([x for x in pattern.split(string) if x])
['  blah', 'lots', 'of', 'spaces', 'here']

See the leading spaces in blah?

Clarification: above uses the Python 3 interpreter, but results are the same in Python 2.

SharePoint 2013 get current user using JavaScript

U can use javascript to achive that like this:

function loadConstants() {

    this.clientContext = new SP.ClientContext.get_current();
    this.clientContext = new SP.ClientContext.get_current();
    this.oWeb = clientContext.get_web();
    currentUser = this.oWeb.get_currentUser();  
    this.clientContext.load(currentUser);
      completefunc:this.clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(this,this.onQueryFailed));


}

//U must set a timeout to recivie the exactly user u want:

function onQuerySucceeded(sender, args) {

    window.setTimeout("ttt();",1000);
}
function onQueryFailed(sender, args) {

    console.log(args.get_message());
}

//By using a proper timeout, u can get current user :

function ttt(){ 

    var clientContext = new SP.ClientContext.get_current();
    var groupCollection = clientContext.get_web().get_siteGroups();
    visitorsGroup = groupCollection.getByName('OLAP Portal Members');

    t=this.currentUser .get_loginName().toLowerCase();

    console.log ('this.currentUser .get_loginName() : '+ t);      

}

What does it mean: The serializable class does not declare a static final serialVersionUID field?

From the javadoc:

The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:

You can configure your IDE to:

  • ignore this, instead of giving a warning.
  • autogenerate an id

As per your additional question "Can it be that the discussed warning message is a reason why my GUI application freeze?":

No, it can't be. It can cause a problem only if you are serializing objects and deserializing them in a different place (or time) where (when) the class has changed, and it will not result in freezing, but in InvalidClassException.

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

Finaly I found another answer for this problem. and this is working for me. Just add below datas to the your webconfig file.

<configuration>
 <system.webServer>
  <security>
   <requestFiltering>
    <verbs allowUnlisted="true">
     <add verb="OPTIONS" allowed="false" />
    </verbs>
   </requestFiltering>
  </security>
 </system.webServer>
</configuration>

Form more information, you can visit this web site: http://www.iis.net/learn/manage/configuring-security/use-request-filtering

if you want to test your web site, is it working or not... You can use "HttpRequester" mozilla firefox plugin. for this plugin: https://addons.mozilla.org/En-us/firefox/addon/httprequester/

Parse DateTime string in JavaScript

This function handles also the invalid 29.2.2001 date.

function parseDate(str) {
    var dateParts = str.split(".");
    if (dateParts.length != 3)
        return null;
    var year = dateParts[2];
    var month = dateParts[1];
    var day = dateParts[0];

    if (isNaN(day) || isNaN(month) || isNaN(year))
        return null;

    var result = new Date(year, (month - 1), day);
    if (result == null)
        return null;
    if (result.getDate() != day)
        return null;
    if (result.getMonth() != (month - 1))
        return null;
    if (result.getFullYear() != year)
        return null;

    return result;
}

How to test the type of a thrown exception in Jest

In Jest you have to pass a function into expect(function).toThrow(<blank or type of error>).

Example:

test("Test description", () => {
  const t = () => {
    throw new TypeError();
  };
  expect(t).toThrow(TypeError);
});

Or if you also want to check for error message:

test("Test description", () => {
  const t = () => {
    throw new TypeError("UNKNOWN ERROR");
  };
  expect(t).toThrow(TypeError);
  expect(t).toThrow("UNKNOWN ERROR");
});

If you need to test an existing function whether it throws with a set of arguments, you have to wrap it inside an anonymous function in expect().

Example:

test("Test description", () => {
  expect(() => {http.get(yourUrl, yourCallbackFn)}).toThrow(TypeError);
});

Call JavaScript function from C#

If you want to call JavaScript function in C#, this will help you:

public string functionname(arg)
{
    if (condition)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        page.ClientScript.RegisterStartupScript(
            typeof(Page),
            "Test",
            "<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
    }
}

In React Native, how do I put a view on top of another view, with part of it lying outside the bounds of the view behind?

The above solutions were not working for me. I solved it by creating a View with the same background colour as the parent and added negative margin to move the image upwards.

<ScrollView style={{ backgroundColor: 'blue' }}>
  <View
    style={{
      width: '95%',
      paddingLeft: '5%',
      marginTop: 80,
      height: 800,
    }}>
    <View style={{ backgroundColor: 'white' }}>

      <Thumbnail square large source={{uri: uri}} style={{ marginTop: -30 }}/>
      <Text>Some Text</Text>
    </View>
  </View>
</ScrollView>

and I got the following result.

enter image description here

How can I show a combobox in Android?

The questions is perfectly valid and clear since Spinner and ComboBox (read it: Spinner where you can provide a custom value as well) are two different things.

I was looking for the same thing myself and I wasn't satisfied with the given answers. So I created my own thing. Perhaps some will find the following hints useful. I am not providing the full source code as I am using some legacy calls in my own project. It should be pretty clear anyway.

Here is the screenshot of the final thing:

ComboBox on Android

The first thing was to create a view that will look the same as the spinner that hasn't been expanded yet. In the screenshot, on the top of the screen (out of focus) you can see the spinner and the custom view right bellow it. For that purpose I used LinearLayout (actually, I inherited from Linear Layout) with style="?android:attr/spinnerStyle". LinearLayout contains TextView with style="?android:attr/spinnerItemStyle". Complete XML snippet would be:

<com.example.comboboxtest.ComboBox 
    style="?android:attr/spinnerStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <TextView
        android:id="@+id/textView"
        style="?android:attr/spinnerItemStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:text="January"
        android:textAlignment="inherit" 
    />

</com.example.comboboxtest.ComboBox>

As, I mentioned earlier ComboBox inherits from LinearLayout. It also implements OnClickListener which creates a dialog with a custom view inflated from the XML file. Here is the inflated view:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" 
    >
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" 
        >
        <EditText
            android:id="@+id/editText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:ems="10"
            android:hint="Enter custom value ..." >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="OK" 
        />
    </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
    />

</LinearLayout>

There are two more listeners that you need to implement: onItemClick for the list and onClick for the button. Both of these set the selected value and dismiss the dialog.

For the list, you want it to look the same as expanded Spinner, you can do that providing the list adapter with the appropriate (Spinner) style like this:

ArrayAdapter<String> adapter = 
    new ArrayAdapter<String>(
        activity,
        android.R.layout.simple_spinner_dropdown_item, 
        states
    );

More or less, that should be it.

no matching function for call to ' '

You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:

Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);

cout << "Numarul complex este: " << firstComplexNumber << endl;
//                                  ^^^^^^^^^^^^^^^^^^ No need to dereference now

// ...

Complex::distanta(firstComplexNumber, secondComplexNumber);

Paste in insert mode?

If you don't want Vim to mangle formatting in incoming pasted text, you might also want to consider using: :set paste. This will prevent Vim from re-tabbing your code. When done pasting, :set nopaste will return to the normal behavior.

It's also possible to toggle the mode with a single key, by adding something like set pastetoggle=<F2> to your .vimrc. More details on toggling auto-indent are here.

How to programmatically get iOS status bar height

Using following single line code you can get status bar height in any orientation and also if it is visible or not

#define STATUS_BAR_HIGHT (
    [UIApplicationsharedApplication].statusBarHidden ? 0 : (
        [UIApplicationsharedApplication].statusBarFrame.size.height > 100 ?
            [UIApplicationsharedApplication].statusBarFrame.size.width :
            [UIApplicationsharedApplication].statusBarFrame.size.height
    )
)

It just a simple but very useful macro just try this you don't need to write any extra code

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

List of tuples to dictionary

It seems everyone here assumes the list of tuples have one to one mapping between key and values (e.g. it does not have duplicated keys for the dictionary). As this is the first question coming up searching on this topic, I post an answer for a more general case where we have to deal with duplicates:

mylist = [(a,1),(a,2),(b,3)]    
result = {}
for i in mylist:  
   result.setdefault(i[0],[]).append(i[1])
print(result)
>>> result = {a:[1,2], b:[3]}

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

How to use NSURLConnection to connect with SSL for an untrusted cert?

In iOS 9, SSL connections will fail for all invalid or self-signed certificates. This is the default behavior of the new App Transport Security feature in iOS 9.0 or later, and on OS X 10.11 and later.

You can override this behavior in the Info.plist, by setting NSAllowsArbitraryLoads to YES in the NSAppTransportSecurity dictionary. However, I recommend overriding this setting for testing purposes only.

enter image description here

For information see App Transport Technote here.