Programs & Examples On #Binaryformatter

`BinaryFormatter` is a serializer built into the .net framework. It serializes fields regardless of their visibility into an unspecified binary format. It supports polymorphism and cyclic object graphs.

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

Serializing/deserializing with memory stream

This code works for me:

public void Run()
{
    Dog myDog = new Dog();
    myDog.Name= "Foo";
    myDog.Color = DogColor.Brown;

    System.Console.WriteLine("{0}", myDog.ToString());

    MemoryStream stream = SerializeToStream(myDog);

    Dog newDog = (Dog)DeserializeFromStream(stream);

    System.Console.WriteLine("{0}", newDog.ToString());
}

Where the types are like this:

[Serializable]
public enum DogColor
{
    Brown,
    Black,
    Mottled
}

[Serializable]
public class Dog
{
    public String Name
    {
        get; set;
    }

    public DogColor Color
    {
        get;set;
    }

    public override String ToString()
    {
        return String.Format("Dog: {0}/{1}", Name, Color);
    }
}

and the utility methods are:

public static MemoryStream SerializeToStream(object o)
{
    MemoryStream stream = new MemoryStream();
    IFormatter formatter = new BinaryFormatter();
    formatter.Serialize(stream, o);
    return stream;
}

public static object DeserializeFromStream(MemoryStream stream)
{
    IFormatter formatter = new BinaryFormatter();
    stream.Seek(0, SeekOrigin.Begin);
    object o = formatter.Deserialize(stream);
    return o;
}

How to convert an object to a byte array in C#

To access the memory of an object directly (to do a "core dump") you'll need to head into unsafe code.

If you want something more compact than BinaryWriter or a raw memory dump will give you, then you need to write some custom serialisation code that extracts the critical information from the object and packs it in an optimal way.

edit P.S. It's very easy to wrap the BinaryWriter approach into a DeflateStream to compress the data, which will usually roughly halve the size of the data.

Rename computer and join to domain in one step with PowerShell

I had a slightly augmented issue. I needed to rename a machine and then RE-JOIN a domain it was already a member of and could not find where to do that but its seems very close to what is here. The individual solutions above don't do it but with some togetherness... If you try to rename, you get denied. If you rename and then rejoin, you get an account already exists error. You need to bail from the domain by joining a workgroup and then you can run the rename and join in one command.

$Chops = Get-Credential 
# Or bring in a stored credential
$NewComputerName = "WhoImGonnaBe" 
# or value from CSV
$MyDomainName = "MyDomain"
Add-Computer -WorkgroupName NotADomain -force -DomainCredential $Chops
Add-Computer -DomainName $MyDomainName -Computername $ENV:Computername -NewName $NewComputerName -DomainCredential $Chops -Force -Restart
#  If running locally you really only need the -NewName and can omit the -Computername

What's the C# equivalent to the With statement in VB?

The closest thing in C# 3.0, is that you can use a constructor to initialize properties:

Stuff.Elements.Foo foo = new Stuff.Elements.Foo() {Name = "Bob Dylan", Age = 68, Location = "On Tour", IsCool = true}

What difference is there between WebClient and HTTPWebRequest classes in .NET?

Also WebClient doesn't have timeout property. And that's the problem, because dafault value is 100 seconds and that's too much to indicate if there's no Internet connection.

Workaround for that problem is here https://stackoverflow.com/a/3052637/1303422

unix diff side-to-side results?

From man diff, you can use -y to do side-by-side.

-y, --side-by-side
       output in two columns

Hence, say:

diff -y /tmp/test1  /tmp/test2

Test

$ cat a                $ cat b
hello                  hello
my name                my name
is me                  is you

Let's compare them:

$ diff -y a b
hello                                                           hello
my name                                                         my name
is me                                                         | is you

Regular expression [Any number]

You can use the following function to find the biggest [number] in any string.

It returns the value of the biggest [number] as an Integer.

var biggestNumber = function(str) {
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;

    while ((match = pattern.exec(str)) !== null) {
        if (match.index === pattern.lastIndex) {
            pattern.lastIndex++;
        }
        match[1] = parseInt(match[1]);
        if(biggest < match[1]) {
            biggest = match[1];
        }
    }
    return biggest;
}

DEMO

The following demo calculates the biggest number in your textarea every time you click the button.

It allows you to play around with the textarea and re-test the function with a different text.

_x000D_
_x000D_
var biggestNumber = function(str) {_x000D_
    var pattern = /\[([0-9]+)\]/g, match, biggest = 0;_x000D_
_x000D_
    while ((match = pattern.exec(str)) !== null) {_x000D_
        if (match.index === pattern.lastIndex) {_x000D_
            pattern.lastIndex++;_x000D_
        }_x000D_
        match[1] = parseInt(match[1]);_x000D_
        if(biggest < match[1]) {_x000D_
            biggest = match[1];_x000D_
        }_x000D_
    }_x000D_
    return biggest;_x000D_
}_x000D_
_x000D_
document.getElementById("myButton").addEventListener("click", function() {_x000D_
    alert(biggestNumber(document.getElementById("myTextArea").value));_x000D_
});
_x000D_
<div>_x000D_
    <textarea rows="6" cols="50" id="myTextArea">_x000D_
this is a test [1] also this [2] is a test_x000D_
and again [18] this is a test. _x000D_
items[14].items[29].firstname too is a test!_x000D_
items[4].firstname too is a test!_x000D_
    </textarea>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
   <button id="myButton">Try me</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

See also this Fiddle!

How do I retrieve query parameters in Spring Boot?

In Spring boot: 2.1.6, you can use like below:

    @GetMapping("/orders")
    @ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
    public List<OrderResponse> getOrders(
            @RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
            @RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
            @RequestParam(value = "location_id", required = true) String location_id) {

        // TODO...

        return response;

@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.

Python object.__repr__(self) should be an expression?

I think the confusion over here roots from the english. I mean __repr__(); short for 'representation' of the value I'm guessing, like @S.Lott said

"What is the difference between "an actual expression, that can ... recreate the object" and "a rehasing of the actual expression which was used [to create the object]"? Both are an expression that creates the object. There's no practical distinction between these. A repr call could produce either a new expression or the original expression. In many cases, they're the same."

But in some cases they might be different. E.g; coordinate points, you might want c.coordinate to return: 3,5 but c.__repr__ to return Coordinate(3, 5). Hope that makes more sense...

strdup() - what does it do in C?

From strdup man:

The strdup() function shall return a pointer to a new string, which is a duplicate of the string pointed to by s1. The returned pointer can be passed to free(). A null pointer is returned if the new string cannot be created.

Open Source HTML to PDF Renderer with Full CSS Support

Try ABCpdf from webSupergoo. It's a commercial solution, not open source, but the standard edition can be obtained free of charge and will do what you are asking.

ABCpdf fully supports HTML and CSS, live forms and live links. It also uses Microsoft XML Core Services (MSXML) while rendering, so the results should match exactly what you see in Internet Explorer.

The on-line demo can be used to test HTML to PDF rendering without needing to install any software. See: http://www.abcpdfeditor.com/

The following C# code example shows how to render a single page HTML document.

Doc theDoc = new Doc();
theDoc.AddImageUrl("http://www.example.com/");
theDoc.Save("htmlimport.pdf");
theDoc.Clear();

To render multiple pages you'll need the AddImageToChain function, documented here: http://www.websupergoo.com/helppdf7net/source/5-abcpdf6/doc/1-methods/addimagetochain.htm

How to call JavaScript function instead of href in HTML

If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.

E.g.:

<button onclick="ShowOld(2367,146986,2)">
    <img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>

Adding up BigDecimals using Streams

You can sum up the values of a BigDecimal stream using a reusable Collector named summingUp:

BigDecimal sum = bigDecimalStream.collect(summingUp());

The Collector can be implemented like this:

public static Collector<BigDecimal, ?, BigDecimal> summingUp() {
    return Collectors.reducing(BigDecimal.ZERO, BigDecimal::add);
}

Open a URL in a new tab (and not a new window)

Opening a new tab from within a Firefox (Mozilla) extension goes like this:

gBrowser.selectedTab = gBrowser.addTab("http://example.com");

Dismissing a Presented View Controller

In addition to Michael Enriquez's answer, I can think of one other reason why this may be a good way to protect yourself from an undetermined state:

Say ViewControllerA presents ViewControllerB modally. But, since you may not have written the code for ViewControllerA you aren't aware of the lifecycle of ViewControllerA. It may dismiss 5 seconds (say) after presenting your view controller, ViewControllerB.

In this case, if you were simply using dismissViewController from ViewControllerB to dismiss itself, you would end up in an undefined state--perhaps not a crash or a black screen but an undefined state from your point of view.

If, instead, you were using the delegate pattern, you would be aware of the state of ViewControllerB and you can program for a case like the one I described.

Convert MySql DateTime stamp into JavaScript's Date format

There is a simpler way, sql timestamp string:

2018-07-19 00:00:00

The closest format to timestamp for Date() to receive is the following, so replace blank space for "T":

var dateString = media.intervention.replace(/\s/g, "T");

"2011-10-10T14:48:00"

Then, create the date object:

var date = new Date(dateString);

result would be the date object:

Thu Jul 19 2018 00:00:00 GMT-0300 (Horário Padrão de Brasília)

finding first day of the month in python

You can use dateutil.rrule:

In [1]: from dateutil.rrule import *

In [2]: rrule(DAILY, bymonthday=1)[0].date()
Out[2]: datetime.date(2018, 10, 1)

In [3]: rrule(DAILY, bymonthday=1)[1].date()
Out[3]: datetime.date(2018, 11, 1)

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

How do I verify that a string only contains letters, numbers, underscores and dashes?

There are a variety of ways of achieving this goal, some are clearer than others. For each of my examples, 'True' means that the string passed is valid, 'False' means it contains invalid characters.

First of all, there's the naive approach:

import string
allowed = string.letters + string.digits + '_' + '-'

def check_naive(mystring):
    return all(c in allowed for c in mystring)

Then there's use of a regular expression, you can do this with re.match(). Note that '-' has to be at the end of the [] otherwise it will be used as a 'range' delimiter. Also note the $ which means 'end of string'. Other answers noted in this question use a special character class, '\w', I always prefer using an explicit character class range using [] because it is easier to understand without having to look up a quick reference guide, and easier to special-case.

import re
CHECK_RE = re.compile('[a-zA-Z0-9_-]+$')
def check_re(mystring):
    return CHECK_RE.match(mystring)

Another solution noted that you can do an inverse match with regular expressions, I've included that here now. Note that [^...] inverts the character class because the ^ is used:

CHECK_INV_RE = re.compile('[^a-zA-Z0-9_-]')
def check_inv_re(mystring):
   return not CHECK_INV_RE.search(mystring)

You can also do something tricky with the 'set' object. Have a look at this example, which removes from the original string all the characters that are allowed, leaving us with a set containing either a) nothing, or b) the offending characters from the string:

def check_set(mystring):
    return not set(mystring) - set(allowed)

Reading InputStream as UTF-8

I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));

while ((line = br.readLine()) != null) {

}

I hope this can help anyone who sees this post.

Clear the form field after successful submission of php form

The POST data which holds the submitted form data is being echoed in the form, eg:

<input name="firstname" type="text" placeholder="First Name" required="required" 
value="<?php echo $_POST['firstname'];?>"  

Either clear the POST data once you have done with the form - ie all inputs were ok and you have actioned whatever your result from a form is.
Or, once you have determined the form is ok and have actioned whatever you action from the form, redirect the user to a new page to say "all done, thanks" etc.

header('Location: thanks.php');
exit();

This stops the POST data being present, it's know as "Post/Redirect/Get":
http://en.wikipedia.org/wiki/Post/Redirect/Get

The Post/Redirect/Get (PRG) method and using another page also ensures that if users click browser refresh, or back button having navigated somewhere else, your form is not submitted again.
This means if your form inserts into a database, or emails someone (etc), without the PRG method the values will (likely) be inserted/emailed every time they click refresh or revisit the page using their history/back button.

Node.js version on the command line? (not the REPL)

If you are windows user and using command line to check following versions then:

  1. Check node version

    node -v

  2. Check npm version

    npm -v

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How do I check for vowels in JavaScript?

Personally, I would define it this way:

function isVowel( chr ){ return 'aeiou'.indexOf( chr[0].toLowerCase() ) !== -1 }

You could also use ['a','e','i','o','u'] and skip the length test, but then you are creating an array each time you call the function. (There are ways of mimicking this via closures, but those are a bit obscure to read)

Auto populate columns in one sheet from another sheet

If I understood you right you want to have sheet1!A1 in sheet2!A1, sheet1!A2 in sheet2!A2,...right?

It might not be the best way but you may type the following

=IF(sheet1!A1<>"",sheet1!A1,"")

and drag it down to the maximum number of rows you expect.

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

This error message...

selenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed
  (unknown error: DevToolsActivePort file doesn't exist)
  (The process started from chrome location /opt/google/chrome/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)

...implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.

Your main issue is the Chrome browser is not installed at the default location within your system.

The server i.e. ChromeDriver expects you to have Chrome installed in the default location for each system as per the image below:

Chrome_binary_expected_location

1For Linux systems, the ChromeDriver expects /usr/bin/google-chrome to be a symlink to the actual Chrome binary.


Solution

In case you are using a Chrome executable in a non-standard location you have to override the Chrome binary location as follows:

  • Python Solution:

    from selenium import webdriver
    from selenium.webdriver.chrome.options import Options
    
    options = Options()
    options.binary_location = "C:\\path\\to\\chrome.exe"    #chrome binary location specified here
    options.add_argument("--start-maximized") #open Browser in maximized mode
    options.add_argument("--no-sandbox") #bypass OS security model
    options.add_argument("--disable-dev-shm-usage") #overcome limited resource problems
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\path\to\chromedriver.exe')
    driver.get('http://google.com/')
    
  • Java Solution:

    System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
    ChromeOptions opt = new ChromeOptions();
    opt.setBinary("C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe");  //chrome binary location specified here
    options.addArguments("start-maximized");
    options.setExperimentalOption("excludeSwitches", Collections.singletonList("enable-automation"));
    options.setExperimentalOption("useAutomationExtension", false);
    WebDriver driver = new ChromeDriver(opt);
    driver.get("https://www.google.com/");
    

Is Django for the frontend or backend?

(a) Django is a framework, not a language

(b) I'm not sure what you're missing - there is no reason why you can't have business logic in a web application. In Django, you would normally expect presentation logic to be separated from business logic. Just because it is hosted in the same application server, it doesn't follow that the two layers are entangled.

(c) Django does provide templating, but it doesn't provide rich libraries for generating client-side content.

Calculating Page Load Time In JavaScript

Why so complicated? When you can do:

var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;

If you need more times check out the window.performance object:

console.log(window.performance);

Will show you the timing object:

connectEnd                 Time when server connection is finished.
connectStart               Time just before server connection begins.
domComplete                Time just before document readiness completes.
domContentLoadedEventEnd   Time after DOMContentLoaded event completes.
domContentLoadedEventStart Time just before DOMContentLoaded starts.
domInteractive             Time just before readiness set to interactive.
domLoading                 Time just before readiness set to loading.
domainLookupEnd            Time after domain name lookup.
domainLookupStart          Time just before domain name lookup.
fetchStart                 Time when the resource starts being fetched.
loadEventEnd               Time when the load event is complete.
loadEventStart             Time just before the load event is fired.
navigationStart            Time after the previous document begins unload.
redirectCount              Number of redirects since the last non-redirect.
redirectEnd                Time after last redirect response ends.
redirectStart              Time of fetch that initiated a redirect.
requestStart               Time just before a server request.
responseEnd                Time after the end of a response or connection.
responseStart              Time just before the start of a response.
timing                     Reference to a performance timing object.
navigation                 Reference to performance navigation object.
performance                Reference to performance object for a window.
type                       Type of the last non-redirect navigation event.
unloadEventEnd             Time after the previous document is unloaded.
unloadEventStart           Time just before the unload event is fired.

Browser Support

More Info

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

Convert txt to csv python script

This is how I do it:

 with open(txtfile, 'r') as infile, open(csvfile, 'w') as outfile:
        stripped = (line.strip() for line in infile)
        lines = (line.split(",") for line in stripped if line)
        writer = csv.writer(outfile)
        writer.writerows(lines)

Hope it helps!

Use different Python version with virtualenv

[November 2019] I needed to install a Python 3.7 environment (env) on my Python 3.8-based Arch Linux system. Python 3.7 was no longer on the system, so I could not downgrade Python, to install a package that I needed.

Furthermore, I wanted to use that package / Python 3.7 inside a virtual environment (venv). This is how I did it.


Download Python version source files:

I downloaded the Python 3.7.4 source files from

https://www.python.org/downloads/source/

to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4.tgz

I then extracted that archive (source files) to

/mnt/Vancouver/apps/python_versions/src/Python-3.7.4/


Installation:

[Note: in my system env, not a venv.]

cd /mnt/Vancouver/apps/python_versions/src/Python-3.7.4/
time ./configure                 ## 17 sec
time make                        ## 1 min 51 sec
time sudo make install           ## 18 sec
time make clean                  ## 0.3 sec

Examine installed Python versions:

$ which python
/usr/bin/python

$ python --version
Python 3.8.0

$ which python3.7
/usr/local/bin/python3.7

$ python    ## Python 3.8 [system / env]
Python 3.8.0 (default, Oct 23 2019, 18:51:26) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

$ python3.7    ## newly-installed Python 3.7 package
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0]
>>>

$ python3.7 --version                                                                                                 
Python 3.7.4

How to create a venv for a specific Python version:

https://docs.python.org/3/tutorial/venv.html

12.2. CREATING VIRTUAL ENVIRONMENTS

The module used to create and manage virtual environments is called venv. venv will usually install the most recent version of Python that you have available. If you have multiple versions of Python on your system, you can select a specific Python version by running python3 or whichever version you want.

To create a virtual environment, decide upon a directory where you want to place it, and run the venv module as a script with the directory path:

python3 -m venv tutorial-env

This will create the tutorial-env directory if it doesn’t exist, and also create directories inside it containing a copy of the Python interpreter, the standard library, and various supporting files. ...


Create Python 3.7 venv [on a Python 3.8 operating env / system]:

python3.7 -m venv ~/venv/py3.7      ## create Python 3.7-based venv
source ~/venv/py3.7/bin/activate    ## activate that venv
deactivate                          ## deactivate that venv (when done, there)

Added to ~/.bashrc:

alias p37='echo "   [Python 3.7 venv (source ~/venv/py3.7/bin/activate)]" && source ~/venv/py3.7/bin/activate'

Test Python 3.7 venv:

$ p37                                                                                                                 
[Python 3.7 venv (source ~/venv/py3.7/bin/activate)]

(py3.7)$ python --version
Python 3.7.4

(py3.7)$ python
Python 3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> print(sys.version)
3.7.4 (default, Nov 20 2019, 11:36:53) 
[GCC 9.2.0] 
>>>

Throwing multiple exceptions in a method of an interface in java

I think you are asking for something like the code below:

public interface A
{
    void foo() 
        throws AException;
}

public class B
    implements A
{
    @Overrides 
    public void foo()
        throws AException,
               BException
    {
    }
}

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main
{
    public static void main(final String[] argv)
    {
        A a;

        a = new B();

        try
        {
            a.foo();
        }
        catch(final AException ex)
        {
        }
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.
    }
}

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

How to check for an active Internet connection on iOS or macOS?

//
//  Connectivity.swift
// 
//
//  Created by Kausik Jati on 17/07/20.
// 
//

import Foundation
import Network

enum ConnectionState: String {
    case notConnected = "Internet connection not avalable"
    case connected = "Internet connection avalable"
    case slowConnection = "Internet connection poor"
}
protocol ConnectivityDelegate: class {
    func checkInternetConnection(_ state: ConnectionState, isLowDataMode: Bool)
}
class Connectivity: NSObject {
    private let monitor = NWPathMonitor()
    weak var delegate: ConnectivityDelegate? = nil
    private let queue = DispatchQueue.global(qos: .background)
    private var isLowDataMode = false
    static let instance = Connectivity()
private override init() {
    super.init()
    monitor.start(queue: queue)
    startMonitorNetwork()
}
private func startMonitorNetwork() {
    monitor.pathUpdateHandler = { path in
        if #available(iOS 13.0, *) {
            self.isLowDataMode = path.isConstrained
        } else {
            // Fallback on earlier versions
            self.isLowDataMode = false
        }
        
        if path.status == .requiresConnection {
            print("requiresConnection")
                self.delegate?.checkInternetConnection(.slowConnection, isLowDataMode: self.isLowDataMode)
        } else if path.status == .satisfied {
            print("satisfied")
                 self.delegate?.checkInternetConnection(.connected, isLowDataMode: self.isLowDataMode)
        } else if path.status == .unsatisfied {
            print("unsatisfied")
                self.delegate?.checkInternetConnection(.notConnected, isLowDataMode: self.isLowDataMode)
            }
        }
    
    }
    func stopMonitorNetwork() {
        monitor.cancel()
    }
}

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

List of Python format characters

Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".

Note that you should start using the new string formatting when possible.

What is an "index out of range" exception, and how do I fix it?

Why does this error occur?

Because you tried to access an element in a collection, using a numeric index that exceeds the collection's boundaries.

The first element in a collection is generally located at index 0. The last element is at index n-1, where n is the Size of the collection (the number of elements it contains). If you attempt to use a negative number as an index, or a number that is larger than Size-1, you're going to get an error.

How indexing arrays works

When you declare an array like this:

var array = new int[6]

The first and last elements in the array are

var firstElement = array[0];
var lastElement = array[5];

So when you write:

var element = array[5];

you are retrieving the sixth element in the array, not the fifth one.

Typically, you would loop over an array like this:

for (int index = 0; index < array.Length; index++)
{
    Console.WriteLine(array[index]);
}

This works, because the loop starts at zero, and ends at Length-1 because index is no longer less than Length.

This, however, will throw an exception:

for (int index = 0; index <= array.Length; index++)
{
    Console.WriteLine(array[index]);
}

Notice the <= there? index will now be out of range in the last loop iteration, because the loop thinks that Length is a valid index, but it is not.

How other collections work

Lists work the same way, except that you generally use Count instead of Length. They still start at zero, and end at Count - 1.

for (int index = 0; i < list.Count; index++)
{
    Console.WriteLine(list[index]);
} 

However, you can also iterate through a list using foreach, avoiding the whole problem of indexing entirely:

foreach (var element in list)
{
    Console.WriteLine(element.ToString());
}

You cannot index an element that hasn't been added to a collection yet.

var list = new List<string>();
list.Add("Zero");
list.Add("One");
list.Add("Two");
Console.WriteLine(list[3]);  // Throws exception.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

When we put together a react-redux application we should expect to see a structure where at the top we have the Provider tag which has an instance of a redux store.

That Provider tag then renders your parent component, lets call it the App component which in turn renders every other component inside the application.

Here is the key part, when we wrap a component with the connect() function, that connect() function expects to see some parent component within the hierarchy that has the Provider tag.

So the instance you put the connect() function in there, it will look up the hierarchy and try to find the Provider.

Thats what you want to have happen, but in your test environment that flow is breaking down.

Why?

Why?

When we go back over to the assumed sportsDatabase test file, you must be the sportsDatabase component by itself and then trying to render that component by itself in isolation.

So essentially what you are doing inside that test file is just taking that component and just throwing it off in the wild and it has no ties to any Provider or store above it and thats why you are seeing this message.

There is not store or Provider tag in the context or prop of that component and so the component throws an error because it want to see a Provider tag or store in its parent hierarchy.

So that’s what that error means.

Rename package in Android Studio

I've found a way easier solution to this problem which also changed the generated imports like com.test.testpackagechange.R and only takes about a minute.

Your first step is to open Android Studio and open the replace all window (Mac: cmd + shift + R, Windows I assume: ctrl + shift + R). Type in your old package name and in the one below your new package name. Click Find. This may take a while because it is also looking through the generated items. If it has over 1000 hits, just click continue.

enter image description here

After you've done that push Replace All to replace your old package name with your new one.

enter image description here

Now close Android Studio and go to Finder on Mac or Windows Explorer on Windows. Change the name of the folders to your new package name, like this:

enter image description here

Now open Android Studio again. Gradle will sync and your package name should be changed to the new one.

I've found this to be the easiest one and the one that covers all areas like generated files.

jQuery to retrieve and set selected option value of html select element

Suppose you have created a Drop Down list using SELECT tag like as follows,

<select id="Country">

Now if you want to see what is the selected value from drop down using JQuery then, simply put following line to retrieve that value..

var result= $("#Country option:selected").text();

it will work fine.

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

Find out which remote branch a local branch is tracking

Two choices:

% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline

or

% git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
origin/mainline

Simple way to convert datarow array to datatable

DataTable dt = myDataRowCollection.CopyToDataTable<DataRow>();

How to convert from java.sql.Timestamp to java.util.Date?

public static Date convertTimestampToDate(Timestamp timestamp)  {
        Instant ins=timestamp.toLocalDateTime().atZone(ZoneId.systemDefault()).toInstant();
        return  Date.from(ins);
}

PHP: How to handle <![CDATA[ with SimpleXMLElement?

This is working perfect for me.

$content = simplexml_load_string(
    $raw_xml
    , null
    , LIBXML_NOCDATA
);

Counter in foreach loop in C#

Probably pointless, but...

foreach (var item in yourList.Select((Value, Index) => new { Value, Index }))
{
    Console.WriteLine("Value=" + item.Value + ", Index=" + item.Index);
}

CSS: image link, change on hover

The problem with changing it via JavaScript or CSS is that if you have a slower connection, the image will take a second to change to the hovered version. This will cause an undesirable flash as one disappears while the other downloads.

What I've done before is have two images. Then hide and show each depending on the hover state. This will allow for a clean switch between the two images.

<a href="/settings">
    <img class="default" src="settings-default.svg"/>
    <img class="hover" src="settings-hover.svg"/>
    <span>Settings</span>
</a>

a img.hover {
    display: none;
}
a img.default {
    display: inherit;
}
a:hover img.hover {
    display: inherit;
}
a:hover img.default {
    display: none;
}

Xcode process launch failed: Security

I had this issue before on Xcode 7 cause then i realized it's all about my internet connection it was down and the security check using the internet to make sure your developer account is correct. and when it see no internet it give this error … after i have fixed my internet it works good.

How do I convert two lists into a dictionary?

If you need to transform keys or values before creating a dictionary then a generator expression could be used. Example:

>>> adict = dict((str(k), v) for k, v in zip(['a', 1, 'b'], [2, 'c', 3])) 

Take a look Code Like a Pythonista: Idiomatic Python.

Convert iterator to pointer?

If you can, a better choice may be to change the function to take either an iterator to an element or a brand new vector (if it does not modify).

While you can do this sort of things with arrays since you know how they are stored, it's probably a bad idea to do the same with vectors. &foo[1] does not have the type vector<int>*.

Also, while the STL implementation is available online, it's usually risky to try and rely on the internal structure of an abstraction.

Undefined reference to `pow' and `floor'

All answers above are incomplete, the problem here lies in linker ld rather than compiler collect2: ld returned 1 exit status. When you are compiling your fib.c to object:

$ gcc -c fib.c
$ nm fib.o
0000000000000028 T fibo
                 U floor
                 U _GLOBAL_OFFSET_TABLE_
0000000000000000 T main
                 U pow
                 U printf

Where nm lists symbols from object file. You can see that this was compiled without an error, but pow, floor, and printf functions have undefined references, now if I will try to link this to executable:

$ gcc fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status

Im getting similar output you get. To solve that, I need to tell linker where to look for references to pow, and floor, for this purpose I will use linker -l flag with m which comes from libm.so library.

$ gcc fib.o -lm
$ nm a.out
0000000000201010 B __bss_start
0000000000201010 b completed.7697
                 w __cxa_finalize@@GLIBC_2.2.5
0000000000201000 D __data_start
0000000000201000 W data_start
0000000000000620 t deregister_tm_clones
00000000000006b0 t __do_global_dtors_aux
0000000000200da0 t 
__do_global_dtors_aux_fini_array_entry
0000000000201008 D __dso_handle
0000000000200da8 d _DYNAMIC
0000000000201010 D _edata
0000000000201018 B _end
0000000000000722 T fibo
0000000000000804 T _fini
                 U floor@@GLIBC_2.2.5
00000000000006f0 t frame_dummy
0000000000200d98 t __frame_dummy_init_array_entry
00000000000009a4 r __FRAME_END__
0000000000200fa8 d _GLOBAL_OFFSET_TABLE_
                 w __gmon_start__
000000000000083c r __GNU_EH_FRAME_HDR
0000000000000588 T _init
0000000000200da0 t __init_array_end
0000000000200d98 t __init_array_start
0000000000000810 R _IO_stdin_used
                 w _ITM_deregisterTMCloneTable
                 w _ITM_registerTMCloneTable
0000000000000800 T __libc_csu_fini
0000000000000790 T __libc_csu_init
                 U __libc_start_main@@GLIBC_2.2.5
00000000000006fa T main
                 U pow@@GLIBC_2.2.5
                 U printf@@GLIBC_2.2.5
0000000000000660 t register_tm_clones
00000000000005f0 T _start
0000000000201010 D __TMC_END__

You can now see, functions pow, floor are linked to GLIBC_2.2.5.

Parameters order is important too, unless your system is configured to use shared librares by default, my system is not, so when I issue:

$ gcc -lm fib.o
fib.o: In function `fibo':
fib.c:(.text+0x57): undefined reference to `pow'
fib.c:(.text+0x84): undefined reference to `floor'
collect2: error: ld returned 1 exit status

Note -lm flag before object file. So in conclusion, add -lm flag after all other flags, and parameters, to be sure.

Checking cin input stream produces an integer

Heh, this is an old question that could use a better answer.

User input should be obtained as a string and then attempt-converted to the data type you desire. Conveniently, this also allows you to answer questions like “what type of data is my input?”

Here is a function I use a lot. Other options exist, such as in Boost, but the basic premise is the same: attempt to perform the string?type conversion and observe the success or failure:

template <typename T>
std::optional <T> string_to( const std::string& s )
{
  std::istringstream ss( s );
  T result;
  ss >> result >> std::ws;      // attempt the conversion
  if (ss.eof()) return result;  // success
  return {};                    // failure
}

Using the optional type is just one way. You could also throw an exception or return a default value on failure. Whatever works for your situation.

Here is an example of using it:

int n;
std::cout << "n? ";
{
  std::string s;
  getline( std::cin, s );
  auto x = string_to <int> ( s );
  if (!x) return complain();
  n = *x;
}
std::cout << "Multiply that by seven to get " << (7 * n) << ".\n";

limitations and type identification

In order for this to work, of course, there must exist a method to unambiguously extract your data type from a stream. This is the natural order of things in C++ — that is, business as usual. So no surprises here.

The next caveat is that some types subsume others. For example, if you are trying to distinguish between int and double, check for int first, since anything that converts to an int is also a double.

How do I find the length of an array?

Instead of using the built in array function aka:

 int x[3] = {0, 1, 2};

you should use the array class and the array template. Try:

#include <array>
array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};

So now if you want to find the length of the array, all you have to do is using the size function in the array class.

Name_of_Array.size();

and that should return the length of elements in the array.

SQL query to make all data in a column UPPER CASE?

If you want to only update on rows that are not currently uppercase (instead of all rows), you'd need to identify the difference using COLLATE like this:

UPDATE MyTable
SET    MyColumn = UPPER(MyColumn)
WHERE  MyColumn != UPPER(MyColumn) COLLATE Latin1_General_CS_AS 

A Bit About Collation

Cases sensitivity is based on your collation settings, and is typically case insensitive by default.

Collation can be set at the Server, Database, Column, or Query Level:

-- Server
SELECT SERVERPROPERTY('COLLATION')
-- Database
SELECT name, collation_name FROM sys.databases
-- Column 
SELECT COLUMN_NAME, COLLATION_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE CHARACTER_SET_NAME IS NOT NULL

Collation Names specify how a string should be encoded and read, for example:

  • Latin1_General_CI_AS ? Case Insensitive
  • Latin1_General_CS_AS ? Case Sensitive

how to convert java string to Date object

The concise version:

String dateStr = "06/27/2007";
DateFormat formatter = new SimpleDateFormat("MM/dd/yyyy");
Date startDate = (Date)formatter.parse(dateStr);  

Add a try/catch block for a ParseException to ensure the format is a valid date.

How can I get all sequences in an Oracle database?

You may not have permission to dba_sequences. So you can always just do:

select * from user_sequences;

Simple int to char[] conversion

You can't truly do it in "standard" C, because the size of an int and of a char aren't fixed. Let's say you are using a compiler under Windows or Linux on an intel PC...

int i = 5;
char a = ((char*)&i)[0];
char b = ((char*)&i)[1];

Remember of endianness of your machine! And that int are "normally" 32 bits, so 4 chars!

But you probably meant "i want to stringify a number", so ignore this response :-)

how to copy only the columns in a DataTable to another DataTable?

DataTable.Clone() should do the trick.

DataTable newTable = originalTable.Clone();

iconv - Detected an illegal character in input string

this bellow solution worked for me

$result_encr="##Sƒ";

iconv("cp1252", "utf-8//IGNORE", $result_encr);

Bundler::GemNotFound: Could not find rake-10.3.2 in any of the sources

Remove your Gemfile.lock.

Move to bash if you are using zsh.

sudo bash
gem update --system 

Now run command bundle to create a new Gemfile.lock file. Move back to your zsh sudo exec zsh now run your rake commands.

Dynamically access object property using variable

I asked a question that kinda duplicated on this topic a while back, and after excessive research, and seeing a lot of information missing that should be here, I feel I have something valuable to add to this older post.

  • Firstly I want to address that there are several ways to obtain the value of a property and store it in a dynamic Variable. The first most popular, and easiest way IMHO would be:
let properyValue = element.style['enter-a-property'];

however I rarely go this route because it doesn't work on property values assigned via style-sheets. To give you an example, I'll demonstrate with a bit of pseudo code.

 let elem = document.getElementById('someDiv');
 let cssProp = elem.style['width'];

Using the code example above; if the width property of the div element that was stored in the 'elem' variable was styled in a CSS style-sheet, and not styled inside of its HTML tag, you are without a doubt going to get a return value of undefined stored inside of the cssProp variable. The undefined value occurs because in-order to get the correct value, the code written inside a CSS Style-Sheet needs to be computed in-order to get the value, therefore; you must use a method that will compute the value of the property who's value lies within the style-sheet.

  • Henceforth the getComputedStyle() method!
function getCssProp(){
  let ele = document.getElementById("test");
  let cssProp = window.getComputedStyle(ele,null).getPropertyValue("width");
}

W3Schools getComputedValue Doc This gives a good example, and lets you play with it, however, this link Mozilla CSS getComputedValue doc talks about the getComputedValue function in detail, and should be read by any aspiring developer who isn't totally clear on this subject.

  • As a side note, the getComputedValue method only gets, it does not set. This, obviously is a major downside, however there is a method that gets from CSS style-sheets, as well as sets values, though it is not standard Javascript. The JQuery method...
$(selector).css(property,value)

...does get, and does set. It is what I use, the only downside is you got to know JQuery, but this is honestly one of the very many good reasons that every Javascript Developer should learn JQuery, it just makes life easy, and offers methods, like this one, which is not available with standard Javascript. Hope this helps someone!!!

Changing Placeholder Text Color with Swift

Here is my quick implementation for swift 4:

extension UITextField {
    func placeholderColor(_ color: UIColor){
        var placeholderText = ""
        if self.placeholder != nil{
            placeholderText = self.placeholder!
        }
        self.attributedPlaceholder = NSAttributedString(string: placeholderText, attributes: [NSAttributedStringKey.foregroundColor : color])
    }
}

use like:

streetTextField?.placeholderColor(AppColor.blueColor)

hope it helps someone!

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

Checking for duplicate strings in JavaScript array

This is the simplest solution I guess :

function diffArray(arr1, arr2) {
  return arr1
    .concat(arr2)
    .filter(item => !arr1.includes(item) || !arr2.includes(item));
}

Programmatically close aspx page from code behind

UPDATE: I have taken all of your input and came up with the following solution:

In code behind:

protected void Page_Load(object sender, EventArgs e)    
{
    Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}

In aspx page:

function CloseWindow() {
    window.close();
}

how to add or embed CKEditor in php page

If you have downloaded the latest Version 4.3.4 then just follow these steps.

  • Download the package, unzip and place in your web directory or root folder.
  • Provide the read write permissions to that folder (preferably Ubuntu machines )
  • Create view page test.php
  • Paste the below mentioned code it should work fine.

Load the mentioned js file

<script type="text/javascript" src="/ckeditor/ckeditor.js"></script>
<textarea class="ckeditor" name="editor"></textarea>

Update one MySQL table with values from another

It depends what is a use of those tables, but you might consider putting trigger on original table on insert and update. When insert or update is done, update the second table based on only one item from the original table. It will be quicker.

How to keep :active css style after clicking an element

If you want to keep your links to look like they are :active class, you should define :visited class same as :active so if you have a links in .example then you do something like this:

a.example:active, a.example:visited {
/* Put your active state style code here */ }

The Link visited Pseudo Class is used to select visited links as says the name.

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

try this

 input[type='text']
 {
   background:red !important;
 }

How to add form validation pattern in Angular 2?

custom validation step by step

Html template

  <form [ngFormModel]="demoForm">
  <input  
  name="NotAllowSpecialCharacters"    
  type="text"                      
  #demo="ngForm"
  [ngFormControl] ="demoForm.controls['spec']"
  >

 <div class='error' *ngIf="demo.control.touched">
   <div *ngIf="demo.control.hasError('required')"> field  is required.</div>
   <div *ngIf="demo.control.hasError('invalidChar')">Special Characters are not Allowed</div>
 </div>
  </form>

Component App.ts

import {Control, ControlGroup, FormBuilder, Validators, NgForm, NgClass} from 'angular2/common';
import {CustomValidator} from '../../yourServices/validatorService';

under class define

 demoForm: ControlGroup;
constructor( @Inject(FormBuilder) private Fb: FormBuilder ) {
    this.demoForm = Fb.group({
       spec: new Control('', Validators.compose([Validators.required,   CustomValidator.specialCharValidator])),
      })
}

under {../../yourServices/validatorService.ts}

export class CustomValidator {
    static specialCharValidator(control: Control): { [key: string]: any } {
   if (control.value) {
       if (!control.value.match(/[-!$%^&*()_+|~=`{}\[\]:";#@'<>?,.\/]/)) {            
           return null;
       }
       else {            
           return { 'invalidChar': true };
       }
   }

 }

 }

Displaying a message in iOS which has the same functionality as Toast in Android

For Swift 3 & 4:

Use Toaster library

Toast(text: "Hello, world!", duration: Delay.long)

enter image description here

For Swift 2:

Use JLToast

How do I get into a Docker container's shell?

Notice: this answer promotes a tool I've written.

I've created a containerized SSH server that you can 'stick' to any running container. This way you can create compositions with every container. The only requirement is that the container has Bash.

The following example would start an SSH server attached to a container with name 'my-container'.

docker run -d -p 2222:22 \
  -v /var/run/docker.sock:/var/run/docker.sock \
  -e CONTAINER=my-container -e AUTH_MECHANISM=noAuth \
  jeroenpeeters/docker-ssh

ssh localhost -p 2222

When you connect to this SSH service (with your SSH client of choice) a Bash session will be started in the container with name 'my-container'.

For more pointers and documentation see: https://github.com/jeroenpeeters/docker-ssh

Given URL is not allowed by the Application configuration Facebook application error

So... facebook distinguishes pretty harshly between http and https in your app. This is just another small thing to check if you run into trouble.

Change a HTML5 input's placeholder color with CSS

Here is one more example:

_x000D_
_x000D_
.form-control::-webkit-input-placeholder {_x000D_
  color: red;_x000D_
  width: 250px;_x000D_
}_x000D_
h1 {_x000D_
  color: red;_x000D_
}
_x000D_
<div class="col-sm-4">_x000D_
  <input class="form-control" placeholder="Enter text here.." ng-model="Email" required/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Best way to check function arguments?

The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.

The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.

How to convert String into Hashmap in java

try this out :)

public static HashMap HashMapFrom(String s){
    HashMap base = new HashMap(); //result
    int dismiss = 0; //dismiss tracker
    StringBuilder tmpVal = new StringBuilder(); //each val holder
    StringBuilder tmpKey = new StringBuilder(); //each key holder

    for (String next:s.split("")){ //each of vale
        if(dismiss==0){ //if not writing value
            if (next.equals("=")) //start writing value
                dismiss=1; //update tracker
            else
                tmpKey.append(next); //writing key
        } else {
            if (next.equals("{")) //if it's value so need to dismiss
                dismiss++;
            else if (next.equals("}")) //value closed so need to focus
                dismiss--;
            else if (next.equals(",") //declaration ends
                    && dismiss==1) {
                //by the way you have to create something to correct the type
                Object ObjVal = object.valueOf(tmpVal.toString()); //correct the type of object
                base.put(tmpKey.toString(),ObjVal);//declaring
                tmpKey = new StringBuilder();
                tmpVal = new StringBuilder();
                dismiss--;
                continue; //next :)
            }
            tmpVal.append(next); //writing value
        }
    }
    Object objVal = object.valueOf(tmpVal.toString()); //same as here
    base.put(tmpKey.toString(), objVal); //leftovers
    return base;
}

examples input : "a=0,b={a=1},c={ew={qw=2}},0=a" output : {0=a,a=0,b={a=1},c={ew={qw=2}}}

Best practice: PHP Magic Methods __set and __get

I have been exactly in your case in the past. And I went for magic methods.

This was a mistake, the last part of your question says it all :

  • this is slower (than getters/setters)
  • there is no auto-completion (and this is a major problem actually), and type management by the IDE for refactoring and code-browsing (under Zend Studio/PhpStorm this can be handled with the @property phpdoc annotation but that requires to maintain them: quite a pain)
  • the documentation (phpdoc) doesn't match how your code is supposed to be used, and looking at your class doesn't bring much answers as well. This is confusing.
  • added after edit: having getters for properties is more consistent with "real" methods where getXXX() is not only returning a private property but doing real logic. You have the same naming. For example you have $user->getName() (returns private property) and $user->getToken($key) (computed). The day your getter gets more than a getter and needs to do some logic, everything is still consistent.

Finally, and this is the biggest problem IMO : this is magic. And magic is very very bad, because you have to know how the magic works to use it properly. That's a problem I've met in a team: everybody has to understand the magic, not just you.

Getters and setters are a pain to write (I hate them) but they are worth it.

How to find out when a particular table was created in Oracle?

Try this query:

SELECT sysdate FROM schema_name.table_name;

This should display the timestamp that you might need.

Keyboard shortcut to paste clipboard content into command prompt window (Win XP)

If you use the clipboard manager Ditto (open source, gratis), you can simply use the shortcut to paste from Ditto, and it will paste the clipboard in CMD for you.

enter image description here

How to programmatically set drawableLeft on Android button?

You can use the setCompoundDrawables method to do this. See the example here. I used this without using the setBounds and it worked. You can try either way.

UPDATE: Copying the code here incase the link goes down

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);

or

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);

or

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

python BeautifulSoup parsing table

from behave import *
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
import pandas as pd
import requests
from bs4 import BeautifulSoup
from tabulate import tabulate

class readTableDataFromDB: 
    def LookupValueFromColumnSingleKey(context, tablexpath, rowName, columnName):
        print("element present readData From Table")
        element = context.driver.find_elements_by_xpath(tablexpath+"/descendant::th")
        indexrow = 1
        indexcolumn = 1
        for values in element:
            valuepresent = values.text
            print("text present here::"+valuepresent+"rowName::"+rowName)
            if valuepresent.find(columnName) != -1:
                 print("current row"+str(indexrow) +"value"+valuepresent)
                 break
            else:
                 indexrow = indexrow+1    

        indexvalue = context.driver.find_elements_by_xpath(
            tablexpath+"/descendant::tr/td[1]")
        for valuescolumn in indexvalue:
            valuepresentcolumn = valuescolumn.text
            print("Team text present here::" +
                  valuepresentcolumn+"columnName::"+rowName)
            print(indexcolumn) 
            if valuepresentcolumn.find(rowName) != -1:
                print("current column"+str(indexcolumn) +
                      "value"+valuepresentcolumn)
                break
            else:
                indexcolumn = indexcolumn+1

        print("index column"+str(indexcolumn))
        print(tablexpath +"//descendant::tr["+str(indexcolumn)+"]/td["+str(indexrow)+"]")
        #lookupelement = context.driver.find_element_by_xpath(tablexpath +"//descendant::tr["+str(indexcolumn)+"]/td["+str(indexrow)+"]")
        #print(lookupelement.text)
        return context.driver.find_elements_by_xpath(tablexpath+"//descendant::tr["+str(indexcolumn)+"]/td["+str(indexrow)+"]")

    def LookupValueFromColumnTwoKeyssss(context, tablexpath, rowName, columnName, columnName1):
        print("element present readData From Table")
        element = context.driver.find_elements_by_xpath(
            tablexpath+"/descendant::th")
        indexrow = 1
        indexcolumn = 1
        indexcolumn1 = 1
        for values in element:
            valuepresent = values.text
            print("text present here::"+valuepresent)
            indexrow = indexrow+1
            if valuepresent == columnName:
                print("current row value"+str(indexrow)+"value"+valuepresent)
                break

        for values in element:
            valuepresent = values.text
            print("text present here::"+valuepresent)
            indexrow = indexrow+1
            if valuepresent.find(columnName1) != -1:
                print("current row value"+str(indexrow)+"value"+valuepresent)
                break

        indexvalue = context.driver.find_elements_by_xpath(
            tablexpath+"/descendant::tr/td[1]")
        for valuescolumn in indexvalue:
            valuepresentcolumn = valuescolumn.text
            print("Team text present here::"+valuepresentcolumn)
            print(indexcolumn)
            indexcolumn = indexcolumn+1
            if valuepresent.find(rowName) != -1:
                print("current column"+str(indexcolumn) +
                      "value"+valuepresentcolumn)
                break
        print("indexrow"+str(indexrow))
        print("index column"+str(indexcolumn))
        lookupelement = context.driver.find_element_by_xpath(
            tablexpath+"//descendant::tr["+str(indexcolumn)+"]/td["+str(indexrow)+"]")
        print(tablexpath +
              "//descendant::tr["+str(indexcolumn)+"]/td["+str(indexrow)+"]")
        print(lookupelement.text)
        return context.driver.find_element_by_xpath(tablexpath+"//descendant::tr["+str(indexrow)+"]/td["+str(indexcolumn)+"]")

iOS: Convert UTC NSDate to local Timezone

NSTimeInterval seconds; // assume this exists
NSDate* ts_utc = [NSDate dateWithTimeIntervalSince1970:seconds];

NSDateFormatter* df_utc = [[[NSDateFormatter alloc] init] autorelease];
[df_utc setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[df_utc setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

NSDateFormatter* df_local = [[[NSDateFormatter alloc] init] autorelease];
[df_local setTimeZone:[NSTimeZone timeZoneWithName:@"EST"]];
[df_local setDateFormat:@"yyyy.MM.dd G 'at' HH:mm:ss zzz"];

NSString* ts_utc_string = [df_utc stringFromDate:ts_utc];
NSString* ts_local_string = [df_local stringFromDate:ts_utc];

// you can also use NSDateFormatter dateFromString to go the opposite way

Table of formatting string parameters:

https://waracle.com/iphone-nsdateformatter-date-formatting-table/

If performance is a priority, you may want to consider using strftime

https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man3/strftime.3.html

Tracing XML request/responses with JAX-WS

// This solution provides a way programatically add a handler to the web service clien w/o the XML config

// See full doc here: http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476

// Create new class that implements SOAPHandler

public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public Set<QName> getHeaders() {
    return Collections.EMPTY_SET;
}

@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage(); //Line 1
    try {
        msg.writeTo(System.out);  //Line 3
    } catch (Exception ex) {
        Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    } 
    return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
    return true;
}

@Override
public void close(MessageContext context) {
}
}

// Programatically add your LogMessageHandler

   com.csd.Service service = null;
    URL url = new URL("https://service.demo.com/ResService.svc?wsdl");

    service = new com.csd.Service(url);

    com.csd.IService port = service.getBasicHttpBindingIService();
    BindingProvider bindingProvider = (BindingProvider)port;
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new LogMessageHandler());
    binding.setHandlerChain(handlerChain);

VS 2012: Scroll Solution Explorer to current file

There are many ways to do this:

Go to current File once:

  • Visual Studio 2013

    VS 13 has it's own shortcut to do this: Ctrl+\, S (Press Ctrl + \, Release both keys, Press the S key)

    You can edit this default shortcut, if you are searching for SolutionExplorer.SyncWithActiveDocument in your Keyboard Settings (Tools->Options->Enviornment->Keyboard)

    In addition there is also a new icon in the Solution Explorer, more about this here.

    Sync with Active Document Button in VS2013 - Solution Explorer

  • Visual Studio 2012

    If you use VS 2012, there is a great plugin to add this new functionality from VS2013 to VS2012: . The default shortcut is strg + alt + ü. I think this one is the best, as navigating to the solution explorer is mapped to strg + ü.

  • Resharper

    If you use Resharper try Shift+Alt+L

    This is a nice mapping as you can use Strg+Alt+L for navigating to the solution explorer

Track current file all the time:

  • Visual Studio >= 2012:

    If you like to track your current file in the solution explorer all the time, you can use the solution from the accepted answer (Tools->Options->Projects and Solutions->Track Active Item in Solution Explorer), but I think this can get very annoying in large projects.

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

How do I escape a single quote ( ' ) in JavaScript?

You can escape a ' in JavaScript like \'

How do I change the text size in a label widget, python tkinter

Try passing width=200 as additional paramater when creating the Label.

This should work in creating label with specified width.

If you want to change it later, you can use:

label.config(width=200)

As you want to change the size of font itself you can try:

label.config(font=("Courier", 44))

How to tell if a <script> tag failed to load

onerror Event

*Update August 2017: onerror is fired by Chrome and Firefox. onload is fired by Internet Explorer. Edge fires neither onerror nor onload. I wouldnt use this method but it could work in some cases. See also

<link> onerror do not work in IE

*

Definition and Usage The onerror event is triggered if an error occurs while loading an external file (e.g. a document or an image).

Tip: When used on audio/video media, related events that occurs when there is some kind of disturbance to the media loading process, are:

  • onabort
  • onemptied
  • onstalled
  • onsuspend

In HTML:

element onerror="myScript">

In JavaScript, using the addEventListener() method:

object.addEventListener("error", myScript);

Note: The addEventListener() method is not supported in Internet Explorer 8 and earlier versions.

Example Execute a JavaScript if an error occurs when loading an image:

img src="image.gif" onerror="myFunction()">

Java POI : How to read Excel cell value and not the formula computing it?

If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:

CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);

At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).

Should MySQL have its timezone set to UTC?

PHP and MySQL have their own default timezone configurations. You should synchronize time between your data base and web application, otherwise you could run some issues.

Read this tutorial: How To Synchronize Your PHP and MySQL Timezones

How to convert a byte to its binary string representation

A simple answer could be:

System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 0
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1})); // 1
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0})); // 256
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0})); // 65536
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0})); // 16777216
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0})); // 4294967296
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0})); // 1099511627776
System.out.println(new BigInteger(new byte[]{0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0})); // 281474976710656
System.out.println(new BigInteger(new byte[]{0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0})); // 72057594037927936
System.out.println(new BigInteger(new byte[]{0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0})); // 18446744073709551616
System.out.println(new BigInteger(new byte[]{0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 4722366482869645213696
System.out.println(new BigInteger(new byte[]{1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0})); // 1208925819614629174706176
System.out.println(Long.MAX_VALUE);                                              // 9223372036854775807

How to move an entire div element up x pixels?

In css add this to the element:

margin-top: -15px; /*for exact positioning */
margin-top: -5%; /* for relative positioning */

you can use either one to position accordingly.

How can I exclude all "permission denied" messages from "find"?

Redirect standard error. For instance, if you're using bash on a unix machine, you can redirect standard error to /dev/null like this:

find . 2>/dev/null >files_and_folders

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

What are the differences between if, else, and else if?

The if statement uses the results of a logical expression to decide if one of two code blocks will be executed.

With this code

if (logical expression) {
    code block 1;
} else {
    code block 2;
}

if the logical expression is true, only the statements in code block 1 will be executed; if false, only the statements in code block 2.

In the case that there are multiple similar tests to be done (for instance if we are testing a number to be less than zero, equal to zero or more than zero) then the second test can be placed as the first statement of the else code block.

if (logical expression 1) {
    code block 1;
} else {
    if (logical expression 2) {
        code block 2;
    } else {
        code block 3;
    }
}

In this case, code block 1 is executed if logical expression 1 is true; code block 2 if logical expression 1 is false and logical expression 2 is true; code block 3 if both logical expressions are false.

Obviously this can be repeated with another if statement as the first statement of code block 3.

The else if statement is simply a reformatted version of this code.

if (logical expression 1) {
    code block 1;
} else if (logical expression 2) {
    code block 2;
} else {
    code block 3;
}

How to resolve javax.mail.AuthenticationFailedException issue?

Just wanted to share with you:
I happened to get this error after changing Digital Ocean machine (IP address). Apparently Gmail recognized it as a hacking attack. After following their directions, and approving the new IP address the code is back and running.

How to print without newline or space?

There are general two ways to do this:

Print without newline in Python 3.x

Append nothing after the print statement and remove '\n' by using end='' as:

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
hello world # it seem correct output

Another Example in Loop:

for i in range(1,10):
    print(i, end='.')

Print without newline in Python 2.x

Adding a trailing comma says that after print ignore \n.

>>> print "hello",; print" world"
hello world

Another Example in Loop:

for i in range(1,10):
    print "{} .".format(i),

Hope this will help you. You can visit this link .

What's the best/easiest GUI Library for Ruby?

Use the browser as GUI using Watir like in this question and answer:

use browser as GUI in Ruby

html <input type="text" /> onchange event not working

Use .on('input'... to monitor every change to an input (paste, keyup, etc) from jQuery 1.7 and above.

For static and dynamic inputs:

$(document).on('input', '.my-class', function(){
    alert('Input changed');
});

For static inputs only:

$('.my-class').on('input', function(){
    alert('Input changed');
});

JSFiddle with static/dynamic example: https://jsfiddle.net/op0zqrgy/7/

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Jquery change background color

The .css() function doesn't queue behind running animations, it's instantaneous.

To match the behaviour that you're after, you'd need to do the following:

$(document).ready(function() {
  $("button").mouseover(function() {
    var p = $("p#44.test").css("background-color", "yellow");
    p.hide(1500).show(1500);
    p.queue(function() {
      p.css("background-color", "red");
    });
  });
});

The .queue() function waits for running animations to run out and then fires whatever's in the supplied function.

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

Getting data-* attribute for onclick event for an html element

Like this:

$(this).data('id');
$(this).data('option');

Working example: http://jsfiddle.net/zwHUc/

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Debugging WebSocket in Google Chrome

The other answers cover the most common scenario: watch the content of the frames (Developer Tools -> Network tab -> Right click on the websocket connection -> frames).

If you want to know some more informations, like which sockets are currently open/idle or be able to close them you'll find this url useful

chrome://net-internals/#sockets

How to remove leading zeros from alphanumeric text?

If you (like me) need to remove all the leading zeros from each "word" in a string, you can modify @polygenelubricants' answer to the following:

String s = "003 d0g 00ss 00 0 00";
s.replaceAll("\\b0+(?!\\b)", "");

which results in:

3 d0g ss 0 0 0

qmake: could not find a Qt installation of ''

A symbolic link to the desired version, defined globally:

sudo ln -s /usr/bin/qmake-qt5 /usr/bin/qmake

... or per user:

sudo ln -s /usr/bin/qmake-qt5 /home/USERNAME/.local/bin/qmake

... to see if it works:

qmake --version

angular-cli server - how to specify default port

In Angular 2 [email protected],

To run a new project on the different port, one way is to specify the port while you run ng serve command.

ng serve --port 4201

or the other way, you can edit your package.json file scripts part and attached the port to your start variable like I mentioned below and then simply run "npm start"

 "scripts": {

    "ng": "ng",
    "start": "ng serve --port 4201",
    ... : ...,
    ... : ....
}

this way is much better where you don't need to define port explicitly every time.

ASP.NET: Session.SessionID changes between requests

There is another, more insidious reason, why this may occur even when the Session object has been initialized as demonstrated by Cladudio.

In the Web.config, if there is an <httpCookies> entry that is set to requireSSL="true" but you are not actually using HTTPS: for a specific request, then the session cookie is not sent (or maybe not returned, I'm not sure which) which means that you end up with a brand new session for each request.

I found this one the hard way, spending several hours going back and forth between several commits in my source control, until I found what specific change had broken my application.

Javascript - User input through HTML input tag to set a Javascript variable?

This is bad style, but I'll assume you have a good reason for doing something similar.

<html>
<body>
    <input type="text" id="userInput">give me input</input>
    <button id="submitter">Submit</button>
    <div id="output"></div>
    <script>
        var didClickIt = false;
        document.getElementById("submitter").addEventListener("click",function(){
            // same as onclick, keeps the JS and HTML separate
            didClickIt = true;
        });

        setInterval(function(){
            // this is the closest you get to an infinite loop in JavaScript
            if( didClickIt ) {
                didClickIt = false;
                // document.write causes silly problems, do this instead (or better yet, use a library like jQuery to do this stuff for you)
                var o=document.getElementById("output"),v=document.getElementById("userInput").value;
                if(o.textContent!==undefined){
                    o.textContent=v;
                }else{
                    o.innerText=v;
                }
            }
        },500);
    </script>
</body>
</html>

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

Your JSON string is malformed: the type of center is an array of invalid objects. Replace [ and ] with { and } in the JSON string around longitude and latitude so they will be objects:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

What's the best way to store Phone number in Django models

Others mentioned django-phonenumber-field. To get the display format how you want you need to set PHONENUMBER_DEFAULT_FORMAT setting to "E164", "INTERNATIONAL", "NATIONAL", or "RFC3966", however you want it displayed. See the GitHub source.

Eclipse count lines of code

Another tool is Google Analytix, which will also allow you to run metrics even if you can`t build the project in case of errors

Why are exclamation marks used in Ruby methods?

This naming convention is lifted from Scheme.

1.3.5 Naming conventions

By convention, the names of procedures that always return a boolean value usually end in ``?''. Such procedures are called predicates.

By convention, the names of procedures that store values into previously allocated locations (see section 3.4) usually end in ``!''. Such procedures are called mutation procedures. By convention, the value returned by a mutation procedure is unspecified.

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

Boolean.parseBoolean("1") = false...?

It accepts only a string value of "true" to represent boolean true. Best what you can do is

boolean uses_votes = "1".equals(o.get("uses_votes"));

Or if the Map actually represents an "entitiy", I think a Javabean is way much better. Or if it represents configuration settings, you may want to take a look into Apache Commons Configuration.

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

Differences

  • KEY or INDEX refers to a normal non-unique index. Non-distinct values for the index are allowed, so the index may contain rows with identical values in all columns of the index. These indexes don't enforce any restraints on your data so they are used only for access - for quickly reaching certain ranges of records without scanning all records.

  • UNIQUE refers to an index where all rows of the index must be unique. That is, the same row may not have identical non-NULL values for all columns in this index as another row. As well as being used to quickly reach certain record ranges, UNIQUE indexes can be used to enforce restraints on data, because the database system does not allow the distinct values rule to be broken when inserting or updating data.

    Your database system may allow a UNIQUE index to be applied to columns which allow NULL values, in which case two rows are allowed to be identical if they both contain a NULL value (the rationale here is that NULL is considered not equal to itself). Depending on your application, however, you may find this undesirable: if you wish to prevent this, you should disallow NULL values in the relevant columns.

  • PRIMARY acts exactly like a UNIQUE index, except that it is always named 'PRIMARY', and there may be only one on a table (and there should always be one; though some database systems don't enforce this). A PRIMARY index is intended as a primary means to uniquely identify any row in the table, so unlike UNIQUE it should not be used on any columns which allow NULL values. Your PRIMARY index should be on the smallest number of columns that are sufficient to uniquely identify a row. Often, this is just one column containing a unique auto-incremented number, but if there is anything else that can uniquely identify a row, such as "countrycode" in a list of countries, you can use that instead.

    Some database systems (such as MySQL's InnoDB) will store a table's records on disk in the order in which they appear in the PRIMARY index.

  • FULLTEXT indexes are different from all of the above, and their behaviour differs significantly between database systems. FULLTEXT indexes are only useful for full text searches done with the MATCH() / AGAINST() clause, unlike the above three - which are typically implemented internally using b-trees (allowing for selecting, sorting or ranges starting from left most column) or hash tables (allowing for selection starting from left most column).

    Where the other index types are general-purpose, a FULLTEXT index is specialised, in that it serves a narrow purpose: it's only used for a "full text search" feature.

Similarities

  • All of these indexes may have more than one column in them.

  • With the exception of FULLTEXT, the column order is significant: for the index to be useful in a query, the query must use columns from the index starting from the left - it can't use just the second, third or fourth part of an index, unless it is also using the previous columns in the index to match static values. (For a FULLTEXT index to be useful to a query, the query must use all columns of the index.)

Python: read all text file lines in loop

There are situations where you can't use the (quite convincing) with... for... structure. In that case, do the following:

line = self.fo.readline()
if len(line) != 0:
     if 'str' in line:
         break

This will work because the the readline() leaves a trailing newline character, where as EOF is just an empty string.

Java List.add() UnsupportedOperationException

Many of the List implementation support limited support to add/remove, and Arrays.asList(membersArray) is one of that. You need to insert the record in java.util.ArrayList or use the below approach to convert into ArrayList.

With the minimal change in your code, you can do below to convert a list to ArrayList. The first solution is having a minimum change in your solution, but the second one is more optimized, I guess.

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = new ArrayList<>(Arrays.asList(membersArray));

OR

    String[] membersArray = request.getParameterValues('members');
    ArrayList<String> membersList = Stream.of(membersArray).collect(Collectors.toCollection(ArrayList::new));

How to encrypt a large file in openssl using public key

Public-key crypto is not for encrypting arbitrarily long files. One uses a symmetric cipher (say AES) to do the normal encryption. Each time a new random symmetric key is generated, used, and then encrypted with the RSA cipher (public key). The ciphertext together with the encrypted symmetric key is transferred to the recipient. The recipient decrypts the symmetric key using his private key, and then uses the symmetric key to decrypt the message.

The private key is never shared, only the public key is used to encrypt the random symmetric cipher.

Something like 'contains any' for Java set?

Use retainAll() in the Set interface. This method provides an intersection of elements common in both sets. See the API docs for more information.

How to make asynchronous HTTP requests in PHP

The answer I'd previously accepted didn't work. It still waited for responses. This does work though, taken from How do I make an asynchronous GET request in PHP?

function post_without_wait($url, $params)
{
    foreach ($params as $key => &$val) {
      if (is_array($val)) $val = implode(',', $val);
        $post_params[] = $key.'='.urlencode($val);
    }
    $post_string = implode('&', $post_params);

    $parts=parse_url($url);

    $fp = fsockopen($parts['host'],
        isset($parts['port'])?$parts['port']:80,
        $errno, $errstr, 30);

    $out = "POST ".$parts['path']." HTTP/1.1\r\n";
    $out.= "Host: ".$parts['host']."\r\n";
    $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
    $out.= "Content-Length: ".strlen($post_string)."\r\n";
    $out.= "Connection: Close\r\n\r\n";
    if (isset($post_string)) $out.= $post_string;

    fwrite($fp, $out);
    fclose($fp);
}

how to implement Pagination in reactJs

I recently created this Pagination component that implements paging logic like Google's search results:

import React, { PropTypes } from 'react';
 
const propTypes = {
    items: PropTypes.array.isRequired,
    onChangePage: PropTypes.func.isRequired,
    initialPage: PropTypes.number   
}
 
const defaultProps = {
    initialPage: 1
}
 
class Pagination extends React.Component {
    constructor(props) {
        super(props);
        this.state = { pager: {} };
    }
 
    componentWillMount() {
        this.setPage(this.props.initialPage);
    }
 
    setPage(page) {
        var items = this.props.items;
        var pager = this.state.pager;
 
        if (page < 1 || page > pager.totalPages) {
            return;
        }
 
        // get new pager object for specified page
        pager = this.getPager(items.length, page);
 
        // get new page of items from items array
        var pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);
 
        // update state
        this.setState({ pager: pager });
 
        // call change page function in parent component
        this.props.onChangePage(pageOfItems);
    }
 
    getPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;
 
        // default page size is 10
        pageSize = pageSize || 10;
 
        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);
 
        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }
 
        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = Math.min(startIndex + pageSize - 1, totalItems - 1);
 
        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);
 
        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
 
    render() {
        var pager = this.state.pager;
 
        return (
            <ul className="pagination">
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(1)}>First</a>
                </li>
                <li className={pager.currentPage === 1 ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage - 1)}>Previous</a>
                </li>
                {pager.pages.map((page, index) =>
                    <li key={index} className={pager.currentPage === page ? 'active' : ''}>
                        <a onClick={() => this.setPage(page)}>{page}</a>
                    </li>
                )}
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.currentPage + 1)}>Next</a>
                </li>
                <li className={pager.currentPage === pager.totalPages ? 'disabled' : ''}>
                    <a onClick={() => this.setPage(pager.totalPages)}>Last</a>
                </li>
            </ul>
        );
    }
}
 
Pagination.propTypes = propTypes;
Pagination.defaultProps
export default Pagination;

And here's an example App component that uses the Pagination component to paginate a list of 150 example items:

import React from 'react';
import Pagination from './Pagination';
 
class App extends React.Component {
    constructor() {
        super();
 
        // an example array of items to be paged
        var exampleItems = _.range(1, 151).map(i => { return { id: i, name: 'Item ' + i }; });
 
        this.state = {
            exampleItems: exampleItems,
            pageOfItems: []
        };
 
        // bind function in constructor instead of render (https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md)
        this.onChangePage = this.onChangePage.bind(this);
    }
 
    onChangePage(pageOfItems) {
        // update state with new page of items
        this.setState({ pageOfItems: pageOfItems });
    }
 
    render() {
        return (
            <div>
                <div className="container">
                    <div className="text-center">
                        <h1>React - Pagination Example with logic like Google</h1>
                        {this.state.pageOfItems.map(item =>
                            <div key={item.id}>{item.name}</div>
                        )}
                        <Pagination items={this.state.exampleItems} onChangePage={this.onChangePage} />
                    </div>
                </div>
                <hr />
                <div className="credits text-center">
                    <p>
                        <a href="http://jasonwatmore.com" target="_top">JasonWatmore.com</a>
                    </p>
                </div>
            </div>
        );
    }
}
 
export default App;

For more details and a live demo you can check out this post

jQuery: Count number of list elements?

var listItems = $("#myList").children();

var count = listItems.length;

Of course you can condense this with

var count = $("#myList").children().length;

For more help with jQuery, http://docs.jquery.com/Main_Page is a good place to start.

Material UI and Grid system

Here is example of grid system with material-ui which is similar to bootstrap:

<Grid container>
    <Grid item xs={12} sm={4} md={4} lg={4}>
    </Grid>
    <Grid item xs={12} sm={4} md={4} lg={4}>
    </Grid>
 </Grid>

In git how is fetch different than pull and how is merge different than rebase?

Fetch vs Pull

Git fetch just updates your repo data, but a git pull will basically perform a fetch and then merge the branch pulled

What is the difference between 'git pull' and 'git fetch'?


Merge vs Rebase

from Atlassian SourceTree Blog, Merge or Rebase:

Merging brings two lines of development together while preserving the ancestry of each commit history.

In contrast, rebasing unifies the lines of development by re-writing changes from the source branch so that they appear as children of the destination branch – effectively pretending that those commits were written on top of the destination branch all along.

Also, check out Learn Git Branching, which is a nice game that has just been posted to HackerNews (link to post) and teaches a lot of branching and merging tricks. I believe it will be very helpful in this matter.

Creating a list of pairs in java

just fixing some small mistakes in Mark Elliot's code:

public class Pair<L,R> {
    private L l;
    private R r;
    public Pair(L l, R r){
        this.l = l;
        this.r = r;
    }
    public L getL(){ return l; }
    public R getR(){ return r; }
    public void setL(L l){ this.l = l; }
    public void setR(R r){ this.r = r; }
}

Shrinking navigation bar when scrolling down (bootstrap3)

If you are using AngularJS, and you are using Angular Bootstrap : https://angular-ui.github.io/bootstrap/

You can do this so nice like this :

HTML:

<nav id="header-navbar" class="navbar navbar-default" ng-class="{'navbar-fixed-top':scrollDown}" role="navigation" scroll-nav>
    <div class="container-fluid top-header">
        <!--- Rest of code --->
    </div>
</nav>

CSS: (Note here I use padding as bigger nav to shrink without padding you can modify as you want)

nav.navbar {
  -webkit-transition: all 0.4s ease;
  transition: all 0.4s ease;

  background-color: white;
  margin-bottom: 0;
  padding: 25px;
}

.navbar-fixed-top {
  padding: 0;
}

And then add your directive

Directive: (Note you may need to change this.pageYOffset >= 50 from 50 to more or less to fulfill your needs)

angular.module('app')
.directive('scrollNav', function ($window) {
  return function(scope, element, attrs) {
    angular.element($window).bind("scroll", function() {
      if (this.pageYOffset >= 50) {
        scope.scrollDown = true;
      } else {
        scope.scrollDown = false;
      }
      scope.$apply();
    });
  };
});

This will do the job nicely, animated and cool way.

What does "Failure [INSTALL_FAILED_OLDER_SDK]" mean in Android Studio?

Make sure you don't have a minSdkVersion set in your build.gradle with a value higher than 8. If you don't specify it at all, it's supposed to use the value in your AndroidManfiest.xml, which seems to already be properly set.

How to get selected value from Dropdown list in JavaScript

According to Html5 specs you should use -- element.options[e.selectedIndex].text

e.g. if you have select box like below :

<select id="selectbox1">
    <option value="1">First</option>
    <option value="2" selected="selected">Second</option>
    <option value="3">Third</option>
</select>
<br/>
<button onClick="GetItemValue('selectbox1');">Get Item</button>

you can get value using following script :

<script>
 function GetItemValue(q) {
   var e = document.getElementById(q);
   var selValue = e.options[e.selectedIndex].text ;
   alert("Selected Value: "+selValue);
 }
</script>

Tried and tested.

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

What is the difference between atomic / volatile / synchronized?

Synchronized Vs Atomic Vs Volatile:

  • Volatile and Atomic is apply only on variable , While Synchronized apply on method.
  • Volatile ensure about visibility not atomicity/consistency of object , While other both ensure about visibility and atomicity.
  • Volatile variable store in RAM and it’s faster in access but we can’t achive Thread safety or synchronization whitout synchronized keyword.
  • Synchronized implemented as synchronized block or synchronized method while both not. We can thread safe multiple line of code with help of synchronized keyword while with both we can’t achieve the same.
  • Synchronized can lock the same class object or different class object while both can’t.

Please correct me if anything i missed.

Efficient way to determine number of digits in an integer

// Meta-program to calculate number of digits in (unsigned) 'N'.    
template <unsigned long long N, unsigned base=10>
struct numberlength
{   // http://stackoverflow.com/questions/1489830/
    enum { value = ( 1<=N && N<base ? 1 : 1+numberlength<N/base, base>::value ) };
};

template <unsigned base>
struct numberlength<0, base>
{
    enum { value = 1 };
};

{
    assert( (1 == numberlength<0,10>::value) );
}
assert( (1 == numberlength<1,10>::value) );
assert( (1 == numberlength<5,10>::value) );
assert( (1 == numberlength<9,10>::value) );

assert( (4 == numberlength<1000,10>::value) );
assert( (4 == numberlength<5000,10>::value) );
assert( (4 == numberlength<9999,10>::value) );

How to make the Facebook Like Box responsive?

NOTE: this answer is obsolete. See the community wiki answer below for an up-to-date solution.


I found this Gist today and it works perfectly: https://gist.github.com/2571173

(Many thanks to https://gist.github.com/smeranda)

/* 
Make the Facebook Like box responsive (fluid width)
https://developers.facebook.com/docs/reference/plugins/like-box/ 
*/

/* 
This element holds injected scripts inside iframes that in 
some cases may stretch layouts. So, we're just hiding it. 
*/

#fb-root {
    display: none;
}

/* To fill the container and nothing else */

.fb_iframe_widget, .fb_iframe_widget span, .fb_iframe_widget span iframe[style] {
    width: 100% !important;
}

Removing pip's cache?

I just had a similar problem and found that the only way to get pip to upgrade the package was to delete the $PWD/build (%CD%\build on Windows) directory that might have been left over from a previously unfinished install or a previous version of pip (it now deletes the build directories after a successful install).

Java Convert GMT/UTC to Local time doesn't work as expected

I also recommend using Joda as mentioned before.

Solving your problem using standard Java Date objects only can be done as follows:

    // **** YOUR CODE **** BEGIN ****
    long ts = System.currentTimeMillis();
    Date localTime = new Date(ts);
    String format = "yyyy/MM/dd HH:mm:ss";
    SimpleDateFormat sdf = new SimpleDateFormat(format);

    // Convert Local Time to UTC (Works Fine)
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    Date gmtTime = new Date(sdf.format(localTime));
    System.out.println("Local:" + localTime.toString() + "," + localTime.getTime() + " --> UTC time:"
            + gmtTime.toString() + "," + gmtTime.getTime());

    // **** YOUR CODE **** END ****

    // Convert UTC to Local Time
    Date fromGmt = new Date(gmtTime.getTime() + TimeZone.getDefault().getOffset(localTime.getTime()));
    System.out.println("UTC time:" + gmtTime.toString() + "," + gmtTime.getTime() + " --> Local:"
            + fromGmt.toString() + "-" + fromGmt.getTime());

Output:

Local:Tue Oct 15 12:19:40 CEST 2013,1381832380522 --> UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000
UTC time:Tue Oct 15 10:19:40 CEST 2013,1381825180000 --> Local:Tue Oct 15 12:19:40 CEST 2013-1381832380000

How to convert SSH keypairs generated using PuTTYgen (Windows) into key-pairs used by ssh-agent and Keychain (Linux)

I think what TCSgrad was trying to ask (a few years ago) was how to make Linux behave like his Windows machine does. That is, there is an agent (pageant) which holds a decrypted copy of a private key so that the passphrase only needs to be put in once. Then, the ssh client, putty, can log in to machines where his public key is listed as "authorized" without a password prompt.

The analog for this is that Linux, acting as an ssh client, has an agent holding a decrypted private key so that when TCSgrad types "ssh host" the ssh command will get his private key and go without being prompted for a password. host would, of course, have to be holding the public key in ~/.ssh/authorized_keys.

The Linux analog to this scenario is accomplished using ssh-agent (the pageant analog) and ssh-add (the analog to adding a private key to pageant).

The method that worked for me was to use: $ ssh-agent $SHELL That $SHELL was the magic trick I needed to make the agent run and stay running. I found that somewhere on the 'net and it ended a few hours of beating my head against the wall.

Now we have the analog of pageant running, an agent with no keys loaded.

Typing $ ssh-add by itself will add (by default) the private keys listed in the default identity files in ~/.ssh .

A web article with a lot more details can be found here

How to specify jackson to only use fields - preferably globally

@since 2.10 version we can use JsonMapper.Builder and accepted answer could look like:

JsonMapper mapper = JsonMapper.builder()
    .visibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY)
    .visibility(PropertyAccessor.GETTER, JsonAutoDetect.Visibility.NONE)
    .visibility(PropertyAccessor.SETTER, JsonAutoDetect.Visibility.NONE)
    .visibility(PropertyAccessor.CREATOR, JsonAutoDetect.Visibility.NONE)
    .build();

Twitter Bootstrap 3 Sticky Footer

I'm a bit late on the subject but I came across this post as I've just been bitten by that question and finally found a really easy way to get over it, simply use a navbar with the navbar-fixed-bottom class enabled. For example:

<div class="navbar navbar-default navbar-fixed-bottom">
  <div class="container">
    <span class="navbar-text">
      Something useful
    </span>
  </div>
</div>

HTH

Autocompletion in Vim

For PHP, Padawan with Deoplete are great solutions for having a robust PHP autocompletion in Neovim. I tried a lot of things and Padawan work like a charm!

For Vim you can use Neocomplete instead of Deoplete.

I wrote an article how to make a Vim PHP IDE if somebody is interested. Of course Padawan is part of it.

PostgreSQL DISTINCT ON with different ORDER BY

Window function may solve that in one pass:

SELECT DISTINCT ON (address_id) 
   LAST_VALUE(purchases.address_id) OVER wnd AS address_id
FROM "purchases"
WHERE "purchases"."product_id" = 1
WINDOW wnd AS (
   PARTITION BY address_id ORDER BY purchases.purchased_at DESC
   ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING)

How to SELECT based on value of another SELECT

If you want to SELECT based on the value of another SELECT, then you probably want a "subselect":

http://beginner-sql-tutorial.com/sql-subquery.htm

For example, (from the link above):

  1. You want the first and last names from table "student_details" ...

  2. But you only want this information for those students in "science" class:

     SELECT id, first_name
     FROM student_details
     WHERE first_name IN (SELECT first_name
     FROM student_details
     WHERE subject= 'Science'); 
    

Frankly, I'm not sure this is what you're looking for or not ... but I hope it helps ... at least a little...

IMHO...

Batch Renaming of Files in a Directory

If you don't mind using regular expressions, then this function would give you much power in renaming files:

import re, glob, os

def renamer(files, pattern, replacement):
    for pathname in glob.glob(files):
        basename= os.path.basename(pathname)
        new_filename= re.sub(pattern, replacement, basename)
        if new_filename != basename:
            os.rename(
              pathname,
              os.path.join(os.path.dirname(pathname), new_filename))

So in your example, you could do (assuming it's the current directory where the files are):

renamer("*.doc", r"^(.*)\.doc$", r"new(\1).doc")

but you could also roll back to the initial filenames:

renamer("*.doc", r"^new\((.*)\)\.doc", r"\1.doc")

and more.

Maven not found in Mac OSX mavericks

Maven is not installed any more by default on Mac OS X 10.9. You need to install it yourself, for example using Homebrew.

The command to install Maven using Homebrew is brew install maven

How do I make Git use the editor of my choice for commits?

For emacs users

.emacs:

(server-start)

shellrc:

export EDITOR=emacsclient

Using "margin: 0 auto;" in Internet Explorer 8

As explained by buti-oxa this is a bug with the way IE8 handles replaced elements. If you don't want to add an explicit width to your button then you can change it to an inline-block and center align the contents:

<div style="height: 500px; width: 500px; background-color: Yellow; text-align: center;">
  <input type="submit" style="display: inline-block;" />
</div>

If you want this to work in older versions of Mozilla (including FF2) that don't support inline-block then you can add display: -moz-inline-stack; to the button.

Handling 'Sequence has no elements' Exception

Instead of .First() change it to .FirstOrDefault()

ByRef argument type mismatch in Excel VBA

I changed a few things to work with Option Explicit, and the code ran fine against a cell containing "abc.123", which returned "abc.12,". There were no compile errors.

Option Explicit ' This is new

Public Function ProcessString(input_string As String) As String
    ' The temp string used throughout the function
    Dim temp_string As String
    Dim i As Integer ' This is new
    Dim return_string As String ' This is new
    For i = 1 To Len(input_string)
        temp_string = Mid(input_string, i, 1)
        If temp_string Like "[A-Z, a-z, 0-9, :, -]" Then
            return_string = return_string & temp_string
        End If
    Next i
    return_string = Mid(return_string, 1, (Len(return_string) - 1))
    ProcessString = return_string & ", "
End Function

I'll suggest you post more of your relevant code (that calls this function). You've stated that last_name is a String, but it appears that may not be the case. Step through your code line by line and ensure that this is actually the case.

Add item to Listview control

  • Very Simple

    private void button1_Click(object sender, EventArgs e)
    {
        ListViewItem item = new ListViewItem();
        item.SubItems.Add(textBox2.Text);
        item.SubItems.Add(textBox3.Text);
        item.SubItems.Add(textBox4.Text);
        listView1.Items.Add(item);
        textBox2.Clear();
        textBox3.Clear();
        textBox4.Clear();
    }
    
  • You can also Do this stuff...

        ListViewItem item = new ListViewItem();
        item.SubItems.Add("Santosh");
        item.SubItems.Add("26");
        item.SubItems.Add("India");
    

Go to "next" iteration in JavaScript forEach loop

just return true inside your if statement

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {

      return true;

    // Go to "next" iteration. Or "continue" to next iteration...
  }

  console.log(elem);
});

Immutable array in Java

As of Java 9 you can use List.of(...), JavaDoc.

This method returns an immutable List and is very efficient.

Where is the visual studio HTML Designer?

Another way of setting the default to the HTML web forms editor is:

  1. At the top menu in Visual Studio go to File > New > File
  2. Select HTML Page
  3. In the lower right corner of the New File dialog on the Open button there is a down arrow
  4. Click it and you should see an option Open With
  5. Select HTML (Web Forms) Editor
  6. Click Set as Default
  7. Press OK

Screenshot showing how to get to the "Open With" dialog box when creating a new file.

jQuery dialog popup

Your problem is on the call for the dialog

If you dont initialize the dialog, you don't have to pass "open" for it to show:

$("#dialog").dialog();

Also, this code needs to be on a $(document).ready(); function or be below the elements for it to work.

How to install a certificate in Xcode (preparing for app store submission)

These instructions are for XCode 6.4 (since I couldn't find the update for the recent versions even this was a bit outdated)

a) Part on the developers' website:

Sign in into: https://developer.apple.com/

Member Center

Certificates, Identifiers & Profiles

Certificates>All

Click "+" to add, and then follow the instructions. You will need to open "Keychain Access.app", there under "Keychain Access" menu > "Certificate Assistant>", choose "Request a Certificate From a Certificate Authority" etc.

b) XCode part:

After all, you need to go to XCode, and open XCode>Preferences..., choose your Apple ID > View Details... > click that rounded arrow to update as well as "+" to check for iOS Distribution or iOS Developer Signing Identities.

Fastest way to count number of occurrences in a Python list

By the use of Counter dictionary counting the occurrences of all element as well as most common element in python list with its occurrence value in most efficient way.

If our python list is:-

l=['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']

To find occurrence of every items in the python list use following:-

\>>from collections import Counter

\>>c=Counter(l)

\>>print c

Counter({'1': 6, '2': 4, '7': 3, '10': 2})

To find most/highest occurrence of items in the python list:-

\>>k=c.most_common()

\>>k

[('1', 6), ('2', 4), ('7', 3), ('10', 2)]

For Highest one:-

\>>k[0][1]

6

For the item just use k[0][0]

\>>k[0][0]

'1'

For nth highest item and its no of occurrence in the list use follow:-

**for n=2 **

\>>print k[n-1][0] # For item

2

\>>print k[n-1][1] # For value

4

an htop-like tool to display disk activity in linux

It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

You must add this code in global.aspx:

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

I tried most of the above answers and they didn't work. For some reason just closing and reopening VS fixed the problem for me.

Equivalent of *Nix 'which' command in PowerShell?

You can install the which command from https://goprogram.co.uk/software/commands, along with all of the other UNIX commands.

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

Use the -ss option:

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

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

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

-ss position (input/output)

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

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

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

What should every programmer know about security?

Just wanted to share this for web developers:

security-guide-for-developers
https://github.com/FallibleInc/security-guide-for-developers

Set content of HTML <span> with Javascript

To do it without using a JavaScript library such as jQuery, you'd do it like this:

var span = document.getElementById("myspan"),
    text = document.createTextNode(''+intValue);
span.innerHTML = ''; // clear existing
span.appendChild(text);

If you do want to use jQuery, it's just this:

$("#myspan").text(''+intValue);

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

Generate ER Diagram from existing MySQL database, created for CakePHP

CakePHP was intended to be used as Ruby on Rails framework clone, done in PHP, so any reverse-engineering of underlying database is pointless. EER diagrams should be reverse-engineered from Model layer.

Such tools do exist for Ruby Here you can see Redmine database EER diagrams reverse-engineered from Models. Not from database. http://redminecookbook.com/Redmine-erd-diagrams.html

With following tools: http://rails-erd.rubyforge.org/ http://railroady.prestonlee.com/

Docker: Multiple Dockerfiles in project

In Intellij, I simple changed the name of the docker files to *.Dockerfile, and associated the file type *.Dockerfile to docker syntax.

Is there a splice method for strings?

I would like to offer a simpler alternative to both the Kumar/Cody and the Louis methods. On all the tests I ran, it performs as fast as the Louis method (see fiddle tests for benchmarks).

String.prototype.splice = function(startIndex,length,insertString){
    return this.substring(0,startIndex) + insertString + this.substring(startIndex + length);
};

You can use it like this:

var creditCardNumber = "5500000000000004";
var cardSuffix = creditCardNumber.splice(0,12,'****');
console.log(cardSuffix);  // output: ****0004

See Test Results: https://jsfiddle.net/0quz9q9m/5/

File path to resource in our war/WEB-INF folder?

Now with Java EE 7 you can find the resource more easily with

InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");

https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--

Very simple C# CSV reader

This is what I used in a project, parses a single line of data.

    private string[] csvParser(string csv, char separator = ',')
    {
        List <string> = new <string>();
        string[] temp = csv.Split(separator);
        int counter = 0;
        string data = string.Empty;
        while (counter < temp.Length)
        {
            data = temp[counter].Trim();
            if (data.Trim().StartsWith("\""))
            {
                bool isLast = false;
                while (!isLast && counter < temp.Length)
                {
                    data += separator.ToString() + temp[counter + 1];
                    counter++;
                    isLast = (temp[counter].Trim().EndsWith("\""));
                }
            }
            parsed.Add(data);
            counter++;
        }

        return parsed.ToArray();

    }

http://zamirsblog.blogspot.com/2013/09/c-csv-parser-csvparser.html

TypeScript Objects as Dictionary types as in C#

In newer versions of typescript you can use:

type Customers = Record<string, Customer>

In older versions you can use:

var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer

You can also make an interface if you don't want to type that whole type annotation out every time:

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

How to check user is "logged in"?

The simplest way:

if (Request.IsAuthenticated) ...

Where is virtualenvwrapper.sh after pip install?

Have you installed it using sudo? Was the error in my case.

Where do I call the BatchNormalization function in Keras?

Batch Normalization is used to normalize the input layer as well as hidden layers by adjusting mean and scaling of the activations. Because of this normalizing effect with additional layer in deep neural networks, the network can use higher learning rate without vanishing or exploding gradients. Furthermore, batch normalization regularizes the network such that it is easier to generalize, and it is thus unnecessary to use dropout to mitigate overfitting.

Right after calculating the linear function using say, the Dense() or Conv2D() in Keras, we use BatchNormalization() which calculates the linear function in a layer and then we add the non-linearity to the layer using Activation().

from keras.layers.normalization import BatchNormalization
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('tanh'))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Activation('softmax'))

sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, 
validation_split=0.2, verbose = 2)

How is Batch Normalization applied?

Suppose we have input a[l-1] to a layer l. Also we have weights W[l] and bias unit b[l] for the layer l. Let a[l] be the activation vector calculated(i.e. after adding the non-linearity) for the layer l and z[l] be the vector before adding non-linearity

  1. Using a[l-1] and W[l] we can calculate z[l] for the layer l
  2. Usually in feed-forward propagation we will add bias unit to the z[l] at this stage like this z[l]+b[l], but in Batch Normalization this step of addition of b[l] is not required and no b[l] parameter is used.
  3. Calculate z[l] means and subtract it from each element
  4. Divide (z[l] - mean) using standard deviation. Call it Z_temp[l]
  5. Now define new parameters ? and ß that will change the scale of the hidden layer as follows:

    z_norm[l] = ?.Z_temp[l] + ß

In this code excerpt, the Dense() takes the a[l-1], uses W[l] and calculates z[l]. Then the immediate BatchNormalization() will perform the above steps to give z_norm[l]. And then the immediate Activation() will calculate tanh(z_norm[l]) to give a[l] i.e.

a[l] = tanh(z_norm[l])

Warning: comparison with string literals results in unspecified behaviour

This an old question, but I have had to explain it to someone recently and I thought recording the answer here would be helpful at least in understanding how C works.

String literals like

"a"

or

"This is a string"

are put in the text or data segments of your program.

A string in C is actually a pointer to a char, and the string is understood to be the subsequent chars in memory up until a NUL char is encountered. That is, C doesn't really know about strings.

So if I have

char *s1 = "This is a string";

then s1 is a pointer to the first byte of the string.

Now, if I have

char *s2 = "This is a string";

this is also a pointer to the same first byte of that string in the text or data segment of the program.

But if I have

char *s3 = malloc( 17 );
strcpy(s3, "This is a string");

then s3 is a pointer to another place in memory into which I copy all the bytes of the other strings.

Illustrative examples:

Although, as your compiler rightly points out, you shouldn't do this, the following will evaluate to true:

s1 == s2 // True: we are comparing two pointers that contain the same address

but the following will evaluate to false

s1 == s3 // False: Comparing two pointers that don't hold the same address.

And although it might be tempting to have something like this:

struct Vehicle{
    char *type;
    // other stuff
}

if( type == "Car" )
   //blah1
else if( type == "Motorcycle )
   //blah2

You shouldn't do it because it's not something that is guarantied to work. Even if you know that type will always be set using a string literal.

I have tested it and it works. If I do

A.type = "Car";

then blah1 gets executed and similarly for "Motorcycle". And you'd be able to do things like

if( A.type == B.type )

but this is just terrible. I'm writing about it because I think it's interesting to know why it works, and it helps understand why you shouldn't do it.

Solutions:

In your case, what you want to do is use strcmp(a,b) == 0 to replace a == b

In the case of my example, you should use an enum.

enum type {CAR = 0, MOTORCYCLE = 1}

The preceding thing with string was useful because you could print the type, so you might have an array like this

char *types[] = {"Car", "Motorcycle"};

And now that I think about it, this is error prone since one must be careful to maintain the same order in the types array.

Therefore it might be better to do

char *getTypeString(int type)
{
    switch(type)
    case CAR: return "Car";
    case MOTORCYCLE: return "Motorcycle"
    default: return NULL;
}

How to connect to SQL Server from command prompt with Windows authentication

Try This :

--Default Instance

SQLCMD -S SERVERNAME -E

--OR
--Named Instance

SQLCMD -S SERVERNAME\INSTANCENAME -E

--OR

SQLCMD -S SERVERNAME\INSTANCENAME,1919 -E

More details can be found here

How to format a number 0..9 to display with 2 digits (it's NOT a date)

I know that is late to respond, but there are a basic way to do it, with no libraries. If your number is less than 100, then:

(number/100).toFixed(2).toString().slice(2);

How to open a web page automatically in full screen mode

window.onload = function() {
    var el = document.documentElement,
        rfs = el.requestFullScreen
        || el.webkitRequestFullScreen
        || el.mozRequestFullScreen;
    rfs.call(el);
};

Convert string with commas to array

You can use javascript Spread Syntax to convert string to an array. In the solution below, I remove the comma then convert the string to an array.

var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

HTML character codes for this ? or this ?

You don't need to use character codes; just use UTF-8 and put them in literally; like so:

??

If you absolutely must use the entites, they are &#x25b2; and &#x25bc;, respectively.

What is the difference between an int and a long in C++?

The C++ Standard says it like this :

3.9.1, §2 :

There are five signed integer types : "signed char", "short int", "int", "long int", and "long long int". In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment (44); the other signed integer types are provided to meet special needs.

(44) that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header <climits>.

The conclusion : it depends on which architecture you're working on. Any other assumption is false.

In Java 8 how do I transform a Map<K,V> to another Map<K,V> using a lambda?

Keep it Simple and use Java 8:-

 Map<String, AccountGroupMappingModel> mapAccountGroup=CustomerDAO.getAccountGroupMapping();
 Map<String, AccountGroupMappingModel> mapH2ToBydAccountGroups = 
              mapAccountGroup.entrySet().stream()
                         .collect(Collectors.toMap(e->e.getValue().getH2AccountGroup(),
                                                   e ->e.getValue())
                                  );

Command to delete all pods in all kubernetes namespaces

K8s completely works on the fundamental of the namespace. if you like to release all the resource related to specified namespace.

you can use the below mentioned :

kubectl delete namespace k8sdemo-app

How can I detect the touch event of an UIImageView?

You can also add a UIGestureRecognizer. It does not require you to add an additional element in your view hierarchy, but still provides you will all the nicely written code for handling touch events with a fairly simple interface:

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
                                            initWithTarget:self action:@selector(handleSwipe:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [imgView_ addGestureRecognizer:swipeRight];        
    [swipeRight release];
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
                                            initWithTarget:self action:@selector(handleSwipe:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [imgView_ addGestureRecognizer:swipeLeft];
    [swipeLeft release];

jquery can't get data attribute value

You can change the selector and data attributes as you wish!

 <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

spring PropertyPlaceholderConfigurer and context:property-placeholder

<context:property-placeholder ... /> is the XML equivalent to the PropertyPlaceholderConfigurer. So, prefer that. The <util:properties/> simply factories a java.util.Properties instance that you can inject.

In Spring 3.1 (not 3.0...) you can do something like this:

@Configuration
@PropertySource("/foo/bar/services.properties")
public class ServiceConfiguration { 

    @Autowired Environment environment; 

    @Bean public javax.sql.DataSource dataSource( ){ 
        String user = this.environment.getProperty("ds.user");
        ...
    } 
}

In Spring 3.0, you can "access" properties defined using the PropertyPlaceHolderConfigurer mechanism using the SpEl annotations:

@Value("${ds.user}") private String user;

If you want to remove the XML all together, simply register the PropertyPlaceholderConfigurer manually using Java configuration. I prefer the 3.1 approach. But, if youre using the Spring 3.0 approach (since 3.1's not GA yet...), you can now define the above XML like this:

@Configuration 
public class MySpring3Configuration {     
        @Bean 
        public static PropertyPlaceholderConfigurer configurer() { 
             PropertyPlaceholderConfigurer ppc = ...
             ppc.setLocations(...);
             return ppc; 
        } 

        @Bean 
        public class DataSource dataSource(
                @Value("${ds.user}") String user, 
                @Value("${ds.pw}") String pw, 
                ...) { 
            DataSource ds = ...
            ds.setUser(user);
            ds.setPassword(pw);                        
            ...
            return ds;
        }
}

Note that the PPC is defined using a static bean definition method. This is required to make sure the bean is registered early, because the PPC is a BeanFactoryPostProcessor - it can influence the registration of the beans themselves in the context, so it necessarily has to be registered before everything else.

How can I measure the similarity between two images?

Beyond Compare has pixel-by-pixel comparison for images, e.g.,

enter image description here

Listing all permutations of a string/integer

class Permutation
{
    public static List<string> Permutate(string seed, List<string> lstsList)
    {
        loopCounter = 0;
        // string s="\w{0,2}";
        var lstStrs = PermuateRecursive(seed);

        Trace.WriteLine("Loop counter :" + loopCounter);
        return lstStrs;
    }

    // Recursive function to find permutation
    private static List<string> PermuateRecursive(string seed)
    {
        List<string> lstStrs = new List<string>();

        if (seed.Length > 2)
        {
            for (int i = 0; i < seed.Length; i++)
            {
                str = Swap(seed, 0, i);

                PermuateRecursive(str.Substring(1, str.Length - 1)).ForEach(
                    s =>
                    {
                        lstStrs.Add(str[0] + s);
                        loopCounter++;
                    });
                ;
            }
        }
        else
        {
            lstStrs.Add(seed);
            lstStrs.Add(Swap(seed, 0, 1));
        }
        return lstStrs;
    }
    //Loop counter variable to count total number of loop execution in various functions
    private static int loopCounter = 0;

    //Non recursive  version of permuation function
    public static List<string> Permutate(string seed)
    {
        loopCounter = 0;
        List<string> strList = new List<string>();
        strList.Add(seed);
        for (int i = 0; i < seed.Length; i++)
        {
            int count = strList.Count;
            for (int j = i + 1; j < seed.Length; j++)
            {
                for (int k = 0; k < count; k++)
                {
                    strList.Add(Swap(strList[k], i, j));
                    loopCounter++;
                }
            }
        }
        Trace.WriteLine("Loop counter :" + loopCounter);
        return strList;
    }

    private static string Swap(string seed, int p, int p2)
    {
        Char[] chars = seed.ToCharArray();
        char temp = chars[p2];
        chars[p2] = chars[p];
        chars[p] = temp;
        return new string(chars);
    }
}

How do you detect where two line segments intersect?

A C++ program to check if two given line segments intersect

#include <iostream>
using namespace std;

struct Point
{
    int x;
    int y;
};

// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
bool onSegment(Point p, Point q, Point r)
{
    if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) &&
        q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y))
       return true;

    return false;
}

// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
int orientation(Point p, Point q, Point r)
{
    // See 10th slides from following link for derivation of the formula
    // http://www.dcs.gla.ac.uk/~pat/52233/slides/Geometry1x1.pdf
    int val = (q.y - p.y) * (r.x - q.x) -
              (q.x - p.x) * (r.y - q.y);

    if (val == 0) return 0;  // colinear

    return (val > 0)? 1: 2; // clock or counterclock wise
}

// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
bool doIntersect(Point p1, Point q1, Point p2, Point q2)
{
    // Find the four orientations needed for general and
    // special cases
    int o1 = orientation(p1, q1, p2);
    int o2 = orientation(p1, q1, q2);
    int o3 = orientation(p2, q2, p1);
    int o4 = orientation(p2, q2, q1);

    // General case
    if (o1 != o2 && o3 != o4)
        return true;

    // Special Cases
    // p1, q1 and p2 are colinear and p2 lies on segment p1q1
    if (o1 == 0 && onSegment(p1, p2, q1)) return true;

    // p1, q1 and p2 are colinear and q2 lies on segment p1q1
    if (o2 == 0 && onSegment(p1, q2, q1)) return true;

    // p2, q2 and p1 are colinear and p1 lies on segment p2q2
    if (o3 == 0 && onSegment(p2, p1, q2)) return true;

     // p2, q2 and q1 are colinear and q1 lies on segment p2q2
    if (o4 == 0 && onSegment(p2, q1, q2)) return true;

    return false; // Doesn't fall in any of the above cases
}

// Driver program to test above functions
int main()
{
    struct Point p1 = {1, 1}, q1 = {10, 1};
    struct Point p2 = {1, 2}, q2 = {10, 2};

    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {10, 0}, q1 = {0, 10};
    p2 = {0, 0}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    p1 = {-5, -5}, q1 = {0, 0};
    p2 = {1, 1}, q2 = {10, 10};
    doIntersect(p1, q1, p2, q2)? cout << "Yes\n": cout << "No\n";

    return 0;
}

milliseconds to time in javascript

var 
         /**
         * Parses time in milliseconds to time structure
         * @param {Number} ms
         * @returns {Object} timeStruct
         * @return {Integer} timeStruct.d days
         * @return  {Integer} timeStruct.h hours
         * @return  {Integer} timeStruct.m minutes
         * @return  {Integer} timeStruct.s seconds
         */
        millisecToTimeStruct = function (ms) {
            var d, h, m, s;
            if (isNaN(ms)) {
                return {};
            }
            d = ms / (1000 * 60 * 60 * 24);
            h = (d - ~~d) * 24;
            m = (h - ~~h) * 60;
            s = (m - ~~m) * 60;
            return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
        },

        toFormattedStr = function(tStruct){
           var res = '';
           if (typeof tStruct === 'object'){
               res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
           }
           return res;
        };

// client code:
var
        ms = new Date().getTime(),
        timeStruct = millisecToTimeStruct(ms),
        formattedString = toFormattedStr(timeStruct);
alert(formattedString);

MySQL add days to a date

update tablename set coldate=DATE_ADD(coldate, INTERVAL 2 DAY)

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

How to define a variable in a Dockerfile?

You can use ARG variable defaultValue and during the run command you can even update this value using --build-arg variable=value. To use these variables in the docker file you can refer them as $variable in run command.

Note: These variables would be available for Linux commands like RUN echo $variable and they wouldn't persist in the image.

Div with horizontal scrolling only

I couldn't get the selected answer to work but after a bit of research, I found that the horizontal scrolling div must have white-space: nowrap in the css.

Here's complete working code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Something</title>
    <style type="text/css">
        #scrolly{
            width: 1000px;
            height: 190px;
            overflow: auto;
            overflow-y: hidden;
            margin: 0 auto;
            white-space: nowrap
        }

        img{
            width: 300px;
            height: 150px;
            margin: 20px 10px;
            display: inline;
        }
    </style>
</head>
<body>
    <div id='scrolly'>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
        <img src='img/car.jpg'></img>
    </div>
</body>
</html>

Eclipse: The declared package does not match the expected package

Just go into the build path and change the source path to be src/prefix1 instead of src.

It may be easiest to right-click on the src directory and select "Build Path / Remove from build path", then find the src/prefix1 directory, right-click it and select "Build Path / Use as source folder".

Search a text file and print related lines in Python?

with open('file.txt', 'r') as searchfile:
    for line in searchfile:
        if 'searchphrase' in line:
            print line

With apologies to senderle who I blatantly copied.

Can scripts be inserted with innerHTML?

Here a solution that does not use eval, and works with scripts, linked scripts , as well as with modules.

The function accepts 3 parameters :

  • html : String with the html code to insert
  • dest : reference to the target element
  • append : boolean flag to enable appending at the end of the target element html
function insertHTML(html, dest, append=false){
    // if no append is requested, clear the target element
    if(!append) dest.innerHTML = '';
    // create a temporary container and insert provided HTML code
    let container = document.createElement('div');
    container.innerHTML = html;
    // cache a reference to all the scripts in the container
    let scripts = container.querySelectorAll('script');
    // get all child elements and clone them in the target element
    let nodes = container.childNodes;
    for( let i=0; i< nodes.length; i++) dest.appendChild( nodes[i].cloneNode(true) );
    // force the found scripts to execute...
    for( let i=0; i< scripts.length; i++){
        let script = document.createElement('script');
        script.type = scripts[i].type || 'text/javascript';
        if( scripts[i].hasAttribute('src') ) script.src = scripts[i].src;
        script.innerHTML = scripts[i].innerHTML;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    // done!
    return true;
}

Publish to IIS, setting Environment Variable

I have modified the answer which @Christian Del Bianco is given. I changed the process for .net core 2 and upper as project.json file now absolute.

  1. First, create appsettings.json file in root directory. with the content

      {
         // Possible string values reported below. When empty it use ENV 
            variable value or Visual Studio setting.
         // - Production
         // - Staging
         // - Test
        // - Development
       "ASPNETCORE_ENVIRONMENT": "Development"
     }
    
  2. Then create another two setting file appsettings.Development.json and appsettings.Production.json with the necessary configuration.

  3. Add necessary code to set up the environment to Program.cs file.

    public class Program
    {
    public static void Main(string[] args)
    {
        var logger = NLogBuilder.ConfigureNLog("nlog.config").GetCurrentClassLogger();
    
      ***var currentDirectoryPath = Directory.GetCurrentDirectory();
        var envSettingsPath = Path.Combine(currentDirectoryPath, "envsettings.json");
        var envSettings = JObject.Parse(File.ReadAllText(envSettingsPath));
        var enviromentValue = envSettings["ASPNETCORE_ENVIRONMENT"].ToString();***
    
        try
        {
            ***CreateWebHostBuilder(args, enviromentValue).Build().Run();***
        }
        catch (Exception ex)
        {
            //NLog: catch setup errors
            logger.Error(ex, "Stopped program because of setup related exception");
            throw;
        }
        finally
        {
            NLog.LogManager.Shutdown();
        }
    }
    
    public static IWebHostBuilder CreateWebHostBuilder(string[] args, string enviromentValue) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .ConfigureLogging(logging =>
            {
                logging.ClearProviders();
                logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
            })
            .UseNLog()
            ***.UseEnvironment(enviromentValue);***
    

    }

  4. Add the envsettings.json to your .csproj file for copy to published directory.

       <ItemGroup>
            <None Include="envsettings.json" CopyToPublishDirectory="Always" />
        </ItemGroup>
    
  5. Now just change the ASPNETCORE_ENVIRONMENT as you want in envsettings.json file and published.

document.getElementById(id).focus() is not working for firefox or chrome

Your focus is working before return false; ,After that is not working. You try this solution. Control after return false;

Put code in function:

function  validateNumber(){
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        return false; 
    }else{
        return true;
    }
}

Caller function:

function submitButton(){
        if(!validateNumber()){
            document.getElementById('mobileno').focus();
            return false;
        }
}

HTML:

Input:<input type="text" id="mobileno">
<button onclick="submitButton();" >Submit</button>

Java array assignment (multiple values)

int a[] = { 2, 6, 8, 5, 4, 3 }; 
int b[] = { 2, 3, 4, 7 };

if you take float number then you take float and it's your choice

this is very good way to show array elements.