Programs & Examples On #Xapian

Open Source Search Engine Library with bindings to allow use from Perl, Python, PHP, Java, Tcl, C#, Ruby and Lua

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

We use Lucene regularly to index and search tens of millions of documents. Searches are quick enough, and we use incremental updates that do not take a long time. It did take us some time to get here. The strong points of Lucene are its scalability, a large range of features and an active community of developers. Using bare Lucene requires programming in Java.

If you are starting afresh, the tool for you in the Lucene family is Solr, which is much easier to set up than bare Lucene, and has almost all of Lucene's power. It can import database documents easily. Solr are written in Java, so any modification of Solr requires Java knowledge, but you can do a lot just by tweaking configuration files.

I have also heard good things about Sphinx, especially in conjunction with a MySQL database. Have not used it, though.

IMO, you should choose according to:

  • The required functionality - e.g. do you need a French stemmer? Lucene and Solr have one, I do not know about the others.
  • Proficiency in the implementation language - Do not touch Java Lucene if you do not know Java. You may need C++ to do stuff with Sphinx. Lucene has also been ported into other languages. This is mostly important if you want to extend the search engine.
  • Ease of experimentation - I believe Solr is best in this aspect.
  • Interfacing with other software - Sphinx has a good interface with MySQL. Solr supports ruby, XML and JSON interfaces as a RESTful server. Lucene only gives you programmatic access through Java. Compass and Hibernate Search are wrappers of Lucene that integrate it into larger frameworks.

How to find all serial devices (ttyS, ttyUSB, ..) on Linux without opening them?

My approach via group dialout to get every tty with user 'dialout' ls -l /dev/tty* | grep 'dialout' to only get its folder ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev

easy listen to the tty output e.g. when arduino serial out: head --lines 1 < /dev/ttyUSB0

listen to every tty out for one line only: for i in $(ls -l /dev/tty* | grep 'dialout' | rev | cut -d " " -f1 | rev); do head --lines 1 < $i; done

I really like the approach via looking for drivers: ll /sys/class/tty/*/device/driver

You can pick the tty-Name now: ls /sys/class/tty/*/device/driver | grep 'driver' | cut -d "/" -f 5

How to send email from MySQL 5.1

I would be very concerned about putting the load of sending e-mails on my database server (small though it may be). I might suggest one of these alternatives:

  1. Have application logic detect the need to send an e-mail and send it.
  2. Have a MySQL trigger populate a table that queues up the e-mails to be sent and have a process monitor that table and send the e-mails.

TABLOCK vs TABLOCKX

Quite an old article on mssqlcity attempts to explain the types of locks:

Shared locks are used for operations that do not change or update data, such as a SELECT statement.

Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.

Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.

What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).


The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.

Big O, how do you calculate/approximate it?

I think about it in terms of information. Any problem consists of learning a certain number of bits.

Your basic tool is the concept of decision points and their entropy. The entropy of a decision point is the average information it will give you. For example, if a program contains a decision point with two branches, it's entropy is the sum of the probability of each branch times the log2 of the inverse probability of that branch. That's how much you learn by executing that decision.

For example, an if statement having two branches, both equally likely, has an entropy of 1/2 * log(2/1) + 1/2 * log(2/1) = 1/2 * 1 + 1/2 * 1 = 1. So its entropy is 1 bit.

Suppose you are searching a table of N items, like N=1024. That is a 10-bit problem because log(1024) = 10 bits. So if you can search it with IF statements that have equally likely outcomes, it should take 10 decisions.

That's what you get with binary search.

Suppose you are doing linear search. You look at the first element and ask if it's the one you want. The probabilities are 1/1024 that it is, and 1023/1024 that it isn't. The entropy of that decision is 1/1024*log(1024/1) + 1023/1024 * log(1024/1023) = 1/1024 * 10 + 1023/1024 * about 0 = about .01 bit. You've learned very little! The second decision isn't much better. That is why linear search is so slow. In fact it's exponential in the number of bits you need to learn.

Suppose you are doing indexing. Suppose the table is pre-sorted into a lot of bins, and you use some of all of the bits in the key to index directly to the table entry. If there are 1024 bins, the entropy is 1/1024 * log(1024) + 1/1024 * log(1024) + ... for all 1024 possible outcomes. This is 1/1024 * 10 times 1024 outcomes, or 10 bits of entropy for that one indexing operation. That is why indexing search is fast.

Now think about sorting. You have N items, and you have a list. For each item, you have to search for where the item goes in the list, and then add it to the list. So sorting takes roughly N times the number of steps of the underlying search.

So sorts based on binary decisions having roughly equally likely outcomes all take about O(N log N) steps. An O(N) sort algorithm is possible if it is based on indexing search.

I've found that nearly all algorithmic performance issues can be looked at in this way.

When do you use varargs in Java?

A good rule of thumb would be:

"Use varargs for any method (or constructor) that needs an array of T (whatever type T may be) as input".

That will make calls to these methods easier (no need to do new T[]{...}).

You could extend this rule to include methods with a List<T> argument, provided that this argument is for input only (ie, the list is not modified by the method).

Additionally, I would refrain from using f(Object... args) because its slips towards a programming way with unclear APIs.

In terms of examples, I have used it in DesignGridLayout, where I can add several JComponents in one call:

layout.row().grid(new JLabel("Label")).add(field1, field2, field3);

In the code above the add() method is defined as add(JComponent... components).

Finally, the implementation of such methods must take care of the fact that it may be called with an empty vararg! If you want to impose at least one argument, then you have to use an ugly trick such as:

void f(T arg1, T... args) {...}

I consider this trick ugly because the implementation of the method will be less straightforward than having just T... args in its arguments list.

Hopes this helps clarifying the point about varargs.

#pragma pack effect

#pragma pack instructs the compiler to pack structure members with particular alignment. Most compilers, when you declare a struct, will insert padding between members to ensure that they are aligned to appropriate addresses in memory (usually a multiple of the type's size). This avoids the performance penalty (or outright error) on some architectures associated with accessing variables that are not aligned properly. For example, given 4-byte integers and the following struct:

struct Test
{
   char AA;
   int BB;
   char CC;
};

The compiler could choose to lay the struct out in memory like this:

|   1   |   2   |   3   |   4   |  

| AA(1) | pad.................. |
| BB(1) | BB(2) | BB(3) | BB(4) | 
| CC(1) | pad.................. |

and sizeof(Test) would be 4 × 3 = 12, even though it only contains 6 bytes of data. The most common use case for the #pragma (to my knowledge) is when working with hardware devices where you need to ensure that the compiler does not insert padding into the data and each member follows the previous one. With #pragma pack(1), the struct above would be laid out like this:

|   1   |

| AA(1) |
| BB(1) |
| BB(2) |
| BB(3) |
| BB(4) |
| CC(1) |

And sizeof(Test) would be 1 × 6 = 6.

With #pragma pack(2), the struct above would be laid out like this:

|   1   |   2   | 

| AA(1) | pad.. |
| BB(1) | BB(2) |
| BB(3) | BB(4) |
| CC(1) | pad.. |

And sizeof(Test) would be 2 × 4 = 8.

Order of variables in struct is also important. With variables ordered like following:

struct Test
{
   char AA;
   char CC;
   int BB;
};

and with #pragma pack(2), the struct would be laid out like this:

|   1   |   2   | 

| AA(1) | CC(1) |
| BB(1) | BB(2) |
| BB(3) | BB(4) |

and sizeOf(Test) would be 3 × 2 = 6.

PDO get the last ID inserted

lastInsertId() only work after the INSERT query.

Correct:

$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass) 
                              VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();

Incorrect:

$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0

How to change the href for a hyperlink using jQuery

Using

$("a").attr("href", "http://www.google.com/")

will modify the href of all hyperlinks to point to Google. You probably want a somewhat more refined selector though. For instance, if you have a mix of link source (hyperlink) and link target (a.k.a. "anchor") anchor tags:

<a name="MyLinks"></a>
<a href="http://www.codeproject.com/">The CodeProject</a>

...Then you probably don't want to accidentally add href attributes to them. For safety then, we can specify that our selector will only match <a> tags with an existing href attribute:

$("a[href]") //...

Of course, you'll probably have something more interesting in mind. If you want to match an anchor with a specific existing href, you might use something like this:

$("a[href='http://www.google.com/']").attr('href', 'http://www.live.com/')

This will find links where the href exactly matches the string http://www.google.com/. A more involved task might be matching, then updating only part of the href:

$("a[href^='http://stackoverflow.com']")
   .each(function()
   { 
      this.href = this.href.replace(/^http:\/\/beta\.stackoverflow\.com/, 
         "http://stackoverflow.com");
   });

The first part selects only links where the href starts with http://stackoverflow.com. Then, a function is defined that uses a simple regular expression to replace this part of the URL with a new one. Note the flexibility this gives you - any sort of modification to the link could be done here.

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

Does IMDB provide an API?

The IMDb has a public API that, although undocumented, is fast and reliable (used on the official website through AJAX).

Search Suggestions API

// 1) Vanilla JavaScript (JSON-P)
function addScript(src) { var s = document.createElement('script'); s.src = src; document.head.appendChild(s); }
window.imdb$foo = function (results) {
  /* ... */
};
addScript('https://sg.media-imdb.com/suggests/f/foo.json');

// 2) Using jQuery (JSON-P)
jQuery.ajax({
    url: 'https://sg.media-imdb.com/suggests/f/foo.json',
    dataType: 'jsonp',
    cache: true,
    jsonp: false,
    jsonpCallback: 'imdb$foo'
}).then(function (results) {
    /* ... */
});

// 3) Pure JSON (with jQuery)
// Use a local proxy that strips the "padding" of JSON-P,
// e.g. "imdb$foo(" and ")", leaving pure JSON only.
jQuery.getJSON('/api/imdb/?q=foo', function (results) {
    /* ... */
});

// 4) Pure JSON (ES2017 and Fetch API)
// Using a custom proxy at "/api" that strips the JSON-P padding.
const resp = await fetch('/api/imdb/?q=foo');
const results = await resp.json();

Advanced Search


Beware that these APIs are unofficial and could change at any time!


Update (January 2019): The Advanced API no longer exists. The good news is, that the Suggestions API now supports the "advanced" features of searching by film titles and actor names as well.

time data does not match format

You have the month and day swapped:

'%m/%d/%Y %H:%M:%S.%f'

28 will never fit in the range for the %m month parameter otherwise.

With %m and %d in the correct order parsing works:

>>> from datetime import datetime
>>> datetime.strptime('07/28/2014 18:54:55.099000', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

You don't need to add '000'; %f can parse shorter numbers correctly:

>>> datetime.strptime('07/28/2014 18:54:55.099', '%m/%d/%Y %H:%M:%S.%f')
datetime.datetime(2014, 7, 28, 18, 54, 55, 99000)

When I catch an exception, how do I get the type, file, and line number?

Without any imports, but also incompatible with imported modules:

try:
    raise TypeError("Hello, World!")  # line 2
except Exception as e:
    print(
        type(e).__name__,          # TypeError
        __file__,                  # /tmp/example.py
        e.__traceback__.tb_lineno  # 2
    )

$ python3 /tmp/example.py
TypeError /tmp/example.py 2

To reiterate, this does not work across imports or modules, so if you do import X; try: X.example(); then the filename and line number will point to the line containing X.example() instead of the line where it went wrong within X.example(). If anyone knows how to easily get the file name and line number from the last stack trace line (I expected something like e[-1].filename, but no such luck), please improve this answer.

The name 'ConfigurationManager' does not exist in the current context

Are you sure you have added a reference to the .NET assembly and not something else? I'd remove your reference and then try re-adding it, making sure you select from the .NET tab in Visual Studio reference dialogue - the latest version should be 2.0.0.0 in GAC.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

With version 2018.1 the keyboard short cuts for navigation are Shift+Alt+Left or Right

UPDATE with CASE and IN - Oracle

"The list are variables/paramaters that is pre-defined as comma separated lists". Do you mean that your query is actually

UPDATE tab1   SET budgpost_gr1=     
CASE  WHEN (budgpost in ('1001,1012,50055'))  THEN 'BP_GR_A'   
      WHEN (budgpost in ('5,10,98,0'))  THEN 'BP_GR_B'  
      WHEN (budgpost in ('11,876,7976,67465'))     
      ELSE 'Missing' END`

If so, you need a function to take a string and parse it into a list of numbers.

create type tab_num is table of number;

create or replace function f_str_to_nums (i_str in varchar2) return tab_num is
  v_tab_num tab_num := tab_num();
  v_start   number := 1;
  v_end     number;
  v_delim   VARCHAR2(1) := ',';
  v_cnt     number(1) := 1;
begin
  v_end := instr(i_str||v_delim,v_delim,1, v_start);
  WHILE v_end > 0 LOOP
    v_cnt := v_cnt + 1;
    v_tab_num.extend;
    v_tab_num(v_tab_num.count) := 
                  substr(i_str,v_start,v_end-v_start);
    v_start := v_end + 1;
    v_end := instr(i_str||v_delim,v_delim,v_start);
  END LOOP;
  RETURN v_tab_num;
end;
/

Then you can use the function like so:

select column_id, 
   case when column_id in 
     (select column_value from table(f_str_to_nums('1,2,3,4'))) then 'red' 
   else 'blue' end
from  user_tab_columns
where table_name = 'EMP'

Check play state of AVPlayer

You can tell it's playing using:

AVPlayer *player = ...
if ((player.rate != 0) && (player.error == nil)) {
    // player is playing
}

Swift 3 extension:

extension AVPlayer {
    var isPlaying: Bool {
        return rate != 0 && error == nil
    }
}

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

console.log not working in Angular2 Component (Typescript)

The console.log should be wrapped in a function , the "default" function for every class is its constructor so it should be declared there.

import { Component } from '@angular/core';
console.log("Hello1");

 @Component({
  selector: 'hello-console',
})
    export class App {
     s: string = "Hello2";
    constructor(){
     console.log(s); 
    }

}

Android Drawing Separator/Divider Line in Layout?

Here is your answer..this is an example to draw line between controls...

<TextView
            android:id="@+id/textView1"
            style="@style/behindMenuItemLabel1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginTop="1dp"
            android:text="FaceBook Feeds" />

         <View
             android:layout_width="fill_parent"
             android:layout_height="2dp"
             android:background="#d13033"/>

         <ListView
            android:id="@+id/list1"
            android:layout_width="350dp"
            android:layout_height="50dp" />

This code draw line between two controls...

Returning JSON object from an ASP.NET page

In your Page_Load you will want to clear out the normal output and write your own, for example:

string json = "{\"name\":\"Joe\"}";
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();

To convert a C# object to JSON you can use a library such as Json.NET.

Instead of getting your .aspx page to output JSON though, consider using a Web Service (asmx) or WCF, both of which can output JSON.

How can I move HEAD back to a previous location? (Detached head) & Undo commits

The question can be read as:

I was in detached-state with HEAD at 23b6772 and typed git reset origin/master (because I wanted to squash). Now I've changed my mind, how do I go back to HEAD being at 23b6772?

The straightforward answer being: git reset 23b6772

But I hit this question because I got sick of typing (copy & pasting) commit hashes or its abbreviation each time I wanted to reference the previous HEAD and was Googling to see if there were any kind of shorthand.

It turns out there is!

git reset - (or in my case git cherry-pick -)

Which incidentally was the same as cd - to return to the previous current directory in *nix! So hurrah, I learned two things with one stone.

XMLHttpRequest module not defined/found

With the xhr2 library you can globally overwrite XMLHttpRequest from your JS code. This allows you to use external libraries in node, that were intended to be run from browsers / assume they are run in a browser.

global.XMLHttpRequest = require('xhr2');

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

There is one big difference between malloc and new. malloc allocates memory. This is fine for C, because in C, a lump of memory is an object.

In C++, if you're not dealing with POD types (which are similar to C types) you must call a constructor on a memory location to actually have an object there. Non-POD types are very common in C++, as many C++ features make an object automatically non-POD.

new allocates memory and creates an object on that memory location. For non-POD types this means calling a constructor.

If you do something like this:

non_pod_type* p = (non_pod_type*) malloc(sizeof *p);

The pointer you obtain cannot be dereferenced because it does not point to an object. You'd need to call a constructor on it before you can use it (and this is done using placement new).

If, on the other hand, you do:

non_pod_type* p = new non_pod_type();

You get a pointer that is always valid, because new created an object.

Even for POD types, there's a significant difference between the two:

pod_type* p = (pod_type*) malloc(sizeof *p);
std::cout << p->foo;

This piece of code would print an unspecified value, because the POD objects created by malloc are not initialised.

With new, you could specify a constructor to call, and thus get a well defined value.

pod_type* p = new pod_type();
std::cout << p->foo; // prints 0

If you really want it, you can use use new to obtain uninitialised POD objects. See this other answer for more information on that.

Another difference is the behaviour upon failure. When it fails to allocate memory, malloc returns a null pointer, while new throws an exception.

The former requires you to test every pointer returned before using it, while the later will always produce valid pointers.

For these reasons, in C++ code you should use new, and not malloc. But even then, you should not use new "in the open", because it acquires resources you need to release later on. When you use new you should pass its result immediately into a resource managing class:

std::unique_ptr<T> p = std::unique_ptr<T>(new T()); // this won't leak

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

How to merge rows in a column into one cell in excel?

For Excel 2011 on Mac it's different. I did it as a three step process.

  1. Create a column of values in column A.
  2. In column B, to the right of the first cell, create a rule that uses the concatenate function on the column value and ",". For example, assuming A1 is the first row, the formula for B1 is =B1. For the next row to row N, the formula is =Concatenate(",",A2). You end up with:
QA
,Sekuli
,Testing
,Applitools
,Visual Testing
,Test Automation
,Selenium
  1. In column C create a formula that concatenates all previous values. Because it is additive you will get all at the end. The formula for cell C1 is =B1. For all other rows to N, the formula is =Concatenate(C1,B2). And you get:
QA,Sekuli
QA,Sekuli,Testing
QA,Sekuli,Testing,Applitools
QA,Sekuli,Testing,Applitools,Visual Testing
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation
QA,Sekuli,Testing,Applitools,Visual Testing,Test Automation,Selenium

The last cell of the list will be what you want. This is compatible with Excel on Windows or Mac.

DateTime.Compare how to check if a date is less than 30 days old?

No it's not correct, try this :

DateTime expiryDate = DateTime.Now.AddDays(-31);
if (DateTime.Compare(expiryDate, DateTime.Now.AddDays(-30)) < 1)
{
    matchFound = true;
}

How to update /etc/hosts file in Docker image during "docker build"

With a more recent version of docker, this could be done with docker-compose and its extra_hosts directive

Add hostname mappings.
Use the same values as the docker run client --add-host parameter (which should already be available for docker 1.8).

extra_hosts:
 - "somehost:162.242.195.82"
 - "otherhost:50.31.209.229"

In short: modify /etc/hosts of your container when running it, instead of when building it.


With Docker 17.x+, you have a docker build --add-host mentioned below, but, as commented in issue 34078 and in this answer:

The --add-host feature during build is designed to allow overriding a host during build, but not to persist that configuration in the image.

The solutions mentioned do refer the docker-compose I was suggesting above:

  • Run an internal DNS; you can set the default DNS server to use in the daemon; that way every container started will automatically use the configured DNS by default
  • Use docker compose and provide a docker-compose.yml to your developers.
    The docker compose file allows you to specify all the options that should be used when starting a container, so developers could just docker compose up to start the container with all the options they need to set.

How to store a dataframe using Pandas

As already mentioned there are different options and file formats (HDF5, JSON, CSV, parquet, SQL) to store a data frame. However, pickle is not a first-class citizen (depending on your setup), because:

  1. pickle is a potential security risk. Form the Python documentation for pickle:

Warning The pickle module is not secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

  1. pickle is slow. Find here and here benchmarks.

Depending on your setup/usage both limitations do not apply, but I would not recommend pickle as the default persistence for pandas data frames.

Count number of lines in a git repository

The best solution, to me anyway, is buried in the comments of @ephemient's answer. I am just pulling it up here so that it doesn't go unnoticed. The credit for this should go to @FRoZeN (and @ephemient).

git diff --shortstat `git hash-object -t tree /dev/null`

returns the total of files and lines in the working directory of a repo, without any additional noise. As a bonus, only the source code is counted - binary files are excluded from the tally.

The command above works on Linux and OS X. The cross-platform version of it is

git diff --shortstat 4b825dc642cb6eb9a060e54bf8d69288fbee4904

That works on Windows, too.

For the record, the options for excluding blank lines,

  • -w/--ignore-all-space,
  • -b/--ignore-space-change,
  • --ignore-blank-lines,
  • --ignore-space-at-eol

don't have any effect when used with --shortstat. Blank lines are counted.

How can I query a value in SQL Server XML column

I came up with a simple work around below which is easy to remember too :-)

select * from  
(select cast (xmlCol as varchar(max)) texty
 from myTable (NOLOCK) 
) a 
where texty like '%MySearchText%'

How do I deploy Node.js applications as a single executable file?

You could create a git repo and setup a link to the node git repo as a dependency. Then any user who clones the repo could also install node.

#git submodule [--quiet] add [-b branch] [-f|--force]
git submodule add /var/Node-repo.git common

You could easily package a script up to automatically clone the git repo you have hosted somewhere and "install" from one that one script file.

#!/bin/sh
#clone git repo
git clone your-repo.git

Can you find all classes in a package using reflection?

You need to look up every class loader entry in the class path:

    String pkg = "org/apache/commons/lang";
    ClassLoader cl = ClassLoader.getSystemClassLoader();
    URL[] urls = ((URLClassLoader) cl).getURLs();
    for (URL url : urls) {
        System.out.println(url.getFile());
        File jar = new File(url.getFile());
        // ....
    }   

If entry is directory, just look up in the right subdirectory:

if (jar.isDirectory()) {
    File subdir = new File(jar, pkg);
    if (!subdir.exists())
        continue;
    File[] files = subdir.listFiles();
    for (File file : files) {
        if (!file.isFile())
            continue;
        if (file.getName().endsWith(".class"))
            System.out.println("Found class: "
                    + file.getName().substring(0,
                            file.getName().length() - 6));
    }
}   

If the entry is the file, and it's jar, inspect the ZIP entries of it:

else {
    // try to open as ZIP
    try {
        ZipFile zip = new ZipFile(jar);
        for (Enumeration<? extends ZipEntry> entries = zip
                .entries(); entries.hasMoreElements();) {
            ZipEntry entry = entries.nextElement();
            String name = entry.getName();
            if (!name.startsWith(pkg))
                continue;
            name = name.substring(pkg.length() + 1);
            if (name.indexOf('/') < 0 && name.endsWith(".class"))
                System.out.println("Found class: "
                        + name.substring(0, name.length() - 6));
        }
    } catch (ZipException e) {
        System.out.println("Not a ZIP: " + e.getMessage());
    } catch (IOException e) {
        System.err.println(e.getMessage());
    }
}

Now once you have all class names withing package, you can try loading them with reflection and analyze if they are classes or interfaces, etc.

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Extract a subset of a dataframe based on a condition involving a field

Just to extend the answer above you can also index your columns rather than specifying the column names which can also be useful depending on what you're doing. Given that your location is the first field it would look like this:

    bar <- foo[foo[ ,1] == "there", ]

This is useful because you can perform operations on your column value, like looping over specific columns (and you can do the same by indexing row numbers too).

This is also useful if you need to perform some operation on more than one column because you can then specify a range of columns:

    foo[foo[ ,c(1:N)], ]

Or specific columns, as you would expect.

    foo[foo[ ,c(1,5,9)], ]

Setting DEBUG = False causes 500 Error

This is old and my problem ended up being related to the problem but not for the OP but my solution is for anyone else who tried the above to no avail.

I had a setting in a modified version of Django to minify CSS and JS files that only ran when DEBUG was off. My server did not have the CSS minifier installed and threw the error. If you are using Django-Mako-Plus, this might be your issue.

Get Bitmap attached to ImageView

Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

How do I properly escape quotes inside HTML attributes?

Another option is replacing double quotes with single quotes if you don't mind whatever it is. But I don't mention this one:

<option value='"asd'>test</option>

I mention this one:

<option value="'asd">test</option>

In my case I used this solution.

How can I clear the input text after clicking

$("input:text").focus(function(){$(this).val("")});

How to add local jar files to a Maven project?

The really quick and dirty way is to point to a local file:

<dependency>
      <groupId>sample</groupId>  
       <artifactId>com.sample</artifactId>  
       <version>1.0</version> 
      <scope>system</scope>
      <systemPath>C:\DEV\myfunnylib\yourJar.jar</systemPath>
</dependency>

However this will only live on your machine (obviously), for sharing it usually makes sense to use a proper m2 archive (nexus/artifactory) or if you do not have any of these or don't want to set one up a local maven structured archive and configure a "repository" in your pom: local:

<repositories>
    <repository>
        <id>my-local-repo</id>
        <url>file://C:/DEV//mymvnrepo</url>
    </repository>
</repositories>

remote:

<repositories>
    <repository>
        <id>my-remote-repo</id>
        <url>http://192.168.0.1/whatever/mavenserver/youwant/repo</url>
    </repository>
</repositories>

for this a relative path is also possible using the basedir variable:

<url>file:${basedir}</url>

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

This is the most concise syntax I could find for a regex expression to be used for this check:

const regex = /^[\w-]+$/;

Is there a list of Pytz Timezones?

Don't create your own list - pytz has a built-in set:

import pytz
set(pytz.all_timezones_set)  
>>> {'Europe/Vienna', 'America/New_York', 'America/Argentina/Salta',..}

You can then apply a timezone:

import datetime
tz = pytz.timezone('Pacific/Johnston')
ct = datetime.datetime.now(tz=tz)
>>> ct.isoformat()
2017-01-13T11:29:22.601991-05:00

Or if you already have a datetime object that is TZ aware (not naive):

# This timestamp is in UTC
my_ct = datetime.datetime.now(tz=pytz.UTC)

# Now convert it to another timezone
new_ct = my_ct.astimezone(tz)
>>> new_ct.isoformat()
2017-01-13T11:29:22.601991-05:00

How to dynamically create CSS class in JavaScript and apply?

Found a better solution, which works across all browsers.
Uses document.styleSheet to add or replace rules. Accepted answer is short and handy but this works across IE8 and less too.

function createCSSSelector (selector, style) {
  if (!document.styleSheets) return;
  if (document.getElementsByTagName('head').length == 0) return;

  var styleSheet,mediaType;

  if (document.styleSheets.length > 0) {
    for (var i = 0, l = document.styleSheets.length; i < l; i++) {
      if (document.styleSheets[i].disabled) 
        continue;
      var media = document.styleSheets[i].media;
      mediaType = typeof media;

      if (mediaType === 'string') {
        if (media === '' || (media.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }
      else if (mediaType=='object') {
        if (media.mediaText === '' || (media.mediaText.indexOf('screen') !== -1)) {
          styleSheet = document.styleSheets[i];
        }
      }

      if (typeof styleSheet !== 'undefined') 
        break;
    }
  }

  if (typeof styleSheet === 'undefined') {
    var styleSheetElement = document.createElement('style');
    styleSheetElement.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(styleSheetElement);

    for (i = 0; i < document.styleSheets.length; i++) {
      if (document.styleSheets[i].disabled) {
        continue;
      }
      styleSheet = document.styleSheets[i];
    }

    mediaType = typeof styleSheet.media;
  }

  if (mediaType === 'string') {
    for (var i = 0, l = styleSheet.rules.length; i < l; i++) {
      if(styleSheet.rules[i].selectorText && styleSheet.rules[i].selectorText.toLowerCase()==selector.toLowerCase()) {
        styleSheet.rules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.addRule(selector,style);
  }
  else if (mediaType === 'object') {
    var styleSheetLength = (styleSheet.cssRules) ? styleSheet.cssRules.length : 0;
    for (var i = 0; i < styleSheetLength; i++) {
      if (styleSheet.cssRules[i].selectorText && styleSheet.cssRules[i].selectorText.toLowerCase() == selector.toLowerCase()) {
        styleSheet.cssRules[i].style.cssText = style;
        return;
      }
    }
    styleSheet.insertRule(selector + '{' + style + '}', styleSheetLength);
  }
}

Function is used as follows.

createCSSSelector('.mycssclass', 'display:none');

Gradle: Could not determine java version from '11.0.2'

Updating gradle/wrapper/gradle-wrapper.properties with the following version fixed it for me:

distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

JavaScript: get code to run every minute

Using setInterval:

setInterval(function() {
    // your code goes here...
}, 60 * 1000); // 60 * 1000 milsec

The function returns an id you can clear your interval with clearInterval:

var timerID = setInterval(function() {
    // your code goes here...
}, 60 * 1000); 

clearInterval(timerID); // The setInterval it cleared and doesn't run anymore.

A "sister" function is setTimeout/clearTimeout look them up.


If you want to run a function on page init and then 60 seconds after, 120 sec after, ...:

function fn60sec() {
    // runs every 60 sec and runs on init.
}
fn60sec();
setInterval(fn60sec, 60*1000);

Can you require two form fields to match with HTML5?

As has been mentioned in other answers, there is no pure HTML5 way to do this.

If you are already using JQuery, then this should do what you need:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#ourForm').submit(function(e){_x000D_
      var form = this;_x000D_
      e.preventDefault();_x000D_
      // Check Passwords are the same_x000D_
      if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
          // Submit Form_x000D_
          alert('Passwords Match, submitting form');_x000D_
          form.submit();_x000D_
      } else {_x000D_
          // Complain bitterly_x000D_
          alert('Password Mismatch');_x000D_
          return false;_x000D_
      }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
    <input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
    <input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
    <input type="submit" value="Go">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to align two elements on the same line without changing HTML

In cases where I use floated elements like that, I usually need to be sure that the container element will always be big enough for the widths of both floated elements plus the desired margin to all fit inside of it. The easiest way to do that is obviously to give both inner elements fixed widths that will fit correctly inside of the outer element like this:

#container {width: 960px;}
#element1  {float:left; width:745px; margin-right:15px;}
#element2  {float:right; width:200px;}

If you can't do that because this is a scaling width layout, another option is to have every set of dimensions be percentages like:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:20%;}

This gets tricky where you need something like this:

#element1 {float:left; width:70%; margin-right:10%}
#element2 {float:right; width:200px;}

In cases like that, I find that sometimes the best option is to not use floats, and use relative/absolute positioning to get the same effect like this:

#container {position:relative;} /* So IE won't bork the absolute positioning of #element2 */
#element1 {margin-right:215px;}
#element2 {display: block; position:absolute; top:0; right:0; height:100%; width:200px;}

While this isn't a floated solution, it does result in side by side columns where they are the same height, and one can remain fluid with while the other has a static width.

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

It might be.. you have to identify it is tablet or phone by programmatically... First check device is phone or tablet

Determine if the device is a smartphone or tablet?

Tablet or Phone - Android

Then......

if(isTablet)
{
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);      
}else
{
      setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

Get fragment (value after hash '#') from a URL in php

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.

If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.

Custom CSS for <audio> tag?

There are CSS options for the audio tag.

Like: html 5 audio tag width

But if you play around with it you'll see results can be unexpected - as of August 2012.

Convert a secure string to plain text

In PS 7, you can use ConvertFrom-SecureString and -AsPlainText:

 $UnsecurePassword = ConvertFrom-SecureString -SecureString $SecurePassword -AsPlainText

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/ConvertFrom-SecureString?view=powershell-7#parameters

ConvertFrom-SecureString
           [-SecureString] <SecureString>
           [-AsPlainText]
           [<CommonParameters>]

'Best' practice for restful POST response

Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.

There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API

It includes an answer to your question here: Updates & creation should return a resource representation

It says:

To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.

Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.

Maximum length for MySQL type text

Acording to http://dev.mysql.com/doc/refman/5.0/en/storage-requirements.html, the limit is L + 2 bytes, where L < 2^16, or 64k.

You shouldn't need to concern yourself with limiting it, it's automatically broken down into chunks that get added as the string grows, so it won't always blindly use 64k.

How to tell if a file is git tracked (by shell exit code)?

using git log will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.

For example if the file is git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

If the file is not git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

How do I share a global variable between c files?

Use the extern keyword to declare the variable in the other .c file. E.g.:

extern int counter;

means that the actual storage is located in another file. It can be used for both variables and function prototypes.

Which characters need to be escaped when using Bash?

There are two easy and safe rules which work not only in sh but also bash.

1. Put the whole string in single quotes

This works for all chars except single quote itself. To escape the single quote, close the quoting before it, insert the single quote, and re-open the quoting.

'I'\''m a s@fe $tring which ends in newline
'

sed command: sed -e "s/'/'\\\\''/g; 1s/^/'/; \$s/\$/'/"

2. Escape every char with a backslash

This works for all characters except newline. For newline characters use single or double quotes. Empty strings must still be handled - replace with ""

\I\'\m\ \a\ \s\@\f\e\ \$\t\r\i\n\g\ \w\h\i\c\h\ \e\n\d\s\ \i\n\ \n\e\w\l\i\n\e"
"

sed command: sed -e 's/./\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.

2b. More readable version of 2

There's an easy safe set of characters, like [a-zA-Z0-9,._+:@%/-], which can be left unescaped to keep it more readable

I\'m\ a\ s@fe\ \$tring\ which\ ends\ in\ newline"
"

sed command: LC_ALL=C sed -e 's/[^a-zA-Z0-9,._+@%/-]/\\&/g; 1{$s/^$/""/}; 1!s/^/"/; $!s/$/"/'.


Note that in a sed program, one can't know whether the last line of input ends with a newline byte (except when it's empty). That's why both above sed commands assume it does not. You can add a quoted newline manually.

Note that shell variables are only defined for text in the POSIX sense. Processing binary data is not defined. For the implementations that matter, binary works with the exception of NUL bytes (because variables are implemented with C strings, and meant to be used as C strings, namely program arguments), but you should switch to a "binary" locale such as latin1.


(You can easily validate the rules by reading the POSIX spec for sh. For bash, check the reference manual linked by @AustinPhillips)

Git: How to pull a single file from a server repository in Git?

It is possible to do (in the deployed repository):

git fetch
// git fetch will download all the recent changes, but it will not put it in your current checked out code (working area).

Followed by:

git checkout origin/master -- path/to/file
// git checkout <local repo name (default is origin)>/<branch name> -- path/to/file will checkout the particular file from the downloaded changes (origin/master).

bash echo number of lines of file given in a bash variable without the file name

An Example Using Your Own Data

You can avoid having your filename embedded in the NUMOFLINES variable by using redirection from JAVA_TAGS_FILE, rather than passing the filename as an argument to wc. For example:

NUMOFLINES=$(wc -l < "$JAVA_TAGS_FILE")

Explanation: Use Pipes or Redirection to Avoid Filenames in Output

The wc utility will not print the name of the file in its output if input is taken from a pipe or redirection operator. Consider these various examples:

# wc shows filename when the file is an argument
$ wc -l /etc/passwd
41 /etc/passwd

# filename is ignored when piped in on standard input
$ cat /etc/passwd | wc -l
41

# unusual redirection, but wc still ignores the filename
$ < /etc/passwd wc -l
41

# typical redirection, taking standard input from a file
$ wc -l < /etc/passwd
41

As you can see, the only time wc will print the filename is when its passed as an argument, rather than as data on standard input. In some cases, you may want the filename to be printed, so it's useful to understand when it will be displayed.

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to terminate script execution when debugging in Google Chrome?

2020 April update

As of Chrome 80, none of the current answers work. There is no visible "Pause" button - you need to long-click the "Play" button to access the Stop icon:

Stop script execution in Chrome DevTools

Check if a string contains a substring in SQL Server 2005, using a stored procedure

You can just use wildcards in the predicate (after IF, WHERE or ON):

@mainstring LIKE '%' + @substring + '%'

or in this specific case

' ' + @mainstring + ' ' LIKE '% ME[., ]%'

(Put the spaces in the quoted string if you're looking for the whole word, or leave them out if ME can be part of a bigger word).

Using str_replace so that it only acts on the first match?

To expand on @renocor's answer, I've written a function that is 100% backward-compatible with str_replace(). That is, you can replace all occurrences of str_replace() with str_replace_limit() without messing anything up, even those using arrays for the $search, $replace, and/or $subject.

The function could be completely self-contained, if you wanted to replace the function call with ($string===strval(intval(strval($string)))), but I'd recommend against it since valid_integer() is a rather useful function when dealing with integers provided as strings.

Note: Whenever possible, str_replace_limit() will use str_replace() instead, so all calls to str_replace() can be replaced with str_replace_limit() without worrying about a hit to performance.

Usage

<?php
$search = 'a';
$replace = 'b';
$subject = 'abcabc';
$limit = -1; // No limit
$new_string = str_replace_limit($search, $replace, $subject, $count, $limit);
echo $count.' replacements -- '.$new_string;

2 replacements -- bbcbbc

$limit = 1; // Limit of 1
$new_string = str_replace_limit($search, $replace, $subject, $count, $limit);
echo $count.' replacements -- '.$new_string;

1 replacements -- bbcabc

$limit = 10; // Limit of 10
$new_string = str_replace_limit($search, $replace, $subject, $count, $limit);
echo $count.' replacements -- '.$new_string;

2 replacements -- bbcbbc

Function

<?php

/**
 * Checks if $string is a valid integer. Integers provided as strings (e.g. '2' vs 2)
 * are also supported.
 * @param mixed $string
 * @return bool Returns boolean TRUE if string is a valid integer, or FALSE if it is not 
 */
function valid_integer($string){
    // 1. Cast as string (in case integer is provided)
    // 1. Convert the string to an integer and back to a string
    // 2. Check if identical (note: 'identical', NOT just 'equal')
    // Note: TRUE, FALSE, and NULL $string values all return FALSE
    $string = strval($string);
    return ($string===strval(intval($string)));
}

/**
 * Replace $limit occurences of the search string with the replacement string
 * @param mixed $search The value being searched for, otherwise known as the needle. An
 * array may be used to designate multiple needles.
 * @param mixed $replace The replacement value that replaces found search values. An
 * array may be used to designate multiple replacements.
 * @param mixed $subject The string or array being searched and replaced on, otherwise
 * known as the haystack. If subject is an array, then the search and replace is
 * performed with every entry of subject, and the return value is an array as well. 
 * @param string $count If passed, this will be set to the number of replacements
 * performed.
 * @param int $limit The maximum possible replacements for each pattern in each subject
 * string. Defaults to -1 (no limit).
 * @return string This function returns a string with the replaced values.
 */
function str_replace_limit(
        $search,
        $replace,
        $subject,
        &$count,
        $limit = -1
    ){

    // Set some defaults
    $count = 0;

    // Invalid $limit provided. Throw a warning.
    if(!valid_integer($limit)){
        $backtrace = debug_backtrace();
        trigger_error('Invalid $limit `'.$limit.'` provided to '.__function__.'() in '.
                '`'.$backtrace[0]['file'].'` on line '.$backtrace[0]['line'].'. Expecting an '.
                'integer', E_USER_WARNING);
        return $subject;
    }

    // Invalid $limit provided. Throw a warning.
    if($limit<-1){
        $backtrace = debug_backtrace();
        trigger_error('Invalid $limit `'.$limit.'` provided to '.__function__.'() in '.
                '`'.$backtrace[0]['file'].'` on line '.$backtrace[0]['line'].'. Expecting -1 or '.
                'a positive integer', E_USER_WARNING);
        return $subject;
    }

    // No replacements necessary. Throw a notice as this was most likely not the intended
    // use. And, if it was (e.g. part of a loop, setting $limit dynamically), it can be
    // worked around by simply checking to see if $limit===0, and if it does, skip the
    // function call (and set $count to 0, if applicable).
    if($limit===0){
        $backtrace = debug_backtrace();
        trigger_error('Invalid $limit `'.$limit.'` provided to '.__function__.'() in '.
                '`'.$backtrace[0]['file'].'` on line '.$backtrace[0]['line'].'. Expecting -1 or '.
                'a positive integer', E_USER_NOTICE);
        return $subject;
    }

    // Use str_replace() whenever possible (for performance reasons)
    if($limit===-1){
        return str_replace($search, $replace, $subject, $count);
    }

    if(is_array($subject)){

        // Loop through $subject values and call this function for each one.
        foreach($subject as $key => $this_subject){

            // Skip values that are arrays (to match str_replace()).
            if(!is_array($this_subject)){

                // Call this function again for
                $this_function = __FUNCTION__;
                $subject[$key] = $this_function(
                        $search,
                        $replace,
                        $this_subject,
                        $this_count,
                        $limit
                );

                // Adjust $count
                $count += $this_count;

                // Adjust $limit, if not -1
                if($limit!=-1){
                    $limit -= $this_count;
                }

                // Reached $limit, return $subject
                if($limit===0){
                    return $subject;
                }

            }

        }

        return $subject;

    } elseif(is_array($search)){
        // Only treat $replace as an array if $search is also an array (to match str_replace())

        // Clear keys of $search (to match str_replace()).
        $search = array_values($search);

        // Clear keys of $replace, if applicable (to match str_replace()).
        if(is_array($replace)){
            $replace = array_values($replace);
        }

        // Loop through $search array.
        foreach($search as $key => $this_search){

            // Don't support multi-dimensional arrays (to match str_replace()).
            $this_search = strval($this_search);

            // If $replace is an array, use the value of $replace[$key] as the replacement. If
            // $replace[$key] doesn't exist, just an empty string (to match str_replace()).
            if(is_array($replace)){
                if(array_key_exists($key, $replace)){
                    $this_replace = strval($replace[$key]);
                } else {
                    $this_replace = '';
                }
            } else {
                $this_replace = strval($replace);
            }

            // Call this function again for
            $this_function = __FUNCTION__;
            $subject = $this_function(
                    $this_search,
                    $this_replace,
                    $subject,
                    $this_count,
                    $limit
            );

            // Adjust $count
            $count += $this_count;

            // Adjust $limit, if not -1
            if($limit!=-1){
                $limit -= $this_count;
            }

            // Reached $limit, return $subject
            if($limit===0){
                return $subject;
            }

        }

        return $subject;

    } else {
        $search = strval($search);
        $replace = strval($replace);

        // Get position of first $search
        $pos = strpos($subject, $search);

        // Return $subject if $search cannot be found
        if($pos===false){
            return $subject;
        }

        // Get length of $search, to make proper replacement later on
        $search_len = strlen($search);

        // Loop until $search can no longer be found, or $limit is reached
        for($i=0;(($i<$limit)||($limit===-1));$i++){

            // Replace 
            $subject = substr_replace($subject, $replace, $pos, $search_len);

            // Increase $count
            $count++;

            // Get location of next $search
            $pos = strpos($subject, $search);

            // Break out of loop if $needle
            if($pos===false){
                break;
            }

        }

        // Return new $subject
        return $subject;

    }

}

Getting the difference between two Dates (months/days/hours/minutes/seconds) in Swift

Swift 5.1 • iOS 13

You can use RelativeDateFormatter that has been introduced by Apple in iOS 13.

let exampleDate = Date().addingTimeInterval(-15000)

let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .full
let relativeDate = formatter.localizedString(for: exampleDate, relativeTo: Date())

print(relativeDate) // 4 hours ago

See How to show a relative date and time using RelativeDateTimeFormatter.

Assign variable in if condition statement, good practice or not?

You can do this in Java too. And no, it's not a good practice. :)

(And use the === in Javascript for typed equality. Read Crockford's The Good Parts book on JS.)

invalid use of non-static data member

You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.

And what is p->param?

Actually, it isn't clear what do you want to do

How to use std::sort to sort an array in C++

you can use,

 std::sort(v.begin(),v.end());

Do I need to close() both FileReader and BufferedReader?

I'm late, but:

BufferReader.java:

public BufferedReader(Reader in) {
  this(in, defaultCharBufferSize);
}

(...)

public void close() throws IOException {
    synchronized (lock) {
        if (in == null)
            return;
        try {
            in.close();
        } finally {
            in = null;
            cb = null;
        }
    }
}

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

AES vs Blowfish for file encryption

I know this answer violates the terms of your question, but I think the correct answer to your intent is simply this: use whichever algorithm allows you the longest key length, then make sure you choose a really good key. Minor differences in the performance of most well regarded algorithms (cryptographically and chronologically) are overwhelmed by a few extra bits of a key.

How to read HDF5 files in Python

What you need to do is create a dataset. If you take a look at the quickstart guide, it shows you that you need to use the file object in order to create a dataset. So, f.create_dataset and then you can read the data. This is explained in the docs.

PowerShell script to return versions of .NET Framework on a machine?

Refer to the page Script for finding which .NET versions are installed on remote workstations.

The script there might be useful to find the .NET version for multiple machines on a network.

Sending HTTP POST with System.Net.WebClient

Based on @carlosfigueira 's answer, I looked further into WebClient's methods and found UploadValues, which is exactly what I want:

Using client As New Net.WebClient
    Dim reqparm As New Specialized.NameValueCollection
    reqparm.Add("param1", "somevalue")
    reqparm.Add("param2", "othervalue")
    Dim responsebytes = client.UploadValues(someurl, "POST", reqparm)
    Dim responsebody = (New Text.UTF8Encoding).GetString(responsebytes)
End Using

The key part is this:

client.UploadValues(someurl, "POST", reqparm)

It sends whatever verb I type in, and it also helps me create a properly url encoded form data, I just have to supply the parameters as a namevaluecollection.

Vue.js get selected option on @change

@ is a shortcut option for v-on. Use @ only when you want to execute some Vue methods. As you are not executing Vue methods, instead you are calling javascript function, you need to use onchange attribute to call javascript function

<select name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

function onChange(value) {
  console.log(value);
}

If you want to call Vue methods, do it like this-

<select name="LeaveType" @change="onChange($event)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
  ...
  ...
  methods:{
    onChange:function(event){
       console.log(event.target.value);
    }
  }
})

You can use v-model data attribute on the select element to bind the value.

<select v-model="selectedValue" name="LeaveType" onchange="onChange(this.value)" class="form-control">
 <option value="1">Annual Leave/ Off-Day</option>
 <option value="2">On Demand Leave</option>
</select>

new Vue({
    data:{
        selectedValue : 1, // First option will be selected by default
    },
    ...
    ...
    methods:{
        onChange:function(event){
            console.log(this.selectedValue);
        }
    }
})

Hope this Helps :-)

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

Java: Replace all ' in a string with \'

You could also try using something like StringEscapeUtils to make your life even easier: http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html

s = StringEscapeUtils.escapeJava(s);

Python string prints as [u'String']

pass the output to str() function and it will remove the convert the unicode output. also by printing the output it will remove the u'' tags from it.

How can I declare a Boolean parameter in SQL statement?

SQL Server recognizes 'TRUE' and 'FALSE' as bit values. So, use a bit data type!

declare @var bit
set @var = 'true'
print @var

That returns 1.

What does `ValueError: cannot reindex from a duplicate axis` mean?

As others have said, you've probably got duplicate values in your original index. To find them do this:

df[df.index.duplicated()]

What's the difference between "super()" and "super(props)" in React when using es6 classes?

Here is the fiddle I've made:jsfiddle.net. It shows that props are assigned not in the constructor by default. As I understand they are assinged in the method React.createElement. Hence super(props) should be called only when the superclass's constructor manually assings props to this.props. If you just extend the React.Component calling super(props) will do nothing with props. Maybe It will be changed in the next versions of React.

How to set width of mat-table column in angular?

As i have implemented, and it is working fine. you just need to add column width using matColumnDef="description"

for example :

<mat-table #table [dataSource]="dataSource" matSortDisableClear>
    <ng-container matColumnDef="productId">
        <mat-header-cell *matHeaderCellDef>product ID</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.id}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="productName">
        <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
        <mat-cell *matCellDef="let product">{{product.name}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="actions">
        <mat-header-cell *matHeaderCellDef>Actions</mat-header-cell>
        <mat-cell *matCellDef="let product">
            <button (click)="view(product)">
                <mat-icon>visibility</mat-icon>
            </button>
        </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

here matColumnDef is productId, productName and action

now we apply width by matColumnDef

styling

.mat-column-productId {
    flex: 0 0 10%;
}
.mat-column-productName {
    flex: 0 0 50%;
}

and remaining width is equally allocated to other columns

The module was expected to contain an assembly manifest

First try to open the file with a decompiler such as ILSpy, your dll might be corrupt. I had this error on an online web site, when I downloaded the dll and tried to open it, it was corrupt, probably some error occurred while uploading it via ftp.

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

How to position two divs horizontally within another div

This should do what you are looking for:

<html>
    <head>
        <style type="text/css">
            #header {
                text-align: center;
            }
            #wrapper {
                margin:0 auto;
                width:600px;
            }
            #submain {
                margin:0 auto;
                width:600px;
            }
            #sub-left {
                float:left;
                width:300px;
            }
            #sub-right {
                float:right;
                width:240px;
                text-align: right;
            }
        </style>

    </head>
    <body>
        <div id="wrapper">
            <div id="header"><h1>Head</h1></div>
            <div id="sub-main">
                <div id="sub-left">
                    Right
                </div>
                <div id="sub-right">
                    Left
                </div>
            </div>
        </div>
    </body>
</html>

And you can control the entire document with the wrapper class, or just the two columns with the sub-main class.

sort files by date in PHP

You need to put the files into an array in order to sort and find the last modified file.

$files = array();
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
           $files[filemtime($file)] = $file;
        }
    }
    closedir($handle);

    // sort
    ksort($files);
    // find the last modification
    $reallyLastModified = end($files);

    foreach($files as $file) {
        $lastModified = date('F d Y, H:i:s',filemtime($file));
        if(strlen($file)-strpos($file,".swf")== 4){
           if ($file == $reallyLastModified) {
             // do stuff for the real last modified file
           }
           echo "<tr><td><input type=\"checkbox\" name=\"box[]\"></td><td><a href=\"$file\" target=\"_blank\">$file</a></td><td>$lastModified</td></tr>";
        }
    }
}

Not tested, but that's how to do it.

Tools for making latex tables in R

Another R package for aggregating multiple regression models into LaTeX tables is texreg.

Session only cookies with Javascript

A simpler solution would be to use sessionStorage, in this case:

var myVariable = "Hello World";

sessionStorage['myvariable'] = myVariable;

var readValue = sessionStorage['myvariable'];
console.log(readValue);

However, keep in mind that sessionStorage saves everything as a string, so when working with arrays / objects, you can use JSON to store them:

var myVariable = {a:[1,2,3,4], b:"some text"};

sessionStorage['myvariable'] = JSON.stringify(myVariable);
var readValue = JSON.parse(sessionStorage['myvariable']);

A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.

So, when you close the page / tab, the data is lost.

LaTeX table positioning

If you want to have two tables next to each other you can use: (with float package loaded)

\begin{table}[H]
 \begin{minipage}{.5\textwidth}
  %first table
 \end{minipage}
 \begin{minipage}{.5\textwidth}
  %second table
 \end{minipage}
\end{table}

Each one will have own caption and number. Another option is subfigure package.

PHP Undefined Index

The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.

When you submit the form it will then exist, and it won't complain about it.

#so change
$_GET['query_age'];
#to:
(!empty($_GET['query_age']) ? $_GET['query_age'] : null);

How do you add a Dictionary of items into another Dictionary

You can use the bridgeToObjectiveC() function to make the dictionary a NSDictionary.

Will be like the following:

var dict1 = ["a":"Foo"]
var dict2 = ["b":"Boo"]

var combinedDict = dict1.bridgeToObjectiveC()
var mutiDict1 : NSMutableDictionary! = combinedDict.mutableCopy() as NSMutableDictionary

var combineDict2 = dict2.bridgeToObjectiveC()

var combine = mutiDict1.addEntriesFromDictionary(combineDict2)

Then you can convert the NSDictionary(combine) back or do whatever.

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

How to set top-left alignment for UILabel for iOS application?

Solution with SoLabel works , Thanks.

Bellow I have added monotouch version:

    public class UICustomLabel : UILabel
{
    private UITextVerticalAlignment _textVerticalAlignment;

    public UICustomLabel()
    {
        TextVerticalAlignment = UITextVerticalAlignment.Top;
    }

    public UITextVerticalAlignment TextVerticalAlignment
    {
        get
        {
            return _textVerticalAlignment;
        }
        set
        {
            _textVerticalAlignment = value;
            SetNeedsDisplay();
        }
    }

    public override void DrawText(RectangleF rect)
    {
        var bound = TextRectForBounds(rect, Lines);
        base.DrawText(bound);
    }

    public override RectangleF TextRectForBounds(RectangleF bounds, int numberOfLines)
    {
        var rect = base.TextRectForBounds(bounds, numberOfLines);
        RectangleF resultRect;
        switch (TextVerticalAlignment)
        {
            case UITextVerticalAlignment.Top:
                resultRect = new RectangleF(bounds.X, bounds.Y, rect.Size.Width, rect.Size.Height);
                break;
            case UITextVerticalAlignment.Middle:
                resultRect = new RectangleF(bounds.X,
                                            bounds.Y + (bounds.Size.Height - rect.Size.Height)/2,
                                            rect.Size.Width, rect.Size.Height);
                break;
            case UITextVerticalAlignment.Bottom:
                resultRect = new RectangleF(bounds.X,
                                            bounds.Y + (bounds.Size.Height - rect.Size.Height),
                                            rect.Size.Width, rect.Size.Height);
                break;

            default:
                resultRect = bounds;
                break;
        }

        return resultRect;
    }
}

public enum UITextVerticalAlignment
{
    Top = 0, // default
    Middle,
    Bottom
}

Vertically align text to top within a UILabel

Swift 2.0:

Make constant enum values in a empty Swift file.

//  AppRef.swift

import UIKit
import Foundation

enum UILabelTextPositions : String {

 case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
 case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
 case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"

}

Using UILabel Extension:

Make a empty Swift class and name it. Add the following

//  AppExtensions.swift

import Foundation
import UIKit

extension UILabel{ 
 func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
 {
  let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)

  switch positionIdentifier
  {
  case "VerticalAlignmentTop":
   sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
   break;

  case "VerticalAlignmentMiddle":
   sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
    rect.size.width, rect.size.height);
   break;

  case "VerticalAlignmentBottom":
   sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
   break;

  default:
   sampleLabel!.frame = bounds;
   break;
  }
  return sampleLabel!

 }
}

Usage :

myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)

I just assigned a variable, but echo $variable shows something else

echo $var output highly depends on the value of IFS variable. By default it contains space, tab, and newline characters:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$

This means that when shell is doing field splitting (or word splitting) it uses all these characters as word separators. This is what happens when referencing a variable without double quotes to echo it ($var) and thus expected output is altered.

One way to prevent word splitting (besides using double quotes) is to set IFS to null. See http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_05 :

If the value of IFS is null, no field splitting shall be performed.

Setting to null means setting to empty value:

IFS=

Test:

[ks@localhost ~]$ echo -n "$IFS" | cat -vte
 ^I$
[ks@localhost ~]$ var=$'key\nvalue'
[ks@localhost ~]$ echo $var
key value
[ks@localhost ~]$ IFS=
[ks@localhost ~]$ echo $var
key
value
[ks@localhost ~]$ 

Can Mysql Split a column?

Here is another variant I posted on related question. The REGEX check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

How to create tar.gz archive file in Windows?

tar.gz file is just a tar file that's been gzipped. Both tar and gzip are available for windows.

If you like GUIs (Graphical user interface), 7zip can pack with both tar and gzip.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

I had a similar issue with PyVmomi Client. With Python Version 2.7.9, I have solved this issue with the following line of code:

default_sslContext = ssl._create_unverified_context()
self.client = \
                Client(<vcenterip>, username=<username>, password=<passwd>,
                       sslContext=default_sslContext )

Note that, for this to work, you need Python 2.7.9 atleast.

Make Div overlay ENTIRE page (not just viewport)?

I had quite a bit of trouble as I didn't want to FIX the overlay in place as I wanted the info inside the overlay to be scrollable over the text. I used:

<html style="height=100%">
   <body style="position:relative">
      <div id="my-awesome-overlay" 
           style="position:absolute; 
                  height:100%; 
                  width:100%; 
                  display: block">
           [epic content here]
      </div>
   </body>
</html>

Of course the div in the middle needs some content and probably a transparent grey background but I'm sure you get the gist!

How to echo (or print) to the js console with php

You can also try this way:

<?php
   echo "<script>console.log('$variableName')</script>";
?>

HTTP Error 500.30 - ANCM In-Process Start Failure

HTTP Error 500.30 – ANCM In-Process Start Failure” is moreover a generic error. To know more information about the error

Go to Azure Portal > your App Service > under development tools open console. We can run the application through this console and thus visualize the real error that is causing our application not to load.

For that put, the name of our project followed by “.exe” and press the enter key.

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.

What does iterator->second mean?

I'm sure you know that a std::vector<X> stores a whole bunch of X objects, right? But if you have a std::map<X, Y>, what it actually stores is a whole bunch of std::pair<const X, Y>s. That's exactly what a map is - it pairs together the keys and the associated values.

When you iterate over a std::map, you're iterating over all of these std::pairs. When you dereference one of these iterators, you get a std::pair containing the key and its associated value.

std::map<std::string, int> m = /* fill it */;
auto it = m.begin();

Here, if you now do *it, you will get the the std::pair for the first element in the map.

Now the type std::pair gives you access to its elements through two members: first and second. So if you have a std::pair<X, Y> called p, p.first is an X object and p.second is a Y object.

So now you know that dereferencing a std::map iterator gives you a std::pair, you can then access its elements with first and second. For example, (*it).first will give you the key and (*it).second will give you the value. These are equivalent to it->first and it->second.

Creating a segue programmatically

For controllers that are in the storyboard.

jhilgert00 is this what you were looking for?

-(IBAction)nav_goHome:(id)sender {
UIViewController *myController = [self.storyboard instantiateViewControllerWithIdentifier:@"HomeController"];
[self.navigationController pushViewController: myController animated:YES];

}

OR...

[self performSegueWithIdentifier:@"loginMainSegue" sender:self];

SQL Update to the SUM of its joined values

An alternate to the above solutions is using Aliases for Tables:

UPDATE T1 SET T1.extrasPrice = (SELECT SUM(T2.Price) FROM BookingPitchExtras T2 WHERE T2.pitchID = T1.ID)
FROM BookingPitches T1;

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How to change position of Toast in Android?

The method to change the color, position and background color of toast is:

Toast toast=Toast.makeText(getApplicationContext(),"This is advanced toast",Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT,0,0);
View view=toast.getView();
TextView  view1=(TextView)view.findViewById(android.R.id.message);
view1.setTextColor(Color.YELLOW);
view.setBackgroundResource(R.color.colorPrimary);
toast.show();

For line by line explanation: https://www.youtube.com/watch?v=5bzhGd1HZOc

Understanding typedefs for function pointers in C

A very easy way to understand typedef of function pointer:

int add(int a, int b)
{
    return (a+b);
}

typedef int (*add_integer)(int, int); //declaration of function pointer

int main()
{
    add_integer addition = add; //typedef assigns a new variable i.e. "addition" to original function "add"
    int c = addition(11, 11);   //calling function via new variable
    printf("%d",c);
    return 0;
}

how to convert an RGB image to numpy array?

PIL (Python Imaging Library) and Numpy work well together.

I use the following functions.

from PIL import Image
import numpy as np

def load_image( infilename ) :
    img = Image.open( infilename )
    img.load()
    data = np.asarray( img, dtype="int32" )
    return data

def save_image( npdata, outfilename ) :
    img = Image.fromarray( np.asarray( np.clip(npdata,0,255), dtype="uint8"), "L" )
    img.save( outfilename )

The 'Image.fromarray' is a little ugly because I clip incoming data to [0,255], convert to bytes, then create a grayscale image. I mostly work in gray.

An RGB image would be something like:

 outimg = Image.fromarray( ycc_uint8, "RGB" )
 outimg.save( "ycc.tif" )

How to round an average to 2 decimal places in PostgreSQL?

Try casting your column to a numeric like:

SELECT ROUND(cast(some_column as numeric),2) FROM table

Xcode 7 error: "Missing iOS Distribution signing identity for ..."

From Apple -

Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.

As noted in a comment below, the expired certificate also needs to be removed from the login section, as well:

To all that cannot get it working despite the instructions... There are two expired WWDR certs. One is in login keychain, and the other one is in the System. You have to delete both of them in order to make things working

Which characters are valid in CSS class names/selectors?

Read the W3C spec. (this is CSS 2.1, find the appropriate version for your assumption of browsers)

edit: relevant paragraph follows:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A1 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".

edit 2: as @mipadi points out in Triptych's answer, there's this caveat, also in the same webpage:

In CSS, identifiers may begin with '-' (dash) or '_' (underscore). Keywords and property names beginning with '-' or '_' are reserved for vendor-specific extensions. Such vendor-specific extensions should have one of the following formats:

'-' + vendor identifier + '-' + meaningful name 
'_' + vendor identifier + '-' + meaningful name

Example(s):

For example, if XYZ organization added a property to describe the color of the border on the East side of the display, they might call it -xyz-border-east-color.

Other known examples:

 -moz-box-sizing
 -moz-border-radius
 -wap-accesskey

An initial dash or underscore is guaranteed never to be used in a property or keyword by any current or future level of CSS. Thus typical CSS implementations may not recognize such properties and may ignore them according to the rules for handling parsing errors. However, because the initial dash or underscore is part of the grammar, CSS 2.1 implementers should always be able to use a CSS-conforming parser, whether or not they support any vendor-specific extensions.

Authors should avoid vendor-specific extensions

Reading an Excel file in python using pandas

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)

How to Disable GUI Button in Java

really that not possible to disable JComponent(s) if output to the GUI is invoked from Listener, in all of cases, all events are inside EDT including setEnabled/setVisible,

JComponent(s) is/are disabled/visible if all Events in EDT ends,

there are there ways

1/ safiest way would be look for GlassPane, which prevents after all MouseEvents (not KeyEvents) best code around is by camickr's

2/ use multithreading with SwingWorker for separate and delay concrete event(s), Action from JComponent -> disable JComponent(s) in GUI -> then required Action, but there (if is possible to adds) you have to identify all actions by using myAction#putProperty("String","String")

3/ put Enabled/Visible to the invokeLater() and all Action from Listener must be wrapped into invokeAndWait()

4/ inside Runnable()#Thread

CSS for the "down arrow" on a <select> element?

There's a cool CSS-only solution to styling dropdowns here: http://bavotasan.com/2011/style-select-box-using-only-css/

Basically, wrap the select in a container div, style the select to be 18px wider than the container with a transparent background, give overflow:hidden to the container (to chop off the browser-generated arrow), and add your background image with stylized arrow to the container.

Doesn't work in IE7 (or 6), but seriously, I say if you're using IE7 you deserve a less-pretty dropdown experience.

How to make FileFilter in java?

File f = null;
File[] paths;

try {

    f = new File(dir);

    // filefilter
    FilenameFilter fileNameFilter = new FilenameFilter() {

        public boolean accept(File dir, String name) {

            if (name.lastIndexOf('.') > 0) {

                int lastIndex = name.lastIndexOf('.');
                String str = name.substring(lastIndex);

                if (str.equals("." + selectlogtype)) {
                    return true;
                }
            }
            return false;
        }
    };

    paths = f.listFiles(fileNameFilter);

    for (int i = 0; i < paths.length; i++) {
        try {

            FileWriter fileWriter = new FileWriter("C:/Users/maya02/workspace/ftp_log/filefilterlogtxt");
            PrintWriter bWriter = new PrintWriter(fileWriter);

            for (File writerpath1 : paths) {
                bWriter.println(writerpath1);
            }

            bWriter.close();
        } 
        catch (IOException e) { System.out.println("HATA!!"); }
    }
    System.out.println("path dosyaya aktarildi!.");
} 
catch (Exception e) { }

Getting datarow values into a string?

I've done this a lot myself. If you just need a comma separated list for all of row values you can do this:

StringBuilder sb = new StringBuilder();
foreach (DataRow row in results.Tables[0].Rows)     
{
    sb.AppendLine(string.Join(",", row.ItemArray));
}

A StringBuilder is the preferred method as string concatenation is significantly slower for large amounts of data.

Difference between INNER JOIN and LEFT SEMI JOIN

Suppose there are 2 tables TableA and TableB with only 2 columns (Id, Data) and following data:

TableA:

+----+---------+
| Id |  Data   |
+----+---------+
|  1 | DataA11 |
|  1 | DataA12 |
|  1 | DataA13 |
|  2 | DataA21 |
|  3 | DataA31 |
+----+---------+

TableB:

+----+---------+
| Id |  Data   |
+----+---------+
|  1 | DataB11 |
|  2 | DataB21 |
|  2 | DataB22 |
|  2 | DataB23 |
|  4 | DataB41 |
+----+---------+

Inner Join on column Id will return columns from both the tables and only the matching records:

.----.---------.----.---------.
| Id |  Data   | Id |  Data   |
:----+---------+----+---------:
|  1 | DataA11 |  1 | DataB11 |
:----+---------+----+---------:
|  1 | DataA12 |  1 | DataB11 |
:----+---------+----+---------:
|  1 | DataA13 |  1 | DataB11 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB21 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB22 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB23 |
'----'---------'----'---------'

Left Join (or Left Outer join) on column Id will return columns from both the tables and matching records with records from left table (Null values from right table):

.----.---------.----.---------.
| Id |  Data   | Id |  Data   |
:----+---------+----+---------:
|  1 | DataA11 |  1 | DataB11 |
:----+---------+----+---------:
|  1 | DataA12 |  1 | DataB11 |
:----+---------+----+---------:
|  1 | DataA13 |  1 | DataB11 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB21 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB22 |
:----+---------+----+---------:
|  2 | DataA21 |  2 | DataB23 |
:----+---------+----+---------:
|  3 | DataA31 |    |         |
'----'---------'----'---------'

Right Join (or Right Outer join) on column Id will return columns from both the tables and matching records with records from right table (Null values from left table):

+-----------------------------+
¦ Id ¦  Data   ¦ Id ¦  Data   ¦
+----+---------+----+---------¦
¦  1 ¦ DataA11 ¦  1 ¦ DataB11 ¦
¦  1 ¦ DataA12 ¦  1 ¦ DataB11 ¦
¦  1 ¦ DataA13 ¦  1 ¦ DataB11 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB21 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB22 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB23 ¦
¦    ¦         ¦  4 ¦ DataB41 ¦
+-----------------------------+

Full Outer Join on column Id will return columns from both the tables and matching records with records from left table (Null values from right table) and records from right table (Null values from left table):

+-----------------------------+
¦ Id ¦  Data   ¦ Id ¦  Data   ¦
¦----+---------+----+---------¦
¦  - ¦         ¦    ¦         ¦
¦  1 ¦ DataA11 ¦  1 ¦ DataB11 ¦
¦  1 ¦ DataA12 ¦  1 ¦ DataB11 ¦
¦  1 ¦ DataA13 ¦  1 ¦ DataB11 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB21 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB22 ¦
¦  2 ¦ DataA21 ¦  2 ¦ DataB23 ¦
¦  3 ¦ DataA31 ¦    ¦         ¦
¦    ¦         ¦  4 ¦ DataB41 ¦
+-----------------------------+

Left Semi Join on column Id will return columns only from left table and matching records only from left table:

+--------------+
¦ Id ¦  Data   ¦
+----+---------¦
¦  1 ¦ DataA11 ¦
¦  1 ¦ DataA12 ¦
¦  1 ¦ DataA13 ¦
¦  2 ¦ DataA21 ¦
+--------------+

How to select a single column with Entity Framework?

If you're fetching a single item only then, you need use select before your FirstOrDefault()/SingleOrDefault(). And you can use anonymous object of the required properties.

var name = dbContext.MyTable.Select(x => new { x.UserId, x.Name }).FirstOrDefault(x => x.UserId == 1)?.Name;

Above query will be converted to this:

Select Top (1) UserId, Name from MyTable where UserId = 1;

For multiple items you can simply chain Select after Where:

var names = dbContext.MyTable.Where(x => x.UserId > 10).Select(x => x.Name);

Use anonymous object inside Select if you need more than one properties.

PHP DateTime __construct() Failed to parse time string (xxxxxxxx) at position x

You should use setTimestamp instead, if you hardcode it:

$start_date = new DateTime();
$start_date->setTimestamp(1372622987);

in your case

$start_date = new DateTime();
$start_date->setTimestamp($dbResult->db_timestamp);

Boolean checking in the 'if' condition

My personal feeling when it comes to reading

if(!status) : if not status

if(status == false) : if status is false

if you are not used to !status reading. I see no harm doing as the second way.

if you use "active" instead of status I thing if(!active) is more readable

Python Pandas : pivot table with aggfunc = count unique distinct

aggfunc=pd.Series.nunique will only count unique values for a series - in this case count the unique values for a column. But this doesn't quite reflect as an alternative to aggfunc='count'

For simple counting, it better to use aggfunc=pd.Series.count

How can I check if a var is a string in JavaScript?

check for null or undefined in all cases a_string

if (a_string && typeof a_string === 'string') {
    // this is a string and it is not null or undefined.
}

Angular 2 @ViewChild annotation returns undefined

I had a similar issue and thought I'd post in case someone else made the same mistake. First, one thing to consider is AfterViewInit; you need to wait for the view to be initialized before you can access your @ViewChild. However, my @ViewChild was still returning null. The problem was my *ngIf. The *ngIf directive was killing my controls component so I couldn't reference it.

import {Component, ViewChild, OnInit, AfterViewInit} from 'angular2/core';
import {ControlsComponent} from './controls/controls.component';
import {SlideshowComponent} from './slideshow/slideshow.component';

@Component({
    selector: 'app',
    template:  `
        <controls *ngIf="controlsOn"></controls>
        <slideshow (mousemove)="onMouseMove()"></slideshow>
    `,
    directives: [SlideshowComponent, ControlsComponent]
})

export class AppComponent {
    @ViewChild(ControlsComponent) controls:ControlsComponent;

    controlsOn:boolean = false;

    ngOnInit() {
        console.log('on init', this.controls);
        // this returns undefined
    }

    ngAfterViewInit() {
        console.log('on after view init', this.controls);
        // this returns null
    }

    onMouseMove(event) {
         this.controls.show();
         // throws an error because controls is null
    }
}

Hope that helps.

EDIT
As mentioned by @Ashg below, a solution is to use @ViewChildren instead of @ViewChild.

Fastest way to convert Image to Byte array

The fastest way i could find out is this :

var myArray = (byte[]) new ImageConverter().ConvertTo(InputImg, typeof(byte[]));

Hope to be useful

Location of ini/config files in linux/unix?

For user configuration I've noticed a tendency towards moving away from individual ~/.myprogramrc to a structure below ~/.config. For example, Qt 4 uses ~/.config/<vendor>/<programname> with the default settings of QSettings. The major desktop environments KDE and Gnome use a file structure below a specific folder too (not sure if KDE 4 uses ~/.config, XFCE does use ~/.config).

How to split a string after specific character in SQL Server and update this value to specific column

SELECT SUBSTRING(ParentBGBU,0,CHARINDEX('-',ParentBGBU,0)) FROM dbo.tblHCMMaster;

LINQ: Select where object does not contain items from list

In general, you're looking for the "Except" extension.

var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);

In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int> of IDs)

What is the difference between lower bound and tight bound?

The phrases minimum time and maximum time are a bit misleading here. When we talk about big O notations, it's not the actual time we are interested in, it is how the time increases when our input size gets bigger. And it's usually the average or worst case time we are talking about, not best case, which usually is not meaningful in solving our problems.

Using the array search in the accepted answer to the other question as an example. The time it takes to find a particular number in list of size n is n/2 * some_constant in average. If you treat it as a function f(n) = n/2*some_constant, it increases no faster than g(n) = n, in the sense as given by Charlie. Also, it increases no slower than g(n) either. Hence, g(n) is actually both an upper bound and a lower bound of f(n) in Big-O notation, so the complexity of linear search is exactly n, meaning that it is Theta(n).

In this regard, the explanation in the accepted answer to the other question is not entirely correct, which claims that O(n) is upper bound because the algorithm can run in constant time for some inputs (this is the best case I mentioned above, which is not really what we want to know about the running time).

Root element is missing

Just in case anybody else lands here from Google, I was bitten by this error message when using XDocument.Load(Stream) method.

XDocument xDoc = XDocument.Load(xmlStream);  

Make sure the stream position is set to 0 (zero) before you try and load the Stream, its an easy mistake I always overlook!

if (xmlStream.Position > 0)
{
    xmlStream.Position = 0;
}
XDocument xDoc = XDocument.Load(xmlStream); 

Jquery how to find an Object by attribute in an Array

copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.

you can pass the search term as predicate function

_x000D_
_x000D_
// Example_x000D_
var listOfObjects = [{key: "1", value: "one"}, {key: "2", value: "two"}]_x000D_
var result = findInArray(listOfObjects, function(element) {_x000D_
  return element.key == "1";_x000D_
});_x000D_
console.log(result);_x000D_
_x000D_
// the function you want_x000D_
function findInArray(listOfObjects, predicate) {_x000D_
      if (listOfObjects == null) {_x000D_
        throw new TypeError('listOfObjects is null or not defined');_x000D_
      }_x000D_
_x000D_
      var o = Object(listOfObjects);_x000D_
_x000D_
      var len = o.length >>> 0;_x000D_
_x000D_
      if (typeof predicate !== 'function') {_x000D_
        throw new TypeError('predicate must be a function');_x000D_
      }_x000D_
_x000D_
      var thisArg = arguments[1];_x000D_
_x000D_
      var k = 0;_x000D_
_x000D_
      while (k < len) {_x000D_
        var kValue = o[k];_x000D_
        if (predicate.call(thisArg, kValue, k, o)) {_x000D_
          return kValue;_x000D_
        }_x000D_
        k++;_x000D_
      }_x000D_
_x000D_
      return undefined;_x000D_
}
_x000D_
_x000D_
_x000D_

Difference between DOMContentLoaded and load events

  • domContentLoaded: marks the point when both the DOM is ready and there are no stylesheets that are blocking JavaScript execution - meaning we can now (potentially) construct the render tree. Many JavaScript frameworks wait for this event before they start executing their own logic. For this reason the browser captures the EventStart and EventEnd timestamps to allow us to track how long this execution took.

  • loadEvent: as a final step in every page load the browser fires an “onload” event which can trigger additional application logic.

source

Cookies vs. sessions

A session is a group of information on the server that is associated with the cookie information. If you're using PHP you can check the session. save _ path location and actually "see sessions". A cookie is a snippet of data sent to and returned from clients. Cookies are often used to facilitate sessions since it tells the server which client handled which session. There are other ways to do this (query string magic etc) but cookies are likely most common for this.

Random number in range [min - max] using PHP

In a new PHP7 there is a finally a support for a cryptographically secure pseudo-random integers.

int random_int ( int $min , int $max )

random_int — Generates cryptographically secure pseudo-random integers

which basically makes previous answers obsolete.

Create a List that contain each Line of a File

I did it this way

lines_list = open('file.txt').read().splitlines()

Every line comes with its end of line characters (\n\r); this way the characters are removed.

Google Chrome Full Black Screen

Same thing just happened to me on Google Chrome v22.0.1221.1 (Nvidia GPU). The workaround was to disable GPU compositing on all pages (setting available on chrome://flags/)

If it happens in Chrome version > 45.x, See answer https://stackoverflow.com/a/32955808/293023 by @detale.

Use google-chrome -disable-gpu from the command line to temporary disable gpu.

What is the use of static variable in C#? When to use it? Why can't I declare the static variable inside method?

Static variables are used when only one copy of it is required. Let me explain this with an example:

class circle
{
    public float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * this._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now here we have created 2 instances for our class circle , i.e 2 sets of copies of _PI along with other variables are created. So say if we have lots of instances of this class multiple copies of _PI will be created occupying memory. So in such cases it is better to make such variables like _PI static and operate on them.

class circle
{
    static float _PI =3.14F;
    public int Radius;

    public funtionArea(int radius)
    {
        return this.radius * Circle._PI      
    }
}
class program
{
    public static void main()
    {
        Circle c1 = new Cirle();
        float area1 = c1.functionRaduis(5);
        Circle c2 = new Cirle();
        float area2 = c1.functionRaduis(6);
    }
}

Now no matter how many instances are made for the class circle , only one copy exists of variable _PI saving our memory.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

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.

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

MATLAB is a fantastic tool for

  • prototyping
  • engineering simulation and
  • fast visualization of data

You can really play with, visualize and test your ideas on a data set very effectively. It should not be regarded as an alternative to other software languages used for product development. I highly recommend it for the above tasks, though it is expensive - free alternatives like Octave and Python are catching up.

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

JavaScript - Get Browser Height

var winWidth = window.screen.width;
var winHeight = window.screen.height;

document.write(winWidth, winHeight);

List all virtualenv

Run workon with no argument to list available environments.

mysql stored-procedure: out parameter

I just tried to call a function in terminal rather then MySQL Query Browser and it works. So, it looks like I'm doing something wrong in that program...

I don't know what since I called some procedures before successfully (but there where no out parameters)...

For this one I had entered

CALL my_sqrt(4,@out_value);
SELECT @out_value;

And it results with an error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT @out_value' at line 2

Strangely, if I write just:

CALL my_sqrt(4,@out_value); 

The result message is: "Query canceled"

I guess, for now I will use only terminal...

How do I embed a mp4 movie into my html?

Most likely the TinyMce editor is adding its own formatting to the post. You'll need to see how you can escape TinyMce's editing abilities. The code works fine for me. Is it a wordpress blog?

Twitter bootstrap float div right

<p class="pull-left">Text left</p>
<p class="text-right">Text right in same line</p>

This work for me.

edit: An example with your snippet:

_x000D_
_x000D_
@import url('https://unpkg.com/[email protected]/dist/css/bootstrap.css');_x000D_
 .container {_x000D_
    margin-top: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
    <div class="row-fluid">_x000D_
        <div class="span6 pull-left">_x000D_
            <p>Text left</p>_x000D_
        </div>_x000D_
        <div class="span6 text-right">_x000D_
            <p>text right</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Splitting applicationContext to multiple files

I'm the author of modular-spring-contexts.

This is a small utility library to allow a more modular organization of spring contexts than is achieved by using Composing XML-based configuration metadata. modular-spring-contexts works by defining modules, which are basically stand alone application contexts and allowing modules to import beans from other modules, which are exported ín their originating module.

The key points then are

  • control over dependencies between modules
  • control over which beans are exported and where they are used
  • reduced possibility of naming collisions of beans

A simple example would look like this:

File moduleDefinitions.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:module id="serverModule">
        <module:config location="/serverModule.xml" />
    </module:module>

    <module:module id="clientModule">
        <module:config location="/clientModule.xml" />
        <module:requires module="serverModule" />
    </module:module>

</beans>

File serverModule.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <bean id="serverSingleton" class="java.math.BigDecimal" scope="singleton">
        <constructor-arg index="0" value="123.45" />
        <meta key="exported" value="true"/>
    </bean>

</beans>

File clientModule.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:module="http://www.gitlab.com/SpaceTrucker/modular-spring-contexts"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                        http://www.gitlab.com/SpaceTrucker/modular-spring-contexts xsd/modular-spring-contexts.xsd
                        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:annotation-config />

    <module:import id="importedSingleton" sourceModule="serverModule" sourceBean="serverSingleton" />

</beans>

jQuery - Fancybox: But I don't want scrollbars!

I did this to get rid of the overflow (scrollbar) ...

by the end of the jquery.fancybox....js file there are onStart, onCancel, onComplete etc. functions, and they are all empty ... so just go ahead and fill into the curly brackets of onStart with "$('body').css('overflow','hidden')" and onClosed "$('body').css('overflow','visible')" ... should look like this ...

onStart:function(){$('body').css('overflow','hidden')},
onClosed:function(){$('body').css('overflow','visible')},

peace

How to programmatically set cell value in DataGridView?

If the DataGridView has been populated by DataSource = x (i.e. is databound) then you need to change the bound data, not the DataGridView cells themselves.

One way of getting to that data from a known row or column is thus:

(YourRow.DataBoundItem as DataRowView).Row['YourColumn'] = NewValue;

Run function from the command line

First you have to call the function as they told you or the founction will display nothing in the output, after that save the file and copy the path of the file by right click to the folder of the file and click on"copy file" then go to terminal and write: - cd "the path of the file" - python "name of the file for example (main.py)" after that it will display the output of your code.

How to loop over a Class attributes in Java?

There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

Related questions


Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

POST JSON to API using Rails and HTTParty

I solved this by adding .to_json and some heading information

@result = HTTParty.post(@urlstring_to_post.to_str, 
    :body => { :subject => 'This is the screen name', 
               :issue_type => 'Application Problem', 
               :status => 'Open', 
               :priority => 'Normal', 
               :description => 'This is the description for the problem'
             }.to_json,
    :headers => { 'Content-Type' => 'application/json' } )

Getting parts of a URL (Regex)

String s = "https://www.thomas-bayer.com/axis2/services/BLZService?wsdl";

String regex = "(^http.?://)(.*?)([/\\?]{1,})(.*)";

System.out.println("1: " + s.replaceAll(regex, "$1"));
System.out.println("2: " + s.replaceAll(regex, "$2"));
System.out.println("3: " + s.replaceAll(regex, "$3"));
System.out.println("4: " + s.replaceAll(regex, "$4"));

Will provide the following output:
1: https://
2: www.thomas-bayer.com
3: /
4: axis2/services/BLZService?wsdl

If you change the URL to
String s = "https://www.thomas-bayer.com?wsdl=qwerwer&ttt=888"; the output will be the following :
1: https://
2: www.thomas-bayer.com
3: ?
4: wsdl=qwerwer&ttt=888

enjoy..
Yosi Lev

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

How do I install and use curl on Windows?

Install Chocolatey package manager for Windows. Once installed, simply enter choco install curl. Then you can use curl from a terminal.

How to wrap text of HTML button with fixed width?

I have found that a button works, but that you'll want to add style="height: 100%;" to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1

Convert JSON array to an HTML table in jQuery

You can do this pretty easily with Javascript+Jquery as below. If you want to exclude some column, just write an if statement inside the for loops to skip those columns. Hope this helps!

_x000D_
_x000D_
//Sample JSON 2D array_x000D_
var json = [{_x000D_
  "Total": "34",_x000D_
  "Version": "1.0.4",_x000D_
  "Office": "New York"_x000D_
}, {_x000D_
  "Total": "67",_x000D_
  "Version": "1.1.0",_x000D_
  "Office": "Paris"_x000D_
}];_x000D_
_x000D_
// Get Table headers and print_x000D_
for (var k = 0; k < Object.keys(json[0]).length; k++) {_x000D_
  $('#table_head').append('<td>' + Object.keys(json[0])[k] + '</td>');_x000D_
}_x000D_
_x000D_
// Get table body and print_x000D_
for (var i = 0; i < Object.keys(json).length; i++) {_x000D_
  $('#table_content').append('<tr>');_x000D_
  for (var j = 0; j < Object.keys(json[0]).length; j++) {_x000D_
    $('#table_content').append('<td>' + json[i][Object.keys(json[0])[j]] + '</td>');_x000D_
  }_x000D_
  $('#table_content').append('</tr>');_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr id="table_head">_x000D_
_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody id="table_content">_x000D_
_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

Ant build failed: "Target "build..xml" does not exist"

  1. Probably you don't have environment variable ANT_HOME set properly
  2. It seems that you are calling Ant like this: "ant build..xml". If your ant script has name build.xml you need to specify only a target in command line. For example: "ant target1".

index.php not loading by default

For info : in some Apache2 conf you must add the DirectoryIndex command in mods_enabled/dir.conf (it's not located in apache2.conf)

Rendering HTML in a WebView with custom CSS

It's as simple as is:

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");

And your some.html needs to contain something like:

<link rel="stylesheet" type="text/css" href="style.css" />

HTML form action and onsubmit issues

You should stop the submit procedure by returning false on the onsubmit callback.

<script>
    function checkRegistration(){
        if(!form_valid){
            alert('Given data is not correct');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()"...

Here you have a fully working example. The form will submit only when you write google into input, otherwise it will return an error:

<script>
    function checkRegistration(){
        var form_valid = (document.getElementById('some_input').value == 'google');
        if(!form_valid){
            alert('Given data is incorrect');
            return false;
        }
        return true;
    }
</script>

<form onsubmit="return checkRegistration()" method="get" action="http://google.com">
    Write google to go to google...<br/>
    <input type="text" id="some_input" value=""/>
    <input type="submit" value="google it"/>
</form>

Stop/Close webcam stream which is opened by navigator.mediaDevices.getUserMedia

Please check this: https://jsfiddle.net/wazb1jks/3/

_x000D_
_x000D_
navigator.getUserMedia(mediaConstraints, function(stream) {_x000D_
    window.streamReference = stream;_x000D_
}, onMediaError);
_x000D_
_x000D_
_x000D_

Stop Recording

_x000D_
_x000D_
function stopStream() {_x000D_
    if (!window.streamReference) return;_x000D_
_x000D_
    window.streamReference.getAudioTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference.getVideoTracks().forEach(function(track) {_x000D_
        track.stop();_x000D_
    });_x000D_
_x000D_
    window.streamReference = null;_x000D_
}
_x000D_
_x000D_
_x000D_

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

how to pass command line arguments to main method dynamically

If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.

Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3

The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.

Consider a program ArgsTest.java:

package test;

import java.io.IOException;

    public class ArgsTest {

        public static void main(String[] args) throws IOException {

            System.out.println("Program Arguments:");
            for (String arg : args) {
                System.out.println("\t" + arg);
            }

            System.out.println("System Properties from VM Arguments");
            String sysProp1 = "sysProp1";
            System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
            String sysProp2 = "sysProp2";
            System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));

        }
    }

If given input as,

java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3 

in the commandline, in project bin folder would give the following result:

Program Arguments:
  pro1
  pro2
  pro3
System Properties from VM Arguments
  Name:sysProp1, Value:sp1
  Name:sysProp2, Value:sp2

Close dialog on click (anywhere)

Facing the same problem, I have created a small plugin that enables to close a dialog when clicking outside of it whether it a modal or non-modal dialog. It supports one or multiple dialogs on the same page.

More information on my website here: http://www.coheractio.com/blog/closing-jquery-ui-dialog-widget-when-clicking-outside

Laurent

How can I reverse the order of lines in a file?

at the end of your command put: | tac

tac does exactly what you're asking for, it "Write each FILE to standard output, last line first."

tac is the opposite of cat :-).

When does a process get SIGABRT (signal 6)?

A case when process get SIGABRT from itself: Hrvoje mentioned about a buried pure virtual being called from ctor generating an abort, i recreated an example for this. Here when d is to be constructed, it first calls its base class A ctor, and passes inside pointer to itself. the A ctor calls pure virtual method before table was filled with valid pointer, because d is not constructed yet.

#include<iostream>
using namespace std;
class A {
public:
 A(A *pa){pa->f();}
 virtual void f()=0;
};
class D : public A {
public:
 D():A(this){}
 virtual void f() {cout<<"D::f\n";}
};
int main(){
 D d;
 A *pa = &d;
 pa->f();
 return 0;
}

compile: g++ -o aa aa.cpp

ulimit -c unlimited

run: ./aa

pure virtual method called
terminate called without an active exception
Aborted (core dumped)

now lets quickly see the core file, and validate that SIGABRT was indeed called:

gdb aa core

see regs:

i r
rdx            0x6      6
rsi            0x69a    1690
rdi            0x69a    1690
rip            0x7feae3170c37

check code:

disas 0x7feae3170c37

mov    $0xea,%eax  = 234  <- this is the kill syscall, sends signal to process
syscall   <-----

http://blog.rchapman.org/posts/Linux_System_Call_Table_for_x86_64/

234 sys_tgkill pid_t tgid pid_t pid int sig = 6 = SIGABRT

:)

How do I get the time of day in javascript/Node.js?

This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS. It also works in Node.js.

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

Convert JsonNode into POJO

String jsonInput = "{ \"hi\": \"Assume this is the JSON\"} ";
com.fasterxml.jackson.databind.ObjectMapper mapper =
    new com.fasterxml.jackson.databind.ObjectMapper();
MyClass myObject = objectMapper.readValue(jsonInput, MyClass.class);

If your JSON input in has more properties than your POJO has and you just want to ignore the extras in Jackson 2.4, you can configure your ObjectMapper as follows. This syntax is different from older Jackson versions. (If you use the wrong syntax, it will silently do nothing.)

mapper.disable(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNK??NOWN_PROPERTIES);

Error Code: 1406. Data too long for column - MySQL

I got the same error while using the imagefield in Django. post_picture = models.ImageField(upload_to='home2/khamulat/mydomain.com/static/assets/images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None)

I just removed the excess code as shown above to post_picture = models.ImageField(upload_to='images/uploads/blog/%Y/%m/%d', height_field=None, default=None, width_field=None, max_length=None) and the error was gone

Best way to deploy Visual Studio application that can run without installing

First you need to publish the file by:

  1. BUILD -> PUBLISH or by right clicking project on Solution Explorer -> properties -> publish or select project in Solution Explorer and press Alt + Enter NOTE: if you are using Visual Studio 2013 then in properties you have to go to BUILD and then you have to disable define DEBUG constant and define TRACE constant and you are ready to go. Representation

  2. Save your file to a particular folder. Find the produced files (the EXE file and the .config, .manifest, and .application files, along with any DLL files, etc.) - they are all in the same folder and typically in the bin\Debug folder below the project file (.csproj). In Visual Studio they are in the Application Files folder and inside that you just need the .exe and dll files. (You have to delete ClickOnce and other files and then make this folder a zip file and distribute it.)

NOTE: The ClickOnce application does install the project to system, but it has one advantage. You DO NOT require administrative privileges here to run (if your application follows the normal guidelines for which folders to use for application data, etc.).

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

Add column to SQL Server

Adding a column using SSMS or ALTER TABLE .. ADD will not drop any existing data.

Eclipse HotKey: how to switch between tabs?

Hold CTRL and press F6 until you reached the editor you want, then release. The UI is not as pretty as the window selection, but the functionality is the same.

SQL sum with condition

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

For HTML Entities
◄ = &#9668;
► = &#9658;
▼ = &#9660;
▲ = &#9650;

scp via java

I wrote an scp server which is much easier than others. I use Apache MINA project (Apache SSHD) to develop it. You can take a look here: https://github.com/boomz/JSCP Also you can download the jar file from /jar directory. How to use? Take a look on: https://github.com/boomz/JSCP/blob/master/src/Main.java

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

Insert entire DataTable into database at once instead of row by row?

I discovered SqlBulkCopy is an easy way to do this, and does not require a stored procedure to be written in SQL Server.

Here is an example of how I implemented it:

// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.  

using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
      foreach (DataColumn col in table.Columns)
      {
          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
      }

      bulkCopy.BulkCopyTimeout = 600;
      bulkCopy.DestinationTableName = destinationTableName;
      bulkCopy.WriteToServer(table);
}

How to save a git commit message from windows cmd?

You are inside vim. To save changes and quit, type:

<esc> :wq <enter>

That means:

  • Press Escape. This should make sure you are in command mode
  • type in :wq
  • Press Return

An alternative that stdcall in the comments mentions is:

  • Press Escape
  • Press shift+Z shift+Z (capital Z twice).

Insert data through ajax into mysql database

The ajax is going to be a javascript snippet that passes information to a small php file that does what you want. So in your page, instead of all that php, you want a little javascript, preferable jquery:

function fun()
{
    $.get('\addEmail.php', {email : $(this).val()}, function(data) {
        //here you would write the "you ve been successfully subscribed" div
    });
}

also you input would have to be:

<input type="button" value="subscribe" class="submit" onclick="fun();" />

last the file addEmail.php should look something like:

mysql_connect("localhost","root","");
mysql_select_db("eciticket_db");

error_reporting(E_ALL && ~E_NOTICE);

$email=mysql_real_escape_string($_GET['email']);
$sql="INSERT INTO newsletter_email(email) VALUES ('$email')";
$result=mysql_query($sql);
if($result){
echo "You have been successfully subscribed.";
}
 if(!$sql)
die(mysql_error());

mysql_close();

Also sergey is right, you should use mysqli. That's not everything, but enough to get you started.

New Array from Index Range Swift

This works for me:

var test = [1, 2, 3]
var n = 2
var test2 = test[0..<n]

Your issue could be with how you're declaring your array to begin with.

EDIT:

To fix your function, you have to cast your Slice to an array:

func aFunction(numbers: Array<Int>, position: Int) -> Array<Int> {
    var newNumbers = Array(numbers[0..<position])
    return newNumbers
}

// test
aFunction([1, 2, 3], 2) // returns [1, 2]

HTTP Status 405 - Method Not Allowed Error for Rest API

@Produces({"text/plain","application/xml","application/json"}) change this to @Produces("text/plain") and try,

HTTP response code for POST when resource already exists

My feeling is 409 Conflict is the most appropriate, however, seldom seen in the wild of course:

The request could not be completed due to a conflict with the current state of the resource. This code is only allowed in situations where it is expected that the user might be able to resolve the conflict and resubmit the request. The response body SHOULD include enough information for the user to recognize the source of the conflict. Ideally, the response entity would include enough information for the user or user agent to fix the problem; however, that might not be possible and is not required.

Conflicts are most likely to occur in response to a PUT request. For example, if versioning were being used and the entity being PUT included changes to a resource which conflict with those made by an earlier (third-party) request, the server might use the 409 response to indicate that it can't complete the request. In this case, the response entity would likely contain a list of the differences between the two versions in a format defined by the response Content-Type.

Characters allowed in GET parameter

"." | "!" | "~" | "*" | "'" | "(" | ")" are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.

What is the purpose of the single underscore "_" variable in Python?

As far as the Python languages is concerned, _ has no special meaning. It is a valid identifier just like _foo, foo_ or _f_o_o_.

Any special meaning of _ is purely by convention. Several cases are common:

  • A dummy name when a variable is not intended to be used, but a name is required by syntax/semantics.

    # iteration disregarding content
    sum(1 for _ in some_iterable)
    # unpacking disregarding specific elements
    head, *_ = values
    # function disregarding its argument
    def callback(_): return True
    
  • Many REPLs/shells store the result of the last top-level expression to builtins._.

    The special identifier _ is used in the interactive interpreter to store the result of the last evaluation; it is stored in the builtins module. When not in interactive mode, _ has no special meaning and is not defined. [source]

    Due to the way names are looked up, unless shadowed by a global or local _ definition the bare _ refers to builtins._ .

    >>> 42
    42
    >>> f'the last answer is {_}'
    'the last answer is 42'
    >>> _
    'the last answer is 42'
    >>> _ = 4  # shadow ``builtins._`` with global ``_``
    >>> 23
    23
    >>> _
    4
    

    Note: Some shells such as ipython do not assign to builtins._ but special-case _.

  • In the context internationalization and localization, _ is used as an alias for the primary translation function.

    gettext.gettext(message)

    Return the localized translation of message, based on the current global domain, language, and locale directory. This function is usually aliased as _() in the local namespace (see examples below).

JSON post to Spring Controller

Try to using application/* instead. And use JSON.maybeJson() to check the data structure in the controller.

How to pass optional parameters while omitting some other optional parameters?

You can create a helper method that accept a one object parameter base on error arguments

 error(message: string, title?: string, autoHideAfter?: number){}

 getError(args: { message: string, title?: string, autoHideAfter?: number }) {
    return error(args.message, args.title, args.autoHideAfter);
 }

Can a normal Class implement multiple interfaces?

It is true that a java class can implement multiple interfaces at the same time, but there is a catch here. If in a class, you are trying to implement two java interfaces, which contains methods with same signature but diffrent return type, in that case you will get compilation error.

interface One
{
    int m1();
}
interface Two
{
    float m1();
}
public class MyClass implements One, Two{
    int m1() {}
    float m1() {}
    public static void main(String... args) {

    }
}

output :

prog.java:14: error: method m1() is already defined in class MyClass
    public float m1() {}
                 ^
prog.java:11: error: MyClass is not abstract and does not override abstract method m1() in Two
public class MyClass implements One, Two{
       ^
prog.java:13: error: m1() in MyClass cannot implement m1() in Two
    public int m1() {}
               ^
  return type int is not compatible with float
3 errors

How to extract base URL from a string in JavaScript?

You can use below codes for get different parameters of Current URL

alert("document.URL : "+document.URL);
alert("document.location.href : "+document.location.href);
alert("document.location.origin : "+document.location.origin);
alert("document.location.hostname : "+document.location.hostname);
alert("document.location.host : "+document.location.host);
alert("document.location.pathname : "+document.location.pathname);

Why is document.write considered a "bad practice"?

It overwrites content on the page which is the most obvious reason but I wouldn't call it "bad".

It just doesn't have much use unless you're creating an entire document using JavaScript in which case you may start with document.write.

Even so, you aren't really leveraging the DOM when you use document.write--you are just dumping a blob of text into the document so I'd say it's bad form.

Find largest and smallest number in an array

big=small=values[0]; //assigns element to be highest or lowest value

Should be AFTER fill loop

//counts to 20 and prompts user for value and stores it
for ( int i = 0; i < 20; i++ )
{
    cout << "Enter value " << i << ": ";
    cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value

since when you declare array - it's unintialized (store some undefined values) and so, your big and small after assigning would store undefined values too.

And of course, you can use std::min_element, std::max_element, or std::minmax_element from C++11, instead of writing your loops.

Calling Web API from MVC controller

From my HomeController I want to call this Method and convert Json response to List

No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!

Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:

public IEnumerable<QDocumentRecord> GetAllRecords()
{
    listOfFiles = ...
    return listOfFiles;
}

If you don't want that and you're absolutely sure you need to return HttpResponseMessage, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject() yourself:

return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);

Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:

public class FileListGetter
{
    public IEnumerable<QDocumentRecord> GetAllRecords()
    {
        listOfFiles = ...
        return listOfFiles;
    }
}

Either way, then you can call this class or the ApiController directly from your MVC controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new DocumentsController().GetAllRecords();
        // OR
        var listOfFiles = new FileListGetter().GetAllRecords();

        return View(listOfFiles);
    }
}

But if you really, really must do an HTTP request, you can use HttpWebRequest, WebClient, HttpClient or RestSharp, for all of which plenty of tutorials exist.

VC++ fatal error LNK1168: cannot open filename.exe for writing

I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

Imitating a blink tag with CSS3 animations

if you want some glow effect use this

@keyframes blink {
  50% {
    opacity: 0.0;
  }
}
@-webkit-keyframes blink {
  50% {
    opacity: 0.0;
  }
}

atom-text-editor::shadow  .bracket-matcher .region {
    border:none;
    background-color: rgba(195,195,255,0.1);
    border-bottom: 1px solid rgb(155,155,255);
    box-shadow: 0px 0px 9px 4px rgba(155,155,255,0.1);
    border-radius: 3px;
    animation: blink 2s steps(115, start) infinite;
    -webkit-animation: blink 2s steps(115, start) infinite;
}