Programs & Examples On #Higher order functions

Higher-order functions are functions which either take functions as arguments or return them as output (or both). They are a cornerstone of functional programming.

How to use ES6 Fat Arrow to .filter() an array of objects

It appears I cannot use an if statement.

Arrow functions either allow to use an expression or a block as their body. Passing an expression

foo => bar

is equivalent to the following block

foo => { return bar; }

However,

if (person.age > 18) person

is not an expression, if is a statement. Hence you would have to use a block, if you wanted to use if in an arrow function:

foo => {  if (person.age > 18) return person; }

While that technically solves the problem, this a confusing use of .filter, because it suggests that you have to return the value that should be contained in the output array. However, the callback passed to .filter should return a Boolean, i.e. true or false, indicating whether the element should be included in the new array or not.

So all you need is

family.filter(person => person.age > 18);

In ES5:

family.filter(function (person) {
  return person.age > 18;
});

Run-time error '1004' - Method 'Range' of object'_Global' failed

Your range value is incorrect. You are referencing cell "75" which does not exist. You might want to use the R1C1 notation to use numeric columns easily without needing to convert to letters.

http://www.bettersolutions.com/excel/EED883/YI416010881.htm

Range("R" & DataImportRow & "C" & DataImportColumn).Offset(0, 2).Value = iFirstCustomerSales

This should fix your problem.

Sieve of Eratosthenes - Finding Primes Python

not sure if my code is efficeient, anyone care to comment?

from math import isqrt

def isPrime(n):
    if n >= 2: # cheating the 2, is 2 even prime?
        for i in range(3, int(n / 2 + 1),2): # dont waste time with even numbers
            if n % i == 0:
                return False
    return True

def primesTo(n): 
    x = [2] if n >= 2 else [] # cheat the only even prime
    if n >= 2:
        for i in range(3, n + 1,2): # dont waste time with even numbers
            if isPrime(i):
                x.append(i)  
    return x

def primes2(n): # trying to do this using set methods and the "Sieve of Eratosthenes"
    base = {2} # again cheating the 2
    base.update(set(range(3, n + 1, 2))) # build the base of odd numbers
    for i in range(3, isqrt(n) + 1, 2): # apply the sieve
        base.difference_update(set(range(2 * i, n + 1 , i)))
    return list(base)

print(primesTo(10000)) # 2 different methods for comparison
print(primes2(10000))

IOPub data rate exceeded in Jupyter notebook (when viewing image)

By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10' in Anaconda PowerShell or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.

Active Directory LDAP Query by sAMAccountName and Domain

"Domain" is not a property of an LDAP object. It is more like the name of the database the object is stored in.

So you have to connect to the right database (in LDAP terms: "bind to the domain/directory server") in order to perform a search in that database.

Once you bound successfully, your query in it's current shape is all you need.

BTW: Choosing "ObjectCategory=Person" over "ObjectClass=user" was a good decision. In AD, the former is an "indexed property" with excellent performance, the latter is not indexed and a tad slower.

SQL Server: Best way to concatenate multiple columns?

SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
       INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995

Why is my xlabel cut off in my matplotlib plot?

plt.autoscale() worked for me.

How to remove .html from URL?

To remove the .html extension from your urls, you can use the following code in root/htaccess :

RewriteEngine on


RewriteCond %{THE_REQUEST} /([^.]+)\.html [NC]
RewriteRule ^ /%1 [NC,L,R]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^ %{REQUEST_URI}.html [NC,L]

NOTE: If you want to remove any other extension, for example to remove the .php extension, just replace the html everywhere with php in the code above.

How do I detect a click outside an element?

I have an application that works similarly to Eran's example, except I attach the click event to the body when I open the menu... Kinda like this:

$('#menucontainer').click(function(event) {
  $('html').one('click',function() {
    // Hide the menus
  });

  event.stopPropagation();
});

More information on jQuery's one() function

JAXB: how to marshall map into <key>value</key>

(Sorry, can't add comments)

In Blaise's answer above, if you change:

@XmlJavaTypeAdapter(MapAdapter.class)
public Map<String, String> getMapProperty() {
    return mapProperty;
}

to:

@XmlJavaTypeAdapter(MapAdapter.class)
@XmlPath(".") // <<-- add this
public Map<String, String> getMapProperty() {
    return mapProperty;
}

then this should get rid of the <mapProperty> tag, and so give you:

<?xml version="1.0" encoding="UTF-8"?>
<root>
    <map>
        <key>value</key>
        <key2>value2</key2>
    </map>
</root>

ALTERNATIVELY:

You can also change it to:

@XmlJavaTypeAdapter(MapAdapter.class)
@XmlAnyElement // <<-- add this
public Map<String, String> getMapProperty() {
    return mapProperty;
}

and then you can get rid of AdaptedMap altogether, and just change MapAdapter to marshall to a Document object directly. I've only tested this with marshalling, so there may be unmarshalling issues.

I'll try and find the time to knock up a full example of this, and edit this post accordingly.

What is the difference between aggregation, composition and dependency?

Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.

Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don't exist separate to a House.

The above two are forms of containment (hence the parent-child relationships).

Dependency is a weaker form of relationship and in code terms indicates that a class uses another by parameter or return type.

Dependency is a form of association.

Could not autowire field:RestTemplate in Spring boot application

Please make sure two things:

1- Use @Bean annotation with the method.

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}

2- Scope of this method should be public not private.

Complete Example -

@Service
public class MakeHttpsCallImpl implements MakeHttpsCall {

@Autowired
private RestTemplate restTemplate;

@Override
public String makeHttpsCall() {
    return restTemplate.getForObject("https://localhost:8085/onewayssl/v1/test",String.class);
}

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder){
    return builder.build();
}
}

How to initialize an array in Kotlin with values?

In this way, you can initialize the int array in koltin.

 val values: IntArray = intArrayOf(1, 2, 3, 4, 5,6,7)

Difference between 3NF and BCNF in simple terms (must be able to explain to an 8-year old)

The subtle difference is that 3NF makes a distinction between key and non-key attributes (also called non-prime attributes) whereas BCNF does not.

This is best explained using Zaniolo's definition of 3NF, which is equivalent to Codd's:

A relation, R, is in 3NF iff for every nontrivial FD (X->A) satisfied by R at least ONE of the following conditions is true:

(a) X is a superkey for R, or

(b) A is a key attribute for R

BCNF requires (a) but doesn't treat (b) as a special case of its own. In other words BCNF requires that every nontrivial determinant is a superkey even its dependent attributes happen to be part of a key.

A relation, R, is in BCNF iff for every nontrivial FD (X->A) satisfied by R the following condition is true:

(a) X is a superkey for R

BCNF is therefore more strict.

The difference is so subtle that what many people informally describe as 3NF is actually BCNF. For example, you stated here that 3NF means "data depends on the key[s]... and nothing but the key[s]", but that is really an informal description of BCNF and not 3NF. 3NF could more accurately be described as "non-key data depends on the keys... and nothing but the keys".

You also stated:

the 3NF quote explicitly says "nothing but the key" meaning that all attributes depend solely on the primary key.

That's an oversimplification. 3NF and BCNF and all the Normal Forms are concerned with all candidate keys and/or superkeys, not just one "primary" key.

Asp Net Web API 2.1 get client IP address

I think this is the most clear solution, using an extension method:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}

So just use it like:

var ipAddress = request.GetClientIpAddress();

We use this in our projects.

Source/Reference: Retrieving the client’s IP address in ASP.NET Web API

How to use makefiles in Visual Studio?

The VS equivalent of a makefile is a "Solution" (over-simplified, I know).

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

jquery Ajax call - data parameters are not being passed to MVC Controller action

  var json = {"ListID" : "1", "ItemName":"test"};
    $.ajax({
            url: url,
            type: 'POST',        
            data: username, 
            cache:false,
            beforeSend: function(xhr) {  
                xhr.setRequestHeader("Accept", "application/json");  
                xhr.setRequestHeader("Content-Type", "application/json");  
            },       
            success:function(response){
             console.log("Success")
            },
              error : function(xhr, status, error) {
            console.log("error")
            }
);

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

Failed to Connect to MySQL at localhost:3306 with user root

Go to >system preferences >mysql >initialize database

-Change password -Click use legacy password -Click start sql server

it should work now

Passing a variable to a powershell script via command line

Make this in your test.ps1, at the first line

param(
[string]$a
)

Write-Host $a

Then you can call it with

./Test.ps1 "Here is your text"

Found here (English)

No templates in Visual Studio 2017

In my case, I had all of the required features, but I had installed the Team Explorer version (accidentally used the wrong installer) before installing Professional.

When running the Team Explorer version, only the Blank Solution option was available.

The Team Explorer EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\TeamExplorer\Common7\IDE\devenv.exe"

Once I launched the correct EXE, Visual Studio started working as expected.

The Professional EXE was located in: "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe"


This solved my issue, and the reason was I had enterprise edition previously installed and then uninstalled and installed the professional edition. Team Explorer was not modified later when I moved to professional from enterprise edition.

ExtJs Gridpanel store refresh

I had a similiar problem. All I needed to do was type store.load(); in the delete handler. There was no need to subsequently type grid.getView().refresh();.

Instead of all this you can also type store.remove(record) in the delete handler; - this ensures that the deleted record no longer shows on the grid.

Get $_POST from multiple checkboxes

It's pretty simple. Pay attention and you'll get it right away! :)

You will create a html array, which will be then sent to php array. Your html code will look like this:

<input type="checkbox" name="check_list[1]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[2]" alt="Checkbox" value="checked">
<input type="checkbox" name="check_list[3]" alt="Checkbox" value="checked">

Where [1] [2] [3] are the IDs of your messages, meaning that you will echo your $row['Report ID'] in their place.

Then, when you submit the form, your PHP array will look like this:

print_r($check_list)

[1] => checked [3] => checked

Depending on which were checked and which were not.

I'm sure you can continue from this point forward.

What is the function of the push / pop instructions used on registers in x86 assembly?

Pushing and popping registers are behind the scenes equivalent to this:

push reg   <= same as =>      sub  $8,%rsp        # subtract 8 from rsp
                              mov  reg,(%rsp)     # store, using rsp as the address

pop  reg    <= same as=>      mov  (%rsp),reg     # load, using rsp as the address
                              add  $8,%rsp        # add 8 to the rsp

Note this is x86-64 At&t syntax.

Used as a pair, this lets you save a register on the stack and restore it later. There are other uses, too.

Concatenating null strings in Java

Why must it work?

The JLS 5, Section 15.18.1.1 JLS 8 § 15.18.1 "String Concatenation Operator +", leading to JLS 8, § 5.1.11 "String Conversion", requires this operation to succeed without failure:

...Now only reference values need to be considered. If the reference is null, it is converted to the string "null" (four ASCII characters n, u, l, l). Otherwise, the conversion is performed as if by an invocation of the toString method of the referenced object with no arguments; but if the result of invoking the toString method is null, then the string "null" is used instead.

How does it work?

Let's look at the bytecode! The compiler takes your code:

String s = null;
s = s + "hello";
System.out.println(s); // prints "nullhello"

and compiles it into bytecode as if you had instead written this:

String s = null;
s = new StringBuilder(String.valueOf(s)).append("hello").toString();
System.out.println(s); // prints "nullhello"

(You can do so yourself by using javap -c)

The append methods of StringBuilder all handle null just fine. In this case because null is the first argument, String.valueOf() is invoked instead since StringBuilder does not have a constructor that takes any arbitrary reference type.

If you were to have done s = "hello" + s instead, the equivalent code would be:

s = new StringBuilder("hello").append(s).toString();

where in this case the append method takes the null and then delegates it to String.valueOf().

Note: String concatenation is actually one of the rare places where the compiler gets to decide which optimization(s) to perform. As such, the "exact equivalent" code may differ from compiler to compiler. This optimization is allowed by JLS, Section 15.18.1.2:

To increase the performance of repeated string concatenation, a Java compiler may use the StringBuffer class or a similar technique to reduce the number of intermediate String objects that are created by evaluation of an expression.

The compiler I used to determine the "equivalent code" above was Eclipse's compiler, ecj.

Could not autowire field in spring. why?

I was getting this same error and searching for it led me here. My fix appeared to be simply to add @Component annotation to the implementation of the abstract service.

In this case, that would look like:

import org.springframework.stereotype.Component;

...

@Component
public class ContactServiceImpl implements ContactService {

What's the difference between display:inline-flex and display:flex?

Using two-value display syntax instead, for clarity

The display CSS property in fact sets two things at once: the outer display type, and the inner display type. The outer display type affects how the element (which acts as a container) is displayed in its context. The inner display type affects how the children of the element (or the children of the container) are laid out.

If you use the two-value display syntax, which is only supported in some browsers like Firefox, the difference between the two is much more obvious:

  • display: block is equivalent to display: block flow
  • display: inline is equivalent to display: inline flow
  • display: flex is equivalent to display: block flex
  • display: inline-flex is equivalent to display: inline flex
  • display: grid is equivalent to display: block grid
  • display: inline-grid is equivalent to display: inline grid

Outer display type: block or inline:

An element with the outer display type of block will take up the whole width available to it, like <div> does. An element with the outer display type of inline will only take up the width that it needs, with wrapping, like <span> does.

Inner display type: flow, flex or grid:

The inner display type flow is the default inner display type when flex or grid is not specified. It is the way of laying out children elements that we are used to in a <p> for instance. flex and grid are new ways of laying out children that each deserve their own post.

Conclusion:

The difference between display: flex and display: inline-flex is the outer display type, the first's outer display type is block, and the second's outer display type is inline. Both of them have the inner display type of flex.

References:

Making custom right-click context menus for my web-app

As Adrian said, the plugins are going to work the same way. There are three basic parts you're going to need:

1: Event handler for 'contextmenu' event:

$(document).bind("contextmenu", function(event) {
    event.preventDefault();
    $("<div class='custom-menu'>Custom menu</div>")
        .appendTo("body")
        .css({top: event.pageY + "px", left: event.pageX + "px"});
});

Here, you could bind the event handler to any selector that you want to show a menu for. I've chosen the entire document.

2: Event handler for 'click' event (to close the custom menu):

$(document).bind("click", function(event) {
    $("div.custom-menu").hide();
});

3: CSS to control the position of the menu:

.custom-menu {
    z-index:1000;
    position: absolute;
    background-color:#C0C0C0;
    border: 1px solid black;
    padding: 2px;
}

The important thing with the CSS is to include the z-index and position: absolute

It wouldn't be too tough to wrap all of this in a slick jQuery plugin.

You can see a simple demo here: http://jsfiddle.net/andrewwhitaker/fELma/

Correct way to find max in an Array in Swift

In Swift 2.0, the minElement and maxElement become methods of SequenceType protocol, you should call them like:

let a = [1, 2, 3]
print(a.maxElement()) //3
print(a.minElement()) //1

Using maxElement as a function like maxElement(a) is unavailable now.

The syntax of Swift is in flux, so I can just confirm this in Xcode version7 beta6.

It may be modified in the future, so I suggest that you'd better check the doc before you use these methods.

Clicking URLs opens default browser

Add this 2 lines in your code -

mWebView.setWebChromeClient(new WebChromeClient()); 
mWebView.setWebViewClient(new WebViewClient());?

How to prevent column break within an element?

This answer might only apply to certain circumstances; If you set a height to your elements, this will be obeyed by the column styling. There-by keeping anything that is contained within that height to a row.

I had a list, like the op, but it contained two elements, items and buttons to act upon those items. I treated it like a table <ul> - table, <li> - table-row, <div> - table-cell put the UL in a 4 column layout. The columns were sometimes being split between the item and it's buttons. The trick I used was to give the Div elements a line height to cover the buttons.

Force hide address bar in Chrome on Android

Check this has everything you need

http://www.html5rocks.com/en/mobile/fullscreen/

The Chrome team has recently implemented a feature that tells the browser to launch the page fullscreen when the user has added it to the home screen. It is similar to the iOS Safari model.

<meta name="mobile-web-app-capable" content="yes">

PDF Blob - Pop up window not showing content

I ended up just downloading my pdf using below code

function downloadPdfDocument(fileName){

var req = new XMLHttpRequest();
req.open("POST", "/pdf/" + fileName, true);
req.responseType = "blob";
fileName += "_" + new Date() + ".pdf";

req.onload = function (event) {

    var blob = req.response;

    //for IE
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else {

        var link = document.createElement('a');
        link.href = window.URL.createObjectURL(blob);
        link.download = fileName;
        link.click();
    }
};

req.send();

}

Explaining Apache ZooKeeper

In a nutshell, ZooKeeper helps you build distributed applications.

How it works

You may describe ZooKeeper as a replicated synchronization service with eventual consistency. It is robust, since the persisted data is distributed between multiple nodes (this set of nodes is called an "ensemble") and one client connects to any of them (i.e., a specific "server"), migrating if one node fails; as long as a strict majority of nodes are working, the ensemble of ZooKeeper nodes is alive. In particular, a master node is dynamically chosen by consensus within the ensemble; if the master node fails, the role of master migrates to another node.

How writes are handled

The master is the authority for writes: in this way writes can be guaranteed to be persisted in-order, i.e., writes are linear. Each time a client writes to the ensemble, a majority of nodes persist the information: these nodes include the server for the client, and obviously the master. This means that each write makes the server up-to-date with the master. It also means, however, that you cannot have concurrent writes.

The guarantee of linear writes is the reason for the fact that ZooKeeper does not perform well for write-dominant workloads. In particular, it should not be used for interchange of large data, such as media. As long as your communication involves shared data, ZooKeeper helps you. When data could be written concurrently, ZooKeeper actually gets in the way, because it imposes a strict ordering of operations even if not strictly necessary from the perspective of the writers. Its ideal use is for coordination, where messages are exchanged between the clients.

How reads are handled

This is where ZooKeeper excels: reads are concurrent since they are served by the specific server that the client connects to. However, this is also the reason for the eventual consistency: the "view" of a client may be outdated, since the master updates the corresponding server with a bounded but undefined delay.

In detail

The replicated database of ZooKeeper comprises a tree of znodes, which are entities roughly representing file system nodes (think of them as directories). Each znode may be enriched by a byte array, which stores data. Also, each znode may have other znodes under it, practically forming an internal directory system.

Sequential znodes

Interestingly, the name of a znode can be sequential, meaning that the name the client provides when creating the znode is only a prefix: the full name is also given by a sequential number chosen by the ensemble. This is useful, for example, for synchronization purposes: if multiple clients want to get a lock on a resource, they can each concurrently create a sequential znode on a location: whoever gets the lowest number is entitled to the lock.

Ephemeral znodes

Also, a znode may be ephemeral: this means that it is destroyed as soon as the client that created it disconnects. This is mainly useful in order to know when a client fails, which may be relevant when the client itself has responsibilities that should be taken by a new client. Taking the example of the lock, as soon as the client having the lock disconnects, the other clients can check whether they are entitled to the lock.

Watches

The example related to client disconnection may be problematic if we needed to periodically poll the state of znodes. Fortunately, ZooKeeper offers an event system where a watch can be set on a znode. These watches may be set to trigger an event if the znode is specifically changed or removed or new children are created under it. This is clearly useful in combination with the sequential and ephemeral options for znodes.

Where and how to use it

A canonical example of Zookeeper usage is distributed-memory computation, where some data is shared between client nodes and must be accessed/updated in a very careful way to account for synchronization.

ZooKeeper offers the library to construct your synchronization primitives, while the ability to run a distributed server avoids the single-point-of-failure issue you have when using a centralized (broker-like) message repository.

ZooKeeper is feature-light, meaning that mechanisms such as leader election, locks, barriers, etc. are not already present, but can be written above the ZooKeeper primitives. If the C/Java API is too unwieldy for your purposes, you should rely on libraries built on ZooKeeper such as cages and especially curator.

Where to read more

Official documentation apart, which is pretty good, I suggest to read Chapter 14 of Hadoop: The Definitive Guide which has ~35 pages explaining essentially what ZooKeeper does, followed by an example of a configuration service.

How do you remove an invalid remote branch reference from Git?

The accepted answer didn't work for me when the ref was packed. This does however:

$ git remote add public http://anything.com/bogus.git
$ git remote rm public

Why is "except: pass" a bad programming practice?

>>> import this

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

So, here is my opinion. Whenever you find an error, you should do something to handle it, i.e. write it in logfile or something else. At least, it informs you that there used to be a error.

Simplest SOAP example

The question is 'What is the simplest SOAP example using Javascript?'

This answer is of an example in the Node.js environment, rather than a browser. (Let's name the script soap-node.js) And we will use the public SOAP web service from Europe PMC as an example to get the reference list of an article.

const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const DOMParser = require('xmldom').DOMParser;

function parseXml(text) {
    let parser = new DOMParser();
    let xmlDoc = parser.parseFromString(text, "text/xml");
    Array.from(xmlDoc.getElementsByTagName("reference")).forEach(function (item) {
        console.log('Title: ', item.childNodes[3].childNodes[0].nodeValue);
    });

}

function soapRequest(url, payload) {
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', url, true);

    // build SOAP request
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
                parseXml(xmlhttp.responseText);
            }
        }
    }

    // Send the POST request
    xmlhttp.setRequestHeader('Content-Type', 'text/xml');
    xmlhttp.send(payload);
}

soapRequest('https://www.ebi.ac.uk/europepmc/webservices/soap', 
    `<?xml version="1.0" encoding="UTF-8"?>
    <S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Header />
    <S:Body>
        <ns4:getReferences xmlns:ns4="http://webservice.cdb.ebi.ac.uk/"
            xmlns:ns2="http://www.scholix.org"
            xmlns:ns3="https://www.europepmc.org/data">
            <id>C7886</id>
            <source>CTX</source>
            <offSet>0</offSet>
            <pageSize>25</pageSize>
            <email>[email protected]</email>
        </ns4:getReferences>
    </S:Body>
    </S:Envelope>`);

Before running the code, you need to install two packages:

npm install xmlhttprequest
npm install xmldom

Now you can run the code:

node soap-node.js

And you'll see the output as below:

Title:  Perspective: Sustaining the big-data ecosystem.
Title:  Making proteomics data accessible and reusable: current state of proteomics databases and repositories.
Title:  ProteomeXchange provides globally coordinated proteomics data submission and dissemination.
Title:  Toward effective software solutions for big biology.
Title:  The NIH Big Data to Knowledge (BD2K) initiative.
Title:  Database resources of the National Center for Biotechnology Information.
Title:  Europe PMC: a full-text literature database for the life sciences and platform for innovation.
Title:  Bio-ontologies-fast and furious.
Title:  BioPortal: ontologies and integrated data resources at the click of a mouse.
Title:  PubMed related articles: a probabilistic topic-based model for content similarity.
Title:  High-Impact Articles-Citations, Downloads, and Altmetric Score.

How to force a SQL Server 2008 database to go Offline

Go offline

USE master
GO
ALTER DATABASE YourDatabaseName
SET OFFLINE WITH ROLLBACK IMMEDIATE
GO

Go online

USE master
GO
ALTER DATABASE YourDatabaseName
SET ONLINE
GO

How do I remove my IntelliJ license in 2019.3?

For PHPStorm 2020.3.2 on ubuntu inorder to reset expiration license, you should run following commands:

sudo rm ~/.config/JetBrains/PhpStorm2020.3/options/other.xml 
sudo rm ~/.config/JetBrains/PhpStorm2020.3/eval/*          
sudo rm -rf .java/.userPrefs

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.32 defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

Intellij JAVA_HOME variable

So far, nobody has answered the actual question.

Someone can figure what is happening ?

The problem here is that while the value of your $JAVA_HOME is correct, you defined it in the wrong place.

  • When you open a terminal and launch a Bash session, it will read the ~/.bash_profile file. Thus, when you enter echo $JAVA_HOME, it will return the value that has been set there.
  • When you launch IntelliJ directly, it will not read ~/.bash_profile … why should it? So to IntelliJ, this variable is not set.

There are two possible solutions to this:

  • Launch IntelliJ from a Bash session: open a terminal and run "/Applications/IntelliJ IDEA.app/Contents/MacOS/idea". The idea process will inherit any environment variables of Bash that have been exported. (Since you did export JAVA_HOME=…, it works!), or, the sophisticated way:
  • Set global environment variables that apply to all programs, not only Bash sessions. This is more complicated than you might think, and is explained here and here, for example. What you should do is run

    /bin/launchctl setenv JAVA_HOME $(/usr/libexec/java_home)
    

    However, this gets reset after a reboot. To make sure this gets run on every boot, execute

    cat << EOF > ~/Library/LaunchAgents/setenv.JAVA_HOME.plist
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
        "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
      <plist version="1.0">
      <dict>
        <key>Label</key>
        <string>setenv.JAVA_HOME</string>
        <key>ProgramArguments</key>
        <array>
          <string>/bin/launchctl</string>
          <string>setenv</string>
          <string>JAVA_HOME</string>
          <string>$(/usr/libexec/java_home)</string>
        </array>
        <key>RunAtLoad</key>
        <true/>
        <key>ServiceIPC</key>
        <false/>
      </dict>
    </plist>
    EOF
    

    Note that this also affects the Terminal process, so there is no need to put anything in your ~/.bash_profile.

How to remove first and last character of a string?

In Kotlin

private fun removeLastChar(str: String?): String? {
    return if (str == null || str.isEmpty()) str else str.substring(0, str.length - 1)
}

Get difference between 2 dates in JavaScript?

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

What is meant by Ems? (Android TextView)

android:ems or setEms(n) sets the width of a TextView to fit a text of n 'M' letters regardless of the actual text extension and text size. See wikipedia Em unit

but only when the layout_width is set to "wrap_content". Other layout_width values override the ems width setting.

Adding an android:textSize attribute determines the physical width of the view to the textSize * length of a text of n 'M's set above.

how to create a list of lists

Create your list before your loop, else it will be created at each loop.

>>> list1 = []
>>> for i in range(10) :
...   list1.append( range(i,10) )
...
>>> list1
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [1, 2, 3, 4, 5, 6, 7, 8, 9], [2, 3, 4, 5, 6, 7, 8, 9], [3, 4, 5, 6, 7, 8, 9], [4, 5, 6, 7, 8, 9], [5, 6, 7, 8, 9], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]]

What is the difference between JOIN and UNION?

1. The SQL Joins clause is used to combine records from two or more tables in a database. A JOIN is a means for combining fields from two tables by using values common to each.

2. The SQL UNION operator combines the result of two or more SELECT statements. Each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.

for example: table 1 customers/table 2 orders

inner join:

SELECT ID, NAME, AMOUNT, DATE

FROM CUSTOMERS?

INNER JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

union:

SELECT ID, NAME, AMOUNT, DATE

?FROM CUSTOMERS?

LEFT JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID

UNION

SELECT ID, NAME, AMOUNT, DATE ? FROM CUSTOMERS?

RIGHT JOIN ORDERS?

ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;

Validating with an XML schema in Python

I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

How to build and use Google TensorFlow C++ api

If you don't mind using CMake, there is also tensorflow_cc project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. The project README contains an example and Dockerfiles you can easily follow.

how to set cursor style to pointer for links without hrefs

Just add this to your global CSS style:

a { cursor: pointer; }

This way you're not dependent on the browser default cursor style anymore.

Pushing from local repository to GitHub hosted remote

You push your local repository to the remote repository using the git push command after first establishing a relationship between the two with the git remote add [alias] [url] command. If you visit your Github repository, it will show you the URL to use for pushing. You'll first enter something like:

git remote add origin [email protected]:username/reponame.git

Unless you started by running git clone against the remote repository, in which case this step has been done for you already.

And after that, you'll type:

git push origin master

After your first push, you can simply type:

git push

when you want to update the remote repository in the future.

Android - implementing startForeground for a service?

Note: If your app targets API level 26 or higher, the system imposes restrictions on using or creating background services unless the app itself is in the foreground.

If an app needs to create a foreground service, the app should call startForegroundService(). That method creates a background service, but the method signals to the system that the service will promote itself to the foreground.

Once the service has been created, the service must call its startForeground() method within five seconds.

How do I run git log to see changes only for a specific branch?

Use:

git log --graph --abbrev-commit --decorate  --first-parent <branch_name>

It is only for the target branch (of course --graph, --abbrev-commit --decorate are more polishing).

The key option is --first-parent: "Follow only the first parent commit upon seeing a merge commit" (https://git-scm.com/docs/git-log)

It prevents the commit forks from being displayed.

Drop all duplicate rows across multiple columns in Python Pandas

Just want to add to Ben's answer on drop_duplicates:

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Drop duplicates except for the first occurrence.

  • last : Drop duplicates except for the last occurrence.

  • False : Drop all duplicates.

So setting keep to False will give you desired answer.

DataFrame.drop_duplicates(*args, **kwargs) Return DataFrame with duplicate rows removed, optionally only considering certain columns

Parameters: subset : column label or sequence of labels, optional Only consider certain columns for identifying duplicates, by default use all of the columns keep : {‘first’, ‘last’, False}, default ‘first’ first : Drop duplicates except for the first occurrence. last : Drop duplicates except for the last occurrence. False : Drop all duplicates. take_last : deprecated inplace : boolean, default False Whether to drop duplicates in place or to return a copy cols : kwargs only argument of subset [deprecated] Returns: deduplicated : DataFrame

Python Create unix timestamp five minutes in the future

Note that solutions with timedelta.total_seconds() work on python-2.7+. Use calendar.timegm(future.utctimetuple()) for lower versions of Python.

How can I set a website image that will show as preview on Facebook?

1. Include the Open Graph XML namespace extension to your HTML declaration

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:fb="http://ogp.me/ns/fb#">

2. Inside your <head></head> use the following meta tag to define the image you want to use

<meta property="og:image" content="fully_qualified_image_url_here" />

Read more about open graph protocol here.

After doing the above, use the Facebook "Object Debugger" if the image does not show up correctly. Also note the first time shared it still won't show up unless height and width are also specified, see Share on Facebook - Thumbnail not showing for the first time

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

AttributeError: 'module' object has no attribute 'urlretrieve'

A Python 2+3 compatible solution is:

import sys

if sys.version_info[0] >= 3:
    from urllib.request import urlretrieve
else:
    # Not Python 3 - today, it is most likely to be Python 2
    # But note that this might need an update when Python 4
    # might be around one day
    from urllib import urlretrieve

# Get file from URL like this:
urlretrieve("http://www-scf.usc.edu/~chiso/oldspice/m-b1-hello.mp3")

How to convert int to QString?

If you need locale-aware number formatting, use QLocale::toString instead.

Create a global variable in TypeScript

I found a way that works if I use JavaScript combined with TypeScript.

logging.d.ts:

declare var log: log4javascript.Logger;

log-declaration.js:

log = null;

initalize-app.ts

import './log-declaration.js';

// Call stuff to actually setup log.  
// Similar to this:
log = functionToSetupLog();

This puts it in the global scope and TypeScript knows about it. So I can use it in all my files.

NOTE: I think this only works because I have the allowJs TypeScript option set to true.

If someone posts an pure TypeScript solution, I will accept that.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Setting android:noHistory="true" on the activity in your manifest will remove an activity from the stack whenever it is navigated away from. see here

How do you add multi-line text to a UIButton?

In Swift 5.0 and Xcode 10.2

//UIButton extension
extension UIButton {
     //UIButton properties
     func btnMultipleLines() {
         titleLabel?.numberOfLines = 0
         titleLabel?.lineBreakMode = .byWordWrapping
         titleLabel?.textAlignment = .center        
     }
}

In your ViewController call like this

button.btnMultipleLines()//This is your button

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

putting a php variable in a HTML form value

value="<?php echo htmlspecialchars($name); ?>"

Nullable property to entity field, Entity Framework through Code First

In Ef .net core there are two options that you can do; first with data annotations:

public class Blog
{
    public int BlogId { get; set; }
    [Required]
    public string Url { get; set; }
}

Or with fluent api:

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .Property(b => b.Url)
            .IsRequired(false)//optinal case
            .IsRequired()//required case
            ;
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

There are more details here

How to get first 5 characters from string

You can get your result by simply use substr():

Syntax substr(string,start,length)

Example

<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>

Output :

 Hello

System.Data.SqlClient.SqlException: Login failed for user

I just ran into this error and it took days to resolve. We were thrown for a loop by the red-herring error message mentioned in the initial question, plus the Windows Event Viewer error log indicated something similar:

Login failed for user '(domain\name-PC)$'. Reason: Could not find a login matching the name provided. [CLIENT: <local machine>]

Neither of these was true, the user had all the necessary permissions in SQL Server.

In our case, the solution was to switch the Application Pool Identity in IIS to NetworkService.

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

To fetch only one distinct record from duplicate column of two rows you can use "rowid" column which is maintained by oracle itself as Primary key,so first try

"select rowid,RequestID,CreatedDate,HistoryStatus  from temptable;"

and then you can fetch second row only by it's value of 'rowid' column by using in SELECT statement.

FileNotFoundError: [Errno 2] No such file or directory

For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.

Convert datetime to Unix timestamp and convert it back in python

def datetime_to_epoch(d1):

    # create 1,1,1970 in same timezone as d1
    d2 = datetime(1970, 1, 1, tzinfo=d1.tzinfo)
    time_delta = d1 - d2
    ts = int(time_delta.total_seconds())
    return ts


def epoch_to_datetime_string(ts, tz_name="UTC"):
    x_timezone = timezone(tz_name)
    d1 = datetime.fromtimestamp(ts, x_timezone)
    x = d1.strftime("%d %B %Y %H:%M:%S")
    return x

Android Studio build fails with "Task '' not found in root project 'MyProject'."

This happened to me recently when I close one Android Studio project and imported another Eclipse project. It seemed to be some bug in Android Studio where it preserves some gradle settings from previously open project and then get confused in the new project.

The solution was extremely simple: Close the project and shut down Android Studio completely, before re-opening it and then import/open the new project. Everything goes smoothly from then on.

How to enter a multi-line command

There's sooo many ways to continue a line in powershell, with pipes, brackets, parentheses, operators, dots, even with a comma. Here's a blog about it: https://get-powershellblog.blogspot.com/2017/07/bye-bye-backtick-natural-line.html

You can continue right after statements like foreach and if as well.

How do I trim leading/trailing whitespace in a standard way?

Here is what I disclosed regarding the question in Linux kernel code:

/**
 * skip_spaces - Removes leading whitespace from @s.
 * @s: The string to be stripped.
 *
 * Returns a pointer to the first non-whitespace character in @s.
 */
char *skip_spaces(const char *str)
{
    while (isspace(*str))
            ++str;
    return (char *)str;
}

/**
 * strim - Removes leading and trailing whitespace from @s.
 * @s: The string to be stripped.
 *
 * Note that the first trailing whitespace is replaced with a %NUL-terminator
 * in the given string @s. Returns a pointer to the first non-whitespace
 * character in @s.
 */
char *strim(char *s)
{
    size_t size;
    char *end;

    size = strlen(s);

    if (!size)
            return s;

    end = s + size - 1;
    while (end >= s && isspace(*end))
            end--;
    *(end + 1) = '\0';

    return skip_spaces(s);
}

It is supposed to be bug free due to the origin ;-)

Mine one piece is closer to KISS principle I guess:

/**
 * trim spaces
 **/
char * trim_inplace(char * s, int len)
{
    // trim leading
    while (len && isspace(s[0]))
    {
        s++; len--;
    }

    // trim trailing
    while (len && isspace(s[len - 1]))
    {
        s[len - 1] = 0; len--;
    }

    return s;
}

How to set corner radius of imageView?

in swift 3 'CGRectGetWidth' has been replaced by property 'CGRect.width'

    view.layer.cornerRadius = view.frame.width/4.0
    view.clipsToBounds = true

AND/OR in Python?

As Matt Ball's answer explains, or is "and/or". But or doesn't work with in the way you use it above. You have to say if "a" in someList or "á" in someList or.... Or better yet,

if any(c in someList for c in ("a", "á", "à", "ã", "â")):
    ...

That's the answer to your question as asked.

Other Notes

However, there are a few more things to say about the example code you've posted. First, the chain of someList.remove... or someList remove... statements here is unnecessary, and may result in unexpected behavior. It's also hard to read! Better to break it into individual lines:

someList.remove("a")
someList.remove("á")
...

Even that's not enough, however. As you observed, if the item isn't in the list, then an error is thrown. On top of that, using remove is very slow, because every time you call it, Python has to look at every item in the list. So if you want to remove 10 different characters, and you have a list that has 100 characters, you have to perform 1000 tests.

Instead, I would suggest a very different approach. Filter the list using a set, like so:

chars_to_remove = set(("a", "á", "à", "ã", "â"))
someList = [c for c in someList if c not in chars_to_remove]

Or, change the list in-place without creating a copy:

someList[:] = (c for c in someList if c not in chars_to_remove)

These both use list comprehension syntax to create a new list. They look at every character in someList, check to see of the character is in chars_to_remove, and if it is not, they include the character in the new list.

This is the most efficient version of this code. It has two speed advantages:

  1. It only passes through someList once. Instead of performing 1000 tests, in the above scenario, it performs only 100.
  2. It can test all characters with a single operation, because chars_to_remove is a set. If it chars_to_remove were a list or tuple, then each test would really be 10 tests in the above scenario -- because each character in the list would need to be checked individually.

lexers vs parsers

What parsers and lexers have in common:

  1. They read symbols of some alphabet from their input.

    • Hint: The alphabet doesn't necessarily have to be of letters. But it has to be of symbols which are atomic for the language understood by parser/lexer.
    • Symbols for the lexer: ASCII characters.
    • Symbols for the parser: the particular tokens, which are terminal symbols of their grammar.
  2. They analyse these symbols and try to match them with the grammar of the language they understood.

    • Here's where the real difference usually lies. See below for more.
    • Grammar understood by lexers: regular grammar (Chomsky's level 3).
    • Grammar understood by parsers: context-free grammar (Chomsky's level 2).
  3. They attach semantics (meaning) to the language pieces they find.

    • Lexers attach meaning by classifying lexemes (strings of symbols from the input) as the particular tokens. E.g. All these lexemes: *, ==, <=, ^ will be classified as "operator" token by the C/C++ lexer.
    • Parsers attach meaning by classifying strings of tokens from the input (sentences) as the particular nonterminals and building the parse tree. E.g. all these token strings: [number][operator][number], [id][operator][id], [id][operator][number][operator][number] will be classified as "expression" nonterminal by the C/C++ parser.
  4. They can attach some additional meaning (data) to the recognized elements.

    • When a lexer recognizes a character sequence constituting a proper number, it can convert it to its binary value and store with the "number" token.
    • Similarly, when a parser recognize an expression, it can compute its value and store with the "expression" node of the syntax tree.
  5. They all produce on their output a proper sentences of the language they recognize.

    • Lexers produce tokens, which are sentences of the regular language they recognize. Each token can have an inner syntax (though level 3, not level 2), but that doesn't matter for the output data and for the one which reads them.
    • Parsers produce syntax trees, which are representations of sentences of the context-free language they recognize. Usually it's only one big tree for the whole document/source file, because the whole document/source file is a proper sentence for them. But there aren't any reasons why parser couldn't produce a series of syntax trees on its output. E.g. it could be a parser which recognizes SGML tags sticked into plain-text. So it'll tokenize the SGML document into a series of tokens: [TXT][TAG][TAG][TXT][TAG][TXT]....

As you can see, parsers and tokenizers have much in common. One parser can be a tokenizer for other parser, which reads its input tokens as symbols from its own alphabet (tokens are simply symbols of some alphabet) in the same way as sentences from one language can be alphabetic symbols of some other, higher-level language. For example, if * and - are the symbols of the alphabet M (as "Morse code symbols"), then you can build a parser which recognizes strings of these dots and lines as letters encoded in the Morse code. The sentences in the language "Morse Code" could be tokens for some other parser, for which these tokens are atomic symbols of its language (e.g. "English Words" language). And these "English Words" could be tokens (symbols of the alphabet) for some higher-level parser which understands "English Sentences" language. And all these languages differ only in the complexity of the grammar. Nothing more.

So what's all about these "Chomsky's grammar levels"? Well, Noam Chomsky classified grammars into four levels depending on their complexity:

  • Level 3: Regular grammars

    They use regular expressions, that is, they can consist only of the symbols of alphabet (a,b), their concatenations (ab,aba,bbb etd.), or alternatives (e.g. a|b).
    They can be implemented as finite state automata (FSA), like NFA (Nondeterministic Finite Automaton) or better DFA (Deterministic Finite Automaton).
    Regular grammars can't handle with nested syntax, e.g. properly nested/matched parentheses (()()(()())), nested HTML/BBcode tags, nested blocks etc. It's because state automata to deal with it should have to have infinitely many states to handle infinitely many nesting levels.
  • Level 2: Context-free grammars

    They can have nested, recursive, self-similar branches in their syntax trees, so they can handle with nested structures well.
    They can be implemented as state automaton with stack. This stack is used to represent the nesting level of the syntax. In practice, they're usually implemented as a top-down, recursive-descent parser which uses machine's procedure call stack to track the nesting level, and use recursively called procedures/functions for every non-terminal symbol in their syntax.
    But they can't handle with a context-sensitive syntax. E.g. when you have an expression x+3 and in one context this x could be a name of a variable, and in other context it could be a name of a function etc.
  • Level 1: Context-sensitive grammars

  • Level 0: Unrestricted grammars
    Also called recursively enumerable grammars.

How can I give an imageview click effect like a button on Android?

I do some similar things See suitable for you or not

View Press Effect Helper:

  • usage : do some simple press effect like iOS

    Simple Usage:

  • ImageView img = (ImageView) findViewById(R.id.img);

  • ViewPressEffectHelper.attach(img)

https://gist.github.com/extralam/7489370

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t = Time.now
d = DateTime.now

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)

Difference between clean, gradlew clean

  1. ./gradlew clean

    Uses your project's gradle wrapper to execute your project's clean task. Usually, this just means the deletion of the build directory.

  2. ./gradlew clean assembleDebug

    Again, uses your project's gradle wrapper to execute the clean and assembleDebug tasks, respectively. So, it will clean first, then execute assembleDebug, after any non-up-to-date dependent tasks.

  3. ./gradlew clean :assembleDebug

    Is essentially the same as #2. The colon represents the task path. Task paths are essential in gradle multi-project's, not so much in this context. It means run the root project's assembleDebug task. Here, the root project is the only project.

  4. Android Studio --> Build --> Clean

    Is essentially the same as ./gradlew clean. See here.

For more info, I suggest taking the time to read through the Android docs, especially this one.

Cancel a vanilla ECMAScript 6 Promise chain

Try promise-abortable: https://www.npmjs.com/package/promise-abortable

$ npm install promise-abortable
import AbortablePromise from "promise-abortable";

const timeout = new AbortablePromise((resolve, reject, signal) => {
  setTimeout(reject, timeToLive, error);
  signal.onabort = resolve;
});

Promise.resolve(fn()).then(() => {
  timeout.abort();
});

How to keep keys/values in same order as declared?

You can do the same thing which i did for dictionary.

Create a list and empty dictionary:

dictionary_items = {}
fields = [['Name', 'Himanshu Kanojiya'], ['email id', '[email protected]']]
l = fields[0][0]
m = fields[0][1]
n = fields[1][0]
q = fields[1][1]
dictionary_items[l] = m
dictionary_items[n] = q
print dictionary_items

List<String> to ArrayList<String> conversion issue

Tried and tested approach.

public static ArrayList<String> listToArrayList(List<Object> myList) {
        ArrayList<String> arl = new ArrayList<String>();
        for (Object object : myList) {
            arl.add((String) object);
        }
        return arl;

    }

How to change the port number for Asp.Net core app?

It's working to me.

I use Asp.net core 2.2 (this way supported in asp.net core 2.1 and upper version).

add Kestrel section in appsettings.json file. like this:

{
  "Kestrel": {
    "EndPoints": {
      "Http": {
        "Url": "http://localhost:4300"
      }
    }
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

and in Startup.cs:

public Startup(IConfiguration configuration, IHostingEnvironment env)
{
      var builder = new ConfigurationBuilder()
         .SetBasePath(env.ContentRootPath)
         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
         .AddEnvironmentVariables();

      Configuration = builder.Build();
}

Get Enum from Description attribute

You need to iterate through all the enum values in Animal and return the value that matches the description you need.

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The problem is because of post back happens on submit button click. So while posting data on submit click again write before returning View()

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

jQuery - Trigger event when an element is removed from the DOM

Hooking .remove() is not the best way to handle this as there are many ways to remove elements from the page (e.g. by using .html(), .replace(), etc).

In order to prevent various memory leak hazards, internally jQuery will try to call the function jQuery.cleanData() for each removed element regardless of the method used to remove it.

See this answer for more details: javascript memory leaks

So, for best results, you should hook the cleanData function, which is exactly what the jquery.event.destroyed plugin does:

http://v3.javascriptmvc.com/jquery/dist/jquery.event.destroyed.js

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

View.GONE makes the view invisible without the view taking up space in the layout. View.INVISIBLE makes the view just invisible still taking up space.

You are first using GONE and then INVISIBLE on the same view.Since, the code is executed sequentially, first the view becomes GONE then it is overridden by the INVISIBLE type still taking up space.

You should add button listener on the button and inside the onClick() method make the views visible. This should be the logic according to me in your onCreate() method.

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

    final DatePicker dp2 = (DatePicker) findViewById(R.id.datePick2);
    final Button btn2 = (Button) findViewById(R.id.btnDate2);
    final Button btn3 = (Button) findViewById(R.id.btnVisibility);

    dp2.setVisibility(View.INVISIBLE);
    btn2.setVisibility(View.INVISIBLE);

    bt3.setOnClickListener(new View.OnCLickListener(){ 
    @Override
    public void onClick(View view)
    {
        dp2.setVisibility(View.VISIBLE);
        bt2.setVisibility(View.VISIBLE);
    }
  });
}

I think this should work easily. Hope this helps.

Setting width and height

You can also simply surround the chart with container (according to official doc http://www.chartjs.org/docs/latest/general/responsive.html#important-note)

<div class="chart-container">
    <canvas id="myCanvas"></canvas>
</div>

CSS

.chart-container {
    width: 1000px;
    height:600px
}

and with options

responsive:true
maintainAspectRatio: false

TempData keep() vs peek()

don't they both keep a value for another request?

Yes they do, but when the first one is void, the second one returns and object:

public void Keep(string key)
{
    _retainedKeys.Add(key); // just adds the key to the collection for retention
}

public object Peek(string key)
{
    object value;
    _data.TryGetValue(key, out value);
    return value; // returns an object without marking it for deletion
}

Extracting the top 5 maximum values in excel

There 3 functions you want to look at here:

I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:

Excel sample

  • In Cells A13 to A17, the values 1 to 5 were inserted to specify the nth highest value.
  • In Cell B13, the following formula was added: =LARGE($B$2:$B$11, A13)
  • In Cell C13, the following formula was added: =INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
  • These formulae get the highest ranking OPS and Player based on the value in A13.
  • Simply select and drag to copy these formulae down to the next 4 cells which will reference the corresponding ranking in Column A.

New line in JavaScript alert box

Works with \n but if the script is into a java tag you must write \\\n

<script type="text/javascript">alert('text\ntext');</script>

or

<h:commandButton action="#{XXXXXXX.xxxxxxxxxx}" value="XXXXXXXX" 
    onclick="alert('text\\\ntext');" />

How to Define Callbacks in Android?

to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>

Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        <code to be executed during callback>
    }
};

Handler handler = new Handler(callback);
handler.sendMessage(message);

EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):

post(new Runnable() {
    @Override
    public void run() {
        <code to be executed during callback>
    }
});

Alternative Windows shells, besides CMD.EXE?

At the moment there are three realy powerfull cmd.exe alternatives:

cmder is an enhancement off ConEmu and Clink

All have features like Copy & Paste, Window Resize per Mouse, Splitscreen, Tabs and a lot of other usefull features.

Convert any object to a byte[]

Like others have said before, you could use binary serialization, but it may produce an extra bytes or be deserialized into an objects with not exactly same data. Using reflection on the other hand is quite complicated and very slow. There is an another solution that can strictly convert your objects to bytes and vise-versa - marshalling:

var size = Marshal.SizeOf(your_object);
// Both managed and unmanaged buffers required.
var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
// Copy object byte-to-byte to unmanaged memory.
Marshal.StructureToPtr(your_object, ptr, false);
// Copy data from unmanaged memory to managed buffer.
Marshal.Copy(ptr, bytes, 0, size);
// Release unmanaged memory.
Marshal.FreeHGlobal(ptr);

And to convert bytes to object:

var bytes = new byte[size];
var ptr = Marshal.AllocHGlobal(size);
Marshal.Copy(bytes, 0, ptr, size);
var your_object = (YourType)Marshal.PtrToStructure(ptr, typeof(YourType));
Marshal.FreeHGlobal(ptr);

It's noticeably slower and partly unsafe to use this approach for small objects and structs comparing to your own serialization field by field (because of double copying from/to unmanaged memory), but it's easiest way to strictly convert object to byte[] without implementing serialization and without [Serializable] attribute.

How to install mysql-connector via pip

execute following command from your terminal

sudo pip install --allow-external mysql-connector-python mysql-connector-python

How to save an image to localStorage and display it on the next page?

I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:

<img data-src="path/to/image">
<script>
    $('img').imageCaching();
</script>

How to do one-liner if else statement?

Ternary ? operator alternatives | golang if else one line You can’t write a short one-line conditional in Go language ; there is no ternary conditional operator. Read more about if..else of Golang

How do I remove an item from a stl vector with a certain value?

From c++20:

A non-member function introduced std::erase, which takes the vector and value to be removed as inputs.

ex:

std::vector<int> v = {90,80,70,60,50};
std::erase(v,50);

Scripting Language vs Programming Language

Scripting languages are programming languages that don't require an explicit compilation step.

For example, in the normal case, you have to compile a C program before you can run it. But in the normal case, you don't have to compile a JavaScript program before you run it. So JavaScript is sometimes called a "scripting" language.

This line is getting more and more blurry since compilation can be so fast with modern hardware and modern compilation techniques. For instance, V8, the JavaScript engine in Google Chrome and used a lot outside of the browser as well, actually compiles the JavaScript code on the fly into machine code, rather than interpreting it. (In fact, V8's an optimizing two-phase compiler.)

Also note that whether a language is a "scripting" language or not can be more about the environment than the language. There's no reason you can't write a C interpreter and use it as a scripting language (and people have). There's also no reason you can't compile JavaScript to machine code and store that in an executable file (and people have). The language Ruby is a good example of this: The original implementation was entirely interpreted (a "scripting" language), but there are now multiple compilers for it.

Some examples of "scripting" languages (e.g., languages that are traditionally used without an explicit compilation step):

  • Lua
  • JavaScript
  • VBScript and VBA
  • Perl

And a small smattering of ones traditionally used with an explicit compilation step:

  • C
  • C++
  • D
  • Java (but note that Java is compiled to bytecode, which is then interpreted and/or recompiled at runtime)
  • Pascal

...and then you have things like Python that sit in both camps: Python is widely used without a compilation step, but the main implementation (CPython) does that by compiling to bytecode on-the-fly and then running the bytecode in a VM, and it can write that bytecode out to files (.pyc, .pyo) for use without recompiling.

That's just a very few, if you do some research you can find a lot more.

How to enable Auto Logon User Authentication for Google Chrome

In addition to setting the registry entry for AuthServerWhitelist you should also set AuthSchemes: "ntlm,negotiate" (or just "ntlm" as appropriate for your situation). Using the above templates the policy for that will be "Supported authentication schemes"

How do I make a fixed size formatted string in python?

Sure, use the .format method. E.g.,

print('{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98))
print('{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0))
print('{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34))

will print

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

You can adjust the field sizes as desired. Note that .format works independently of print to format a string. I just used print to display the strings. Brief explanation:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

For right alignment

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

Can Console.Clear be used to only clear a line instead of whole console?

Description

You can use the Console.SetCursorPosition function to go to a specific line number. Than you can use this function to clear the line

public static void ClearCurrentConsoleLine()
{
    int currentLineCursor = Console.CursorTop;
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth)); 
    Console.SetCursorPosition(0, currentLineCursor);
}

Sample

Console.WriteLine("Test");
Console.SetCursorPosition(0, Console.CursorTop - 1);
ClearCurrentConsoleLine();

More Information

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

JQUERY: Uncaught Error: Syntax error, unrecognized expression

This can also happen in safari if you try a selector with a missing ], for example

$('select[name="something"')

but interestingly, this same jquery selector with a missing bracket will work in chrome.

Where does Java's String constant pool live, the heap or the stack?

As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.

It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931

And in Java 8 Hotspot, Permanent Generation has been completely removed.

Converting a JS object to an array using jQuery

Fiddle Demo

Extension to answer of bjornd .

var myObj = {
    1: [1, [2], 3],
    2: [4, 5, [6]]
}, count = 0,
    i;
//count the JavaScript object length supporting IE < 9 also
for (i in myObj) {
    if (myObj.hasOwnProperty(i)) {
        count++;
    }
}
//count = Object.keys(myObj).length;// but not support IE < 9
myObj.length = count + 1; //max index + 1
myArr = Array.prototype.slice.apply(myObj);
console.log(myArr);


Reference

Array.prototype.slice()

Function.prototype.apply()

Object.prototype.hasOwnProperty()

Object.keys()

String.contains in Java

The obvious answer to this is "that's what the JLS says."

Thinking about why that is, consider that this behavior can be useful in certain cases. Let's say you want to check a string against a set of other strings, but the number of other strings can vary.

So you have something like this:

for(String s : myStrings) {
   check(aString.contains(s));
}

where some s's are empty strings.

If the empty string is interpreted as "no input," and if your purpose here is ensure that aString contains all the "inputs" in myStrings, then it is misleading for the empty string to return false. All strings contain it because it is nothing. To say they didn't contain it would imply that the empty string had some substance that was not captured in the string, which is false.

Process to convert simple Python script into Windows executable

PyInstaller will create a single-file executable if you use the --onefile option (though what it actually does is extracts then runs itself).

There's a simple PyInstaller tutorial here. If you have any questions about using it, please post them...

How do I initialize an empty array in C#?

I had tried:

string[] sample = new string[0];

But I could only insert one string into it, and then I got an exceptionOutOfBound error, so I just simply put a size for it, like

string[] sample = new string[100];

Or another way that work for me:

List<string> sample = new List<string>();

Assigning Value for list:

sample.Add(your input);

Open JQuery Datepicker by clicking on an image w/ no input field

$(function() {
   $("#datepicker").datepicker({
       //showOn: both - datepicker will come clicking the input box as well as the calendar icon
       //showOn: button - datepicker will come only clicking the calendar icon
       showOn: 'button',
      //you can use your local path also eg. buttonImage: 'images/x_office_calendar.png'
      buttonImage: 'http://theonlytutorials.com/demo/x_office_calendar.png',
      buttonImageOnly: true,
      changeMonth: true,
      changeYear: true,
      showAnim: 'slideDown',
      duration: 'fast',
      dateFormat: 'dd-mm-yy'
  });
});

The above code belongs to this link

string to string array conversion in java

Splitting an empty string with String.split() returns a single element array containing an empty string. In most cases you'd probably prefer to get an empty array, or a null if you passed in a null, which is exactly what you get with org.apache.commons.lang3.StringUtils.split(str).

import org.apache.commons.lang3.StringUtils;

StringUtils.split(null)       => null
StringUtils.split("")         => []
StringUtils.split("abc def")  => ["abc", "def"]
StringUtils.split("abc  def") => ["abc", "def"]
StringUtils.split(" abc ")    => ["abc"]

Another option is google guava Splitter.split() and Splitter.splitToList() which return an iterator and a list correspondingly. Unlike the apache version Splitter will throw an NPE on null:

import com.google.common.base.Splitter;

Splitter SPLITTER = Splitter.on(',').trimResults().omitEmptyStrings();

SPLITTER.split("a,b,   c , , ,, ")     =>  [a, b, c]
SPLITTER.split("")                     =>  []
SPLITTER.split("  ")                   =>  []
SPLITTER.split(null)                   =>  NullPointerException

If you want a list rather than an iterator then use Splitter.splitToList().

How to merge two arrays of objects by ID using lodash?

If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.

var merge = _.merge(arr1, arr2);

Which is the short version of:

var merge = _.chain(arr1).zip(arr2).map(function(item) {
    return _.merge.apply(null, item);
}).value();

Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.

var merge = _.map(arr1, function(item) {
    return _.merge(item, _.find(arr2, { 'member' : item.member }));
});

You can easily convert this to a mixin. See the example below:

_x000D_
_x000D_
_.mixin({_x000D_
  'mergeByKey' : function(arr1, arr2, key) {_x000D_
    var criteria = {};_x000D_
    criteria[key] = null;_x000D_
    return _.map(arr1, function(item) {_x000D_
      criteria[key] = item[key];_x000D_
      return _.merge(item, _.find(arr2, criteria));_x000D_
    });_x000D_
  }_x000D_
});_x000D_
_x000D_
var arr1 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "bank": 'ObjectId("575b052ca6f66a5732749ecc")',_x000D_
  "country": 'ObjectId("575b0523a6f66a5732749ecb")'_x000D_
}];_x000D_
_x000D_
var arr2 = [{_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',_x000D_
  "name": 'yyyyyyyyyy',_x000D_
  "age": 26_x000D_
}, {_x000D_
  "member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',_x000D_
  "name": 'xxxxxx',_x000D_
  "age": 25_x000D_
}];_x000D_
_x000D_
var arr3 = _.mergeByKey(arr1, arr2, 'member');_x000D_
_x000D_
document.body.innerHTML = JSON.stringify(arr3, null, 4);
_x000D_
body { font-family: monospace; white-space: pre; }
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

jQuery select option elements by value

function select_option(index)
{
    var optwewant;
    for (opts in $('#span_id').children('select'))
    {
        if (opts.value() = index)
        {
            optwewant = opts;
            break;
        }
    }
    alert (optwewant);
}

How to close Browser Tab After Submitting a Form?

Window.close( ) does not work as it used to. Can be seen here:

window.close and self.close do not close the window in Chrome

In my case, I realized that I didn't need to close the page. So you can redirect the user to another page with:

window.location.replace("https://stackoverflow.com/");

The import com.google.android.gms cannot be resolved

I checked off Google API as project build target.

That is irrelevant, as that is for Maps V1, and you are trying to use Maps V2.

I included .jar file for maps by right-clicking on my project, went to build path and added external archive locating it in my SDK: android-sdk-windows\add-ons\addon_google_apis_google_inc_8\libs\maps

This is doubly wrong.

First, never manually modify the build path in an Android project. If you are doing that, at best, you will crash at runtime, because the JAR you think you put in your project (via the manual build path change) is not in your APK. For an ordinary third-party JAR, put it in the libs/ directory of your project, which will add it to your build path automatically and add its contents to your APK file.

However, Maps V2 is not a JAR. It is an Android library project that contains a JAR. You need the whole library project.

You need to import the android-sdk-windows\add-ons\addon_google_apis_google_inc_8 project into Eclipse, then add it to your app as a reference to an Android library project.

How to subtract X day from a Date object in Java?

Java 8 and later

With Java 8's date time API change, Use LocalDate

LocalDate date = LocalDate.now().minusDays(300);

Similarly you can have

LocalDate date = someLocalDateInstance.minusDays(300);

Refer to https://stackoverflow.com/a/23885950/260990 for translation between java.util.Date <--> java.time.LocalDateTime

Date in = new Date();
LocalDateTime ldt = LocalDateTime.ofInstant(in.toInstant(), ZoneId.systemDefault());
Date out = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

Java 7 and earlier

Use Calendar's add() method

Calendar cal = Calendar.getInstance();
cal.setTime(dateInstance);
cal.add(Calendar.DATE, -30);
Date dateBefore30Days = cal.getTime();

Query EC2 tags from within instance

Once you've got ec2-metadata and ec2-describe-tags installed (as mentioned in Ranieri's answer above), here's an example shell command to get the "name" of the current instance, assuming you have a "Name=Foo" tag on it.

Assumes EC2_PRIVATE_KEY and EC2_CERT environment variables are set.

ec2-describe-tags \
  --filter "resource-type=instance" \
  --filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
  --filter "key=Name" | cut -f5

This returns Foo.

LINK : fatal error LNK1104: cannot open file 'D:\...\MyProj.exe'

You might have not closed the the output. Close the output, clean and rebuild the file. You might be able to run the file now.

Is there a foreach loop in Go?

You can in fact use range without referencing it's return values by using for range against your type:

arr := make([]uint8, 5)
i,j := 0,0
for range arr {
    fmt.Println("Array Loop",i)
    i++
}

for range "bytes" {
    fmt.Println("String Loop",j)
    j++
}

https://play.golang.org/p/XHrHLbJMEd

Changing selection in a select with the Chosen plugin

In case of multiple type of select and/or if you want to remove already selected items one by one, directly within a dropdown list items, you can use something like:

jQuery("body").on("click", ".result-selected", function() {
    var locID = jQuery(this).attr('class').split('__').pop();
    // I have a class name: class="result-selected locvalue__209"
    var arrayCurrent = jQuery('#searchlocation').val();
    var index = arrayCurrent.indexOf(locID);
    if (index > -1) {
        arrayCurrent.splice(index, 1);
    }
    jQuery('#searchlocation').val(arrayCurrent).trigger('chosen:updated');
});

Javascript Iframe innerHTML

This solution works same as iFrame. I have created a PHP script that can get all the contents from the other website, and most important part is you can easily apply your custom jQuery to that external content. Please refer to the following script that can get all the contents from the other website and then you can apply your cusom jQuery/JS as well. This content can be used anywhere, inside any element or any page.

<div id='myframe'>

  <?php 
   /* 
    Use below function to display final HTML inside this div
   */

   //Display Frame
   echo displayFrame(); 
  ?>

</div>

<?php

/* 
  Function to display frame from another domain 
*/

function displayFrame()
{
  $webUrl = 'http://[external-web-domain.com]/';

  //Get HTML from the URL
  $content = file_get_contents($webUrl);

  //Add custom JS to returned HTML content
  $customJS = "
  <script>

      /* Here I am writing a sample jQuery to hide the navigation menu
         You can write your own jQuery for this content
      */
    //Hide Navigation bar
    jQuery(\".navbar\").hide();

  </script>";

  //Append Custom JS with HTML
  $html = $content . $customJS;

  //Return customized HTML
  return $html;
}

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

Try this

 <allow  users="?" />

Now you are using <deny users="?" /> that means you are not allowing authenticated user to use your site.

authorization Element

What do raw.githubusercontent.com URLs represent?

raw.githubusercontent.com/username/repo-name/branch-name/path

Replace username with the username of the user that created the repo.

Replace repo-name with the name of the repo.

Replace branch-name with the name of the branch.

Replace path with the path to the file.

To reverse to go to GitHub.com:

GitHub.com/username/repo-name/directory-path/blob/branch-name/filename

Group array items using object

var array = [{
      id: "123",
      name: "aaaaaaaa"
    }, {
      id: "123",
      name: "aaaaaaaa"
    }, {
      id: '456',
      name: 'bbbbbbbbbb'
    }, {
      id: '789',
      name: 'ccccccccc'
    }, {
      id: '789',
      name: 'ccccccccc'
    }, {
      id: '098',
      name: 'dddddddddddd'
    }];
//if you want to group this array
group(array, key) {
  console.log(array);
  let finalArray = [];
  array.forEach(function(element) {
    var newArray = [];
    array.forEach(function(element1) {
      if (element[key] == element1[key]) {
          newArray.push(element)
      }
    });
    if (!(finalArray.some(arrVal => newArray[0][key] == arrVal[0][key]))) {
        finalArray.push(newArray);
    }
  });
  return finalArray
}
//and call this function
groupArray(arr, key) {
  console.log(this.group(arr, key))
}

PowerShell array initialization

You can also rely on the default value of the constructor if you wish to create a typed array:

> $a = new-object bool[] 5
> $a
False
False
False
False
False

The default value of a bool is apparently false so this works in your case. Likewise if you create a typed int[] array, you'll get the default value of 0.

Another cool way that I use to initialze arrays is with the following shorthand:

> $a = ($false, $false, $false, $false, $false)
> $a
False
False
False
False
False

Or if you can you want to initialize a range, I've sometimes found this useful:

> $a = (1..5)   
> $a
1
2
3
4
5

Hope this was somewhat helpful!

Are there constants in JavaScript?

with the "new" Object api you can do something like this:

var obj = {};
Object.defineProperty(obj, 'CONSTANT', {
  configurable: false
  enumerable: true,
  writable: false,
  value: "your constant value"
});

take a look at this on the Mozilla MDN for more specifics. It's not a first level variable, as it is attached to an object, but if you have a scope, anything, you can attach it to that. this should work as well. So for example doing this in the global scope will declare a pseudo constant value on the window (which is a really bad idea, you shouldn't declare global vars carelessly)

Object.defineProperty(this, 'constant', {
  enumerable: true, 
  writable: false, 
  value: 7, 
  configurable: false
});

> constant
=> 7
> constant = 5
=> 7

note: assignment will give you back the assigned value in the console, but the variable's value will not change

Disable button in angular with two conditions?

In addition to the other answer, I would like to point out that this reasoning is also known as the De Morgan's law. It's actually more about mathematics than programming, but it is so fundamental that every programmer should know about it.

Your problem started like this:

enabled  = A and B
disabled = not ( A and B )

So far so good, but you went one step further and tried to remove the braces. And that's a little tricky, because you have to replace the and/&& with an or/||.

not ( A and B ) = not(A) OR not(B)

Or in a more mathematical notation:

enter image description here

I always keep this law in mind whenever I simplify conditions or work with probabilities.

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

How do I find my host and username on mysql?

You should be able to access the local database by using the name localhost. There is also a way to determine the hostname of the computer you're running on, but it doesn't sound like you need that. As for the username, you can either (1) give permissions to the account that PHP runs under to access the database without a password, or (2) store the username and password that you need to connect with (hard-coded or stored in a config file), and pass those as arguments to mysql_connect. See http://php.net/manual/en/function.mysql-connect.php.

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

How to get access to job parameters from ItemReader, in Spring Batch?

While executing the job we need to pass Job parameters as follows:

JobParameters jobParameters= new JobParametersBuilder().addString("file.name", "filename.txt").toJobParameters();   
JobExecution execution = jobLauncher.run(job, jobParameters);  

by using the expression language we can import the value as follows:

 #{jobParameters['file.name']}

AssertNull should be used or AssertNotNull

Use assertNotNull(obj). assert means must be.

How Do I Upload Eclipse Projects to GitHub?

You need a git client to upload your project to git servers. For eclipse EGIT is a nice plugin to use GIT.

to learn the basic of git , see here // i think you should have the basic first

Python - abs vs fabs

math.fabs() converts its argument to float if it can (if it can't, it throws an exception). It then takes the absolute value, and returns the result as a float.

In addition to floats, abs() also works with integers and complex numbers. Its return type depends on the type of its argument.

In [7]: type(abs(-2))
Out[7]: int

In [8]: type(abs(-2.0))
Out[8]: float

In [9]: type(abs(3+4j))
Out[9]: float

In [10]: type(math.fabs(-2))
Out[10]: float

In [11]: type(math.fabs(-2.0))
Out[11]: float

In [12]: type(math.fabs(3+4j))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/npe/<ipython-input-12-8368761369da> in <module>()
----> 1 type(math.fabs(3+4j))

TypeError: can't convert complex to float

Convert month int to month name

CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(
    Convert.ToInt32(e.Row.Cells[7].Text.Substring(3,2))).Substring(0,3) 
    + "-" 
    + Convert.ToDateTime(e.Row.Cells[7].Text).ToString("yyyy");

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

error: invalid type argument of ‘unary *’ (have ‘int’)

Once you declare the type of a variable, you don't need to cast it to that same type. So you can write a=&b;. Finally, you declared c incorrectly. Since you assign it to be the address of a, where a is a pointer to int, you must declare it to be a pointer to a pointer to int.

#include <stdio.h>
int main(void)
{
    int b=10;
    int *a=&b;
    int **c=&a;
    printf("%d", **c);
    return 0;
} 

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

ImportError: no module named win32api

This is resolve my case as found on Where to find the win32api module for Python?

pip install pypiwin32

What is C# equivalent of <map> in C++?

The equivalent would be class SortedDictionary<TKey, TValue> in the System.Collections.Generic namespace.

If you don't care about the order the class Dictionary<TKey, TValue> in the System.Collections.Generic namespace would probably be sufficient.

Remove last character from C++ string

If the length is non zero, you can also

str[str.length() - 1] = '\0';

Authenticating in PHP using LDAP through Active Directory

You would think that simply authenticating a user in Active Directory would be a pretty simple process using LDAP in PHP without the need for a library. But there are a lot of things that can complicate it pretty fast:

  • You must validate input. An empty username/password would pass otherwise.
  • You should ensure the username/password is properly encoded when binding.
  • You should be encrypting the connection using TLS.
  • Using separate LDAP servers for redundancy in case one is down.
  • Getting an informative error message if authentication fails.

It's actually easier in most cases to use a LDAP library supporting the above. I ultimately ended up rolling my own library which handles all the above points: LdapTools (Well, not just for authentication, it can do much more). It can be used like the following:

use LdapTools\Configuration;
use LdapTools\DomainConfiguration;
use LdapTools\LdapManager;

$domain = (new DomainConfiguration('example.com'))
    ->setUsername('username') # A separate AD service account used by your app
    ->setPassword('password')
    ->setServers(['dc1', 'dc2', 'dc3'])
    ->setUseTls(true);
$config = new Configuration($domain);
$ldap = new LdapManager($config);

if (!$ldap->authenticate($username, $password, $message)) {
    echo "Error: $message";
} else {
    // Do something...
}

The authenticate call above will:

  • Validate that neither the username or password is empty.
  • Ensure the username/password is properly encoded (UTF-8 by default)
  • Try an alternate LDAP server in case one is down.
  • Encrypt the authentication request using TLS.
  • Provide additional information if it failed (ie. locked/disabled account, etc)

There are other libraries to do this too (Such as Adldap2). However, I felt compelled enough to provide some additional information as the most up-voted answer is actually a security risk to rely on with no input validation done and not using TLS.

Download files from SFTP with SSH.NET library

This solves the problem on my end.

var files = sftp.ListDirectory(remoteVendorDirectory).Where(f => !f.IsDirectory);

foreach (var file in files)
{
    var filename = $"{LocalDirectory}/{file.Name}";
    if (!File.Exists(filename))
    {
        Console.WriteLine("Downloading  " + file.FullName);
        var localFile = File.OpenWrite(filename);
        sftp.DownloadFile(file.FullName, localFile);
    }
}

How to convert date to string and to date again?

Convert Date to String using this function

public String convertDateToString(Date date, String format) {
        String dateStr = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            dateStr = df.format(date);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return dateStr;
    }

From Convert Date to String in Java . And convert string to date again

public Date convertStringToDate(String dateStr, String format) {
        Date date = null;
        DateFormat df = new SimpleDateFormat(format);
        try {
            date = df.parse(dateStr);
        } catch (Exception ex) {
            System.out.println(ex);
        }
        return date;
    }

From Convert String to date in Java

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How to get ip address of a server on Centos 7 in bash

Ref: https://garbagevalue.com/blog/4-simle-ways-to-check-ip-adress-in-centos-7


I'm using CentOS 7 and command

ip a

is enough to do the job.

enter image description here

Edit

Just slice out the IP address part from that test.

ip a | grep 192

Changing project port number in Visual Studio 2013

This is the only solution that worked for me after trying several of those above. Switch to your c:\users folder and search for .sln and then remove all .sln files that have your project name. Then restart your computer and rebuild the solution (F5) and it worked!

What does <T> denote in C#

It is a Generic Type Parameter.

A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.

For example:

public T[] Reverse<T>(T[] array)
{
    var result = new T[array.Length];
    int j=0;
    for(int i=array.Length - 1; i>= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.

So, to reverse an array of strings:

string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);

Will produce a string array in result of { "5", "4", "3", "2", "1" }

This has the same effect as if you had called an ordinary (non-generic) method that looks like this:

public string[] Reverse(string[] array)
{
    var result = new string[array.Length];
    int j=0;
    for(int i=array.Length - 1; i >= 0; i--)
    {
        result[j] = array[i];
        j++;
    }
    return result;
}

The compiler sees that array contains strings, so it returns an array of strings. Type string is substituted for the T type parameter.


Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>, the T is a placeholder for an arbitrary type; it means that SampleCollection can represent a collection of objects, the type of which you specify when you create the collection.

So:

var collection = new SampleCollection<string>();

creates a collection that can hold strings. The Reverse method illustrated above, in a somewhat different form, can be used to reverse the collection's members.

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

Try editing your eclipse.ini file and add the following at the top

-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home

Of course the path may be slightly different, looks like I have an older version...

I'm not sure if it will add itself automatically. If not go into

Preferences --> Java --> Installed JREs

Click Add and follow the instructions there to add it

How to print a specific row of a pandas DataFrame?

When you call loc with a scalar value, you get a pd.Series. That series will then have one dtype. If you want to see the row as it is in the dataframe, you'll want to pass an array like indexer to loc.

Wrap your index value with an additional pair of square brackets

print(df.loc[[159220]])

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

How do I fix a merge conflict due to removal of a file in a branch?

I normally just run git mergetool and it will prompt me if I want to keep the modified file or keep it deleted. This is the quickest way IMHO since it's one command instead of several per file.

If you have a bunch of deleted files in a specific subdirectory and you want all of them to be resolved by deleting the files, you can do this:

yes d | git mergetool -- the/subdirectory

The d is provided to choose deleting each file. You can also use m to keep the modified file. Taken from the prompt you see when you run mergetool:

Use (m)odified or (d)eleted file, or (a)bort?

javascript date to string

A little bit simpler using regex and toJSON().

var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]

Which at the time of writing gives you "20151111180924".

The good thing of using toJSON() is that everything comes already padded.

Selecting Folder Destination in Java?

You could try something like this (as shown here: Select a Directory with a JFileChooser):

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {            
    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //    
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
      System.out.println("getCurrentDirectory(): " 
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " 
         +  chooser.getSelectedFile());
      }
    else {
      System.out.println("No Selection ");
      }
     }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

ES6 Map in Typescript

As a bare minimum:

tsconfig:

 "lib": [
      "es2015"
    ]

and install a polyfill such as https://github.com/zloirock/core-js if you want IE < 11 support: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

Generating (pseudo)random alpha-numeric strings

I know it's an old post but I'd like to contribute with a class I've created based on Jeremy Ruten's answer and improved with suggestions in comments:

    class RandomString
    {
      private static $characters = 'abcdefghijklmnopqrstuvwxyz0123456789';
      private static $string;
      private static $length = 8; //default random string length

      public static function generate($length = null)
      {

        if($length){
          self::$length = $length;
        }

        $characters_length = strlen(self::$characters) - 1;

        for ($i = 0; $i < self::$length; $i++) {
          self::$string .= self::$characters[mt_rand(0, $characters_length)];
        }

        return self::$string;

      }

    }

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

The easiest way is to use Resource Manager

enter image description here

Then you can select each density

enter image description here

And after importing you can see the 6 different versions of this image

enter image description here

concatenate char array in C

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

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

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

What is the difference between JavaScript and jQuery?

Javascript is a programming language whereas jQuery is a library to help make writing in javascript easier. It's particularly useful for simply traversing the DOM in an HTML page.

Remove blank attributes from an Object in Javascript

You can do a recursive removal in one line using json.stringify's replacer argument

const removeEmptyValues = obj => (
  JSON.parse(JSON.stringify(obj, (k,v) => v ?? undefined))
)

Usage:

removeEmptyValues({a:{x:1,y:null,z:undefined}}) // Returns {a:{x:1}}

As mentioned in Emmanuel's comment, this technique only worked if your data structure contains only data types that can be put into JSON format (strings, numbers, lists, etc).

(This answer has been updated to use the new Nullish Coalescing operator. depending on browser support needs you may want to use this function instead: (k,v) => v!=null ? v : undefined)

Detect if an input has text in it using CSS -- on a page I am visiting and do not control?

You can style input[type=text] differently depending on whether or not the input has text by styling the placeholder. This is not an official standard at this point but has wide browser support, though with different prefixes:

input[type=text] {
    color: red;
}
input[type=text]:-moz-placeholder {
    color: green;
}
input[type=text]::-moz-placeholder {
    color: green;
}
input[type=text]:-ms-input-placeholder {
    color: green;
}
input[type=text]::-webkit-input-placeholder {
    color: green;
}

Example: http://fiddlesalad.com/scss/input-placeholder-css

How to import an Oracle database from dmp file and log file?

All this peace of code put into *.bat file and run all at once:

My code for creating user in oracle. crate_drop_user.sql file

drop user "USER" cascade;
DROP TABLESPACE "USER";

CREATE TABLESPACE USER DATAFILE 'D:\ORA_DATA\ORA10\USER.ORA' SIZE 10M REUSE 
    AUTOEXTEND 
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    SEGMENT SPACE MANAGEMENT  AUTO
/ 

CREATE  TEMPORARY TABLESPACE "USER_TEMP" TEMPFILE 
    'D:\ORA_DATA\ORA10\USER_TEMP.ORA' SIZE 10M REUSE AUTOEXTEND
    ON NEXT  5M  EXTENT MANAGEMENT LOCAL 
    UNIFORM SIZE 1M    
/

CREATE USER "USER"  PROFILE "DEFAULT" 
    IDENTIFIED BY "user_password" DEFAULT TABLESPACE "USER" 
    TEMPORARY TABLESPACE "USER_TEMP" 
/    

alter user USER quota unlimited on "USER";

GRANT CREATE PROCEDURE TO "USER";
GRANT CREATE PUBLIC SYNONYM TO "USER";
GRANT CREATE SEQUENCE TO "USER";
GRANT CREATE SNAPSHOT TO "USER";
GRANT CREATE SYNONYM TO "USER";
GRANT CREATE TABLE TO "USER";
GRANT CREATE TRIGGER TO "USER";
GRANT CREATE VIEW TO "USER";
GRANT "CONNECT" TO "USER";
GRANT SELECT ANY DICTIONARY to "USER";
GRANT CREATE TYPE TO "USER";

create file import.bat and put this lines in it:

SQLPLUS SYSTEM/systempassword@ORA_alias @"crate_drop_user.SQL"
IMP SYSTEM/systempassword@ORA_alias FILE=user.DMP FROMUSER=user TOUSER=user GRANTS=Y log =user.log

Be carefull if you will import from one user to another. For example if you have user named user1 and you will import to user2 you may lost all grants , so you have to recreate it.

Good luck, Ivan

How to get the first column of a pandas DataFrame as a Series?

You can get the first column as a Series by following code:

x[x.columns[0]]

How to calculate mean, median, mode and range from a set of numbers

public class Mode {
    public static void main(String[] args) {
        int[] unsortedArr = new int[] { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};
        Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

        for (int i = 0; i < unsortedArr.length; i++) {
            Integer value = countMap.get(unsortedArr[i]);

            if (value == null) {
                countMap.put(unsortedArr[i], 0);
            } else {
                int intval = value.intValue();
                intval++;
                countMap.put(unsortedArr[i], intval);
            }
        }

        System.out.println(countMap.toString());

        int max = getMaxFreq(countMap.values());
        List<Integer> modes = new ArrayList<Integer>();

        for (Entry<Integer, Integer> entry : countMap.entrySet()) {
            int value = entry.getValue();
            if (value == max)
                modes.add(entry.getKey());
        }
        System.out.println(modes);
    }

    public static int getMaxFreq(Collection<Integer> valueSet) {
        int max = 0;
        boolean setFirstTime = false;

        for (Iterator iterator = valueSet.iterator(); iterator.hasNext();) {
            Integer integer = (Integer) iterator.next();

            if (!setFirstTime) {
                max = integer;
                setFirstTime = true;
            }
            if (max < integer) {
                max = integer;
            }
        }
        return max;
    }
}

Test data

Modes {1,3} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 };
Modes {-1} for { 3, 1, 5, 2, 4, 1, 3, 4, 3, 2, 1, 3, 4, 1 ,-1,-1,-1,-1,-1};

Common MySQL fields and their appropriate data types

Someone's going to post a much better answer than this, but just wanted to make the point that personally I would never store a phone number in any kind of integer field, mainly because:

  1. You don't need to do any kind of arithmetic with it, and
  2. Sooner or later someone's going to try to (do something like) put brackets around their area code.

In general though, I seem to almost exclusively use:

  • INT(11) for anything that is either an ID or references another ID
  • DATETIME for time stamps
  • VARCHAR(255) for anything guaranteed to be under 255 characters (page titles, names, etc)
  • TEXT for pretty much everything else.

Of course there are exceptions, but I find that covers most eventualities.

Checking on a thread / remove from list

mythreads = threading.enumerate()

Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

Display milliseconds in Excel

I did this in Excel 2000.

This statement should be: ms = Round(temp - Int(temp), 3) * 1000

You need to create a custom format for the result cell of [h]:mm:ss.000

How to modify list entries during for loop?

It is not clear from your question what the criteria for deciding what strings to remove is, but if you have or can make a list of the strings that you want to remove , you could do the following:

my_strings = ['a','b','c','d','e']
undesirable_strings = ['b','d']
for undesirable_string in undesirable_strings:
    for i in range(my_strings.count(undesirable_string)):
        my_strings.remove(undesirable_string)

which changes my_strings to ['a', 'c', 'e']

Android Studio - Auto complete and other features not working

Close Android Studio Go to C:\Users\UserName.android and rename the folder:

  • build-cache to build-cache_old

Go to C:\Users\UserName.AndroidStudio3.x\system OR (Android studio 4 and Higher) Go to C:\Users\UserName\AppData\Local\Google\AndroidStudio4.x and rename these folders:

  • caches to caches_old

  • compiler to compiler_old

  • compile-server to compile-server_old

  • conversion to conversion_old

  • external_build_system to external_build_system_old

  • frameworks to frameworks_old

  • gradle to gradle_old

  • resource_folder_cache to resource_folder_cache_old

Open the Android Studio and open your project again.

sql select with column name like

Thank you @Blorgbeard for the genious idea.

By the way Blorgbeard's query was not working for me so I edited it:

DECLARE @Table_Name as VARCHAR(50) SET @Table_Name = 'MyTable'          -- put here you table name
DECLARE @Column_Like as VARCHAR(20) SET @Column_Like = '%something%'    -- put here you element
DECLARE @sql NVARCHAR(MAX) SET @sql = 'select '

SELECT @sql = @sql + '[' + sys.columns.name + '],'
FROM sys.columns 
JOIN sys.tables ON sys.columns.object_id = tables.object_id
WHERE sys.columns.name like @Column_Like
and sys.tables.name = @Table_Name

SET @sql = left(@sql,len(@sql)-1) -- remove trailing comma
SET @sql = @sql + ' from ' + @Table_Name

EXEC sp_executesql @sql

Build .so file from .c file using gcc command line

To generate a shared library you need first to compile your C code with the -fPIC (position independent code) flag.

gcc -c -fPIC hello.c -o hello.o

This will generate an object file (.o), now you take it and create the .so file:

gcc hello.o -shared -o libhello.so

EDIT: Suggestions from the comments:

You can use

gcc -shared -o libhello.so -fPIC hello.c

to do it in one step. – Jonathan Leffler

I also suggest to add -Wall to get all warnings, and -g to get debugging information, to your gcc commands. – Basile Starynkevitch

select2 changing items dynamically

I fix the lack of example's library here:

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.js">

http://jsfiddle.net/bbAU9/328/

Int or Number DataType for DataAnnotation validation attribute

ASP.NET Core 3.1

This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:

The attribute:

  [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
    public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
    {
        public void AddValidation(ClientModelValidationContext context)
        {
            MergeAttribute(context.Attributes, "data-val", "true");
            var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
            MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
        }

        public override bool IsValid(object value)
        {
            return int.TryParse(value?.ToString() ?? "", out int newVal);
        }

        private bool MergeAttribute(
              IDictionary<string, string> attributes,
              string key,
              string value)
        {
            if (attributes.ContainsKey(key))
            {
                return false;
            }
            attributes.Add(key, value);
            return true;
        }
    }

Client side logic:

$.validator.addMethod("mustbeinteger",
    function (value, element, parameters) {
        return !isNaN(parseInt(value)) && isFinite(value);
    });

$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
    options.rules.mustbeinteger = {};
    options.messages["mustbeinteger"] = options.message;
});

And finally the Usage:

 [MustBeInteger(ErrorMessage = "You must provide a valid number")]
 public int SomeNumber { get; set; }

How do I start an activity from within a Fragment?

The difference between starting an Activity from a Fragment and an Activity is how you get the context, because in both cases it has to be an activity.

From an activity: The context is the current activity (this)

Intent intent = new Intent(this, NewActivity.class);
startActivity(intent);

From a fragment: The context is the parent activity (getActivity()). Notice, that the fragment itself can start the activity via startActivity(), this is not necessary to be done from the activity.

Intent intent = new Intent(getActivity(), NewActivity.class);
startActivity(intent);

Force encode from US-ASCII to UTF-8 (iconv)

Here's a script that will find all files matching a pattern you pass it, and then converting them from their current file encoding to UTF-8. If the encoding is US ASCII, then it will still show as US ASCII, since that is a subset of UTF-8.

#!/usr/bin/env bash
find . -name "${1}" |
    while read line;
    do
        echo "***************************"
        echo "Converting ${line}"

        encoding=$(file -b --mime-encoding ${line})
        echo "Found Encoding: ${encoding}"

        iconv -f "${encoding}" -t "utf-8" ${line} -o ${line}.tmp
        mv ${line}.tmp ${line}
    done

UNIX export command

When you execute a program the child program inherits its environment variables from the parent. For instance if $HOME is set to /root in the parent then the child's $HOME variable is also set to /root.

This only applies to environment variable that are marked for export. If you set a variable at the command-line like

$ FOO="bar"

That variable will not be visible in child processes. Not unless you export it:

$ export FOO

You can combine these two statements into a single one in bash (but not in old-school sh):

$ export FOO="bar"

Here's a quick example showing the difference between exported and non-exported variables. To understand what's happening know that sh -c creates a child shell process which inherits the parent shell's environment.

$ FOO=bar
$ sh -c 'echo $FOO'

$ export FOO
$ sh -c 'echo $FOO'
bar

Note: To get help on shell built-in commands use help export. Shell built-ins are commands that are part of your shell rather than independent executables like /bin/ls.

Autoresize View When SubViews are Added

Yes, it is because you are using auto layout. Setting the view frame and resizing mask will not work.

You should read Working with Auto Layout Programmatically and Visual Format Language.

You will need to get the current constraints, add the text field, adjust the contraints for the text field, then add the correct constraints on the text field.

How to hide element using Twitter Bootstrap and show it using jQuery?

Use bootstrap .collapse instead of .hidden

Later in JQuery you can use .show() or .hide() to manipulate it

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

One additional step I needed to take was to switch my URL from http://localhost to http://127.0.0.0

How to preSelect an html dropdown list with php?

This answer is not relevant for particular recepient, but maybe useful for others. I had similiar issue with 'selecting' right 'option' by value returned from database. I solved it by adding additional tag with applied display:none.

<?php
$status =  "NOT_ON_LIST";

$text = "<html>
<head>
</head>
<body>
<select id=\"statuses\">
   <option value=\"status\" selected=\"selected\" style=\"display:none\">$status</option>
   <option value=\"status\">OK</option>
   <option value=\"status\">DOWN</option>
   <option value=\"status\">UNKNOWN</option>
</select>
</body>
</html>";

print $text;
?>

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

How to write a file with C in Linux?

You need to write() the read() data into the new file:

ssize_t nrd;
int fd;
int fd1;

fd = open(aa[1], O_RDONLY);
fd1 = open(aa[2], O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
while (nrd = read(fd,buffer,50)) {
    write(fd1,buffer,nrd);
}

close(fd);
close(fd1);

Update: added the proper opens...

Btw, the O_CREAT can be OR'd (O_CREAT | O_WRONLY). You are actually opening too many file handles. Just do the open once.

Assign pandas dataframe column dtypes

Another way to set the column types is to first construct a numpy record array with your desired types, fill it out and then pass it to a DataFrame constructor.

import pandas as pd
import numpy as np    

x = np.empty((10,), dtype=[('x', np.uint8), ('y', np.float64)])
df = pd.DataFrame(x)

df.dtypes ->

x      uint8
y    float64

How to select rows in a DataFrame between two values, in Python Pandas?

you can also use .between() method

emp = pd.read_csv("C:\\py\\programs\\pandas_2\\pandas\\employees.csv")

emp[emp["Salary"].between(60000, 61000)]

Output

enter image description here

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

how to set font size based on container size?

Here is the function:

document.body.setScaledFont = function(f) {
  var s = this.offsetWidth, fs = s * f;
  this.style.fontSize = fs + '%';
  return this
};

Then convert all your documents child element font sizes to em's or %.

Then add something like this to your code to set the base font size.

document.body.setScaledFont(0.35);
window.onresize = function() {
    document.body.setScaledFont(0.35);
}

http://jsfiddle.net/0tpvccjt/

syntax error when using command line in python

I faced a similar problem, on my Windows computer, please do check that you have set the Environment Variables correctly.

To check that Environment variable is set correctly:

  1. Open cmd.exe

  2. Type Python and press return

  3. (a) If it outputs the version of python then the environment variables are set correctly.

    (b) If it outputs "no such program or file name" then your environment variable are not set correctly.

To set environment variable:

  1. goto Computer-> System Properties-> Advanced System Settings -> Set Environment Variables
  2. Goto path in the system variables; append ;C:\Python27 in the end.

If you have correct variables already set; then you are calling the file inside the python interpreter.

How to use the 'replace' feature for custom AngularJS directives?

replace:true is Deprecated

From the Docs:

replace ([DEPRECATED!], will be removed in next major release - i.e. v2.0)

specify what the template should replace. Defaults to false.

  • true - the template will replace the directive's element.
  • false - the template will replace the contents of the directive's element.

-- AngularJS Comprehensive Directive API

From GitHub:

Caitp-- It's deprecated because there are known, very silly problems with replace: true, a number of which can't really be fixed in a reasonable fashion. If you're careful and avoid these problems, then more power to you, but for the benefit of new users, it's easier to just tell them "this will give you a headache, don't do it".

-- AngularJS Issue #7636


Update

Note: replace: true is deprecated and not recommended to use, mainly due to the issues listed here. It has been completely removed in the new Angular.

Issues with replace: true

For more information, see

Extract substring from a string

There is another way , if you want to get sub string before and after a character

String s ="123dance456";
String[] split = s.split("dance");
String firstSubString = split[0];
String secondSubString = split[1];

check this post- how to find before and after sub-string in a string

How to add a "sleep" or "wait" to my Lua Script?

This homebrew function have precision down to a 10th of a second or less.

function sleep (a) 
    local sec = tonumber(os.clock() + a); 
    while (os.clock() < sec) do 
    end 
end

How to add row in JTable?

Use:

DefaultTableModel model = new DefaultTableModel(); 
JTable table = new JTable(model); 

// Create a couple of columns 
model.addColumn("Col1"); 
model.addColumn("Col2"); 

// Append a row 
model.addRow(new Object[]{"v1", "v2"});