Programs & Examples On #Presentationml

Part of the Office Open XML specification ECMA-376

Writing MemoryStream to Response Object

Assuming you can get a Stream, FileStream or MemoryStream for instance, you can do this:

Stream file = [Some Code that Gets you a stream];
var filename = [The name of the file you want to user to download/see];

if (file != null && file.CanRead)
{
    context.Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
    context.Response.ContentType = "application/octet-stream";
    context.Response.ClearContent();
    file.CopyTo(context.Response.OutputStream);
}

Thats a copy and paste from some of my working code, so the content type might not be what youre looking for, but writing the stream to the response is the trick on the last line.

Iterating Over Dictionary Key Values Corresponding to List in Python

Dictionaries have a built in function called iterkeys().

Try:

for team in league.iterkeys():
    runs_scored = float(league[team][0])
    runs_allowed = float(league[team][1])
    win_percentage = round((runs_scored**2)/((runs_scored**2)+(runs_allowed**2))*1000)
    print win_percentage

$ is not a function - jQuery error

When jQuery is not present you get $ is undefined and not your message.

Did you check if you don't have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.

Slightly out of the question, but I can't resist to write a shorter code to your class assignment:

    var i = 1;
    $("ol li").each(function(){
        $(this).addClass('olli' + i++);
    });

How is attr_accessible used in Rails 4?

We can use

params.require(:person).permit(:name, :age)

where person is Model, you can pass this code on a method person_params & use in place of params[:person] in create method or else method

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How can I get the number of days between 2 dates in Oracle 11g?

You can try using:

select trunc(sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) as days from dual

How to generate a random alpha-numeric string

You can use an Apache Commons library for this, RandomStringUtils:

RandomStringUtils.randomAlphanumeric(20).toUpperCase();

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

As Lambdageek pointed out float multiplication is not associative and you can get less accuracy, but also when get better accuracy you can argue against optimisation, because you want a deterministic application. For example in game simulation client/server, where every client has to simulate the same world you want floating point calculations to be deterministic.

Is JavaScript's "new" keyword considered harmful?

I am newbie to Javascript so maybe I am just not too experienced in providing a good view point to this. Yet I want to share my view on this "new" thing.

I have come from the C# world where using the keyword "new" is so natural that it is the factory design pattern that looks weird to me.

When I first code in Javascript, I don't realize that there is the "new" keyword and code like the one in YUI pattern and it doesn't take me long to run into disaster. I lose track of what a particular line is supposed to be doing when looking back the code I've written. More chaotic is that my mind can't really transit between object instances boundaries when I am "dry-running" the code.

Then, I found the "new" keyword which to me, it "separate" things. With the new keyword, it creates things. Without the new keyword, I know I won't confuse it with creating things unless the function I am invoking gives me strong clues of that.

For instance, with var bar=foo(); I have no clues as what bar could possibly be.... Is it a return value or is it a newly created object? But with var bar = new foo(); I know for sure bar is an object.

How to read a string one letter at a time in python

For the actual processing I'd keep a string of finished product, and loop through each letter in the string they have entered. I'd call a function to convert a letter to morse code, then add it to the string of existing morse code.

finishedProduct = []
userInput = input("Enter text")
for letter in userInput:
    finishedProduct.append( letterToMorseCode(letter) )
theString = ''.join(finishedProduct)
print(theString)

You could either check for space in the loop, or in the function that is called.

ClassCastException, casting Integer to Double

sum = Double.parseDouble(""+marks.get(i));

Functional style of Java 8's Optional.ifPresent and if-not-Present?

You cannot call orElse after ifPresent, the reason is, orElse is called on an optiional but ifPresent returns void. So the best approach to achieve is ifPresentOrElse. It could be like this:

op.ifPresentOrElse( 
            (value) 
                -> { System.out.println( 
                         "Value is present, its: "
                         + value); }, 
            () 
                -> { System.out.println( 
                         "Value is empty"); }); 

How to publish a Web Service from Visual Studio into IIS?

If using Visual Studio 2010 you can right-click on the project for the service, and select properties. Then select the Web tab. Under the Servers section you can configure the URL. There is also a button to create the virtual directory.

java.util.Date and getYear()

        try{ 
int year = Integer.parseInt(new Date().toString().split("-")[0]); 
} 
catch(NumberFormatException e){
}

Much of Date is deprecated.

Split string to equal length substrings in Java

public String[] splitInParts(String s, int partLength)
{
    int len = s.length();

    // Number of parts
    int nparts = (len + partLength - 1) / partLength;
    String parts[] = new String[nparts];

    // Break into parts
    int offset= 0;
    int i = 0;
    while (i < nparts)
    {
        parts[i] = s.substring(offset, Math.min(offset + partLength, len));
        offset += partLength;
        i++;
    }

    return parts;
}

How to connect to a remote Windows machine to execute commands using python?

Maybe you can use SSH to connect to a remote server.

Install freeSSHd on your windows server.

SSH Client connection Code:

import paramiko

hostname = "your-hostname"
username = "your-username"
password = "your-password"
cmd = 'your-command'

try:
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname,username=username,password=password)
    print("Connected to %s" % hostname)
except paramiko.AuthenticationException:
    print("Failed to connect to %s due to wrong username/password" %hostname)
    exit(1)
except Exception as e:
    print(e.message)    
    exit(2)

Execution Command and get feedback:

try:
    stdin, stdout, stderr = ssh.exec_command(cmd)
except Exception as e:
    print(e.message)

err = ''.join(stderr.readlines())
out = ''.join(stdout.readlines())
final_output = str(out)+str(err)
print(final_output)

How to get char from string by index?

This should further clarify the points:

a = int(raw_input('Enter the index'))
str1 = 'Example'
leng = len(str1)
if (a < (len-1)) and (a > (-len)):
    print str1[a]
else:
    print('Index overflow')

Input 3 Output m

Input -3 Output p

'dict' object has no attribute 'has_key'

The whole code in the document will be:

graph = {'A': ['B', 'C'],
             'B': ['C', 'D'],
             'C': ['D'],
             'D': ['C'],
             'E': ['F'],
             'F': ['C']}
def find_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph:
            return None
        for node in graph[start]:
            if node not in path:
                newpath = find_path(graph, node, end, path)
                if newpath: return newpath
        return None

After writing it, save the document and press F 5

After that, the code you will run in the Python IDLE shell will be:

find_path(graph, 'A','D')

The answer you should receive in IDLE is

['A', 'B', 'C', 'D'] 

Execute jar file with multiple classpath libraries from command prompt

You cannot use both -jar and -cp on the command line - see the java documentation that says that if you use -jar:

the JAR file is the source of all user classes, and other user class path settings are ignored.

You could do something like this:

java -cp lib\*.jar;. myproject.MainClass

Notice the ;. in the -cp argument, to work around a Java command-line bug. Also, please note that this is the Windows version of the command. The path separator on Unix is :.

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

JUnit tests pass in Eclipse but fail in Maven Surefire

I had a similar problem, the annotation @Autowired in the test code did not work under using the Maven command line while it worked fine in Eclipse. I just update my JUnit version from 4.4 to 4.9 and the problem was solved.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.13.1</version>
</dependency>

How can I determine the URL that a local Git repository was originally cloned from?

I think you can find it under .git/config and remote["origin"] if you didn't manipulate that.

HTML / CSS How to add image icon to input type="button"?

Simply add icon in button element here is the example

   <button class="social-signup facebook"> 
     <i class="fa fa-facebook-official"></i>  
      Sign up with Facebook</button>

What and where are the stack and heap?

I think many other people have given you mostly correct answers on this matter.

One detail that has been missed, however, is that the "heap" should in fact probably be called the "free store". The reason for this distinction is that the original free store was implemented with a data structure known as a "binomial heap." For that reason, allocating from early implementations of malloc()/free() was allocation from a heap. However, in this modern day, most free stores are implemented with very elaborate data structures that are not binomial heaps.

Add support library to Android Studio project

I no longer work on Android project for a while. Although the below provides some clue to how an android studio project can be configured, but I can't guarantee it works flawlessly.

In principle, IntelliJ respects the build file and will try to use it to configure the IDE project. It's not true in the other way round, IDE changes normally will not affect the build file.

Since most Android projects are built by Gradle, it's always a good idea to understand this tool.

I'd suggest referring to @skyfishjy's answer, as it seems to be more updated than this one.


The below is not updated

Although android studio is based on IntelliJ IDEA, at the same time it relies on gradle to build your apk. As of 0.2.3, these two doesn't play nicely in term of configuring from GUI. As a result, in addition to use the GUI to setup dependencies, it will also require you to edit the build.gradle file manually.

Assuming you have a Test Project > Test structure. The build.gradle file you're looking for is located at TestProject/Test/build.gradle

Look for the dependencies section, and make sure you have

compile 'com.android.support:support-v4:13.0.+'

Below is an example.

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
    compile 'com.android.support:support-v4:13.0.+'
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 16
    }
}

You can also add 3rd party libraries from the maven repository

compile group: 'com.google.code.gson', name: 'gson', version: '2.2.4'

The above snippet will add gson 2.2.4 for you.

In my experiment, it seems that adding the gradle will also setup correct IntelliJ dependencies for you.

When to use DataContract and DataMember attributes?

In terms of WCF, we can communicate with the server and client through messages. For transferring messages, and from a security prospective, we need to make a data/message in a serialized format.

For serializing data we use [datacontract] and [datamember] attributes. In your case if you are using datacontract WCF uses DataContractSerializer else WCF uses XmlSerializer which is the default serialization technique.

Let me explain in detail:

basically WCF supports 3 types of serialization:

  1. XmlSerializer
  2. DataContractSerializer
  3. NetDataContractSerializer

XmlSerializer :- Default order is Same as class

DataContractSerializer/NetDataContractSerializer :- Default order is Alphabetical

XmlSerializer :- XML Schema is Extensive

DataContractSerializer/NetDataContractSerializer :- XML Schema is Constrained

XmlSerializer :- Versioning support not possible

DataContractSerializer/NetDataContractSerializer :- Versioning support is possible

XmlSerializer :- Compatibility with ASMX

DataContractSerializer/NetDataContractSerializer :- Compatibility with .NET Remoting

XmlSerializer :- Attribute not required in XmlSerializer

DataContractSerializer/NetDataContractSerializer :- Attribute required in this serializing

so what you use depends on your requirements...

How to format DateTime to 24 hours time?

Console.WriteLine(curr.ToString("HH:mm"));

Copy and paste content from one file to another file in vi

Use the variations of d like dd to cut.

To write a range of lines to another file you can use:

:<n>,<m> w filename

Where <n> and <m> are numbers (or symbols) that designate a range of lines.

For using the desktop clipboard, take a look at the +g commands.

Multiple Indexes vs Multi-Column Indexes

I agree with Cade Roux.

This article should get you on the right track:

One thing to note, clustered indexes should have a unique key (an identity column I would recommend) as the first column. Basically it helps your data insert at the end of the index and not cause lots of disk IO and Page splits.

Secondly, if you are creating other indexes on your data and they are constructed cleverly they will be reused.

e.g. imagine you search a table on three columns

state, county, zip.

  • you sometimes search by state only.
  • you sometimes search by state and county.
  • you frequently search by state, county, zip.

Then an index with state, county, zip. will be used in all three of these searches.

If you search by zip alone quite a lot then the above index will not be used (by SQL Server anyway) as zip is the third part of that index and the query optimiser will not see that index as helpful.

You could then create an index on Zip alone that would be used in this instance.

By the way We can take advantage of the fact that with Multi-Column indexing the first index column is always usable for searching and when you search only by 'state' it is efficient but yet not as efficient as Single-Column index on 'state'

I guess the answer you are looking for is that it depends on your where clauses of your frequently used queries and also your group by's.

The article will help a lot. :-)

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

What is a "static" function in C?

"What is a “static” function in C?"

Let's start at the beginning.

It´s all based upon a thing called "linkage":

"An identifier declared in different scopes or in the same scope more than once can be made to refer to the same object or function by a process called linkage. 29)There are three kinds of linkage: external, internal, and none."

Source: C18, 6.2.2/1


"In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. Each declaration of an identifier with no linkage denotes a unique entity."

Source: C18, 6.2.2/2


If a function is defined without a storage-class specifier, the function has external linkage by default:

"If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern."

Source: C18, 6.2.2/5

That means that - if your program is contained of several translation units/source files (.c or .cpp) - the function is visible in all translation units/source files your program has.

This can be a problem in some cases. What if you want to use f.e. two different function (definitions), but with the same function name in two different contexts (actually the file-context).

In C and C++, the static storage-class qualifier applied to a function at file scope (not a static member function of a class in C++ or a function within another block) now comes to help and signifies that the respective function is only visible inside of the translation unit/source file it was defined in and not in the other TLUs/files.

"If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage. 30)"


  1. A function declaration can contain the storage-class specifier static only if it is at file scope; see 6.7.1.

Source: C18, 6.2.2/3


Thus, A static function only makes sense, iff:

  1. Your program is contained of several translation units/source files (.c or .cpp).

and

  1. You want to limit the scope of a function to the file, in which the specific function is defined.

If not both of these requirements match, you don't need to wrap your head around about qualifying a function as static.


Side Notes:

  • As already mentioned, A static function has absolutely no difference at all between C and C++, as this is a feature C++ inherited from C.

It does not matter that in the C++ community, there is a heartbreaking debate about the depreciation of qualifying functions as static in comparison to the use of unnamed namespaces instead, first initialized by a misplaced paragraph in the C++03 standard, declaring the use of static functions as deprecated which soon was revised by the committee itself and removed in C++11.

This was subject to various SO questions:

Unnamed/anonymous namespaces vs. static functions

Superiority of unnamed namespace over static?

Why an unnamed namespace is a "superior" alternative to static?

Deprecation of the static keyword... no more?

In fact, it is not deprecated per C++ standard yet. Thus, the use of static functions is still legit. Even if unnamed namespaces have advantages, the discussion about using or not using static functions in C++ is subject to one´s one mind (opinion-based) and with that not suitable for this website.

How to take the nth digit of a number in python

Ok, first of all, use the str() function in python to turn 'number' into a string

number = 9876543210 #declaring and assigning
number = str(number) #converting

Then get the index, 0 = 1, 4 = 3 in index notation, use int() to turn it back into a number

print(int(number[3])) #printing the int format of the string "number"'s index of 3 or '6'

if you like it in the short form

print(int(str(9876543210)[3])) #condensed code lol, also no more variable 'number'

Maintain aspect ratio of div but fill screen width and height in CSS?

There is now a new CSS property specified to address this: object-fit.

http://docs.webplatform.org/wiki/css/properties/object-fit

Browser support is still somewhat lacking (http://caniuse.com/#feat=object-fit) - currently works to some extent in most browsers except Microsoft - but given time it is exactly what was required for this question.

CSS width of a <span> tag

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

SQL Server CTE and recursion example

Would like to outline a brief semantic parallel to an already correct answer.

In 'simple' terms, a recursive CTE can be semantically defined as the following parts:

1: The CTE query. Also known as ANCHOR.

2: The recursive CTE query on the CTE in (1) with UNION ALL (or UNION or EXCEPT or INTERSECT) so the ultimate result is accordingly returned.

3: The corner/termination condition. Which is by default when there are no more rows/tuples returned by the recursive query.

A short example that will make the picture clear:

;WITH SupplierChain_CTE(supplier_id, supplier_name, supplies_to, level)
AS
(
SELECT S.supplier_id, S.supplier_name, S.supplies_to, 0 as level
FROM Supplier S
WHERE supplies_to = -1    -- Return the roots where a supplier supplies to no other supplier directly

UNION ALL

-- The recursive CTE query on the SupplierChain_CTE
SELECT S.supplier_id, S.supplier_name, S.supplies_to, level + 1
FROM Supplier S
INNER JOIN SupplierChain_CTE SC
ON S.supplies_to = SC.supplier_id
)
-- Use the CTE to get all suppliers in a supply chain with levels
SELECT * FROM SupplierChain_CTE

Explanation: The first CTE query returns the base suppliers (like leaves) who do not supply to any other supplier directly (-1)

The recursive query in the first iteration gets all the suppliers who supply to the suppliers returned by the ANCHOR. This process continues till the condition returns tuples.

UNION ALL returns all the tuples over the total recursive calls.

Another good example can be found here.

PS: For a recursive CTE to work, the relations must have a hierarchical (recursive) condition to work on. Ex: elementId = elementParentId.. you get the point.

Printing the last column of a line in a file

You don't see anything, because of buffering. The output is shown, when there are enough lines or end of file is reached. tail -f means wait for more input, but there are no more lines in file and so the pipe to grep is never closed.

If you omit -f from tail the output is shown immediately:

tail file | grep A1 | awk '{print $NF}'

@EdMorton is right of course. Awk can search for A1 as well, which shortens the command line to

tail file | awk '/A1/ {print $NF}'

or without tail, showing the last column of all lines containing A1

awk '/A1/ {print $NF}' file

Thanks to @MitchellTracy's comment, tail might miss the record containing A1 and thus you get no output at all. This may be solved by switching tail and awk, searching first through the file and only then show the last line:

awk '/A1/ {print $NF}' file | tail -n1

Freeze screen in chrome debugger / DevTools panel for popover inspection?

UPDATE: As Brad Parks wrote in his comment there is a much better and easier solution with only one line of JS code:

run setTimeout(function(){debugger;},5000);, then go show your element and wait until it breaks into the Debugger


Original answer:

I just had the same problem, and I think I found an "universal" solution. (assuming the site uses jQuery)
Hope it helps someone!

  1. Go to elements tab in inspector
  2. Right click <body> and click "Edit as HTML"
  3. Add the following element after <body> then press Ctrl+Enter:
    <div id="debugFreeze" data-rand="0"></div>
  4. Right click this new element, and select "Break on..." -> "Attributes modifications"
  5. Now go to Console view and run the following command:
    setTimeout(function(){$("#debugFreeze").attr("data-rand",Math.random())},5000);
  6. Now go back to the browser window and you have 5 seconds to find your element and click/hover/focus/etc it, before the breakpoint will be hit and the browser will "freeze".
  7. Now you can inspect your clicked/hovered/focused/etc element in peace.

Of course you can modify the javascript and the timing, if you get the idea.

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

How to read GET data from a URL using JavaScript?

I also made a fairly simple function. You call on it by: get("yourgetname");

and get whatever there was. (now that i wrote it i noticed it will give you %26 if you had a & in your value..)

function get(name){
  var url = window.location.search;
  var num = url.search(name);
  var namel = name.length;
  var frontlength = namel+num+1; //length of everything before the value 
  var front = url.substring(0, frontlength);  
  url = url.replace(front, "");  
  num = url.search("&");

 if(num>=0) return url.substr(0,num); 
 if(num<0)  return url;             
}

What's the difference between Perl's backticks, system, and exec?

In general I use system, open, IPC::Open2, or IPC::Open3 depending on what I want to do. The qx// operator, while simple, is too constraining in its functionality to be very useful outside of quick hacks. I find open to much handier.

system: run a command and wait for it to return

Use system when you want to run a command, don't care about its output, and don't want the Perl script to do anything until the command finishes.

#doesn't spawn a shell, arguments are passed as they are
system("command", "arg1", "arg2", "arg3");

or

#spawns a shell, arguments are interpreted by the shell, use only if you
#want the shell to do globbing (e.g. *.txt) for you or you want to redirect
#output
system("command arg1 arg2 arg3");

qx// or ``: run a command and capture its STDOUT

Use qx// when you want to run a command, capture what it writes to STDOUT, and don't want the Perl script to do anything until the command finishes.

#arguments are always processed by the shell

#in list context it returns the output as a list of lines
my @lines = qx/command arg1 arg2 arg3/;

#in scalar context it returns the output as one string
my $output = qx/command arg1 arg2 arg3/;

exec: replace the current process with another process.

Use exec along with fork when you want to run a command, don't care about its output, and don't want to wait for it to return. system is really just

sub my_system {
    die "could not fork\n" unless defined(my $pid = fork);
    return waitpid $pid, 0 if $pid; #parent waits for child
    exec @_; #replace child with new process
}

You may also want to read the waitpid and perlipc manuals.

open: run a process and create a pipe to its STDIN or STDERR

Use open when you want to write data to a process's STDIN or read data from a process's STDOUT (but not both at the same time).

#read from a gzip file as if it were a normal file
open my $read_fh, "-|", "gzip", "-d", $filename
    or die "could not open $filename: $!";

#write to a gzip compressed file as if were a normal file
open my $write_fh, "|-", "gzip", $filename
    or die "could not open $filename: $!";

IPC::Open2: run a process and create a pipe to both STDIN and STDOUT

Use IPC::Open2 when you need to read from and write to a process's STDIN and STDOUT.

use IPC::Open2;

open2 my $out, my $in, "/usr/bin/bc"
    or die "could not run bc";

print $in "5+6\n";

my $answer = <$out>;

IPC::Open3: run a process and create a pipe to STDIN, STDOUT, and STDERR

use IPC::Open3 when you need to capture all three standard file handles of the process. I would write an example, but it works mostly the same way IPC::Open2 does, but with a slightly different order to the arguments and a third file handle.

Is there a java setting for disabling certificate validation?

Not exactly a setting but you can override the default TrustManager and HostnameVerifier to accept anything. Not a safe approach but in your situation, it can be acceptable.

Complete example : Fix certificate problem in HTTPS

Jquery: how to trigger click event on pressing enter key

try out this....

$('#txtSearchProdAssign').keypress(function (e) {
 var key = e.which;
 if(key == 13)  // the enter key code
  {
    $('input[name = butAssignProd]').click();
    return false;  
  }
});   

_x000D_
_x000D_
$(function() {

  $('input[name="butAssignProd"]').click(function() {
    alert('Hello...!');
  });

  //press enter on text area..

  $('#txtSearchProdAssign').keypress(function(e) {
    var key = e.which;
    if (key == 13) // the enter key code
    {
      $('input[name = butAssignProd]').click();
      return false;
    }
  });

});
_x000D_
<!DOCTYPE html>
<html>

<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
  <meta charset=utf-8 />
  <title>JS Bin</title>
</head>

<body>
  <textarea id="txtSearchProdAssign"></textarea>
  <input type="text" name="butAssignProd" placeholder="click here">
</body>

</html>
_x000D_
_x000D_
_x000D_


Find Demo in jsbin.com

How do pointer-to-pointer's work in C? (and when might you use them?)

Let's assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses):

  54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    | 58 |    |    | 63 |    | 55 |    |    | h  | e  | l  | l  | o  | \0 |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

What you can see here, is that at address 63 the string "hello" starts. So in this case, if this is the only occurrence of "hello" in memory then,

const char *c = "hello";

... defines c to be a pointer to the (read-only) string "hello", and thus contains the value 63. c must itself be stored somewhere: in the example above at location 58. Of course we can not only point to characters, but also to other pointers. E.g.:

const char **cp = &c;

Now cp points to c, that is, it contains the address of c (which is 58). We can go even further. Consider:

const char ***cpp = &cp;

Now cpp stores the address of cp. So it has value 55 (based on the example above), and you guessed it: it is itself stored at address 60.


As to why one uses pointers to pointers:

  • The name of an array usually yields the address of its first element. So if the array contains elements of type t, a reference to the array has type t *. Now consider an array of arrays of type t: naturally a reference to this 2D array will have type (t *)* = t **, and is hence a pointer to a pointer.
  • Even though an array of strings sounds one-dimensional, it is in fact two-dimensional, since strings are character arrays. Hence: char **.
  • A function f will need to accept an argument of type t ** if it is to alter a variable of type t *.
  • Many other reasons that are too numerous to list here.

RSA encryption and decryption in Python

You can use simple way for genarate RSA . Use rsa library

pip install rsa 

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

Difference between \b and \B in regex

Source © Copyright RexEgg.com

Word Boundary: \b*

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character).

The regex \bcat\b would, therefore, match cat in a black cat, but it wouldn't match it in catatonic, tomcat or certificate. Removing one of the boundaries, \bcat would match cat in catfish, and cat\b would match cat in tomcat, but not vice-versa. Both, of course, would match cat on its own.

Not-a-word-boundary: \B

\B matches all positions where \b doesn't match. Therefore, it matches:

? When neither side is a word character, for instance at any position in the string $=(@-%++) (including the beginning and end of the string)

? When both sides are a word character, for instance between the H and the i in Hi!

This may not seem very useful, but sometimes \B is just what you want. For instance,

? \Bcat\B will find cat fully surrounded by word characters, as in certificate, but neither on its own nor at the beginning or end of words.

? cat\B will find cat both in certificate and catfish, but neither in tomcat nor on its own.

? \Bcat will find cat both in certificate and tomcat, but neither in catfish nor on its own.

? \Bcat|cat\B will find cat in embedded situation, e.g. in certificate, catfish or tomcat, but not on its own.

How to build jars from IntelliJ properly?

I recently had this problem and think these steps are easy to follow if any prior solution or link is missing detail.

How to create a .jar using IntelliJ IDEA 14.1.5:

  1. File > Save All.
  2. Run driver or class with main method.
  3. File > Project Structure.
  4. Select Tab "Artifacts".
  5. Click green plus button near top of window.
  6. Select JAR from Add drop down menu. Select "From modules with dependencies"
  7. Select main class.
  8. The radio button should be selecting "extract to the target JAR." Press OK.
  9. Check the box "Build on make"
  10. Press apply and OK.
  11. From the main menu, select the build dropdown.
  12. Select the option build artifacts.

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

For all those who are reading this but do not have problem with application.css and instead with their custom CSS classes e.g. admin.css, base.css etc.

Solution is to use as mentioned

bundle exec rake assets:precompile

And in stylesheets references just reference application.css

<%= stylesheet_link_tag    "application", :media => "all" %>

Since assets pipeline will precompile all of your stylesheets in application.css. This also happens in development so using any other references is wrong when using assets pipeline.

Jenkins: Is there any way to cleanup Jenkins workspace?

IMPORTANT: It is safe to remove the workspace for a given Jenkins job as long as the job is not currently running!

NOTE: I am assuming your $JENKINS_HOME is set to the default: /var/jenkins_home.

Clean up one workspace

rm -rf /var/jenkins_home/workspaces/<workspace>

Clean up all workspaces

rm -rf /var/jenkins_home/workspaces/*

Clean up all workspaces with a few exceptions

This one uses grep to create a whitelist:

ls /var/jenkins_home/workspace \ 
  | grep -v -E '(job-to-skip|another-job-to-skip)$' \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

Clean up 10 largest workspaces

This one uses du and sort to list workspaces in order of largest to smallest. Then, it uses head to grab the first 10:

du -d 1 /var/jenkins_home/workspace \
  | sort -n -r \
  | head -n 10 \
  | xargs -I {} rm -rf /var/jenkins_home/workspace/{}

How to find rows that have a value that contains a lowercase letter

mysql> SELECT '1234aaaa578' REGEXP '^[a-z]';

What is the best way to declare global variable in Vue.js?

I strongly recommend taking a look at Vuex, it is made for globally accessible data in Vue.

If you only need a few base variables that will never be modified, I would use ES6 imports:

// config.js
export default {
   hostname: 'myhostname'
}

// .vue file
import config from 'config.js'

console.log(config.hostname)

You could also import a json file in the same way, which can be edited by people without code knowledge or imported into SASS.

Installing a dependency with Bower from URL and specify version

Use a git endpoint instead of a package name:

bower install https://github.com/jquery/jquery.git#2.0.3

Object variable or With block variable not set (Error 91)

As I wrote in my comment, the solution to your problem is to write the following:

Set hyperLinkText = hprlink.Range

Set is needed because TextRange is a class, so hyperLinkText is an object; as such, if you want to assign it, you need to make it point to the actual object that you need.

Use curly braces to initialize a Set in Python

You need to do empty_set = set() to initialize an empty set. {} is an empty dict.

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

SQL to find the number of distinct values in a column

Count(distinct({fieldname})) is redundant

Simply Count({fieldname}) gives you all the distinct values in that table. It will not (as many presume) just give you the Count of the table [i.e. NOT the same as Count(*) from table]

Generate random numbers following a normal distribution in C/C++

I've followed the definition of the PDF given in http://www.mathworks.com/help/stats/normal-distribution.html and came up with this:

const double DBL_EPS_COMP = 1 - DBL_EPSILON; // DBL_EPSILON is defined in <limits.h>.
inline double RandU() {
    return DBL_EPSILON + ((double) rand()/RAND_MAX);
}
inline double RandN2(double mu, double sigma) {
    return mu + (rand()%2 ? -1.0 : 1.0)*sigma*pow(-log(DBL_EPS_COMP*RandU()), 0.5);
}
inline double RandN() {
    return RandN2(0, 1.0);
}

It is maybe not the best approach, but it's quite simple.

How to vertically align an image inside a div

You can use this:

 .loaderimage {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 60px;
    height: 60px;
    margin-top: -30px; /* 50% of the height */
    margin-left: -30px;
 }

How to vertically align a html radio button to it's label?

Might as well add a bit of flex to the answers.

_x000D_
_x000D_
.Radio {_x000D_
  display: inline-flex;_x000D_
  align-items: center;_x000D_
}_x000D_
_x000D_
.Radio--large {_x000D_
  font-size: 2rem;_x000D_
}_x000D_
_x000D_
.Radio-Input {_x000D_
  margin: 0 0.5rem 0;_x000D_
}
_x000D_
<div>_x000D_
  <label class="Radio" for="sex-female">_x000D_
    <input class="Radio-Input" type="radio" id="sex-female" name="sex" value="female" />_x000D_
    Female_x000D_
  </label>_x000D_
_x000D_
  <label class="Radio" for="sex-male">_x000D_
    <input class="Radio-Input" type="radio" id="sex-male" name="sex" value="male" />_x000D_
    Male_x000D_
  </label>_x000D_
</div>_x000D_
_x000D_
_x000D_
<div>_x000D_
  <label class="Radio Radio--large" for="sex-female2">_x000D_
    <input class="Radio-Input" type="radio" id="sex-female2" name="sex" value="female" />_x000D_
    Female_x000D_
  </label>_x000D_
_x000D_
  <label class="Radio Radio--large" for="sex-male2">_x000D_
    <input class="Radio-Input" type="radio" id="sex-male2" name="sex" value="male" />_x000D_
    Male_x000D_
  </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

How can I check for Python version in a program that uses new language features?

I think the best way is to test for functionality rather than versions. In some cases, this is trivial, not so in others.

eg:

try :
    # Do stuff
except : # Features weren't found.
    # Do stuff for older versions.

As long as you're specific in enough in using the try/except blocks, you can cover most of your bases.

Convert numpy array to tuple

I was not satisfied, so I finally used this:

>>> a=numpy.array([[1,2,3],[4,5,6]])
>>> a
array([[1, 2, 3],
       [4, 5, 6]])

>>> tuple(a.reshape(1, -1)[0])
(1, 2, 3, 4, 5, 6)

I don't know if it's quicker, but it looks more effective ;)

Is it possible to use Java 8 for Android development?

Yes, Android Supports Java 8 Now (24.1.17)

Now it is possible

But you will need to have your device rom run on java 1.8 and enable "jackOptions" to run it. Jack is the name for the new Android compiler that runs Java 8

https://developer.android.com/guide/platform/j8-jack.html

add these lines to build_gradle

    android {
  ...
  defaultConfig {
    ...
    jackOptions {
      enabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }
}

Java 8 seem to be the running java engine of Android studio 2.0, But it still does not accept the syntax of java 8 after I checked, and you cannot chose a compiler from android studio now. However, you can use the scala plugin if you need functional programming mechanism in your android client.

enter image description here

Error: Cannot invoke an expression whose type lacks a call signature

I think what you want is:

abstract class Component {
  public deps: any = {};
  public props: any = {};

  public makePropSetter<T>(prop: string): (val: T) => T {
    return function(val) {
      this.props[prop] = val
      return val
    }
  }
}

class Post extends Component {
  public toggleBody: (val: boolean) => boolean;

  constructor () {
    super()
    this.toggleBody = this.makePropSetter<boolean>('showFullBody')
  }

  showMore (): boolean {
    return this.toggleBody(true)
  }

  showLess (): boolean {
    return this.toggleBody(false)
  }
}

The important change is in setProp (i.e., makePropSetter in the new code). What you're really doing there is to say: this is a function, which provided with a property name, will return a function which allows you to change that property.

The <T> on makePropSetter allows you to lock that function in to a specific type. The <boolean> in the subclass's constructor is actually optional. Since you're assigning to toggleBody, and that already has the type fully specified, the TS compiler will be able to work it out on its own.

Then, in your subclass, you call that function, and the return type is now properly understood to be a function with a specific signature. Naturally, you'll need to have toggleBody respect that same signature.

How to pass an object from one activity to another on Android

While calling an activity

Intent intent = new Intent(fromClass.this,toClass.class).putExtra("myCustomerObj",customerObj);

In toClass.java receive the activity by

Customer customerObjInToClass = getIntent().getExtras().getParcelable("myCustomerObj");

Please make sure that customer class implements parcelable

public class Customer implements Parcelable {

    private String firstName, lastName, address;
    int age;

    /* all your getter and setter methods */

    public Customer(Parcel in ) {
        readFromParcel( in );
    }

    public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
        public LeadData createFromParcel(Parcel in ) {
            return new Customer( in );
        }

        public Customer[] newArray(int size) {
            return new Customer[size];
        }
    };


    @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeString(firstName);
        dest.writeString(lastName);
        dest.writeString(address);
        dest.writeInt(age);
    }

    private void readFromParcel(Parcel in ) {

        firstName = in .readString();
        lastName  = in .readString();
        address   = in .readString();
        age       = in .readInt();
    }

Return the most recent record from ElasticSearch index

I used @timestamp instead of _timestamp

{
    'size' : 1,
    'query': {
        'match_all' : {}
            },
    "sort" : [{"@timestamp":{"order": "desc"}}]
}

Java Timestamp - How can I create a Timestamp with the date 23/09/2007?

You could also do the following:

// untested
Calendar cal = GregorianCalendar.getInstance();
cal.set(Calendar.DAY_OF_MONTH, 23);// I might have the wrong Calendar constant...
cal.set(Calendar.MONTH, 8);// -1 as month is zero-based
cal.set(Calendar.YEAR, 2009);
Timestamp tstamp = new Timestamp(cal.getTimeInMillis());

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

What is the difference between IQueryable<T> and IEnumerable<T>?

ienumerable:when we want to deal with inprocess memory, i.e without dataconnection iqueryable:when to deal with sql server, i.e with data connection ilist : operations like add object, delete object etc

Java Calendar, getting current month value, clarification needed

as others said Calendar.MONTH returns int and is zero indexed.

to get the current month as a String use SimpleDateFormat.format() method

Calendar cal = Calendar.getInstance();
System.out.println(new SimpleDateFormat("MMM").format(cal.getTime()));

returns NOV

Disable and later enable all table indexes in Oracle

From here: http://forums.oracle.com/forums/thread.jspa?messageID=2354075

alter session set skip_unusable_indexes = true;

alter index your_index unusable;

do import...

alter index your_index rebuild [online];

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

Convert HashBytes to VarChar

Use master.dbo.fn_varbintohexsubstring(0, HashBytes('SHA1', @input), 1, 0) instead of master.dbo.fn_varbintohexstr and then substringing the result.

In fact fn_varbintohexstr calls fn_varbintohexsubstring internally. The first argument of fn_varbintohexsubstring tells it to add 0xF as the prefix or not. fn_varbintohexstr calls fn_varbintohexsubstring with 1 as the first argument internaly.

Because you don't need 0xF, call fn_varbintohexsubstring directly.

How to copy file from one location to another location?

  public static void copyFile(File oldLocation, File newLocation) throws IOException {
        if ( oldLocation.exists( )) {
            BufferedInputStream  reader = new BufferedInputStream( new FileInputStream(oldLocation) );
            BufferedOutputStream  writer = new BufferedOutputStream( new FileOutputStream(newLocation, false));
            try {
                byte[]  buff = new byte[8192];
                int numChars;
                while ( (numChars = reader.read(  buff, 0, buff.length ) ) != -1) {
                    writer.write( buff, 0, numChars );
                }
            } catch( IOException ex ) {
                throw new IOException("IOException when transferring " + oldLocation.getPath() + " to " + newLocation.getPath());
            } finally {
                try {
                    if ( reader != null ){                      
                        writer.close();
                        reader.close();
                    }
                } catch( IOException ex ){
                    Log.e(TAG, "Error closing files when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() ); 
                }
            }
        } else {
            throw new IOException("Old location does not exist when transferring " + oldLocation.getPath() + " to " + newLocation.getPath() );
        }
    }  

How do I assert equality on two classes without an equals method?

You can override the equals method of the class like:

@Override
public int hashCode() {
    int hash = 0;
    hash += (app != null ? app.hashCode() : 0);
    return hash;
}

@Override
public boolean equals(Object object) {
    HubRule other = (HubRule) object;

    if (this.app.equals(other.app)) {
        boolean operatorHubList = false;

        if (other.operator != null ? this.operator != null ? this.operator
                .equals(other.operator) : false : true) {
            operatorHubList = true;
        }

        if (operatorHubList) {
            return true;
        } else {
            return false;
        }
    } else {
        return false;
    }
}

Well, if you want to compare two object from a class you must implement in some way the equals and the hash code method

Java, How to add library files in netbeans?

How to import a commons-library into netbeans.

  1. Evaluate the error message in NetBeans:

    java.lang.NoClassDefFoundError: org/apache/commons/logging/LogFactory
    
  2. NoClassDeffFoundError means somewhere under the hood in the code you used, a method called another method which invoked a class that cannot be found. So what that means is your code did this: MyFoobarClass foobar = new MyFoobarClass() and the compiler is confused because nowhere is defined this MyFoobarClass. This is why you get an error.

  3. To know what to do next, you have to look at the error message closely. The words 'org/apache/commons' lets you know that this is the codebase that provides the tools you need. You have a choice, either you can import EVERYTHING in apache commons, or you could import JUST the LogFactory class, or you could do something in between. Like for example just get the logging bit of apache commons.

  4. You'll want to go the middle of the road and get commons-logging. Excellent choice, fire up the google and search for apache commons-logging. The first link takes you to http://commons.apache.org/proper/commons-logging/. Go to downloads. There you will find the most up-to-date ones. If your project was compiled under ancient versions of commons-logging, then use those same ancient ones because if you use the newer ones, the code may fail because the newer versions are different.

  5. You're going to want to download the commons-logging-1.1.3-bin.zip or something to that effect. Read what the name is saying. The .zip means it's a compressed file. commons-logging means that this one should contain the LogFactory class you desire. the middle 1.1.3 means that is the version. if you are compiling for an old version, you'll need to match these up, or else you risk the code not compiling right due to changes due to upgrading.

  6. Download that zip. Unzip it. Search around for things that end in .jar. In netbeans right click your project, click properties, click libraries, click "add jar/folder" and import those jars. Save the project, and re-run, and the errors should be gone.

The binaries don't include the source code, so you won't be able to drill down and see what is happening when you debug. As programmers you should be downloading "the source" of apache commons and compiling from source, generating the jars yourself and importing those for experience. You should be smart enough to understand and correct the source code you are importing. These ancient versions of apache commons might have been compiled under an older version of Java, so if you go too far back, they may not even compile unless you compile them under an ancient version of java.

Chrome: console.log, console.debug are not working

In my case was webpack having the UglifyPlugin running with drop_console: true set

event.returnValue is deprecated. Please use the standard event.preventDefault() instead

I saw this warning on many websites. Also, I saw that YUI 3 library also gives the same warning. It's a warning generated from the library (whether is it jQuery or YUI).

Measure the time it takes to execute a t-sql query

One simplistic approach to measuring the "elapsed time" between events is to just grab the current date and time.

In SQL Server Management Studio

SELECT GETDATE();
SELECT /* query one */ 1 ;
SELECT GETDATE();
SELECT /* query two */ 2 ; 
SELECT GETDATE(); 

To calculate elapsed times, you could grab those date values into variables, and use the DATEDIFF function:

DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;

SET @t1 = GETDATE();
SELECT /* query one */ 1 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;

SET @t1 = GETDATE();
SELECT /* query two */ 2 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;

That's just one approach. You can also get elapsed times for queries using SQL Profiler.

Parsing JSON using C

You can have a look at Jansson

The website states the following: Jansson is a C library for encoding, decoding and manipulating JSON data. It features:

  • Simple and intuitive API and data model
  • Can both encode to and decode from JSON
  • Comprehensive documentation
  • No dependencies on other libraries
  • Full Unicode support (UTF-8)
  • Extensive test suite

XPath - Selecting elements that equal a value

The XPath spec. defines the string value of an element as the concatenation (in document order) of all of its text-node descendents.

This explains the "strange results".

"Better" results can be obtained using the expressions below:

//*[text() = 'qwerty']

The above selects every element in the document that has at least one text-node child with value 'qwerty'.

//*[text() = 'qwerty' and not(text()[2])]

The above selects every element in the document that has only one text-node child and its value is: 'qwerty'.

What's the fastest way to convert String to Number in JavaScript?

There are at least 5 ways to do this:

If you want to convert to integers only, another fast (and short) way is the double-bitwise not (i.e. using two tilde characters):

e.g.

~~x;

Reference: http://james.padolsey.com/cool-stuff/double-bitwise-not/

The 5 common ways I know so far to convert a string to a number all have their differences (there are more bitwise operators that work, but they all give the same result as ~~). This JSFiddle shows the different results you can expect in the debug console: http://jsfiddle.net/TrueBlueAussie/j7x0q0e3/22/

var values = ["123",
          undefined,
          "not a number",
          "123.45",
          "1234 error",
          "2147483648",
          "4999999999"
          ];

for (var i = 0; i < values.length; i++){
    var x = values[i];

    console.log(x);
    console.log(" Number(x) = " + Number(x));
    console.log(" parseInt(x, 10) = " + parseInt(x, 10));
    console.log(" parseFloat(x) = " + parseFloat(x));
    console.log(" +x = " + +x);
    console.log(" ~~x = " + ~~x);
}

Debug console:

123
  Number(x) = 123
  parseInt(x, 10) = 123
  parseFloat(x) = 123
  +x = 123
  ~~x = 123
undefined
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
null
  Number(x) = 0
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = 0
  ~~x = 0
"not a number"
  Number(x) = NaN
  parseInt(x, 10) = NaN
  parseFloat(x) = NaN
  +x = NaN
  ~~x = 0
123.45
  Number(x) = 123.45
  parseInt(x, 10) = 123
  parseFloat(x) = 123.45
  +x = 123.45
  ~~x = 123
1234 error
  Number(x) = NaN
  parseInt(x, 10) = 1234
  parseFloat(x) = 1234
  +x = NaN
  ~~x = 0
2147483648
  Number(x) = 2147483648
  parseInt(x, 10) = 2147483648
  parseFloat(x) = 2147483648
  +x = 2147483648
  ~~x = -2147483648
4999999999
  Number(x) = 4999999999
  parseInt(x, 10) = 4999999999
  parseFloat(x) = 4999999999
  +x = 4999999999
  ~~x = 705032703

The ~~x version results in a number in "more" cases, where others often result in undefined, but it fails for invalid input (e.g. it will return 0 if the string contains non-number characters after a valid number).

Overflow

Please note: Integer overflow and/or bit truncation can occur with ~~, but not the other conversions. While it is unusual to be entering such large values, you need to be aware of this. Example updated to include much larger values.

Some Perf tests indicate that the standard parseInt and parseFloat functions are actually the fastest options, presumably highly optimised by browsers, but it all depends on your requirement as all options are fast enough: http://jsperf.com/best-of-string-to-number-conversion/37

This all depends on how the perf tests are configured as some show parseInt/parseFloat to be much slower.

My theory is:

  • Lies
  • Darn lines
  • Statistics
  • JSPerf results :)

What is a "web service" in plain English?

A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., between Java and Python, or Windows and Linux applications) is due to the use of open standards (XML, SOAP, HTTP).

All the standard Web Services works using following components:

  • SOAP (Simple Object Access Protocol)
  • UDDI (Universal Description, Discovery and Integration)
  • WSDL (Web Services Description Language)

It works somewhat like this:

  • The client program bundles the account registration information into a SOAP message.
  • This SOAP message is sent to the Web Service as the body of an HTTP POST request.
  • The Web Service unpacks the SOAP request and converts it into a command that the application can understand.
  • The application processes the information as required and responds with a new unique account number for that customer.
  • Next, the Web Service packages up the response into another SOAP message, which it sends back to the client program in response to its HTTP request.
  • The client program unpacks the SOAP message to obtain the results of the account registration process.

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

I think this is what you need:

$("body").trigger("click");

This will allow you to trigger the body click event from anywhere.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

If you are getting the error

Attempt by security transparent method ‘WebMatrix.WebData.PreApplicationStartCode.Start()’ to access security critical method ‘System.Web.WebPages.Razor.WebPageRazorHost.AddGlobalImport(System.String)’ failed.

In order to fix this install this package using NuGet package manager.

Install-Package Microsoft.AspNet.WebHelpers

After that , probably you will get another error

Cannot load WebMatrix.Data version 3.0.0.0 assembly

to fix this install this package using NuGet package manager.

Install-Package Microsoft.AspNet.WebPages.Data

Using cURL with a username and password?

pretty easy, do the below:

curl -X GET/POST/PUT <URL> -u username:password

How to create a custom attribute in C#

You start by writing a class that derives from Attribute:

public class MyCustomAttribute: Attribute
{
    public string SomeProperty { get; set; }
}

Then you could decorate anything (class, method, property, ...) with this attribute:

[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{

}

and finally you would use reflection to fetch it:

var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
    var myAttribute = customAttributes[0];
    string value = myAttribute.SomeProperty;
    // TODO: Do something with the value
}

You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:

/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute

Important things to know about attributes:

  • Attributes are metadata.
  • They are baked into the assembly at compile-time which has very serious implications of how you could set their properties. Only constant (known at compile time) values are accepted
  • The only way to make any sense and usage of custom attributes is to use Reflection. So if you don't use reflection at runtime to fetch them and decorate something with a custom attribute don't expect much to happen.
  • The time of creation of the attributes is non-deterministic. They are instantiated by the CLR and you have absolutely no control over it.

Angularjs $http.get().then and binding to a list

Actually you get promise on $http.get.

Try to use followed flow:

<li ng-repeat="document in documents" ng-class="IsFiltered(document.Filtered)">
    <span><input type="checkbox" name="docChecked" id="doc_{{document.Id}}" ng-model="document.Filtered" /></span>
    <span>{{document.Name}}</span>
</li>

Where documents is your array.

$scope.documents = [];

$http.get('/Documents/DocumentsList/' + caseId).then(function(result) {
    result.data.forEach(function(val, i) { 
        $scope.documents.push(/* put data here*/);
    });
}, function(error) {
    alert(error.message);
});                       

How to handle anchor hash linking in AngularJS

Sometime in angularjs application hash navigation not work and bootstrap jquery javascript libraries make extensive use of this type of navigation, to make it work add target="_self" to anchor tag. e.g. <a data-toggle="tab" href="#id_of_div_to_navigate" target="_self">

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

PHP DOMDocument loadHTML not encoding UTF-8 correctly

Use it for correct result

$dom = new DOMDocument();
$dom->loadHTML('<meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . $profile);
echo $dom->saveHTML();
echo $profile;

This operation

mb_convert_encoding($profile, 'HTML-ENTITIES', 'UTF-8');

It is bad way, because special symbols like &lt ; , &gt ; can be in $profile, and they will not convert twice after mb_convert_encoding. It is the hole for XSS and incorrect HTML.

JS search in object values

This is a cool solution that works perfectly

const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];

var item = array.filter(item=>item.title.toLowerCase().includes('this'));

 alert(JSON.stringify(item))

EDITED

_x000D_
_x000D_
const array = [{"title":"tile hgfgfgfh"},{"title":"Wise cool"},{"title":"titlr DEytfd ftgftgfgtgtf gtftftft"},{"title":"This is the title"},{"title":"yeah this is cool"},{"title":"tile hfyf"},{"title":"tile ehey"}];_x000D_
_x000D_
_x000D_
// array.filter loops through your array and create a new array returned as Boolean value given out "true" from eachIndex(item) function _x000D_
_x000D_
var item = array.filter((item)=>eachIndex(item));_x000D_
_x000D_
//var item = array.filter();_x000D_
_x000D_
_x000D_
_x000D_
function eachIndex(e){_x000D_
console.log("Looping each index element ", e)_x000D_
return e.title.toLowerCase().includes("this".toLowerCase())_x000D_
}_x000D_
_x000D_
console.log("New created array that returns \"true\" value by eachIndex ", item)
_x000D_
_x000D_
_x000D_

Which Architecture patterns are used on Android?

Update November 2018

After working and blogging about MVC and MVP in Android for several years (see the body of the answer below), I decided to capture my knowledge and understanding in a more comprehensive and easily digestible form.

So, I released a full blown video course about Android applications architecture. So, if you're interested in mastering the most advanced architectural patterns in Android development, check out this comprehensive course here.

This answer was updated in order to remain relevant as of November 2016


It looks like you are seeking for architectural patterns rather than design patterns.

Design patterns aim at describing a general "trick" that programmer might implement for handling a particular set of recurring software tasks. For example: In OOP, when there is a need for an object to notify a set of other objects about some events, the observer design pattern can be employed.

Since Android applications (and most of AOSP) are written in Java, which is object-oriented, I think you'll have a hard time looking for a single OOP design pattern which is NOT used on Android.

Architectural patterns, on the other hand, do not address particular software tasks - they aim to provide templates for software organization based on the use cases of the software component in question.

It sounds a bit complicated, but I hope an example will clarify: If some application will be used to fetch data from a remote server and present it to the user in a structured manner, then MVC might be a good candidate for consideration. Note that I said nothing about software tasks and program flow of the application - I just described it from user's point of view, and a candidate for an architectural pattern emerged.

Since you mentioned MVC in your question, I'd guess that architectural patterns is what you're looking for.

Enter image description here


Historically, there were no official guidelines by Google about applications' architectures, which (among other reasons) led to a total mess in the source code of Android apps. In fact, even today most applications that I see still do not follow OOP best practices and do not show a clear logical organization of code.

But today the situation is different - Google recently released the Data Binding library, which is fully integrated with Android Studio, and, even, rolled out a set of architecture blueprints for Android applications.

Two years ago it was very hard to find information about MVC or MVP on Android. Today, MVC, MVP and MVVM has become "buzz-words" in the Android community, and we are surrounded by countless experts which constantly try to convince us that MVx is better than MVy. In my opinion, discussing whether MVx is better than MVy is totally pointless because the terms themselves are very ambiguous - just look at the answers to this question, and you'll realize that different people can associate these abbreviations with completely different constructs.

Due to the fact that a search for a best architectural pattern for Android has officially been started, I think we are about to see several more ideas come to light. At this point, it is really impossible to predict which pattern (or patterns) will become industry standards in the future - we will need to wait and see (I guess it is matter of a year or two).

However, there is one prediction I can make with a high degree of confidence: Usage of the Data Binding library will not become an industry standard. I'm confident to say that because the Data Binding library (in its current implementation) provides short-term productivity gains and some kind of architectural guideline, but it will make the code non-maintainable in the long run. Once long-term effects of this library will surface - it will be abandoned.


Now, although we do have some sort of official guidelines and tools today, I, personally, don't think that these guidelines and tools are the best options available (and they are definitely not the only ones). In my applications I use my own implementation of an MVC architecture. It is simple, clean, readable and testable, and does not require any additional libraries.

This MVC is not just cosmetically different from others - it is based on a theory that Activities in Android are not UI Elements, which has tremendous implications on code organization.

So, if you're looking for a good architectural pattern for Android applications that follows SOLID principles, you can find a description of one in my post about MVC and MVP architectural patterns in Android.

Get contentEditable caret index position

window.getSelection - vs - document.selection

This one works for me:

_x000D_
_x000D_
function getCaretCharOffset(element) {_x000D_
  var caretOffset = 0;_x000D_
_x000D_
  if (window.getSelection) {_x000D_
    var range = window.getSelection().getRangeAt(0);_x000D_
    var preCaretRange = range.cloneRange();_x000D_
    preCaretRange.selectNodeContents(element);_x000D_
    preCaretRange.setEnd(range.endContainer, range.endOffset);_x000D_
    caretOffset = preCaretRange.toString().length;_x000D_
  } _x000D_
_x000D_
  else if (document.selection && document.selection.type != "Control") {_x000D_
    var textRange = document.selection.createRange();_x000D_
    var preCaretTextRange = document.body.createTextRange();_x000D_
    preCaretTextRange.moveToElementText(element);_x000D_
    preCaretTextRange.setEndPoint("EndToEnd", textRange);_x000D_
    caretOffset = preCaretTextRange.text.length;_x000D_
  }_x000D_
_x000D_
  return caretOffset;_x000D_
}_x000D_
_x000D_
_x000D_
// Demo:_x000D_
var elm = document.querySelector('[contenteditable]');_x000D_
elm.addEventListener('click', printCaretPosition)_x000D_
elm.addEventListener('keydown', printCaretPosition)_x000D_
_x000D_
function printCaretPosition(){_x000D_
  console.log( getCaretCharOffset(elm), 'length:', this.textContent.trim().length )_x000D_
}
_x000D_
<div contenteditable>some text here <i>italic text here</i> some other text here <b>bold text here</b> end of text</div>
_x000D_
_x000D_
_x000D_

The calling line depends on event type, for key event use this:

getCaretCharOffsetInDiv(e.target) + ($(window.getSelection().getRangeAt(0).startContainer.parentNode).index());

for mouse event use this:

getCaretCharOffsetInDiv(e.target.parentElement) + ($(e.target).index())

on these two cases I take care for break lines by adding the target index

ImportError: No module named Crypto.Cipher

I've had the same problem 'ImportError: No module named Crypto.Cipher', since using GoogleAppEngineLauncher (version > 1.8.X) with GAE Boilerplate on OSX 10.8.5 (Mountain Lion). In Google App Engine SDK with python 2.7 runtime, pyCrypto 2.6 is the suggested version. The solution that worked for me was...

1) Download pycrypto2.6 source extract it somewhere(~/Downloads/pycrypto26)

e.g., git clone https://github.com/dlitz/pycrypto.git

2) cd (cd ~/Downloads/pycrypto26) then

3) Execute the following terminal command inside the previous folder in order to install pyCrypto 2.6 manually in GAE folder.

sudo python setup.py install --install-lib /Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine

Deep copy of a dict in python

I like and learned a lot from Lasse V. Karlsen. I modified it into the following example, which highlights pretty well the difference between shallow dictionary copies and deep copies:

    import copy

    my_dict = {'a': [1, 2, 3], 'b': [4, 5, 6]}
    my_copy = copy.copy(my_dict)
    my_deepcopy = copy.deepcopy(my_dict)

Now if you change

    my_dict['a'][2] = 7

and do

    print("my_copy a[2]: ",my_copy['a'][2],",whereas my_deepcopy a[2]: ", my_deepcopy['a'][2])

you get

    >> my_copy a[2]:  7 ,whereas my_deepcopy a[2]:  3

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

The solutions to the same problem in my case was the following combination of steps:

  1. Solution --> Properties Select multiple startup projects select Start action on the projects you need to debug.
  2. Removed the service from Service References and clean up the solution.
  3. Rebuild the service project
  4. Added it back to the Service References
  5. Clean up the solution and rebuild it.

How to change facebook login button with my custom image

The method which you are using is rendering login button from the Facebook Javascript code. However, you can write your own Javascript code function to mimic the functionality. Here is how to do it -

  1. Create a simple anchor tag link with the image you want to show. Have a onclick method on anchor tag which would actually do the real job.
<a href="#" onclick="fb_login();"><img src="images/fb_login_awesome.jpg" border="0" alt=""></a>
  1. Next, we create the Javascript function which will show the actual popup and will fetch the complete user information, if user allows. We also handle the scenario if user disallows our facebook app.
window.fbAsyncInit = function() {
    FB.init({
        appId   : 'YOUR_APP_ID',
        oauth   : true,
        status  : true, // check login status
        cookie  : true, // enable cookies to allow the server to access the session
        xfbml   : true // parse XFBML
    });

  };

function fb_login(){
    FB.login(function(response) {

        if (response.authResponse) {
            console.log('Welcome!  Fetching your information.... ');
            //console.log(response); // dump complete info
            access_token = response.authResponse.accessToken; //get access token
            user_id = response.authResponse.userID; //get FB UID

            FB.api('/me', function(response) {
                user_email = response.email; //get user email
          // you can store this data into your database             
            });

        } else {
            //user hit cancel button
            console.log('User cancelled login or did not fully authorize.');

        }
    }, {
        scope: 'public_profile,email'
    });
}
(function() {
    var e = document.createElement('script');
    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
    e.async = true;
    document.getElementById('fb-root').appendChild(e);
}());
  1. We are done.

Please note that the above function is fully tested and works. You just need to put your facebook APP ID and it will work.

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

CREATE TABLE sometable (t TIMESTAMP, d DATE);
INSERT INTO sometable SELECT '2011/05/26 09:00:00';
UPDATE sometable SET d = t; -- OK
-- UPDATE sometable SET d = t::date; OK
-- UPDATE sometable SET d = CAST (t AS date); OK
-- UPDATE sometable SET d = date(t); OK
SELECT * FROM sometable ;
          t          |     d      
---------------------+------------
 2011-05-26 09:00:00 | 2011-05-26
(1 row)

Another test kit:

SELECT pg_catalog.date(t) FROM sometable;
    date    
------------
 2011-05-26
(1 row)

SHOW datestyle ;
 DateStyle 
-----------
 ISO, MDY
(1 row)

Set HTML element's style property in javascript

You can try grabbing the cssText and className.

var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;

// sort

// loop
    if (i%2==0) {
        table.rows[i].style.cssText = css1;
        table.rows[i].className = class1;
    } else {
        table.rows[i].style.cssText = css2;
        table.rows[i].className = class2;
    }

Not entirely sure about browser compatibility with cssText, though.

What is the difference between dynamic programming and greedy approach?

Difference between greedy method and dynamic programming are given below :

  1. Greedy method never reconsiders its choices whereas Dynamic programming may consider the previous state.

  2. Greedy algorithm is less efficient whereas Dynamic programming is more efficient.

  3. Greedy algorithm have a local choice of the sub-problems whereas Dynamic programming would solve the all sub-problems and then select one that would lead to an optimal solution.

  4. Greedy algorithm take decision in one time whereas Dynamic programming take decision at every stage.

iterrows pandas get next rows value

a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.

my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.

# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]

Hope it will help.

Using .text() to retrieve only text not nested in child tags

This untested, but I think you may be able to try something like this:

 $('#listItem').not('span').text();

http://api.jquery.com/not/

How to pass multiple parameters to a get method in ASP.NET Core

To parse the search parameters from the URL, you need to annotate the controller method parameters with [FromQuery], for example:

[Route("api/person")]
public class PersonController : Controller
{
    [HttpGet]
    public string GetById([FromQuery]int id)
    {

    }

    [HttpGet]
    public string GetByName([FromQuery]string firstName, [FromQuery]string lastName)
    {

    }

    [HttpGet]
    public string GetByNameAndAddress([FromQuery]string firstName, [FromQuery]string lastName, [FromQuery]string address)
    {

    }
}

Apache: The requested URL / was not found on this server. Apache

I had the same problem, but believe it or not is was a case of case sensitivity.

This on localhost: http://localhost/.../getdata.php?id=3

Did not behave the same as this on the server: http://server/.../getdata.php?id=3

Changing the server url to this (notice the capital D in getData) solved my issue. http://localhost/.../getData.php?id=3

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

This is for others (like me :) ). Don't forget to add the spring tx jar/maven dependency. Also correct configuration in appctx is:

xmlns:tx="http://www.springframework.org/schema/tx"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

, by mistake wrong configuration which others may have

xmlns:tx="http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

i.e., extra "/spring-tx-3.1.xsd"

xsi:schemaLocation="http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"

in other words what is there in xmlns(namespace) should have proper mapping in schemaLocation (namespace vs schema).

namespace here is : http://www.springframework.org/schema/tx

schema Doc Of namespace is : http://www.springframework.org/schema/tx/spring-tx-3.1.xsd

this schema of namespace later is mapped in jar to locate the path of actual xsd located in org.springframework.transaction.config

SQL Server ON DELETE Trigger

Better to use:

DELETE tbl FROM tbl INNER JOIN deleted ON tbl.key=deleted.key

Convert Mercurial project to Git

From:

http://hivelogic.com/articles/converting-from-mercurial-to-git

Migrating

It’s a relatively simple process. First we download fast-export (the best way is via its Git repository, which I’ll clone right to the desktop), then we create a new git repository, perform the migration, and check out the HEAD. On the command line, it goes like this:

cd ~/Desktop
git clone git://repo.or.cz/fast-export.git
git init git_repo
cd git_repo
~/Desktop/fast-export/hg-fast-export.sh -r /path/to/old/mercurial_repo
git checkout HEAD

You should see a long listing of commits fly by as your project is migrated after running fast-export. If you see errors, they are likely related to an improperly specified Python path (see the note above and customize for your system).

That’s it, you’re done.

Which mime type should I use for mp3

mp3 files sometimes throw strange mime types as per this answer: https://stackoverflow.com/a/2755288/14482130

If you are doing some user validation do not allow 'application/octet-stream' or 'application/x-zip-compressed' as suggested above since they can contain be .exe or other potentially dangerous files.

In order to validate when mime type gives a false negative you can use fleep as per this answer https://stackoverflow.com/a/52570299/14482130 to finish the validation.

What do two question marks together mean in C#?

It's a null coalescing operator that works similarly to a ternary operator.

    a ?? b  => a !=null ? a : b 

Another interesting point for this is, "A nullable type can contain a value, or it can be undefined". So if you try to assign a nullable value type to a non-nullable value type you will get a compile-time error.

int? x = null; // x is nullable value type
int z = 0; // z is non-nullable value type
z = x; // compile error will be there.

So to do that using ?? operator:

z = x ?? 1; // with ?? operator there are no issues

List and kill at jobs on UNIX

You should be able to find your command with a ps variant like:

ps -ef
ps -fubob # if your job's user ID is bob.

Then, once located, it should be a simple matter to use kill to kill the process (permissions permitting).

If you're talking about getting rid of jobs in the at queue (that aren't running yet), you can use atq to list them and atrm to get rid of them.

AttributeError: 'list' object has no attribute 'encode'

You need to unicode each element of the list individually

[x.encode('utf-8') for x in tmp]

"A lambda expression with a statement body cannot be converted to an expression tree"

The LINQ to SQL return object were implementing IQueryable interface. So for Select method predicate parameter you should only supply single lambda expression without body.

This is because LINQ for SQL code is not execute inside program rather than on remote side like SQL server or others. This lazy loading execution type were achieve by implementing IQueryable where its expect delegate is being wrapped in Expression type class like below.

Expression<Func<TParam,TResult>>

Expression tree do not support lambda expression with body and its only support single line lambda expression like var id = cols.Select( col => col.id );

So if you try the following code won't works.

Expression<Func<int,int>> function = x => {
    return x * 2;
}

The following will works as per expected.

Expression<Func<int,int>> function = x => x * 2;

enable cors in .htaccess

I tried @abimelex solution, but in Slim 3.0, mapping the OPTIONS requests goes like:

$app = new \Slim\App();
$app->options('/books/{id}', function ($request, $response, $args) {
    // Return response headers
});

https://www.slimframework.com/docs/objects/router.html#options-route

Streaming Audio from A URL in Android using MediaPlayer?

I guess that you are trying to play an .pls directly or something similar.

try this out:

1: the code

mediaPlayer = MediaPlayer.create(this, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"));
mediaPlayer.start();

2: the .pls file

This URL is from BBC just as an example. It was an .pls file that on linux i downloaded with

wget http://foo.bar/file.pls

and then i opened with vim (use your favorite editor ;) and i've seen the real URLs inside this file. Unfortunately not all of the .pls are plain text like that.

I've read that 1.6 would not support streaming mp3 over http, but, i've just tested the obove code with android 1.6 and 2.2 and didn't have any issue.

good luck!

How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

bytes[] buffer = UnicodeEncoding.UTF8.GetBytes(string something); //for converting to UTF then get its bytes

bytes[] buffer = ASCIIEncoding.ASCII.GetBytes(string something); //for converting to ascii then get its bytes

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

jQuery - select all text from a textarea

I ended up using this:

$('.selectAll').toggle(function() {
  $(this).select();
}, function() {
  $(this).unselect();
});

How to kill MySQL connections

While you can't kill all open connections with a single command, you can create a set of queries to do that for you if there are too many to do by hand.

This example will create a series of KILL <pid>; queries for all some_user's connections from 192.168.1.1 to my_db.

SELECT 
CONCAT('KILL ', id, ';') 
FROM INFORMATION_SCHEMA.PROCESSLIST 
WHERE `User` = 'some_user' 
AND `Host` = '192.168.1.1';
AND `db` = 'my_db';

How to use sessions in an ASP.NET MVC 4 application?

U can store any value in session like Session["FirstName"] = FirstNameTextBox.Text; but i will suggest u to take as static field in model assign value to it and u can access that field value any where in application. U don't need session. session should be avoided.

public class Employee
{
   public int UserId { get; set; }
   public string EmailAddress { get; set; }
   public static string FullName { get; set; }
}

on controller - Employee.FullName = "ABC"; Now u can access this full Name anywhere in application.

How generate unique Integers based on GUIDs

Eric Lippert did a very interesting (as always) post about the probability of hash collisions.

You should read it all but he concluded with this very illustrative graphic:

Probability of hash collisions

Related to your specific question, I would also go with GetHashCode since collisions will be unavoidable either way.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

The most condensed version:

public String getNameFromURI(Uri uri) {
    Cursor c = getContentResolver().query(uri, null, null, null, null);
    c.moveToFirst();
    return c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}

How to get address of a pointer in c/c++?

To get the address of p do:

int **pp = &p;

and you can go on:

int ***ppp = &pp;
int ****pppp = &ppp;
...

or, only in C++11, you can do:

auto pp = std::addressof(p);

To print the address in C, most compilers support %p, so you can simply do:

printf("addr: %p", pp);

otherwise you need to cast it (assuming a 32 bit platform)

printf("addr: 0x%u", (unsigned)pp);

In C++ you can do:

cout << "addr: " << pp;

Get values from label using jQuery

You can use the attr method. For example, if you have a jQuery object called label, you could use this code:

console.log(label.attr("year")); // logs the year
console.log(label.attr("month")); // logs the month

Unable to login to SQL Server + SQL Server Authentication + Error: 18456

After enabling "SQL Server and Windows Authentication mode"(check above answers on how to), navigate to the following.

  1. Computer Mangement(in Start Menu)
  2. Services And Applications
  3. SQL Server Configuration Manager
  4. SQL Server Network Configuration
  5. Protocols for MSSQLSERVER
  6. Right click on TCP/IP and Enable it.

Finally restart the SQL Server.

Python how to write to a binary file?

Use struct.pack to convert the integer values into binary bytes, then write the bytes. E.g.

newFile.write(struct.pack('5B', *newFileBytes))

However I would never give a binary file a .txt extension.

The benefit of this method is that it works for other types as well, for example if any of the values were greater than 255 you could use '5i' for the format instead to get full 32-bit integers.

Changing datagridview cell color dynamically

If you want every cell in the grid to have the same background color, you can just do this:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

Error: cannot open display: localhost:0.0 - trying to open Firefox from CentOS 6.2 64bit and display on Win7

So, it turns out that X11 wasn't actually installed on the centOS. There didn't seem to be any indication anywhere of it not being installed. I did the following command and now firefox opens:

yum groupinstall 'X Window System' 

Hope this answer will help others that are confused :)

H2 in-memory database. Table not found

I have tried to add

jdbc:h2:mem:test;DB_CLOSE_DELAY=-1

However, that didn't helped. On the H2 site, I have found following, which indeed could help in some cases.

By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.

However, my issue was that just the schema supposed to be different than default one. So insted of using

JDBC URL: jdbc:h2:mem:test

I had to use:

JDBC URL: jdbc:h2:mem:testdb

Then the tables were visible

How to extract HTTP response body from a Python requests call?

Your code is correct. I tested:

r = requests.get("http://www.google.com")
print(r.content)

And it returned plenty of content. Check the url, try "http://www.google.com". Cheers!

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

To find first N prime numbers in python

count = -1
n = int(raw_input("how many primes you want starting from 2 "))
primes=[[]]*n
for p in range(2, n**2):
    for i in range(2, p):
        if p % i == 0:
            break
    else:
        count +=1
        primes[count]= p
        if count == n-1:
            break

print (primes)
print 'Done'

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

MongoDb shuts down with Code 100

In MacOS:-

If you forgot to give the path of the previously created database while running the mongo server, the above error will appear.

sudo ./mongod --dbpath ../../mongo-data/

Reference

Note :- ./mongod && ../../mongo-data is relative path. So you can avoid it by configuration in environment variable

Reference

Easiest way to loop through a filtered list with VBA?

One way assuming filtered data in A1 downwards;

dim Rng as Range
set Rng = Range("A2", Range("A2").End(xlDown)).Cells.SpecialCells(xlCellTypeVisible)
...
for each cell in Rng 
   ...     

How to simulate "Press any key to continue?"

If you're on Windows, you can use kbhit() which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit thus (source):

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c and compiled on both Linux and OS X with

gcc -o kbhit kbhit.c

When run with

./kbhit

It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).

@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit() you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?

Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.

POST: sending a post request in a url itself

You can use postman.

Where select Post as method. and In Request Body send JSON Object.

How to import local packages in go?

Well, I figured out the problem. Basically Go starting path for import is $HOME/go/src

So I just needed to add myapp in front of the package names, that is, the import should be:

import (
    "log"
    "net/http"
    "myapp/common"
    "myapp/routers"
)

docker run <IMAGE> <MULTIPLE COMMANDS>

Just to make a proper answer from the @Eddy Hernandez's comment and which is very correct since Alpine comes with ash not bash.

The question now referes to Starting a shell in the Docker Alpine container which implies using sh or ash or /bin/sh or /bin/ash/.

Based on the OP's question:

docker run image sh -c "cd /path/to/somewhere && python a.py"

Entity Framework Provider type could not be loaded?

Late to the party, but the top voted answers all seemed like hacks to me.

All I did was remove the following from my app.config in the test project. Worked.

  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>

How do I upgrade to Python 3.6 with conda?

I found this page with detailed instructions to upgrade Anaconda to a major newer version of Python (from Anaconda 4.0+). First,

conda update conda
conda remove argcomplete conda-manager

I also had to conda remove some packages not on the official list:

  • backports_abc
  • beautiful-soup
  • blaze-core

Depending on packages installed on your system, you may get additional UnsatisfiableError errors - simply add those packages to the remove list. Next, install the version of Python,

conda install python==3.6

which takes a while, after which a message indicated to conda install anaconda-client, so I did

conda install anaconda-client

which said it's already there. Finally, following the directions,

conda update anaconda

I did this in the Windows 10 command prompt, but things should be similar in Mac OS X.

Turning off eslint rule for a specific file

Simply create an empty file .eslintignore in your project root the type the path to the file you want it to be ignore.

Source: https://eslint.org/docs/2.13.1/user-guide/configuring#:~:text=To%20disable%20rule%20warnings%20in,*%2F%20alert('foo')%3B

Line Ignoring Files and Directories

Breadth First Vs Depth First

Given this binary tree:

enter image description here

Breadth First Traversal:
Traverse across each level from left to right.

"I'm G, my kids are D and I, my grandkids are B, E, H and K, their grandkids are A, C, F"

- Level 1: G 
- Level 2: D, I 
- Level 3: B, E, H, K 
- Level 4: A, C, F

Order Searched: G, D, I, B, E, H, K, A, C, F

Depth First Traversal:
Traversal is not done ACROSS entire levels at a time. Instead, traversal dives into the DEPTH (from root to leaf) of the tree first. However, it's a bit more complex than simply up and down.

There are three methods:

1) PREORDER: ROOT, LEFT, RIGHT.
You need to think of this as a recursive process:  
Grab the Root. (G)  
Then Check the Left. (It's a tree)  
Grab the Root of the Left. (D)  
Then Check the Left of D. (It's a tree)  
Grab the Root of the Left (B)  
Then Check the Left of B. (A)  
Check the Right of B. (C, and it's a leaf node. Finish B tree. Continue D tree)  
Check the Right of D. (It's a tree)  
Grab the Root. (E)  
Check the Left of E. (Nothing)  
Check the Right of E. (F, Finish D Tree. Move back to G Tree)  
Check the Right of G. (It's a tree)  
Grab the Root of I Tree. (I)  
Check the Left. (H, it's a leaf.)  
Check the Right. (K, it's a leaf. Finish G tree)  
DONE: G, D, B, A, C, E, F, I, H, K  

2) INORDER: LEFT, ROOT, RIGHT
Where the root is "in" or between the left and right child node.  
Check the Left of the G Tree. (It's a D Tree)  
Check the Left of the D Tree. (It's a B Tree)  
Check the Left of the B Tree. (A)  
Check the Root of the B Tree (B)  
Check the Right of the B Tree (C, finished B Tree!)  
Check the Right of the D Tree (It's a E Tree)  
Check the Left of the E Tree. (Nothing)  
Check the Right of the E Tree. (F, it's a leaf. Finish E Tree. Finish D Tree)...  
Onwards until...   
DONE: A, B, C, D, E, F, G, H, I, K  

3) POSTORDER: 
LEFT, RIGHT, ROOT  
DONE: A, C, B, F, E, D, H, K, I, G

Usage (aka, why do we care):
I really enjoyed this simple Quora explanation of the Depth First Traversal methods and how they are commonly used:
"In-Order Traversal will print values [in order for the BST (binary search tree)]"
"Pre-order traversal is used to create a copy of the [binary search tree]."
"Postorder traversal is used to delete the [binary search tree]."
https://www.quora.com/What-is-the-use-of-pre-order-and-post-order-traversal-of-binary-trees-in-computing

Json.NET serialize object with root name

Sorry, my english is not that good. But i like to improve the upvoted answers. I think that using Dictionary is more simple and clean.

class Program
    {
        static void Main(string[] args)
        {
            agencia ag1 = new agencia()
            {
                name = "Iquique",
                data = new object[] { new object[] {"Lucas", 20 }, new object[] {"Fernando", 15 } }
            };
            agencia ag2 = new agencia()
            {
                name = "Valparaiso",
                data = new object[] { new object[] { "Rems", 20 }, new object[] { "Perex", 15 } }
            };
            agencia agn = new agencia()
            {
                name = "Santiago",
                data = new object[] { new object[] { "Jhon", 20 }, new object[] { "Karma", 15 } }
            };


            Dictionary<string, agencia> dic = new Dictionary<string, agencia>
            {
                { "Iquique", ag1 },
                { "Valparaiso", ag2 },
                { "Santiago", agn }
            };

            string da = Newtonsoft.Json.JsonConvert.SerializeObject(dic);

            Console.WriteLine(da);
            Console.ReadLine();
        }


    }

    public class agencia
    {
        public string name { get; set; }
        public object[] data { get; set; }
    }

This code generate the following json (This is desired format)

{  
   "Iquique":{  
      "name":"Iquique",
      "data":[  
         [  
            "Lucas",
            20
         ],
         [  
            "Fernando",
            15
         ]
      ]
   },
   "Valparaiso":{  
      "name":"Valparaiso",
      "data":[  
         [  
            "Rems",
            20
         ],
         [  
            "Perex",
            15
         ]
      ]
   },
   "Santiago":{  
      "name":"Santiago",
      "data":[  
         [  
            "Jhon",
            20
         ],
         [  
            "Karma",
            15
         ]
      ]
   }
}

Add new column with foreign key constraint in one command

For SQL Server it should be something like

ALTER TABLE one
ADD two_id integer constraint fk foreign key references two(id)

How to execute a java .class from the command line

First, have you compiled the class using the command line javac compiler? Second, it seems that your main method has an incorrect signature - it should be taking in an array of String objects, rather than just one:

public static void main(String[] args){

Once you've changed your code to take in an array of String objects, then you need to make sure that you're printing an element of the array, rather than array itself:

System.out.println(args[0])

If you want to print the whole list of command line arguments, you'd need to use a loop, e.g.

for(int i = 0; i < args.length; i++){
    System.out.print(args[i]);
}
System.out.println();

what is the most efficient way of counting occurrences in pandas?

When you want to count the frequency of categorical data in a column in pandas dataFrame use: df['Column_Name'].value_counts()

-Source.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

As another variation on Totem's known type solution, you can use reflection to create a generic type resolver to avoid the need to use known type attributes.

This uses a technique similar to Juval Lowy's GenericResolver for WCF.

As long as your base class is abstract or an interface, the known types will be automatically determined rather than having to be decorated with known type attributes.

In my own case I opted to use a $type property to designate type in my json object rather than try to determine it from the properties, though you could borrow from other solutions here to use property based determination.

 public class JsonKnownTypeConverter : JsonConverter
{
    public IEnumerable<Type> KnownTypes { get; set; }

    public JsonKnownTypeConverter() : this(ReflectTypes())
    {

    }
    public JsonKnownTypeConverter(IEnumerable<Type> knownTypes)
    {
        KnownTypes = knownTypes;
    }

    protected object Create(Type objectType, JObject jObject)
    {
        if (jObject["$type"] != null)
        {
            string typeName = jObject["$type"].ToString();
            return Activator.CreateInstance(KnownTypes.First(x => typeName == x.Name));
        }
        else
        {
            return Activator.CreateInstance(objectType);
        }
        throw new InvalidOperationException("No supported type");
    }

    public override bool CanConvert(Type objectType)
    {
        if (KnownTypes == null)
            return false;

        return (objectType.IsInterface || objectType.IsAbstract) && KnownTypes.Any(objectType.IsAssignableFrom);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // Load JObject from stream
        JObject jObject = JObject.Load(reader);

        // Create target object based on JObject
        var target = Create(objectType, jObject);
        // Populate the object properties
        serializer.Populate(jObject.CreateReader(), target);
        return target;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    //Static helpers
    static Assembly CallingAssembly = Assembly.GetCallingAssembly();

    static Type[] ReflectTypes()
    {
        List<Type> types = new List<Type>();
        var referencedAssemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies();
        foreach (var assemblyName in referencedAssemblies)
        {
            Assembly assembly = Assembly.Load(assemblyName);
            Type[] typesInReferencedAssembly = GetTypes(assembly);
            types.AddRange(typesInReferencedAssembly);
        }

        return types.ToArray();
    }

    static Type[] GetTypes(Assembly assembly, bool publicOnly = true)
    {
        Type[] allTypes = assembly.GetTypes();

        List<Type> types = new List<Type>();

        foreach (Type type in allTypes)
        {
            if (type.IsEnum == false &&
               type.IsInterface == false &&
               type.IsGenericTypeDefinition == false)
            {
                if (publicOnly == true && type.IsPublic == false)
                {
                    if (type.IsNested == false)
                    {
                        continue;
                    }
                    if (type.IsNestedPrivate == true)
                    {
                        continue;
                    }
                }
                types.Add(type);
            }
        }
        return types.ToArray();
    }

It can then be installed as a formatter

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new JsonKnownTypeConverter());

Undefined reference to pthread_create in Linux

Compile it like this : gcc demo.c -o demo -pthread

How do I align views at the bottom of the screen?

This also works.

<LinearLayout 
    android:id="@+id/linearLayout4"
    android:layout_width="wrap_content"
    android:layout_height="fill_parent"
    android:layout_below="@+id/linearLayout3"
    android:layout_centerHorizontal="true"
    android:orientation="horizontal" 
    android:gravity="bottom"
    android:layout_alignParentBottom="true"
    android:layout_marginTop="20dp"
>

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" 

    />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" 


    />

</LinearLayout>

gravity="bottom" to float LinearLayout elements to bottom

Coarse-grained vs fine-grained

In the terms of POS (Part of Speech) Tag,

Node.js connect only works on localhost

On your app, makes it reachable from any device in the network:

app.listen(3000, "0.0.0.0");

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS

How to detect when keyboard is shown and hidden

You may just need addObserver in viewDidLoad. But having addObserver in viewWillAppear and removeObserver in viewWillDisappear prevents rare crashes which happens when you are changing your view.

Swift 4.2

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: UIResponder.keyboardWillHideNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: UIResponder.keyboardWillShowNotification, object: nil)
}

@objc func keyboardWillAppear() {
    //Do something here
}

@objc func keyboardWillDisappear() {
    //Do something here
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}

Swift 3 and 4

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillDisappear), name: Notification.Name.UIKeyboardWillHide, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear), name: Notification.Name.UIKeyboardWillShow, object: nil)
}

@objc func keyboardWillAppear() {
    //Do something here
}

@objc func keyboardWillDisappear() {
    //Do something here
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self)
}

Older Swift

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"keyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWillAppear(notification: NSNotification){
    // Do something here
}

func keyboardWillDisappear(notification: NSNotification){
    // Do something here
}

override func viewWillDisappear(animated: Bool) {
    super.viewWillDisappear(animated)
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

How to merge multiple dicts with same key or different key?

If keys are nested:

d1 = { 'key1': { 'nkey1': 'x1' }, 'key2': { 'nkey2': 'y1' } } 
d2 = { 'key1': { 'nkey1': 'x2' }, 'key2': { 'nkey2': 'y2' } }
ds = [d1, d2]
d = {}
for k in d1.keys():
    for k2 in d1[k].keys():
        d.setdefault(k, {})
        d[k].setdefault(k2, [])
        d[k][k2] = tuple(d[k][k2] for d in ds)

yields:

{'key1': {'nkey1': ('x1', 'x2')}, 'key2': {'nkey2': ('y1', 'y2')}}

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

Send a ajax request to your server like this in your js and get your result in success function.

jQuery.ajax({
            url: "/rest/abc",
            type: "GET",

            contentType: 'application/json; charset=utf-8',
            success: function(resultData) {
                //here is your json.
                  // process it

            },
            error : function(jqXHR, textStatus, errorThrown) {
            },

            timeout: 120000,
        });

at server side send response as json type.

And you can use jQuery.getJSON for your application.

How do I prevent CSS inheritance?

There is a property called all in the CSS3 inheritance module. It works like this:

#sidebar ul li {
  all: initial;
}

As of 2016-12, all browsers but IE/Edge and Opera Mini support this property.

How to open a link in new tab using angular?

Try this:

 window.open(this.url+'/create-account')

No need to use '_blank'. window.open by default opens a link in a new tab.

How to make layout with View fill the remaining space?

For those having the same glitch with <LinearLayout...> as I did:

It is important to specify android:layout_width="fill_parent", it will not work with wrap_content.

OTOH, you may omit android:layout_weight = "0", it is not required.

My code is basically the same as the code in https://stackoverflow.com/a/25781167/755804 (by Vivek Pandey)

Escaping backslash in string - javascript

Add an input id to the element and do something like that:

document.getElementById('inputId').value.split(/[\\$]/).pop()

Add target="_blank" in CSS

There are a few ways CSS can 'target' navigation. This will style internal and external links using attribute styling, which could help signal visitors to what your links will do.

a[href="#"] { color: forestgreen; font-weight: normal; }
a[href="http"] { color: dodgerblue; font-weight: normal; }  

You can also target the traditional inline HTML 'target=_blank'.

a[target=_blank] { font-weight: bold; } 

Also :target selector to style navigation block and element targets.

nav { display: none; }
nav:target { display: block; }  

CSS :target pseudo-class selector is supported - caniuse, w3schools, MDN.

a[href="http"] { target: new; target-name: new; target-new: tab; }

CSS/CSS3 'target-new' property etc, not supported by any major browsers, 2017 August, though it is part of the W3 spec since 2004 February.

W3Schools 'modal' construction, uses ':target' pseudo-class that could contain WP navigation. You can also add HTML rel="noreferrer and noopener beside target="_blank" to improve 'new tab' performance. CSS will not open links in tabs for now, but this page explains how to do that with jQuery (compatibility may depend for WP coders). MDN has a good review at Using the :target pseudo-class in selectors

Best way to implement keyboard shortcuts in a Windows Forms application?

You probably forgot to set the form's KeyPreview property to True. Overriding the ProcessCmdKey() method is the generic solution:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {
  if (keyData == (Keys.Control | Keys.F)) {
    MessageBox.Show("What the Ctrl+F?");
    return true;
  }
  return base.ProcessCmdKey(ref msg, keyData);
}

Restart container within pod

There was an issue in coredns pod, I deleted such pod by

kubectl delete pod -n=kube-system coredns-fb8b8dccf-8ggcf

Its pod will restart automatically.

Using a dictionary to select function to execute

You are wasting your time:

  1. You are about to write a lot of useless code and introduce new bugs.
  2. To execute the function, your user will need to know the P1 name anyway.
  3. Etc., etc., etc.

Just put all your functions in the .py file:

# my_module.py

def f1():
    pass

def f2():
    pass

def f3():
    pass

And use them like this:

import my_module

my_module.f1()
my_module.f2()
my_module.f3()

or:

from my_module import f1
from my_module import f2
from my_module import f3

f1()
f2()
f3()

This should be enough for starters.

How do I pass along variables with XMLHTTPRequest

Yes that's the correct method to do it with a GET request.

However, please remember that multiple query string parameters should be separated with &

eg. ?variable1=value1&variable2=value2

How to add url parameter to the current url?

In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

<script>
function addUrlParameter(name, value) {
  var searchParams = new URLSearchParams(window.location.search)
  searchParams.set(name, value)
  window.location.search = searchParams.toString()
}
</script>

<body>
...
  <a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>

Multiple aggregate functions in HAVING clause

For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

In your general case:

GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

Or (possibly easier to read?),

GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

Float a div in top right corner without overlapping sibling header

section {
    position: relative;
    width: 50%;
    border: 1px solid;
}
h1 {
    display: inline;
}
div {
    position: relative;
    float:right;
    top: 0;
    right: 0;

}

How to compress an image via Javascript in the browser?

i improved the function a head to be this :

var minifyImg = function(dataUrl,newWidth,imageType="image/jpeg",resolve,imageArguments=0.7){
    var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
    (new Promise(function(resolve){
      image = new Image(); image.src = dataUrl;
      log(image);
      resolve('Done : ');
    })).then((d)=>{
      oldWidth = image.width; oldHeight = image.height;
      log([oldWidth,oldHeight]);
      newHeight = Math.floor(oldHeight / oldWidth * newWidth);
      log(d+' '+newHeight);

      canvas = document.createElement("canvas");
      canvas.width = newWidth; canvas.height = newHeight;
      log(canvas);
      ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, newWidth, newHeight);
      //log(ctx);
      newDataUrl = canvas.toDataURL(imageType, imageArguments);
      resolve(newDataUrl);
    });
  };

the use of it :

minifyImg(<--DATAURL_HERE-->,<--new width-->,<--type like image/jpeg-->,(data)=>{
   console.log(data); // the new DATAURL
});

enjoy ;)

How to pass in a react component into another react component to transclude the first component's content?

Here is an example of a parent List react component and whos props contain a react element. In this case, just a single Link react component is passed in (as seen in the dom render).

class Link extends React.Component {
  constructor(props){
    super(props);
  }
  render(){
    return (
      <div>
        <p>{this.props.name}</p>
      </div>
     );
  }
}
class List extends React.Component {
  render(){
   return(
    <div>
       {this.props.element}
       {this.props.element}
    </div>
   );
  }
}

ReactDOM.render(
  <List element = {<Link name = "working"/>}/>,
  document.getElementById('root')
);

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For me it was important to delete the "php.executablePath" path from the VS code settings and leave only the path to PHP in the Path variable.

When I had the Path variable together with php.executablePath, an irritating error still occurred (despite the fact that the path to php was correct).

Submit HTML form, perform javascript function (alert then redirect)

<form action="javascript:completeAndRedirect();">
    <input type="text" id="Edit1" 
    style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>

Changing action to point at your function would solve the problem, in a different way.

Setting button text via javascript

Create a text node and append it to the button element:

var t = document.createTextNode("test content");
b.appendChild(t);

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

getting JRE system library unbound error in build path

The solution that work for me is the following:

  1. Select a project
  2. Select the project menu
  3. Select properties sub-menu
  4. In the window "properties for 'your project'", select Java Build Path tab
  5. Select libraries tab
  6. Select the troublesome JRE entry
  7. Click on edit button
  8. Select JRE entry
  9. Click on finish button

Converting an integer to binary in C

If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char* to the solution

unsigned int_to_int(unsigned k) {
    if (k == 0) return 0;
    if (k == 1) return 1;                       /* optional */
    return (k % 2) + 10 * int_to_int(k / 2);
}

HalosGhost suggested to compact the code into a single line

unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

Android studio Gradle icon error, Manifest Merger

This issue occurs when you add a third-party library with @drawable/ic_launcher attribute thus android merger is unable to differentiate your app icon attribute and the library's attribute. To solve this add this line in your manifest file under the application tag

tools:replace="android:icon"

excel VBA run macro automatically whenever a cell is changed

Another option is

Private Sub Worksheet_Change(ByVal Target As Range)
    IF Target.Address = "$D$2" Then
        MsgBox("Cell D2 Has Changed.")
    End If
End Sub

I believe this uses fewer resources than Intersect, which will be helpful if your worksheet changes a lot.

HTML anchor link - href and onclick both?

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

How can I show data using a modal when clicking a table row (using bootstrap)?

The solution from PSL will not work in Firefox. FF accepts event only as a formal parameter. So you have to find another way to identify the selected row. My solution is something like this:

...
$('#mySelector')
  .on('show.bs.modal', function(e) {
  var mid;


  if (navigator.userAgent.toLowerCase().indexOf('firefox') > -1) 
    mid = $(e.relatedTarget).data('id');
  else
    mid = $(event.target).closest('tr').data('id');

...

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

import the ReactiveForms Module to your components module

Tools for making latex tables in R

I have a few tricks and work arounds to interesting 'features' of xtable and Latex that I'll share here.

Trick #1: Removing Duplicates in Columns and Trick #2: Using Booktabs

First, load packages and define my clean function

<<label=first, include=FALSE, echo=FALSE>>= 
    library(xtable)
    library(plyr)

    cleanf <- function(x){     
        oldx <- c(FALSE, x[-1]==x[-length(x)])  
        # is the value equal to the previous?    
        res <- x
        res[oldx] <- NA
        return(res)} 

Now generate some fake data

data<-data.frame(animal=sample(c("elephant", "dog", "cat", "fish", "snake"), 100,replace=TRUE),
            colour=sample(c("red", "blue", "green", "yellow"), 100,replace=TRUE),
            size=rnorm(100,mean=500, sd=150),
            age=rlnorm(100, meanlog=3, sdlog=0.5))

    #generate a table
    datatable<-ddply(data, .(animal, colour), function(df) {
                return(data.frame(size=mean(df$size), age=mean(df$age)))
            })

Now we can generate a table, and use the clean function to remove duplicate entries in the label columns.

cleandata<-datatable
cleandata$animal<-cleanf(cleandata$animal)
cleandata$colour<-cleanf(cleandata$colour)
@ 

this is a normal xtable

<<label=normal, results=tex, echo=FALSE>>=
print(
    xtable(
        datatable
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

this is a normal xtable where a custom function has turned duplicates to NA

<<label=cleandata, results=tex, echo=FALSE>>=
print(
    xtable(
        cleandata
        ),
        tabular.environment='longtable',
        latex.environments=c("center"), 
        floating=FALSE, 
        include.rownames=FALSE
    )
@ 

This table uses the booktab package (and needs a \usepackage{booktabs} in the headers)

\begin{table}[!h] 
        \centering
        \caption{table using booktabs.}
        \label{tab:mytable}
<<label=booktabs, echo=F,results=tex>>= 
            mat <- xtable(cleandata,digits=rep(2,ncol(cleandata)+1))
            foo<-0:(length(mat$animal))
            bar<-foo[!is.na(mat$animal)]
            print(mat, 
                  sanitize.text.function = function(x){x},
                  floating=FALSE,
                  include.rownames=FALSE,
                  hline.after=NULL, 
                  add.to.row=list(pos=list(-1,bar,nrow(mat)), 
                  command=c("\\toprule ", "\\midrule ", "\\bottomrule ")))
  #could extend this with \cmidrule to have a partial line over
  #a sub category column and \addlinespace to add space before a total row
@ 

get list of pandas dataframe columns based on data type

I use infer_objects()

Docstring: Attempt to infer better dtypes for object columns.

Attempts soft conversion of object-dtyped columns, leaving non-object and unconvertible columns unchanged. The inference rules are the same as during normal Series/DataFrame construction.

df.infer_objects().dtypes

Check if an array item is set in JS

if (assoc_pagine.indexOf('home') > -1) {
   // we have home element in the assoc_pagine array
}

Mozilla indexOf

Get record counts for all tables in MySQL database

SELECT SUM(TABLE_ROWS) 
     FROM INFORMATION_SCHEMA.TABLES 
     WHERE TABLE_SCHEMA = '{your_db}';

Note from the docs though: For InnoDB tables, the row count is only a rough estimate used in SQL optimization. You'll need to use COUNT(*) for exact counts (which is more expensive).

How to center horizontal table-cell

If you add text-align: center to the declarations for .columns-container then they align centrally:

.columns-container {
    display: table-cell;
    height: 100%;
    width:600px;
    text-align: center;
}

_x000D_
_x000D_
/*************************_x000D_
 * Sticky footer hack_x000D_
 * Source: http://pixelsvsbytes.com/blog/2011/09/sticky-css-footers-the-flexible-way/_x000D_
 ************************/_x000D_
_x000D_
/* Stretching all container's parents to full height */_x000D_
_x000D_
html,_x000D_
body {_x000D_
  height: 100%;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
/* Setting the container to be a table with maximum width and height */_x000D_
_x000D_
#container {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
}_x000D_
/* All sections (container's children) should be table rows with minimal height */_x000D_
_x000D_
.section {_x000D_
  display: table-row;_x000D_
  height: 1px;_x000D_
}_x000D_
/* The last-but-one section should be stretched to automatic height */_x000D_
_x000D_
.section.expand {_x000D_
  height: auto;_x000D_
}_x000D_
/*************************_x000D_
 * Full height columns_x000D_
 ************************/_x000D_
_x000D_
/* We need one extra container, setting it to full width */_x000D_
_x000D_
.columns-container {_x000D_
display: table-cell;_x000D_
height: 100%;_x000D_
width:600px;_x000D_
text-align: center;_x000D_
}_x000D_
/* Creating columns */_x000D_
_x000D_
.column {_x000D_
  /* The float:left won't work for Chrome for some reason, so inline-block */_x000D_
  display: inline-block;_x000D_
  /* for this to work, the .column elements should have NO SPACE BETWEEN THEM */_x000D_
  vertical-align: top;_x000D_
  height: 100%;_x000D_
  width: 100px;_x000D_
}_x000D_
/****************************************************************_x000D_
 * Just some coloring so that we're able to see height of columns_x000D_
 ****************************************************************/_x000D_
_x000D_
header {_x000D_
  background-color: yellow;_x000D_
}_x000D_
#a {_x000D_
  background-color: pink;_x000D_
}_x000D_
#b {_x000D_
  background-color: lightgreen;_x000D_
}_x000D_
#c {_x000D_
  background-color: lightblue;_x000D_
}_x000D_
footer {_x000D_
  background-color: purple;_x000D_
}
_x000D_
<div id="container">_x000D_
  <header class="section">_x000D_
    foo_x000D_
  </header>_x000D_
_x000D_
  <div class="section expand">_x000D_
    <div class="columns-container">_x000D_
      <div class="column" id="a">_x000D_
        <p>Contents A</p>_x000D_
      </div>_x000D_
      <div class="column" id="b">_x000D_
        <p>Contents B</p>_x000D_
      </div>_x000D_
      <div class="column" id="c">_x000D_
        <p>Contents C</p>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <footer class="section">_x000D_
    bar_x000D_
  </footer>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This does, though, require that you reset the .column elements to text-align: left (assuming you want them left-aligned, obviously (JS Fiddle demo).

<ng-container> vs <template>

Imo use cases for ng-container are simple replacements for which a custom template/component would be overkill. In the API doc they mention the following

use a ng-container to group multiple root nodes

and I guess that's what it is all about: grouping stuff.

Be aware that the ng-container directive falls away instead of a template where its directive wraps the actual content.

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

How to move/rename a file using an Ansible task on a remote system

This may seem like overkill, but if you want to avoid using the command module (which I do, because it using command is not idempotent) you can use a combination of copy and unarchive.

  1. Use tar to archive the file(s) you will need. If you think ahead this actually makes sense. You may want a series of files in a given directory. Create that directory with all of the files and archive them in a tar.
  2. Use the unarchive module. When you do that, along with the destination: and remote_src: keyword, you can place copy all of your files to a temporary folder to start with and then unpack them exactly where you want to.

Visual Studio 2013 Install Fails: Program Compatibility Mode is on (Windows 10)

If you disable the Program Compatibility Mode and the problem persists, copy the content of ISO to a local path and try install with a simple double click

MySQL: Convert INT to DATETIME

select from_unixtime(column,'%Y-%m-%d') from myTable; 

Creating a recursive method for Palindrome

Well:

  • It's not clear why you've got two methods with the same signature. What are they meant to accomplish?
  • In the first method, why are you testing for testing for a single space or any single character?
  • You might want to consider generalizing your termination condition to "if the length is less than two"
  • Consider how you want to recurse. One option:
    • Check that the first letter is equal to the last letter. If not, return false
    • Now take a substring to effectively remove the first and last letters, and recurse
  • Is this meant to be an exercise in recursion? That's certainly one way of doing it, but it's far from the only way.

I'm not going to spell it out any more clearly than that for the moment, because I suspect this is homework - indeed some may consider the help above as too much (I'm certainly slightly hesitant myself). If you have any problems with the above hints, update your question to show how far you've got.

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6