Programs & Examples On #Melt

In R, the "melt" function from the "reshape2" and "data.table" (and earlier, "reshape") packages converts data into a long form. Melt is also a web application framework written in PHP.

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis

if x is numeric, then add scale_x_continuous(); if x is character/factor, then add scale_x_discrete(). This might solve your problem.

Saving binary data as file using JavaScript from a browser

Try

_x000D_
_x000D_
let bytes = [65,108,105,99,101,39,115,32,65,100,118,101,110,116,117,114,101];_x000D_
_x000D_
let base64data = btoa(String.fromCharCode.apply(null, bytes));_x000D_
_x000D_
let a = document.createElement('a');_x000D_
a.href = 'data:;base64,' + base64data;_x000D_
a.download = 'binFile.txt'; _x000D_
a.click();
_x000D_
_x000D_
_x000D_

I convert here binary data to base64 (for bigger data conversion use this) - during downloading browser decode it automatically and save raw data in file. 2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop working (probably due to sandbox security restrictions) - but JSFiddle version works - here

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

Replacing NULL and empty string within Select statement

Try this

COALESCE(NULLIF(Address.COUNTRY,''), 'United States')

R: "Unary operator error" from multiline ggplot2 command

This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source() a script to when you copy-and-paste the lines, both with multiline and comments)

Rule: always put the dangling '+' at the end of a line so R knows the command is unfinished:

ggplot(...) + geom_whatever1(...) +
  geom_whatever2(...) +
  stat_whatever3(...) +
  geom_title(...) + scale_y_log10(...)

Don't put the dangling '+' at the start of the line, since that tickles the error:

Error in "+ geom_whatever2(...) invalid argument to unary operator"

And obviously don't put dangling '+' at both end and start since that's a syntax error.

So, learn a habit of being consistent: always put '+' at end-of-line.

cf. answer to "Split code over multiple lines in an R script"

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

uncaught syntaxerror unexpected token U JSON

Most common case of this error happening is using template that is generating the control then changing the way id and/or nameare being generated by 'overriding' default template with something like

@Html.TextBoxFor(m => m, new {Name = ViewData["Name"], id = ViewData["UniqueId"]} )

and then forgetting to change ValidationMessageFor to

@Html.ValidationMessageFor(m => m, null, new { data_valmsg_for = ViewData["Name"] })    

Hope this saves you some time.

How to make Sonar ignore some classes for codeCoverage metric?

When using sonar-scanner for swift, use sonar.coverage.exclusions in your sonar-project.properties to exclude any file for only code coverage. If you want to exclude files from analysis as well, you can use sonar.exclusions. This has worked for me in swift

sonar.coverage.exclusions=**/*ViewController.swift,**/*Cell.swift,**/*View.swift

ggplot2 legend to bottom and horizontal

If you want to move the position of the legend please use the following code:

library(reshape2) # for melt
df <- melt(outer(1:4, 1:4), varnames = c("X1", "X2"))
p1 <- ggplot(df, aes(X1, X2)) + geom_tile(aes(fill = value))
p1 + scale_fill_continuous(guide = guide_legend()) +
    theme(legend.position="bottom")

This should give you the desired result. Legend at bottom

Safari 3rd party cookie iframe trick no longer working?

Google actually let the cat out of the bag on this one. They were using it for a while to access tracking cookies. It was fixed almost immediately by Apple =\

original Wall Street Journal post

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

How to reshape data from long to wide format

You can do this with the reshape() function, or with the melt() / cast() functions in the reshape package. For the second option, example code is

library(reshape)
cast(dat1, name ~ numbers)

Or using reshape2

library(reshape2)
dcast(dat1, name ~ numbers)

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

Reshaping data.frame from wide to long format

Here's a solution:

sqldf("Select Code, Country, '1950' As Year, `1950` As Value From wide
        Union All
       Select Code, Country, '1951' As Year, `1951` As Value From wide
        Union All
       Select Code, Country, '1952' As Year, `1952` As Value From wide
        Union All
       Select Code, Country, '1953' As Year, `1953` As Value From wide
        Union All
       Select Code, Country, '1954' As Year, `1954` As Value From wide;")

To make the query without typing in everything, you can use the following:

Thanks to G. Grothendieck for implementing it.

ValCol <- tail(names(wide), -2)

s <- sprintf("Select Code, Country, '%s' As Year, `%s` As Value from wide", ValCol, ValCol)
mquery <- paste(s, collapse = "\n Union All\n")

cat(mquery) #just to show the query
 #> Select Code, Country, '1950' As Year, `1950` As Value from wide
 #>  Union All
 #> Select Code, Country, '1951' As Year, `1951` As Value from wide
 #>  Union All
 #> Select Code, Country, '1952' As Year, `1952` As Value from wide
 #>  Union All
 #> Select Code, Country, '1953' As Year, `1953` As Value from wide
 #>  Union All
 #> Select Code, Country, '1954' As Year, `1954` As Value from wide

sqldf(mquery)
 #>    Code     Country Year  Value
 #> 1   AFG Afghanistan 1950 20,249
 #> 2   ALB     Albania 1950  8,097
 #> 3   AFG Afghanistan 1951 21,352
 #> 4   ALB     Albania 1951  8,986
 #> 5   AFG Afghanistan 1952 22,532
 #> 6   ALB     Albania 1952 10,058
 #> 7   AFG Afghanistan 1953 23,557
 #> 8   ALB     Albania 1953 11,123
 #> 9   AFG Afghanistan 1954 24,555
 #> 10  ALB     Albania 1954 12,246

Unfortunately, I don't think that PIVOT and UNPIVOT would work for R SQLite. If you want to write up your query in a more sophisticated manner, you can also take a look at these posts:

Using sprintf writing up sql queries   Or    Pass variables to sqldf

Mod of negative number is melting my brain

A single line implementation of dcastro's answer (the most compliant with other languages):

int Mod(int a, int n)
{
    return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
}

If you'd like to keep the use of % operator (you can't overload native operators in C#):

public class IntM
{
    private int _value;

    private IntM(int value)
    {
        _value = value;
    }

    private static int Mod(int a, int n)
    {
        return (((a %= n) < 0) && n > 0) || (a > 0 && n < 0) ? a + n : a;
    }

    public static implicit operator int(IntM i) => i._value;
    public static implicit operator IntM(int i) => new IntM(i);
    public static int operator %(IntM a, int n) => Mod(a, n);
    public static int operator %(int a, IntM n) => Mod(a, n);
}

Use case, both works:

int r = (IntM)a % n;

// Or
int r = a % n(IntM);

.htaccess or .htpasswd equivalent on IIS?

There isn't a direct 1:1 equivalent.

You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.

If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/

convert xml to java object using jaxb (unmarshal)

Tests

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

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

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

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

}

TestData

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

package forum11221136;

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

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

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

Demo

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

package forum11221136;

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

public class Demo {

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

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

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

}

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

Python NameError: name is not defined

Note that sometimes you will want to use the class type name inside its own definition, for example when using Python Typing module, e.g.

class Tree:
    def __init__(self, left: Tree, right: Tree):
        self.left = left
        self.right = right

This will also result in

NameError: name 'Tree' is not defined

That's because the class has not been defined yet at this point. The workaround is using so called Forward Reference, i.e. wrapping a class name in a string, i.e.

class Tree:
    def __init__(self, left: 'Tree', right: 'Tree'):
        self.left = left
        self.right = right

Removing double quotes from a string in Java

You can just go for String replace method.-

line1 = line1.replace("\"", "");

How do I use a C# Class Library in a project?

I'm not certain why everyone is claiming that you need a using statement at the top of your file, as this is entirely unnecessary.

Right-click on the "References" folder in your project and select "Add Reference". If your new class library is a project in the same solution, select the "Project" tab and pick the project. If the new library is NOT in the same solution, click the "Browse" tab and find the .dll for your new project.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

For me the problem was that I had installed cx_Oracle via DOS pip which changed it to lower case. Installing it through Git Bash instead kept the mixed case.

Jquery Chosen plugin - dynamically populate list by Ajax

If you have two or more selects and use Steve McLenithan's answer, try to replace the first line with:

$('#CHOSENINPUTFIELDID_chosen > div > div input').autocomplete({

not remove suffix: _chosen

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

It is actually a permission issue. Add these lines in your platforms/android/AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

Finding blocking/locking queries in MS SQL (mssql)

I found this query which helped me find my locked table and query causing the issue.

SELECT  L.request_session_id AS SPID, 
        DB_NAME(L.resource_database_id) AS DatabaseName,
        O.Name AS LockedObjectName, 
        P.object_id AS LockedObjectId, 
        L.resource_type AS LockedResource, 
        L.request_mode AS LockType,
        ST.text AS SqlStatementText,        
        ES.login_name AS LoginName,
        ES.host_name AS HostName,
        TST.is_user_transaction as IsUserTransaction,
        AT.name as TransactionName,
        CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
        JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
        JOIN sys.objects O ON O.object_id = P.object_id
        JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
        JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
        JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
        JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
        CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Both of them are ways of subsetting. The single bracket will return a subset of the list, which in itself will be a list. ie:It may or may not contain more than one elements. On the other hand a double bracket will return just a single element from the list.

-Single bracket will give us a list. We can also use single bracket if we wish to return multiple elements from the list. consider the following list:-

>r<-list(c(1:10),foo=1,far=2);

Now please note the way the list is returned when I try to display it. I type r and press enter

>r

#the result is:-

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

$foo

[1] 1

$far

[1] 2

Now we will see the magic of single bracket:-

>r[c(1,2,3)]

#the above command will return a list with all three elements of the actual list r as below

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

$foo

[1] 1


$far

[1] 2

which is exactly the same as when we tried to display value of r on screen, which means the usage of single bracket has returned a list, where at index 1 we have a vector of 10 elements, then we have two more elements with names foo and far. We may also choose to give a single index or element name as input to the single bracket. eg:

> r[1]

[[1]]

 [1]  1  2  3  4  5  6  7  8  9 10

In this example we gave one index "1" and in return got a list with one element(which is an array of 10 numbers)

> r[2]

$foo

[1] 1

In the above example we gave one index "2" and in return got a list with one element

> r["foo"];

$foo

[1] 1

In this example we passed the name of one element and in return a list was returned with one element.

You may also pass a vector of element names like:-

> x<-c("foo","far")

> r[x];

$foo

[1] 1

$far
[1] 2

In this example we passed an vector with two element names "foo" and "far"

In return we got a list with two elements.

In short single bracket will always return you another list with number of elements equal to the number of elements or number of indices you pass into the single bracket.

In contrast, a double bracket will always return only one element. Before moving to double bracket a note to be kept in mind. NOTE:THE MAJOR DIFFERENCE BETWEEN THE TWO IS THAT SINGLE BRACKET RETURNS YOU A LIST WITH AS MANY ELEMENTS AS YOU WISH WHILE A DOUBLE BRACKET WILL NEVER RETURN A LIST. RATHER A DOUBLE BRACKET WILL RETURN ONLY A SINGLE ELEMENT FROM THE LIST.

I will site a few examples. Please keep a note of the words in bold and come back to it after you are done with the examples below:

Double bracket will return you the actual value at the index.(It will NOT return a list)

  > r[[1]]

     [1]  1  2  3  4  5  6  7  8  9 10


  >r[["foo"]]

    [1] 1

for double brackets if we try to view more than one elements by passing a vector it will result in an error just because it was not built to cater to that need, but just to return a single element.

Consider the following

> r[[c(1:3)]]
Error in r[[c(1:3)]] : recursive indexing failed at level 2
> r[[c(1,2,3)]]
Error in r[[c(1, 2, 3)]] : recursive indexing failed at level 2
> r[[c("foo","far")]]
Error in r[[c("foo", "far")]] : subscript out of bounds

How to prevent long words from breaking my div?

The solution I usually use for this problem is to set 2 different css rules for IE and other browsers:

word-wrap: break-word;

woks perfect in IE, but word-wrap is not a standard CSS property. It's a Microsoft specific property and doesn't work in Firefox.

For Firefox, the best thing to do using only CSS is to set the rule

overflow: hidden;

for the element that contains the text you want to wrap. It doesn't wrap the text, but hide the part of text that go over the limit of the container. It can be a nice solution if is not essential for you to display all the text (i.e. if the text is inside an <a> tag)

2D character array initialization in C

C strings are enclosed in double quotes:

const char *options[2][100];

options[0][0] = "test1";
options[1][0] = "test2";

Re-reading your question and comments though I'm guessing that what you really want to do is this:

const char *options[2] = { "test1", "test2" };

Fixed footer in Bootstrap

Add this:

<div class="footer navbar-fixed-bottom">

https://stackoverflow.com/a/21604189

EDIT: class navbar-fixed-bottom has been changed to fixed-bottom as of Bootstrap v4-alpha.6.

http://v4-alpha.getbootstrap.com/components/navbar/#placement

How do you build a Singleton in Dart?

Dart singleton by const constructor & factory

class Singleton {
  factory Singleton() =>
    Singleton._internal_();
  Singleton._internal_();
}
 
 
void main() {
  print(new Singleton() == new Singleton());
  print(identical(new Singleton() , new Singleton()));
}

how to properly display an iFrame in mobile safari

Sharon's method worked for me, however when a link in the iframe is followed and then the browser back button is pressed, the cached version of the page is loaded and the iframe is no longer scrollable. To overcome this I used some code to refresh the page as follows:

if ('ontouchstart' in document.documentElement)
     {
        document.getElementById('Scrolling').src = document.getElementById('SCrolling').src;
    }

Example of waitpid() in use?

The syntax is

pid_t waitpid(pid_t pid, int *statusPtr, int options);

1.where pid is the process of the child it should wait.

2.statusPtr is a pointer to the location where status information for the terminating process is to be stored.

3.specifies optional actions for the waitpid function. Either of the following option flags may be specified, or they can be combined with a bitwise inclusive OR operator:

WNOHANG WUNTRACED WCONTINUED

If successful, waitpid returns the process ID of the terminated process whose status was reported. If unsuccessful, a -1 is returned.

benifits over wait

1.Waitpid can used when you have more than one child for the process and you want to wait for particular child to get its execution done before parent resumes

2.waitpid supports job control

3.it supports non blocking of the parent process

How to scroll page in flutter

Very easy if you are already using a statelessWidget checkOut my code

class _MyThirdPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Understanding Material-Cards'),
      ),
      body: SingleChildScrollView(
          child: Column(
        children: <Widget>[
          _buildStack(),
          _buildCard(),
          SingleCard(),
          _inkwellCard()
        ],
      )),
    );
  }
}

Calculating average of an array list?

Using Guava, it gets syntactically simplified:

Stats.meanOf(numericList);

Get ASCII value at input word

There is a major gotcha associated with getting an ASCII code of a char value.

In the proper sense, it can't be done.

It's because char has a range of 65535 whereas ASCII is restricted to 128. There is a huge amount of characters that have no ASCII representation at all.

The proper way would be to use a Unicode code point which is the standard numerical equivalent of a character in the Java universe.

Thankfully, Unicode is a complete superset of ASCII. That means Unicode numbers for Latin characters are equal to their ASCII counterparts. For example, A in Unicode is U+0041 or 65 in decimal. In contrast, ASCII has no mapping for 99% of char-s. Long story short:

char ch = 'A';
int cp = String.valueOf(ch).codePointAt(0);

Furthermore, a 16-bit primitive char actually represents a code unit, not a character and is thus restricted to Basic Multilingual Plane, for historical reasons. Entities beyond it require Character objects which deal away with the fixed bit-length limitation.

In Bootstrap open Enlarge image in modal

I know your question is tagged as boostrap-modal (althought you didn't mentioned Bootstrap explicity neither), but I loved to see the simple way W3.CSS solved this and I think is good to share it.

  <img src="/myImage.png" style="width:30%;cursor:zoom-in"
  onclick="document.getElementById('modal01').style.display='block'">

  <div id="modal01" class="w3-modal" onclick="this.style.display='none'">
    <div class="w3-modal-content w3-animate-zoom">
      <img src="/myImage.png" style="width:100%">
    </div>
  </div>

I let you a link to the W3School modal image example to see the headers to make W3.CSS work.

How do you calculate program run time in python?

You might want to take a look at the timeit module:

http://docs.python.org/library/timeit.html

or the profile module:

http://docs.python.org/library/profile.html

There are some additionally some nice tutorials here:

http://www.doughellmann.com/PyMOTW/profile/index.html

http://www.doughellmann.com/PyMOTW/timeit/index.html

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

http://docs.python.org/library/time.html

Request format is unrecognized for URL unexpectedly ending in

Make sure you disable custom errors. This can mask the original problem in your code:

change

<customErrors defaultRedirect="~/Error" mode="On">

to

<customErrors defaultRedirect="~/Error" mode="Off">

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

As mentioned by Frank, you can use Firebase Cloud Messaging (FCM) HTTP API to trigger push notification from your own back-end. But you won't be able to

  1. send notifications to a Firebase User Identifier (UID) and
  2. send notifications to user segments (targeting properties & events like you can on the user console).

Meaning: you'll have to store FCM/GCM registration ids (push tokens) yourself or use FCM topics to subscribe users. Keep also in mind that FCM is not an API for Firebase Notifications, it's a lower-level API without scheduling or open-rate analytics. Firebase Notifications is build on top on FCM.

Convert DataTable to List<T>

thanks for all of posts.... I have done it with using Linq Query, to view this please visit the following link

http://codenicely.blogspot.com/2012/02/converting-your-datatable-into-list.html

How do I output coloured text to a Linux terminal?

As others have stated, you can use escape characters. You can use my header in order to make it easier:

#ifndef _COLORS_
#define _COLORS_

/* FOREGROUND */
#define RST  "\x1B[0m"
#define KRED  "\x1B[31m"
#define KGRN  "\x1B[32m"
#define KYEL  "\x1B[33m"
#define KBLU  "\x1B[34m"
#define KMAG  "\x1B[35m"
#define KCYN  "\x1B[36m"
#define KWHT  "\x1B[37m"

#define FRED(x) KRED x RST
#define FGRN(x) KGRN x RST
#define FYEL(x) KYEL x RST
#define FBLU(x) KBLU x RST
#define FMAG(x) KMAG x RST
#define FCYN(x) KCYN x RST
#define FWHT(x) KWHT x RST

#define BOLD(x) "\x1B[1m" x RST
#define UNDL(x) "\x1B[4m" x RST

#endif  /* _COLORS_ */

An example using the macros of the header could be:

#include <iostream>
#include "colors.h"
using namespace std;

int main()
{
    cout << FBLU("I'm blue.") << endl;
    cout << BOLD(FBLU("I'm blue-bold.")) << endl;
    return 0;
}

enter image description here

ASP.NET GridView RowIndex As CommandArgument

<asp:TemplateField HeaderText="" ItemStyle-Width="20%" HeaderStyle-HorizontalAlign="Center">
                    <ItemTemplate>
                        <asp:LinkButton runat="server" ID="lnkAdd" Text="Add" CommandName="Add" CommandArgument='<%# Eval("EmpID"))%>' />
                    </ItemTemplate>
                </asp:TemplateField>

This is the traditional way and latest version of asp.net framework having strongly typed data and you don't need to use as string like "EMPID"

Tkinter scrollbar for frame

Please note that the proposed code is only valid with Python 2

Here is an example:

from Tkinter import *   # from x import * is bad practice
from ttk import *

# http://tkinter.unpythonic.net/wiki/VerticalScrolledFrame

class VerticalScrolledFrame(Frame):
    """A pure Tkinter scrollable frame that actually works!
    * Use the 'interior' attribute to place widgets inside the scrollable frame
    * Construct and pack/place/grid normally
    * This frame only allows vertical scrolling

    """
    def __init__(self, parent, *args, **kw):
        Frame.__init__(self, parent, *args, **kw)            

        # create a canvas object and a vertical scrollbar for scrolling it
        vscrollbar = Scrollbar(self, orient=VERTICAL)
        vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
        canvas = Canvas(self, bd=0, highlightthickness=0,
                        yscrollcommand=vscrollbar.set)
        canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
        vscrollbar.config(command=canvas.yview)

        # reset the view
        canvas.xview_moveto(0)
        canvas.yview_moveto(0)

        # create a frame inside the canvas which will be scrolled with it
        self.interior = interior = Frame(canvas)
        interior_id = canvas.create_window(0, 0, window=interior,
                                           anchor=NW)

        # track changes to the canvas and frame width and sync them,
        # also updating the scrollbar
        def _configure_interior(event):
            # update the scrollbars to match the size of the inner frame
            size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
            canvas.config(scrollregion="0 0 %s %s" % size)
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the canvas's width to fit the inner frame
                canvas.config(width=interior.winfo_reqwidth())
        interior.bind('<Configure>', _configure_interior)

        def _configure_canvas(event):
            if interior.winfo_reqwidth() != canvas.winfo_width():
                # update the inner frame's width to fill the canvas
                canvas.itemconfigure(interior_id, width=canvas.winfo_width())
        canvas.bind('<Configure>', _configure_canvas)


if __name__ == "__main__":

    class SampleApp(Tk):
        def __init__(self, *args, **kwargs):
            root = Tk.__init__(self, *args, **kwargs)


            self.frame = VerticalScrolledFrame(root)
            self.frame.pack()
            self.label = Label(text="Shrink the window to activate the scrollbar.")
            self.label.pack()
            buttons = []
            for i in range(10):
                buttons.append(Button(self.frame.interior, text="Button " + str(i)))
                buttons[-1].pack()

    app = SampleApp()
    app.mainloop()

It does not yet have the mouse wheel bound to the scrollbar but it is possible. Scrolling with the wheel can get a bit bumpy, though.

edit:

to 1)
IMHO scrolling frames is somewhat tricky in Tkinter and does not seem to be done a lot. It seems there is no elegant way to do it.
One problem with your code is that you have to set the canvas size manually - that's what the example code I posted solves.

to 2)
You are talking about the data function? Place works for me, too. (In general I prefer grid).

to 3)
Well, it positions the window on the canvas.

One thing I noticed is that your example handles mouse wheel scrolling by default while the one I posted does not. Will have to look at that some time.

How to get input from user at runtime

SQL> DECLARE
  2     a integer;
  3     b integer;
  4  BEGIN
  5     a:=&a;
  6     b:=&b;
  7     dbms_output.put_line('The a value is : ' || a);
  8     dbms_output.put_line('The b value is : ' || b);
  9  END;
 10  /

java.io.IOException: Invalid Keystore format

go to build clean the project then rebuild your project it worked for me.

importing jar libraries into android-studio

Avoid redundancy. If you have your jars under /libs in your app build.gradle by default you will have

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    ...
}

that is enough to add all the jars you have under /libs

this is not necessary

//    compile files('libs/activation.jar')
//    compile files('libs/additional.jar')
//    compile files('libs/mail.jar')

Internet Explorer 11 detection

And how I implemented this

<script type="text/javascript">
  !(window.ActiveXObject) && "ActiveXObject"
  function isIE11(){
    return !!navigator.userAgent.match(/Trident.*rv[ :]*11\./);
  }
</script>

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

How to embed a video into GitHub README.md?

This is an old post but I was looking for an answer and I found this: https://gifs.com. Just upload the video, then it creates a gif we can add easily in a github markdown. I tried it, the quality of the gif is a good one.

How to get the selected item from ListView?

In touch mode, there is no focus and no selection. Your UI should use a different type of widget, such as radio buttons, for selection.

The documentation on ListView about this is terrible, just one obscure mention on setSelection.

How can I get a random number in Kotlin?

No need to use custom extension functions anymore. IntRange has a random() extension function out-of-the-box now.

val randomNumber = (0..10).random()

Return list using select new in LINQ

You can do it as following:

class ProjectInfo
{
    public string Name {get; set; }
    public long Id {get; set; }

    ProjectInfo(string n, long id)
    {
        name = n;   Id = id;
    }
}

public List<ProjectInfo> GetProjectForCombo()
{
    using (MyDataContext db = new MyDataContext (DBHelper.GetConnectionString()))
    {
         var query = from pro in db.Projects
                    select new ProjectInfo(pro.ProjectName,pro.ProjectId);

         return query.ToList<ProjectInfo>();
    }
}

What are Aggregates and PODs and how/why are they special?

What changes for C++11?

Aggregates

The standard definition of an aggregate has changed slightly, but it's still pretty much the same:

An aggregate is an array or a class (Clause 9) with no user-provided constructors (12.1), no brace-or-equal-initializers for non-static data members (9.2), no private or protected non-static data members (Clause 11), no base classes (Clause 10), and no virtual functions (10.3).

Ok, what changed?

  1. Previously, an aggregate could have no user-declared constructors, but now it can't have user-provided constructors. Is there a difference? Yes, there is, because now you can declare constructors and default them:

    struct Aggregate {
        Aggregate() = default; // asks the compiler to generate the default implementation
    };
    

    This is still an aggregate because a constructor (or any special member function) that is defaulted on the first declaration is not user-provided.

  2. Now an aggregate cannot have any brace-or-equal-initializers for non-static data members. What does this mean? Well, this is just because with this new standard, we can initialize members directly in the class like this:

    struct NotAggregate {
        int x = 5; // valid in C++11
        std::vector<int> s{1,2,3}; // also valid
    };
    

    Using this feature makes the class no longer an aggregate because it's basically equivalent to providing your own default constructor.

So, what is an aggregate didn't change much at all. It's still the same basic idea, adapted to the new features.

What about PODs?

PODs went through a lot of changes. Lots of previous rules about PODs were relaxed in this new standard, and the way the definition is provided in the standard was radically changed.

The idea of a POD is to capture basically two distinct properties:

  1. It supports static initialization, and
  2. Compiling a POD in C++ gives you the same memory layout as a struct compiled in C.

Because of this, the definition has been split into two distinct concepts: trivial classes and standard-layout classes, because these are more useful than POD. The standard now rarely uses the term POD, preferring the more specific trivial and standard-layout concepts.

The new definition basically says that a POD is a class that is both trivial and has standard-layout, and this property must hold recursively for all non-static data members:

A POD struct is a non-union class that is both a trivial class and a standard-layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). Similarly, a POD union is a union that is both a trivial class and a standard layout class, and has no non-static data members of type non-POD struct, non-POD union (or array of such types). A POD class is a class that is either a POD struct or a POD union.

Let's go over each of these two properties in detail separately.

Trivial classes

Trivial is the first property mentioned above: trivial classes support static initialization. If a class is trivially copyable (a superset of trivial classes), it is ok to copy its representation over the place with things like memcpy and expect the result to be the same.

The standard defines a trivial class as follows:

A trivially copyable class is a class that:

— has no non-trivial copy constructors (12.8),

— has no non-trivial move constructors (12.8),

— has no non-trivial copy assignment operators (13.5.3, 12.8),

— has no non-trivial move assignment operators (13.5.3, 12.8), and

— has a trivial destructor (12.4).

A trivial class is a class that has a trivial default constructor (12.1) and is trivially copyable.

[ Note: In particular, a trivially copyable or trivial class does not have virtual functions or virtual base classes.—end note ]

So, what are all those trivial and non-trivial things?

A copy/move constructor for class X is trivial if it is not user-provided and if

— class X has no virtual functions (10.3) and no virtual base classes (10.1), and

— the constructor selected to copy/move each direct base class subobject is trivial, and

— for each non-static data member of X that is of class type (or array thereof), the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.

Basically this means that a copy or move constructor is trivial if it is not user-provided, the class has nothing virtual in it, and this property holds recursively for all the members of the class and for the base class.

The definition of a trivial copy/move assignment operator is very similar, simply replacing the word "constructor" with "assignment operator".

A trivial destructor also has a similar definition, with the added constraint that it can't be virtual.

And yet another similar rule exists for trivial default constructors, with the addition that a default constructor is not-trivial if the class has non-static data members with brace-or-equal-initializers, which we've seen above.

Here are some examples to clear everything up:

// empty classes are trivial
struct Trivial1 {};

// all special members are implicit
struct Trivial2 {
    int x;
};

struct Trivial3 : Trivial2 { // base class is trivial
    Trivial3() = default; // not a user-provided ctor
    int y;
};

struct Trivial4 {
public:
    int a;
private: // no restrictions on access modifiers
    int b;
};

struct Trivial5 {
    Trivial1 a;
    Trivial2 b;
    Trivial3 c;
    Trivial4 d;
};

struct Trivial6 {
    Trivial2 a[23];
};

struct Trivial7 {
    Trivial6 c;
    void f(); // it's okay to have non-virtual functions
};

struct Trivial8 {
     int x;
     static NonTrivial1 y; // no restrictions on static members
};

struct Trivial9 {
     Trivial9() = default; // not user-provided
      // a regular constructor is okay because we still have default ctor
     Trivial9(int x) : x(x) {};
     int x;
};

struct NonTrivial1 : Trivial3 {
    virtual void f(); // virtual members make non-trivial ctors
};

struct NonTrivial2 {
    NonTrivial2() : z(42) {} // user-provided ctor
    int z;
};

struct NonTrivial3 {
    NonTrivial3(); // user-provided ctor
    int w;
};
NonTrivial3::NonTrivial3() = default; // defaulted but not on first declaration
                                      // still counts as user-provided
struct NonTrivial5 {
    virtual ~NonTrivial5(); // virtual destructors are not trivial
};

Standard-layout

Standard-layout is the second property. The standard mentions that these are useful for communicating with other languages, and that's because a standard-layout class has the same memory layout of the equivalent C struct or union.

This is another property that must hold recursively for members and all base classes. And as usual, no virtual functions or virtual base classes are allowed. That would make the layout incompatible with C.

A relaxed rule here is that standard-layout classes must have all non-static data members with the same access control. Previously these had to be all public, but now you can make them private or protected, as long as they are all private or all protected.

When using inheritance, only one class in the whole inheritance tree can have non-static data members, and the first non-static data member cannot be of a base class type (this could break aliasing rules), otherwise, it's not a standard-layout class.

This is how the definition goes in the standard text:

A standard-layout class is a class that:

— has no non-static data members of type non-standard-layout class (or array of such types) or reference,

— has no virtual functions (10.3) and no virtual base classes (10.1),

— has the same access control (Clause 11) for all non-static data members,

— has no non-standard-layout base classes,

— either has no non-static data members in the most derived class and at most one base class with non-static data members, or has no base classes with non-static data members, and

— has no base classes of the same type as the first non-static data member.

A standard-layout struct is a standard-layout class defined with the class-key struct or the class-key class.

A standard-layout union is a standard-layout class defined with the class-key union.

[ Note: Standard-layout classes are useful for communicating with code written in other programming languages. Their layout is specified in 9.2.—end note ]

And let's see a few examples.

// empty classes have standard-layout
struct StandardLayout1 {};

struct StandardLayout2 {
    int x;
};

struct StandardLayout3 {
private: // both are private, so it's ok
    int x;
    int y;
};

struct StandardLayout4 : StandardLayout1 {
    int x;
    int y;

    void f(); // perfectly fine to have non-virtual functions
};

struct StandardLayout5 : StandardLayout1 {
    int x;
    StandardLayout1 y; // can have members of base type if they're not the first
};

struct StandardLayout6 : StandardLayout1, StandardLayout5 {
    // can use multiple inheritance as long only
    // one class in the hierarchy has non-static data members
};

struct StandardLayout7 {
    int x;
    int y;
    StandardLayout7(int x, int y) : x(x), y(y) {} // user-provided ctors are ok
};

struct StandardLayout8 {
public:
    StandardLayout8(int x) : x(x) {} // user-provided ctors are ok
// ok to have non-static data members and other members with different access
private:
    int x;
};

struct StandardLayout9 {
    int x;
    static NonStandardLayout1 y; // no restrictions on static members
};

struct NonStandardLayout1 {
    virtual f(); // cannot have virtual functions
};

struct NonStandardLayout2 {
    NonStandardLayout1 X; // has non-standard-layout member
};

struct NonStandardLayout3 : StandardLayout1 {
    StandardLayout1 x; // first member cannot be of the same type as base
};

struct NonStandardLayout4 : StandardLayout3 {
    int z; // more than one class has non-static data members
};

struct NonStandardLayout5 : NonStandardLayout3 {}; // has a non-standard-layout base class

Conclusion

With these new rules a lot more types can be PODs now. And even if a type is not POD, we can take advantage of some of the POD properties separately (if it is only one of trivial or standard-layout).

The standard library has traits to test these properties in the header <type_traits>:

template <typename T>
struct std::is_pod;
template <typename T>
struct std::is_trivial;
template <typename T>
struct std::is_trivially_copyable;
template <typename T>
struct std::is_standard_layout;

Is there a replacement for unistd.h for Windows (Visual C)?

I would recommend using mingw/msys as a development environment. Especially if you are porting simple console programs. Msys implements a Unix-like shell on Windows, and mingw is a port of the GNU compiler collection (GCC) and other GNU build tools to the Windows platform. It is an open-source project, and well-suited to the task. I currently use it to build utility programs and console applications for Windows XP, and it most certainly has that unistd.h header you are looking for.

The install procedure can be a little bit tricky, but I found that the best place to start is in MSYS.

Execute ssh with password authentication via windows command prompt

What about this expect script?

#!/usr/bin/expect -f
spawn ssh root@myhost
expect -exact "root@myhost's password: "
send -- "mypassword\r"
interact

How to write specific CSS for mozilla, chrome and IE

Check out this link : http://webdesignerwall.com/tutorials/css-specific-for-internet-explorer

2 CSS Rules Specific to Explorer (IE CSS hacks)

Another option is to declare CSS rules that can only be read by Explorer. For example, add an asterisk (*) before the CSS property will target IE7 or add an underscore before the property will target IE6. However, this method is not recommended because they are not valid CSS syntax.

IE8 or below: to write CSS rules specificially to IE8 or below, add a backslash and 9 (\9) at the end before the semicolon. IE7 or below: add an asterisk (*) before the CSS property. IE6: add an underscore (_) before the property. .box {

background: gray; /* standard */

background: pink\9; /* IE 8 and below */

*background: green; /* IE 7 and below */

_background: blue; /* IE 6 */

}

HTML CSS Invisible Button

HTML

<input type="button">

CSS

input[type=button]{
 background:transparent;
 border:0;
}

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

What is the preferred Bash shebang?

I recommend using:

#!/bin/bash

It's not 100% portable (some systems place bash in a location other than /bin), but the fact that a lot of existing scripts use #!/bin/bash pressures various operating systems to make /bin/bash at least a symlink to the main location.

The alternative of:

#!/usr/bin/env bash

has been suggested -- but there's no guarantee that the env command is in /usr/bin (and I've used systems where it isn't). Furthermore, this form will use the first instance of bash in the current users $PATH, which might not be a suitable version of the bash shell.

(But /usr/bin/env should work on any reasonably modern system, either because env is in /usr/bin or because the system does something to make it work. The system I referred to above was SunOS 4, which I probably haven't used in about 25 years.)

If you need a script to run on a system that doesn't have /bin/bash, you can modify the script to point to the correct location (that's admittedly inconvenient).

I've discussed the tradeoffs in greater depth in my answer to this question.

A somewhat obscure update: One system I use, Termux, a desktop-Linux-like layer that runs under Android, doesn't have /bin/bash (bash is /data/data/com.termux/files/usr/bin/bash) -- but it has special handling to support #!/bin/bash.

Is it possible to program Android to act as physical USB keyboard?

Your Android already identifies with a VID/PID when plugged into a host. It already has an interface for Mass Storage. You would need to hack the driver at a low level to support a 2nd interface for 03:01 HID. Then it would just be a question of pushing scancodes to the modified driver. This wouldn't be simple, but it would be a neat hack. One use would be for typing long random passwords for logins.

How to generate a random string of a fixed length in Go?

Here is a simple and performant solution for a cryptographically secure random string.

package main

import (
    "crypto/rand"
    "unsafe"
    "fmt"
)

var alphabet = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")

func main() {
    fmt.Println(generate(16))
}

func generate(size int) string {
    b := make([]byte, size)
    rand.Read(b)
    for i := 0; i < size; i++ {
        b[i] = alphabet[b[i] / 5]
    }
    return *(*string)(unsafe.Pointer(&b))
}

Benchmark

Benchmark  95.2 ns/op      16 B/op      1 allocs/op

Is it possible to put a ConstraintLayout inside a ScrollView?

Try giving some padding bottom to your constraint layout like below

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/top"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="100dp">
        </android.support.constraint.ConstraintLayout>

    </ScrollView>

convert UIImage to NSData

If you have an image inside a UIImageView , e.g. "myImageView", you can do the following:

Convert your image using UIImageJPEGRepresentation() or UIImagePNGRepresentation() like this:

NSData *data = UIImagePNGRepresentation(myImageView.image);
//or
NSData *data = UIImageJPEGRepresentation(myImageView.image, 0.8);
//The float param (0.8 in this example) is the compression quality 
//expressed as a value from 0.0 to 1.0, where 1.0 represents 
//the least compression (or best quality).

You can also put this code inside a GCD block and execute in another thread, showing an UIActivityIndicatorView during the process ...

//*code to show a loading view here*

dispatch_queue_t myQueue = dispatch_queue_create("com.my.queue", DISPATCH_QUEUE_SERIAL);

dispatch_async(myQueue, ^{ 

    NSData *data = UIImagePNGRepresentation(myImageView.image);
    //some code....

    dispatch_async( dispatch_get_main_queue(), ^{
        //*code to hide the loading view here*
    });
});

numbers not allowed (0-9) - Regex Expression in javascript

Like this: ^[^0-9]+$

Explanation:

  • ^ matches the beginning of the string
  • [^...] matches anything that isn't inside
  • 0-9 means any character between 0 and 9
  • + matches one or more of the previous thing
  • $ matches the end of the string

Convert HashBytes to VarChar

convert(varchar(34), HASHBYTES('MD5','Hello World'),1)

(1 for converting hexadecimal to string)

convert this to lower and remove 0x from the start of the string by substring:

substring(lower(convert(varchar(34), HASHBYTES('MD5','Hello World'),1)),3,32)

exactly the same as what we get in C# after converting bytes to string

how to rename an index in a cluster?

Another different way to achieve the renaming or change the mappings for an index is to reindex using logstash. Here is a sample of the logstash 2.1 configuration:

input {
  elasticsearch {
   hosts => ["es01.example.com", "es02.example.com"]
   index => "old-index-name"
   size => 500
   scroll => "5m"
  }
}
filter {

 mutate {
  remove_field => [ "@version" ]
 }

 date {
   "match" => [ "custom_timestamp", "MM/dd/YYYY HH:mm:ss" ]
   target => "@timestamp"
 }

}
output {
 elasticsearch {
   hosts => ["es01.example.com", "es02.example.com" ]
   manage_template => false
   index => "new-index-name"
 }
}

How does python numpy.where() work?

np.where returns a tuple of length equal to the dimension of the numpy ndarray on which it is called (in other words ndim) and each item of tuple is a numpy ndarray of indices of all those values in the initial ndarray for which the condition is True. (Please don't confuse dimension with shape)

For example:

x=np.arange(9).reshape(3,3)
print(x)
array([[0, 1, 2],
      [3, 4, 5],
      [6, 7, 8]])
y = np.where(x>4)
print(y)
array([1, 2, 2, 2], dtype=int64), array([2, 0, 1, 2], dtype=int64))


y is a tuple of length 2 because x.ndim is 2. The 1st item in tuple contains row numbers of all elements greater than 4 and the 2nd item contains column numbers of all items greater than 4. As you can see, [1,2,2,2] corresponds to row numbers of 5,6,7,8 and [2,0,1,2] corresponds to column numbers of 5,6,7,8 Note that the ndarray is traversed along first dimension(row-wise).

Similarly,

x=np.arange(27).reshape(3,3,3)
np.where(x>4)


will return a tuple of length 3 because x has 3 dimensions.

But wait, there's more to np.where!

when two additional arguments are added to np.where; it will do a replace operation for all those pairwise row-column combinations which are obtained by the above tuple.

x=np.arange(9).reshape(3,3)
y = np.where(x>4, 1, 0)
print(y)
array([[0, 0, 0],
   [0, 0, 1],
   [1, 1, 1]])

How does internationalization work in JavaScript?

You can also try another library - https://github.com/wikimedia/jquery.i18n .

In addition to parameter replacement and multiple plural forms, it has support for gender a rather unique feature of custom grammar rules that some languages need.

How to get file name when user select a file via <input type="file" />?

I'll answer this question via Simple Javascript that is supported in all browsers that I have tested so far (IE8 to IE11, Chrome, FF etc).

Here is the code.

_x000D_
_x000D_
function GetFileSizeNameAndType()_x000D_
        {_x000D_
        var fi = document.getElementById('file'); // GET THE FILE INPUT AS VARIABLE._x000D_
_x000D_
        var totalFileSize = 0;_x000D_
_x000D_
        // VALIDATE OR CHECK IF ANY FILE IS SELECTED._x000D_
        if (fi.files.length > 0)_x000D_
        {_x000D_
            // RUN A LOOP TO CHECK EACH SELECTED FILE._x000D_
            for (var i = 0; i <= fi.files.length - 1; i++)_x000D_
            {_x000D_
                //ACCESS THE SIZE PROPERTY OF THE ITEM OBJECT IN FILES COLLECTION. IN THIS WAY ALSO GET OTHER PROPERTIES LIKE FILENAME AND FILETYPE_x000D_
                var fsize = fi.files.item(i).size;_x000D_
                totalFileSize = totalFileSize + fsize;_x000D_
                document.getElementById('fp').innerHTML =_x000D_
                document.getElementById('fp').innerHTML_x000D_
                +_x000D_
                '<br /> ' + 'File Name is <b>' + fi.files.item(i).name_x000D_
                +_x000D_
                '</b> and Size is <b>' + Math.round((fsize / 1024)) //DEFAULT SIZE IS IN BYTES SO WE DIVIDING BY 1024 TO CONVERT IT IN KB_x000D_
                +_x000D_
                '</b> KB and File Type is <b>' + fi.files.item(i).type + "</b>.";_x000D_
            }_x000D_
        }_x000D_
        document.getElementById('divTotalSize').innerHTML = "Total File(s) Size is <b>" + Math.round(totalFileSize / 1024) + "</b> KB";_x000D_
    }
_x000D_
    <p>_x000D_
        <input type="file" id="file" multiple onchange="GetFileSizeNameAndType()" />_x000D_
    </p>_x000D_
_x000D_
    <div id="fp"></div>_x000D_
    <p>_x000D_
        <div id="divTotalSize"></div>_x000D_
    </p>
_x000D_
_x000D_
_x000D_

*Please note that we are displaying filesize in KB (Kilobytes). To get in MB divide it by 1024 * 1024 and so on*.

It'll perform file outputs like these on selecting Snapshot of a sample output of this code

Update index after sorting data-frame

df.sort() is deprecated, use df.sort_values(...): https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.sort_values.html

Then follow joris' answer by doing df.reset_index(drop=True)

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

How to check if an excel cell is empty using Apache POI?

There is one other option also .

row=(Row) sheet.getRow(i);
        if (row == null || isEmptyRow(row)) {
            return;
        }
Iterator<Cell> cells = row.cellIterator();
    while (cells.hasNext())
     {}

bundle install returns "Could not locate Gemfile"

You may also indicate the path to the gemfile in the same command e.g.

BUNDLE_GEMFILE="MyProject/Gemfile.ios" bundle install

INSERT INTO ... SELECT FROM ... ON DUPLICATE KEY UPDATE

Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT query with GROUP BY clause, I came up with the work around for this.

Taking further the answer of Marcus Adams and accounting GROUP BY in it, this is how I would solve the problem by using Subqueries in the FROM Clause

INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct, 
                inact, inadur, inadist, 
                smlct, smldur, smldist, 
                larct, lardur, lardist, 
                emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct, 
       sb.inact, sb.inadur, sb.inadist, 
       sb.smlct, sb.smldur, sb.smldist, 
       sb.larct, sb.lardur, sb.lardist, 
       sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct, 
       inact, inadur, inadist, 
       smlct, smldur, smldist, 
       larct, lardur, lardist, 
       emptyct, emptydur 
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...

What's the key difference between HTML 4 and HTML 5?

HTML5 has several goals which differentiate it from HTML4.

Consistency in Handling Malformed Documents

The primary one is consistent, defined error handling. As you know, HTML purposely supports 'tag soup', or the ability to write malformed code and have it corrected into a valid document. The problem is that the rules for doing this aren't written down anywhere. When a new browser vendor wants to enter the market, they just have to test malformed documents in various browsers (especially IE) and reverse-engineer their error handling. If they don't, then many pages won't display correctly (estimates place roughly 90% of pages on the net as being at least somewhat malformed).

So, HTML5 is attempting to discover and codify this error handling, so that browser developers can all standardize and greatly reduce the time and money required to display things consistently. As well, long in the future after HTML has died as a document format, historians may still want to read our documents, and having a completely defined parsing algorithm will greatly aid this.

Better Web Application Features

The secondary goal of HTML5 is to develop the ability of the browser to be an application platform, via HTML, CSS, and Javascript. Many elements have been added directly to the language that are currently (in HTML4) Flash or JS-based hacks, such as <canvas>, <video>, and <audio>. Useful things such as Local Storage (a js-accessible browser-built-in key-value database, for storing information beyond what cookies can hold), new input types such as date for which the browser can expose easy user interface (so that we don't have to use our js-based calendar date-pickers), and browser-supported form validation will make developing web applications much simpler for the developers, and make them much faster for the users (since many things will be supported natively, rather than hacked in via javascript).

Improved Element Semantics

There are many other smaller efforts taking place in HTML5, such as better-defined semantic roles for existing elements (<strong> and <em> now actually mean something different, and even <b> and <i> have vague semantics that should work well when parsing legacy documents) and adding new elements with useful semantics - <article>, <section>, <header>, <aside>, and <nav> should replace the majority of <div>s used on a web page, making your pages a bit more semantic, but more importantly, easier to read. No more painful scanning to see just what that random </div> is closing - instead you'll have an obvious </header>, or </article>, making the structure of your document much more intuitive.

Write string to output stream

By design it is to be done this way:

OutputStream out = ...;
try (Writer w = new OutputStreamWriter(out, "UTF-8")) {
    w.write("Hello, World!");
} // or w.close(); //close will auto-flush

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

I had the same problem, and non of the answers here helped my case. So after several hours of searching I found the solution for me and I hope it'll help somebody else.

This is a solution for anyone who gets the "Server Tomcat v7.0 Server at localhost failed to start." error after configuring the tomcat server in eclipse and trying to run a project on it.

After configuring the tomcat server in eclipse you need to copy the "WEB-INF" directory from your tomcat. C:\ ... %TOMCAT_HOME%\webapps\ROOT and their you will find the "WEB-INF" just copy and paste it in your WebContent folder in you eclipse project (overwrite the web.xml file).

Hope this helps.

How do I run SSH commands on remote system using Java?

Below is the easiest way to SSh in java. Download any of the file in the below link and extract, then add the jar file from the extracted file and add to your build path of the project http://www.ganymed.ethz.ch/ssh2/ and use the below method

public void SSHClient(String serverIp,String command, String usernameString,String password) throws IOException{
        System.out.println("inside the ssh function");
        try
        {
            Connection conn = new Connection(serverIp);
            conn.connect();
            boolean isAuthenticated = conn.authenticateWithPassword(usernameString, password);
            if (isAuthenticated == false)
                throw new IOException("Authentication failed.");        
            ch.ethz.ssh2.Session sess = conn.openSession();
            sess.execCommand(command);  
            InputStream stdout = new StreamGobbler(sess.getStdout());
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout));
            System.out.println("the output of the command is");
            while (true)
            {
                String line = br.readLine();
                if (line == null)
                    break;
                System.out.println(line);
            }
            System.out.println("ExitCode: " + sess.getExitStatus());
            sess.close();
            conn.close();
        }
        catch (IOException e)
        {
            e.printStackTrace(System.err);

        }
    }

Why can't I do <img src="C:/localfile.jpg">?

starts with file:/// and ends with filename should work:

<img src="file:///C:/Users/91860/Desktop/snow.jpg" alt="Snow" style="width:100%;">

getting only name of the class Class.getName()

You can use following simple technique for print log with class name.

private String TAG = MainActivity.class.getSimpleName();

Suppose we have to check coming variable value in method then we can use log like bellow :

private void printVariable(){
Log.e(TAG, "printVariable: ");
}

Importance of this line is that, we can check method name along with class name. To write this type of log.

write :- loge and Enter.

will print on console

E/MainActivity: printVariable:

How to trigger a click on a link using jQuery

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

C# get and set properties for a List Collection

If I understand your request correctly, you have to do the following:

public class Section 
{ 
    public String Head
    {
        get
        {
            return SubHead.LastOrDefault();
        }
        set
        {
            SubHead.Add(value);
        }

    public List<string> SubHead { get; private set; }
    public List<string> Content { get; private set; }
} 

You use it like this:

var section = new Section();
section.Head = "Test string";

Now "Test string" is added to the subHeads collection and will be available through the getter:

var last = section.Head; // last will be "Test string"

Hope I understood you correctly.

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

Xampp Access Forbidden php

Try with this code below, add it in your virtual host config. Add this lines to httpd-vhosts.conf file:

<Directory "c:/<path-to-projects>/">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride all
        Order Deny,Allow
        Allow from all
        Require all granted
</Directory>

I fixed the same issue by this way. Hope it helps.

Note:

after changes please test it in incognito because you redirected by cache

REST API - Bulk Create or Update in single request

I think that you could use a POST or PATCH method to handle this since they typically design for this.

  • Using a POST method is typically used to add an element when used on list resource but you can also support several actions for this method. See this answer: How to Update a REST Resource Collection. You can also support different representation formats for the input (if they correspond to an array or a single elements).

    In the case, it's not necessary to define your format to describe the update.

  • Using a PATCH method is also suitable since corresponding requests correspond to a partial update. According to RFC5789 (http://tools.ietf.org/html/rfc5789):

    Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

    In the case, you have to define your format to describe the partial update.

I think that in this case, POST and PATCH are quite similar since you don't really need to describe the operation to do for each element. I would say that it depends on the format of the representation to send.

The case of PUT is a bit less clear. In fact, when using a method PUT, you should provide the whole list. As a matter of fact, the provided representation in the request will be in replacement of the list resource one.

You can have two options regarding the resource paths.

  • Using the resource path for doc list

In this case, you need to explicitely provide the link of docs with a binder in the representation you provide in the request.

Here is a sample route for this /docs.

The content of such approach could be for method POST:

[
    { "doc_number": 1, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 2, "binder": 4, (other fields in the case of creation) },
    { "doc_number": 3, "binder": 5, (other fields in the case of creation) },
    (...)
]
  • Using sub resource path of binder element

In addition you could also consider to leverage sub routes to describe the link between docs and binders. The hints regarding the association between a doc and a binder doesn't have now to be specified within the request content.

Here is a sample route for this /binder/{binderId}/docs. In this case, sending a list of docs with a method POST or PATCH will attach docs to the binder with identifier binderId after having created the doc if it doesn't exist.

The content of such approach could be for method POST:

[
    { "doc_number": 1, (other fields in the case of creation) },
    { "doc_number": 2, (other fields in the case of creation) },
    { "doc_number": 3, (other fields in the case of creation) },
    (...)
]

Regarding the response, it's up to you to define the level of response and the errors to return. I see two levels: the status level (global level) and the payload level (thinner level). It's also up to you to define if all the inserts / updates corresponding to your request must be atomic or not.

  • Atomic

In this case, you can leverage the HTTP status. If everything goes well, you get a status 200. If not, another status like 400 if the provided data aren't correct (for example binder id not valid) or something else.

  • Non atomic

In this case, a status 200 will be returned and it's up to the response representation to describe what was done and where errors eventually occur. ElasticSearch has an endpoint in its REST API for bulk update. This could give you some ideas at this level: http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/bulk.html.

  • Asynchronous

You can also implement an asynchronous processing to handle the provided data. In this case, the HTTP status returns will be 202. The client needs to pull an additional resource to see what happens.

Before finishing, I also would want to notice that the OData specification addresses the issue regarding relations between entities with the feature named navigation links. Perhaps could you have a look at this ;-)

The following link can also help you: https://templth.wordpress.com/2014/12/15/designing-a-web-api/.

Hope it helps you, Thierry

Fixed point vs Floating point number

From my understanding, fixed-point arithmetic is done using integers. where the decimal part is stored in a fixed amount of bits, or the number is multiplied by how many digits of decimal precision is needed.

For example, If the number 12.34 needs to be stored and we only need two digits of precision after the decimal point, the number is multiplied by 100 to get 1234. When performing math on this number, we'd use this rule set. Adding 5620 or 56.20 to this number would yield 6854 in data or 68.54.

If we want to calculate the decimal part of a fixed-point number, we use the modulo (%) operand.

12.34 (pseudocode):

v1 = 1234 / 100 // get the whole number
v2 = 1234 % 100 // get the decimal number (100ths of a whole).
print v1 + "." + v2 // "12.34"

Floating point numbers are a completely different story in programming. The current standard for floating point numbers use something like 23 bits for the data of the number, 8 bits for the exponent, and 1 but for sign. See this Wikipedia link for more information on this.

send bold & italic text on telegram bot with html

For JS:

First, if you haven't installed telegram bot just install with the command

npm i messaging-api-telegram

Now, initialize its client with

const client = new TelegramClient({
    accessToken: process.env.<TELEGRAM_ACCESS_TOKEN>
});

Then, to send message use sendMessage() async function like below -

    const resp = await client.sendMessage(chatId, msg, {
        disableWebPagePreview: false,
        disableNotification: false,
        parseMode: "HTML"
    });

Here parse mode by default would be plain text but with parseOptions parseMode we can do 1. "HTML" and "MARKDOWN" to let use send messages in stylish way. Also get your access token of bot from telegram page and chatId or group chat Id from same.

How to connect to local instance of SQL Server 2008 Express

Please check the ServerName which you provided. It should match with the below shown Name in the UserName textbox, and that name should followed with \SQLEXPRESS:

Connect dialog

Pandas count(distinct) equivalent

Using crosstab, this will return more information than groupby nunique

pd.crosstab(df.YEARMONTH,df.CLIENTCODE)
Out[196]: 
CLIENTCODE  1  2  3
YEARMONTH          
201301      2  1  0
201302      1  2  1

After a little bit modify ,yield the result

pd.crosstab(df.YEARMONTH,df.CLIENTCODE).ne(0).sum(1)
Out[197]: 
YEARMONTH
201301    2
201302    3
dtype: int64

How to query DATETIME field using only date in Microsoft SQL Server?

select *
  from invoice
 where TRUNC(created_date) <=TRUNC(to_date('04-MAR-18 15:00:00','dd-mon-yy hh24:mi:ss'));

jQuery: Load Modal Dialog Contents via Ajax

$(function ()    {
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('Sample.htm');
        },         
        height: 400,
        width: 400,
        title: 'Dynamically Loaded Page'
    });
});

http://www.devcurry.com/2010/06/load-page-dynamically-inside-jquery-ui.html

Run a PostgreSQL .sql file using command line arguments

You can give both user name and PASSSWORD on the command line itself.

   psql "dbname='urDbName' user='yourUserName' password='yourPasswd' host='yourHost'" -f yourFileName.sql

How to print to console in pytest?

According to the pytest docs, pytest --capture=sys should work. If you want to capture standard out inside a test, refer to the capsys fixture.

passing JSON data to a Spring MVC controller

You can stringify the JSON Object with JSON.stringify(jsonObject) and receive it on controller as String.

In the Controller, you can use the javax.json to convert and manipulate this.

Download and add the .jar to the project libs and import the JsonObject.

To create an json object, you can use

JsonObjectBuilder job = Json.createObjectBuilder();
job.add("header1", foo1);
job.add("header2", foo2);
JsonObject json = job.build();

To read it from String, you can use

JsonReader jr = Json.createReader(new StringReader(jsonString));
JsonObject json = jsonReader.readObject();
jsonReader.close();

How can I get the actual video URL of a YouTube live stream?

You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk

First, get the formats of the video:

?  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
137          mp4        1920x1080  DASH video 4347k , avc1.640028, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k
96           mp4        1080p      HLS , h264, aac  @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam

In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL:

?  ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8

These are your HLS m3u8 playlists, one for each camera associated with the live stream.

Without youtube-dl, your flow might look like this:

Take your video id and make a GET request to the get_video_info endpoint:

HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en

In the response, the hlsvp value will be the link to the m3u8 HLS playlist:

https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8

Installing Java 7 on Ubuntu

Oracle Java 1.7.0 from .deb packages

wget https://raw.github.com/flexiondotorg/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

Workaround for 1.7.0_51

There is an Issue 123 currently in OAB and a pull request

Here is the patched vesion:

wget https://raw.github.com/ladios/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

Create a temporary table in MySQL with an index from a select

Did find the answer on my own. My problem was, that i use two temporary tables for a join and create the second one out of the first one. But the Index was not copied during creation...

CREATE TEMPORARY TABLE tmpLivecheck (tmpid INTEGER NOT NULL AUTO_INCREMENT, PRIMARY    
KEY(tmpid), INDEX(tmpid))
SELECT * FROM tblLivecheck_copy WHERE tblLivecheck_copy.devId = did;

CREATE TEMPORARY TABLE tmpLiveCheck2 (tmpid INTEGER NOT NULL, PRIMARY KEY(tmpid), 
INDEX(tmpid))  
SELECT * FROM tmpLivecheck;

... solved my problem.

Greetings...

Add empty columns to a dataframe with specified names from a vector

Maybe

df <- do.call("cbind", list(df, rep(list(NA),length(namevector))))
colnames(df)[-1*(1:(ncol(df) - length(namevector)))] <- namevector

How to use border with Bootstrap

As of Bootstrap 3, you can use Panel classes:

<div class="panel panel-default">Surrounded by border</div>

In Bootstrap 4, you can use Border classes:

<div class="border border-secondary">Surrounded by border</div>

How do I check (at runtime) if one class is a subclass of another?

According to the Python doc, we can also use class.__mro__ attribute or class.mro() method:

class Suit:
    pass
class Heart(Suit):
    pass
class Spade(Suit):
    pass
class Diamond(Suit):
    pass
class Club(Suit):
    pass

>>> Heart.mro()
[<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>]
>>> Heart.__mro__
(<class '__main__.Heart'>, <class '__main__.Suit'>, <class 'object'>)

Suit in Heart.mro()  # True
object in Heart.__mro__  # True
Spade in Heart.mro()  # False

How to make div background color transparent in CSS

    /*Fully Opaque*/
    .class-name {
      opacity:1.0;
    }

    /*Translucent*/
    .class-name {
      opacity:0.5;
    }

    /*Transparent*/
    .class-name {
      opacity:0;
    }

    /*or you can use a transparent rgba value like this*/
    .class-name{
      background-color: rgba(255, 242, 0, 0.7);
      }

    /*Note - Opacity value can be anything between 0 to 1;
    Eg(0.1,0.8)etc */

How to copy file from host to container using Dockerfile

I was able to copy a file from my host to the container within a dockerfile as such:

  1. Created a folder on my c driver --> c:\docker
  2. Create a test file in the same folder --> c:\docker\test.txt
  3. Create a docker file in the same folder --> c:\docker\dockerfile
  4. The contents of the docker file as follows,to copy a file from local host to the root of the container: FROM ubuntu:16.04

    COPY test.txt /

  5. Pull a copy of ubuntu from docker hub --> docker pull ubuntu:16.04
  6. Build the image from the dockerfile --> docker build -t myubuntu c:\docker\
  7. Build the container from your new image myubuntu --> docker run -d -it --name myubuntucontainer myubuntu "/sbin/init"
  8. Connect to the newly created container -->docker exec -it myubuntucontainer bash
  9. Check if the text.txt file is in the root --> ls

You should see the file.

How can I open a website in my web browser using Python?

I think it should be

import webbrowser

webbrowser.open('http://gatedin.com')

NOTE: make sure that you give http or https

if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE. here you are importing webbrowser library

Programmatically extract contents of InstallShield setup.exe

On Linux there is unshield, which worked well for me (even if the GUI includes custom deterrents like license key prompts). It is included in the repositories of all major distributions (arch, suse, debian- and fedora-based) and its source is available at https://github.com/twogood/unshield

How to export data as CSV format from SQL Server using sqlcmd?

With PowerShell you can solve the problem neatly by piping Invoke-Sqlcmd into Export-Csv.

#Requires -Module SqlServer
Invoke-Sqlcmd -Query "SELECT * FROM DimDate;" `
              -Database AdventureWorksDW2012 `
              -Server localhost |
Export-Csv -NoTypeInformation `
           -Path "DimDate.csv" `
           -Encoding UTF8

SQL Server 2016 includes the SqlServer module, which contains the Invoke-Sqlcmd cmdlet, which you'll have even if you just install SSMS 2016. Prior to that, SQL Server 2012 included the old SQLPS module, which would change the current directory to SQLSERVER:\ when the module was first used (among other bugs) so for it, you'll need to change the #Requires line above to:

Push-Location $PWD
Import-Module -Name SQLPS
# dummy query to catch initial surprise directory change
Invoke-Sqlcmd -Query "SELECT 1" `
              -Database  AdventureWorksDW2012 `
              -Server localhost |Out-Null
Pop-Location
# actual Invoke-Sqlcmd |Export-Csv pipeline

To adapt the example for SQL Server 2008 and 2008 R2, remove the #Requires line entirely and use the sqlps.exe utility instead of the standard PowerShell host.

Invoke-Sqlcmd is the PowerShell equivalent of sqlcmd.exe. Instead of text it outputs System.Data.DataRow objects.

The -Query parameter works like the -Q parameter of sqlcmd.exe. Pass it a SQL query that describes the data you want to export.

The -Database parameter works like the -d parameter of sqlcmd.exe. Pass it the name of the database that contains the data to be exported.

The -Server parameter works like the -S parameter of sqlcmd.exe. Pass it the name of the server that contains the data to be exported.

Export-CSV is a PowerShell cmdlet that serializes generic objects to CSV. It ships with PowerShell.

The -NoTypeInformation parameter suppresses extra output that is not part of the CSV format. By default the cmdlet writes a header with type information. It lets you know the type of the object when you deserialize it later with Import-Csv, but it confuses tools that expect standard CSV.

The -Path parameter works like the -o parameter of sqlcmd.exe. A full path for this value is safest if you are stuck using the old SQLPS module.

The -Encoding parameter works like the -f or -u parameters of sqlcmd.exe. By default Export-Csv outputs only ASCII characters and replaces all others with question marks. Use UTF8 instead to preserve all characters and stay compatible with most other tools.

The main advantage of this solution over sqlcmd.exe or bcp.exe is that you don't have to hack the command to output valid CSV. The Export-Csv cmdlet handles it all for you.

The main disadvantage is that Invoke-Sqlcmd reads the whole result set before passing it along the pipeline. Make sure you have enough memory for the whole result set you want to export.

It may not work smoothly for billions of rows. If that's a problem, you could try the other tools, or roll your own efficient version of Invoke-Sqlcmd using System.Data.SqlClient.SqlDataReader class.

SyntaxError: Unexpected token o in JSON at position 1

Give a try catch like this, this will parse it if its stringified or else will take the default value

let example;
   try {
   example  = JSON.parse(data)
  } catch(e) {
    example = data
  }

Adding a stylesheet to asp.net (using Visual Studio 2010)

The only thing you have to do is to add in the cshtml file, in the head, the following line:

        @Styles.Render("~/Content/Main.css")

The entire head will look somethink like that:

    <head>
         <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
         <title>HTML Page</title>
         @Styles.Render("~/Content/main.css")
    </head>

Hope it helps!!

How to retrieve JSON Data Array from ExtJS Store

In my case I wanted a javascript jagged array e.g. [["row1Cell1", "row1cell2"],["row2Cell1", "row2cell2"]] based on the contents of the Ext grid store.

The javascript as below will create such an array, dropping the id key in the object which I didn't need.

var tableDataArray = [];
Ext.ComponentQuery.query('[name="table1"]')[0].store.each(function(record){
    var thisRecordArray = [];
    for (var key in record.data) {
        if (key != 'id') {
            thisRecordArray.push(record.data[key]);
        }
    }
    tableDataArray.push(thisRecordArray);
});

Oracle client and networking components were not found

Simplest solution: The Oracle client is not installed on the remote server where the SSIS package is being executed.

Slightly less simple solution: The Oracle client is installed on the remote server, but in the wrong bit-count for the SSIS installation. For example, if the 64-bit Oracle client is installed but SSIS is being executed with the 32-bit dtexec executable, SSIS will not be able to find the Oracle client. The solution in this case would be to install the 32-bit Oracle client side-by-side with the 64-bit client.

(Deep) copying an array using jQuery

how about complex types? when array contains objects... or any else

My variant:

Object.prototype.copy = function(){
    var v_newObj = {};
    for(v_i in this)
        v_newObj[v_i] = (typeof this[v_i]).contains(/^(array|object)$/) ? this[v_i].copy() : this[v_i];
    return v_newObj;
}

Array.prototype.copy = function(){
    var v_newArr = [];
    this.each(function(v_i){
        v_newArr.push((typeof v_i).contains(/^(array|object)$/) ? v_i.copy() : v_i);
    });
    return v_newArr;
}

It's not final version, just an idea.

PS: method each and contains are prototypes also.

Only on Firefox "Loading failed for the <script> with source"

I noticed that in Firefox this can happen when requests are aborted (switching page or quickly refreshing page), but it is hard to reproduce the error even if I try to.

Other possible reasons: cert related issues and this one talks about blockers (as other answers stated).

Naming returned columns in Pandas aggregate function?

With the inspiration of @Joel Ostblom

For those who already have a workable dictionary for merely aggregation, you can use/modify the following code for the newer version aggregation, separating aggregation and renaming part. Please be aware of the nested dictionary if there are more than 1 item.

def agg_translate_agg_rename(input_agg_dict):
    agg_dict = {}
    rename_dict = {}
    for k, v in input_agg_dict.items():
        if len(v) == 1:
            agg_dict[k] = list(v.values())[0]
            rename_dict[k] = list(v.keys())[0]
        else:
            updated_index = 1
            for nested_dict_k, nested_dict_v in v.items():
                modified_key = k + "_" + str(updated_index)
                agg_dict[modified_key] = nested_dict_v
                rename_dict[modified_key] = nested_dict_k
                updated_index += 1
    return agg_dict, rename_dict

one_dict = {"column1": {"foo": 'sum'}, "column2": {"mean": 'mean', "std": 'std'}}
agg, rename = agg_translator_aa(one_dict)

We get

agg = {'column1': 'sum', 'column2_1': 'mean', 'column2_2': 'std'}
rename = {'column1': 'foo', 'column2_1': 'mean', 'column2_2': 'std'}

Please let me know if there is a smarter way to do it. Thanks.

Updating PartialView mvc 4

Controller :

public ActionResult Refresh(string ID)
    {
        DetailsViewModel vm = new DetailsViewModel();  // Model
        vm.productDetails = _product.GetproductDetails(ID); 
        /* "productDetails " is a property in "DetailsViewModel"
        "GetProductDetails" is a method in "Product" class
        "_product" is an interface of "Product" class */

        return PartialView("_Details", vm); // Details is a partial view
    }

In yore index page you should to have refresh link :

     <a href="#" id="refreshItem">Refresh</a>

This Script should be also in your index page:

<script type="text/javascript">

    $(function () {
    $('a[id=refreshItem]:last').click(function (e) {
        e.preventDefault();

        var url = MVC.Url.action('Refresh', 'MyController', { itemId: '@(Model.itemProp.itemId )' }); // Refresh is an Action in controller, MyController is a controller name

        $.ajax({
            type: 'GET',
            url: url,
            cache: false,
            success: function (grid) {
                $('#tabItemDetails').html(grid);
                clientBehaviors.applyPlugins($("#tabProductDetails")); // "tabProductDetails" is an id of div in your "Details partial view"
            }
        });
    });
});

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

Can jQuery read/write cookies to a browser?

The default JavaScript "API" for setting a cookie is as easy as:

document.cookie = 'mycookie=valueOfCookie;expires=DateHere;path=/'

Use the jQuery cookie plugin like:

$.cookie('mycookie', 'valueOfCookie')

In CSS how do you change font size of h1 and h2

What have you tried? This should work.

h1 { font-size: 20pt; }
h2 { font-size: 16pt; }

Adding a view controller as a subview in another view controller

Thanks to Rob. Adding detailed syntax for your second observation :

let controller:MyView = self.storyboard!.instantiateViewControllerWithIdentifier("MyView") as! MyView
controller.ANYPROPERTY=THEVALUE // If you want to pass value
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
self.addChildViewController(controller)
controller.didMoveToParentViewController(self)

And to remove the viewcontroller :

self.willMoveToParentViewController(nil)
self.view.removeFromSuperview()
self.removeFromParentViewController() 

Getting an element from a Set

To answer the precise question "Why doesn't Set provide an operation to get an element that equals another element?", the answer would be: because the designers of the collection framework were not very forward looking. They didn't anticipate your very legitimate use case, naively tried to "model the mathematical set abstraction" (from the javadoc) and simply forgot to add the useful get() method.

Now to the implied question "how do you get the element then": I think the best solution is to use a Map<E,E> instead of a Set<E>, to map the elements to themselves. In that way, you can efficiently retrieve an element from the "set", because the get() method of the Map will find the element using an efficient hash table or tree algorithm. If you wanted, you could write your own implementation of Set that offers the additional get() method, encapsulating the Map.

The following answers are in my opinion bad or wrong:

"You don't need to get the element, because you already have an equal object": the assertion is wrong, as you already showed in the question. Two objects that are equal still can have different state that is not relevant to the object equality. The goal is to get access to this state of the element contained in the Set, not the state of the object used as a "query".

"You have no other option but to use the iterator": that is a linear search over a collection which is totally inefficient for large sets (ironically, internally the Set is organized as hash map or tree that could be queried efficiently). Don't do it! I have seen severe performance problems in real-life systems by using that approach. In my opinion what is terrible about the missing get() method is not so much that it is a bit cumbersome to work around it, but that most programmers will use the linear search approach without thinking of the implications.

Tab key == 4 spaces and auto-indent after curly braces in Vim

From the VIM wiki:

:set tabstop=4
:set shiftwidth=4
:set expandtab

Cloning specific branch

To clone a particular branch in a git repository

- Command: git clone "repository_url" -b "branch_name"
- Example: git clone https://gitlab.com/amm.kazi/yusufoverseas.git -b routes

Negate if condition in bash script

If you're feeling lazy, here's a terse method of handling conditions using || (or) and && (and) after the operation:

wget -q --tries=10 --timeout=20 --spider http://google.com || \
{ echo "Sorry you are Offline" && exit 1; }

ORA-00904: invalid identifier

In my case, this error occurred, due to lack of existence of column name in the table.

When i executed "describe tablename" , i was not able to find the column specified in the mapping hbm file.

After altering the table, it worked fine.

PHP Check for NULL

I think you want to use

mysql_fetch_assoc($query)

rather than

mysql_fetch_row($query)

The latter returns an normal array index by integers, whereas the former returns an associative array, index by the field names.

How do I add 1 day to an NSDate?

NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit fromDate:now];
NSDate *startDate = [calendar dateFromComponents:components];
NSLog(@"StartDate = %@", startDate);

components.day += 1;
NSDate *endDate = [calendar dateFromComponents:components];
NSLog(@"EndDate = %@", endDate);

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

HTML5 Dynamically create Canvas

The problem is that you do not insert your canvas element in the document body.

Just do the following:

document.body.appendChild(canvas);

Example:

_x000D_
_x000D_
var canvas = document.createElement('canvas');_x000D_
_x000D_
canvas.id = "CursorLayer";_x000D_
canvas.width = 1224;_x000D_
canvas.height = 768;_x000D_
canvas.style.zIndex = 8;_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.border = "1px solid";_x000D_
_x000D_
_x000D_
var body = document.getElementsByTagName("body")[0];_x000D_
body.appendChild(canvas);_x000D_
_x000D_
cursorLayer = document.getElementById("CursorLayer");_x000D_
_x000D_
console.log(cursorLayer);_x000D_
_x000D_
// below is optional_x000D_
_x000D_
var ctx = canvas.getContext("2d");_x000D_
ctx.fillStyle = "rgba(255, 0, 0, 0.2)";_x000D_
ctx.fillRect(100, 100, 200, 200);_x000D_
ctx.fillStyle = "rgba(0, 255, 0, 0.2)";_x000D_
ctx.fillRect(150, 150, 200, 200);_x000D_
ctx.fillStyle = "rgba(0, 0, 255, 0.2)";_x000D_
ctx.fillRect(200, 50, 200, 200);
_x000D_
_x000D_
_x000D_

Deserialize a JSON array in C#

[JsonProperty("name")]
public string name { get; set; }
[JsonProperty("Age")]
public int required { get; set; }
[JsonProperty("Location")]
public string type { get; set; }

and Remove a "{"..,

strFieldString = strFieldString.Remove(0, strFieldString.IndexOf('{'));

DeserializeObject..,

   optionsItem objActualField = JsonConvert.DeserializeObject<optionsItem(strFieldString);

How can I force users to access my page over HTTPS instead of HTTP?

For those using IIS adding this line in the web.config will help:

<httpProtocol>
    <customHeaders>
        <add name="Strict-Transport-Security" value="max-age=31536000"/>
    </customHeaders>
</httpProtocol>
<rewrite>
    <rules>
        <rule name="HTTP to HTTPS redirect" stopProcessing="true">
              <match url="(.*)" />
              <conditions>
                 <add input="{HTTPS}" pattern="off" ignoreCase="true" />
              </conditions>
              <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
         </rule>
    </rules>
</rewrite>

A full example file

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <httpProtocol>
            <customHeaders>
                <add name="Strict-Transport-Security" value="max-age=31536000"/>
             </customHeaders>
        </httpProtocol>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                      <match url="(.*)" />
                      <conditions>
                         <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                      </conditions>
                      <action type="Redirect" redirectType="Found" url="https://{HTTP_HOST}/{R:1}" />
                 </rule>
            </rules>
       </rewrite>
   </system.webServer>
</configuration>

Is there an easy way to check the .NET Framework version?

This is the solution I landed on:

private static string GetDotNetVersion()
{
  var v4 = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full", false)?.GetValue("Version");
  if(v4 != null)
    return v4;
  var v35 = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5", false)?.GetValue("Version");
  if(v35 != null)
    return v35;
  var v3 = (string)Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.0", false)?.GetValue("Version");
  return v3 ?? "< 3";
}

Is it possible to simulate key press events programmatically?

Here is a solution that works in Chrome and Chromium (have only tested these platforms). It seems Chrome has some bug or own approach to handling key codes so this property has to be added separately to the KeyboardEvent.

_x000D_
_x000D_
    function simulateKeydown (keycode,isCtrl,isAlt,isShift){
        var e = new KeyboardEvent( "keydown", { bubbles:true, cancelable:true, char:String.fromCharCode(keycode), key:String.fromCharCode(keycode), shiftKey:isShift, ctrlKey:isCtrl, altKey:isAlt } );
        Object.defineProperty(e, 'keyCode', {get : function() { return this.keyCodeVal; } });     
        e.keyCodeVal = keycode;
        document.dispatchEvent(e);
    }
    simulateKeydown(39, false, false, false);
_x000D_
_x000D_
_x000D_

Create thumbnail image

You have to use GetThumbnailImage method in the Image class:

https://msdn.microsoft.com/en-us/library/8t23aykb%28v=vs.110%29.aspx

Here's a rough example that takes an image file and makes a thumbnail image from it, then saves it back to disk.

Image image = Image.FromFile(fileName);
Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
thumb.Save(Path.ChangeExtension(fileName, "thumb"));

It is in the System.Drawing namespace (in System.Drawing.dll).

Behavior:

If the Image contains an embedded thumbnail image, this method retrieves the embedded thumbnail and scales it to the requested size. If the Image does not contain an embedded thumbnail image, this method creates a thumbnail image by scaling the main image.


Important: the remarks section of the Microsoft link above warns of certain potential problems:

The GetThumbnailImage method works well when the requested thumbnail image has a size of about 120 x 120 pixels. If you request a large thumbnail image (for example, 300 x 300) from an Image that has an embedded thumbnail, there could be a noticeable loss of quality in the thumbnail image.

It might be better to scale the main image (instead of scaling the embedded thumbnail) by calling the DrawImage method.

Angular2 http.get() ,map(), subscribe() and observable pattern - basic understanding

Here is where you went wrong:

this.result = http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result.json());

it should be:

http.get('friends.json')
                  .map(response => response.json())
                  .subscribe(result => this.result =result);

or

http.get('friends.json')
                  .subscribe(result => this.result =result.json());

You have made two mistakes:

1- You assigned the observable itself to this.result. When you actually wanted to assign the list of friends to this.result. The correct way to do it is:

  • you subscribe to the observable. .subscribe is the function that actually executes the observable. It takes three callback parameters as follow:

    .subscribe(success, failure, complete);

for example:

.subscribe(
    function(response) { console.log("Success Response" + response)},
    function(error) { console.log("Error happened" + error)},
    function() { console.log("the subscription is completed")}
);

Usually, you take the results from the success callback and assign it to your variable. the error callback is self explanatory. the complete callback is used to determine that you have received the last results without any errors. On your plunker, the complete callback will always be called after either the success or the error callback.

2- The second mistake, you called .json() on .map(res => res.json()), then you called it again on the success callback of the observable. .map() is a transformer that will transform the result to whatever you return (in your case .json()) before it's passed to the success callback you should called it once on either one of them.

jQuery autocomplete with callback ajax json

$(document).on('keyup','#search_product',function(){
    $( "#search_product" ).autocomplete({
      source:function(request,response){
                  $.post("<?= base_url('ecommerce/autocomplete') ?>",{'name':$( "#search_product" ).val()}).done(function(data, status){

                    response(JSON.parse(data));
        });
      }
    });
});

PHP code :

public function autocomplete(){
    $name=$_POST['name'];
    $result=$this->db->select('product_name,sku_code')->like('product_name',$name)->get('product_list')->result_array();
    $names=array();
    foreach($result as $row){
        $names[]=$row['product_name'];
    }
    echo json_encode($names);
}

Remove part of string in Java

originalString.replaceFirst("[(].*?[)]", "");

https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

XML Parser for C

How about one written in pure assembler :-) Don't forget to check out the benchmarks.

ConnectivityManager getNetworkInfo(int) deprecated

Kotlin version:

fun isInternetOn(context: Context): Boolean {
   val cm = context.getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager
   val activeNetwork = cm?.activeNetworkInfo
   return activeNetwork != null && activeNetwork.isConnected
}

How to git-cherry-pick only changes to certain files?

I found another way which prevents any conflicting merge on cherry-picking which IMO is kind of easy to remember and understand. Since you are actually not cherry-picking a commit, but part of it, you need to split it first and then create a commit which will suit your needs and cherry-pick it.

First create a branch from the commit you want to split and checkout it:

$ git checkout COMMIT-TO-SPLIT-SHA -b temp

Then revert previous commit:

$ git reset HEAD~1

Then add the files/changes you want to cherry-pick:

$ git add FILE

and commit it:

$ git commit -m "pick me"

note the commit hash, let's call it PICK-SHA and go back to your main branch, master for example forcing the checkout:

$ git checkout -f master

and cherry-pick the commit:

$ git cherry-pick PICK-SHA

now you can delete the temp branch:

$ git branch -d temp -f

Troubleshooting "Illegal mix of collations" error in mysql

MySQL really dislikes mixing collations unless it can coerce them to the same one (which clearly is not feasible in your case). Can't you just force the same collation to be used via a COLLATE clause? (or the simpler BINARY shortcut if applicable...).

Disable sorting on last column when using jQuery DataTables

Use this:

$(document).ready(function () {
            $('#workPatternDataTable').dataTable({
                //"aaSorting": [],
                ajax: null,
                columnDefs: [
                    {
                        targets: 0,
                        sortable: false,
                        autoWidth: false,
                    }
                ]
            });
        });

Save array in mysql database

Use the PHP function serialize() to convert arrays to strings. These strings can easily be stored in MySQL database. Using unserialize() they can be converted to arrays again if needed.

Simple Pivot Table to Count Unique Values

You can make an additional column to store the uniqueness, then sum that up in your pivot table.

What I mean is, cell C1 should always be 1. Cell C2 should contain the formula =IF(COUNTIF($A$1:$A1,$A2)*COUNTIF($B$1:$B1,$B2)>0,0,1). Copy this formula down so cell C3 would contain =IF(COUNTIF($A$1:$A2,$A3)*COUNTIF($B$1:$B2,$B3)>0,0,1) and so on.

If you have a header cell, you'll want to move these all down a row and your C3 formula should be =IF(COUNTIF($A$2:$A2,$A3)*COUNTIF($B$2:$B2,$B3)>0,0,1).

Passing a 2D array to a C++ function

There are three ways to pass a 2D array to a function:

  1. The parameter is a 2D array

    int array[10][10];
    void passFunc(int a[][10])
    {
        // ...
    }
    passFunc(array);
    
  2. The parameter is an array containing pointers

    int *array[10];
    for(int i = 0; i < 10; i++)
        array[i] = new int[10];
    void passFunc(int *a[10]) //Array containing pointers
    {
        // ...
    }
    passFunc(array);
    
  3. The parameter is a pointer to a pointer

    int **array;
    array = new int *[10];
    for(int i = 0; i <10; i++)
        array[i] = new int[10];
    void passFunc(int **a)
    {
        // ...
    }
    passFunc(array);
    

ValueError when checking if variable is None or numpy.array

You can see if object has shape or not

def check_array(x):
    try:
        x.shape
        return True
    except:
        return False

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

"Class.forName()" returns the Class-Type for the given name. "newInstance()" does return an instance of this class.

On the type you can't call directly any instance methods but can only use reflection for the class. If you want to work with an object of the class you have to create an instance of it (same as calling "new MyClass()").

Example for "Class.forName()"

Class myClass = Class.forName("test.MyClass");
System.out.println("Number of public methods: " + myClass.getMethods().length);

Example for "Class.forName().newInstance()"

MyClass myClass = (MyClass) Class.forName("test.MyClass").newInstance();
System.out.println("String representation of MyClass instance: " + myClass.toString());

Modular multiplicative inverse function in Python

Here is my code, it might be sloppy but it seems to work for me anyway.

# a is the number you want the inverse for
# b is the modulus

def mod_inverse(a, b):
    r = -1
    B = b
    A = a
    eq_set = []
    full_set = []
    mod_set = []

    #euclid's algorithm
    while r!=1 and r!=0:
        r = b%a
        q = b//a
        eq_set = [r, b, a, q*-1]
        b = a
        a = r
        full_set.append(eq_set)

    for i in range(0, 4):
        mod_set.append(full_set[-1][i])

    mod_set.insert(2, 1)
    counter = 0

    #extended euclid's algorithm
    for i in range(1, len(full_set)):
        if counter%2 == 0:
            mod_set[2] = full_set[-1*(i+1)][3]*mod_set[4]+mod_set[2]
            mod_set[3] = full_set[-1*(i+1)][1]

        elif counter%2 != 0:
            mod_set[4] = full_set[-1*(i+1)][3]*mod_set[2]+mod_set[4]
            mod_set[1] = full_set[-1*(i+1)][1]

        counter += 1

    if mod_set[3] == B:
        return mod_set[2]%B
    return mod_set[4]%B

How using try catch for exception handling is best practice

Leave blank catch block is the worse thing to do. If there is an error the best way to handle it is to:

  1. Log it into file\database etc..
  2. Try to fix it on the fly (maybe trying alternative way of doing that operation)
  3. If we cannot fix that, notify the user that there is some error and of course abort the operation

Is there a way to list all resources in AWS

You can use a query in the AWS Config Console here. (Region may change for you) https://console.aws.amazon.com/config/home?region=us-east-1#/resources/query

the query will look like.

SELECT
  resourceId,
  resourceName,
  resourceType,
  relationships
WHERE
relationships.resourceId = 'vpc-#######'

How to check the extension of a filename in a bash script?

I think you want to say "Are the last four characters of $file equal to .txt?" If so, you can use the following:

if [ ${file: -4} == ".txt" ]

Note that the space between file: and -4 is required, as the ':-' modifier means something different.

Prevent redirect after form is submitted

You must put the return inside submit() call.

  $('.submit').click(function() {
     $('#registerform').submit(function () {
     sendContactForm();
     return false;
    });
    //Here you can do anything after submit
}

Python: Assign Value if None Exists

You should initialize variables to None and then check it:

var1 = None
if var1 is None:
    var1 = 4

Which can be written in one line as:

var1 = 4 if var1 is None else var1

or using shortcut (but checking against None is recommended)

var1 = var1 or 4

alternatively if you will not have anything assigned to variable that variable name doesn't exist and hence using that later will raise NameError, and you can also use that knowledge to do something like this

try:
    var1
except NameError:
    var1 = 4

but I would advise against that.

How to add Tomcat Server in eclipse

If by mistake, you have deleted your Tomcat Server and Eclipse is not showing more options (Next button will be inactive) then in this case follow the bellow steps:

  1. First remove the two files from the following path:

    • Path : workspace/.metadata/.plugins/org.eclipse.runtime/.settings/
    • And that two files are :

      1. org.eclipse.wst.server.core.prefs
      2. org.eclipse.jst/server.tomcat.core.prefs
    • After deleting/removing the above two files from the workspace, Restart the Eclipse IDE.

    • Change to the Server View, Right Click 'New', Window 'Define a New Server' is shown, --> Select the Apache Folder, choose Tomcat-Version

    • Browse to the unzipped 'Apache-Tomcat folder', choose the second level

    • Now you are able to add/configure your new Tomcat Server. (Now you will see the 'Next' button will become active, and you can then follow the normal instructions)

How to use random in BATCH script?

If you will divide by some large value you will get a huge amount of duplicates one after other. What you need to do is to take modulo of the %RANDOM% value:

@echo off
REM 
SET maxvalue=10
SET minvalue=1

SETLOCAL 
SET /A tmpRandom=((%RANDOM%)%%(%maxvalue%))+(%minvalue%)
echo "Tmp random: %tmpRandom%"
echo "Random:  %RANDOM%"
ENDLOCAL

Insert an item into sorted list in Python

This is the best way to append the list and insert values to sorted list:

 a = [] num = int(input('How many numbers: ')) for n in range(num):
     numbers = int(input('Enter values:'))
     a.append(numbers)

 b = sorted(a) print(b) c = int(input("enter value:")) for i in
 range(len(b)):
     if b[i] > c:
         index = i
         break d = b[:i] + [c] + b[i:] print(d)`

When does socket.recv(recv_size) return?

I think you conclusions are correct but not accurate.

As the docs indicates, socket.recv is majorly focused on the network buffers.

When socket is blocking, socket.recv will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv can handle, it will return all the bytes in the network buffers.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

Make a phone call programmatically

Swift

if let url = NSURL(string: "tel://\(number)"), 
    UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
}

How to make Google Fonts work in IE?

Google Fonts uses Web Open Font Format (WOFF), which is good, because it's the recommended font format by the W3C.

IE versions older than IE9 don't support Web Open Font Format (WOFF) because it didn't exist back then. To support < IE9, you need to serve your font in Embedded Open Type (EOT). To do this you will need to write your own @font-face css tag instead of using the embed script from Google. Also you need to convert the original WOFF file to EOT.

You can convert your WOFF to EOT over here by first converting it to TTF and then to EOT: http://convertfonts.com/

Then you can serve the EOT font like this:

@font-face {
    font-family: 'MyFont';
    src: url('myfont.eot');
}

Now it works in < IE9. However, modern browsers don't support EOT anymore, so now your fonts won't work in modern browsers. So you need to specify them both. The src property supports this by comma seperating the font urls and specefying the type:

src: url('myfont.woff') format('woff'),
     url('myfont.eot') format('embedded-opentype');

However, < IE9 doesn't understand this, it just graps the text between the first quote and the last quote, so it will actually get:

myfont.woff') format('woff'),
url('myfont.eot') format('embedded-opentype

as the URL to the font. We can fix this by first specifying a src with only one url which is the EOT format, then specifying a second src property that's meant for the modern browsers and < IE9 will not understand. Because < IE9 will not understand it it will ignore the tag so the EOT will still be working. The modern browsers will use the last specified font they support, so probably WOFF.

src: url('myfont.eot');
src: url('myfont.woff') format('woff');

So only because in the second src property you specify the format('woff'), < IE9 won't understand it (or actually it just can't find the font at the url myfont.woff') format('woff) and will keep using the first specified one (eot).

So now you got your Google Webfonts working for < IE9 and modern browsers!

For more information about different font type and browser support, read this perfect article by Alex Tatiyants: http://tatiyants.com/how-to-get-ie8-to-support-html5-tags-and-web-fonts/

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

I tested various combinations of android:background, android:backgroundTint and android:backgroundTintMode.

android:backgroundTint applies the color filter to the resource of android:background when used together with android:backgroundTintMode.

Here are the results:

Tint Check

Here's the code if you want to experiment further:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:orientation="vertical"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:showIn="@layout/activity_main">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:text="Background" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:backgroundTint="#FEFBDE"
        android:text="Background tint" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:text="Both together" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:background="#37AEE4"
        android:backgroundTint="#FEFBDE"
        android:backgroundTintMode="multiply"
        android:text="With tint mode" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:textSize="45sp"
        android:text="Without any" />
</LinearLayout>

Does 'position: absolute' conflict with Flexbox?

You have to give width:100% to parent to center the text.

_x000D_
_x000D_
 .parent {_x000D_
   display: flex;_x000D_
   justify-content: center;_x000D_
   position: absolute;_x000D_
   width:100%_x000D_
 }
_x000D_
<div class="parent">_x000D_
  <div class="child">text</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

If you also need to centre align vertically, give height:100% and align-itens: center

.parent {
   display: flex;
   justify-content: center;
   align-items: center;
   position: absolute;
   width:100%;
   height: 100%;
 }

what happens when you type in a URL in browser

Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server's IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it's gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).

VBA changing active workbook

Use ThisWorkbook which will refer to the original workbook which holds the code.

Alternatively at code start

Dim Wb As Workbook
Set Wb = ActiveWorkbook

sample code that activates all open books before returning to ThisWorkbook

Sub Test()
Dim Wb As Workbook
Dim Wb2 As Workbook
Set Wb = ThisWorkbook
For Each Wb2 In Application.Workbooks
    Wb2.Activate
Next
Wb.Activate
End Sub

Oracle 11g Express Edition for Windows 64bit?

This is a very useful question. It has 5 different helpful answers that say quite different but complementary things (surprising, eh?). This answer combines those answers into a more useful form as well as adding two more solutions.

There is no Oracle Express Edition for 64 bit Windows. See this official [but unanswered] forum thread. Therefore, these are the classes of solutions:

  • Pay. The paid versions of Oracle (Standard/Enterprise) support 64-bit Windows.
  • Hack. Many people have successfully installed the 32 bit Oracle XE software on 64 bit Windows. This blog post seems to be the one most often cited as helpful. This is unsupported, of course, and session trace is known to fail. But for many folks this is a good solution.
  • VM. If your goal is simply to run Oracle on a 64 bit Windows machine, then running Oracle in a Virtual Machine may be a good solution. VirtualBox is a natural choice because it's free and Oracle provides pre-configured VMs with Oracle DB installed. VMWare or other virtualization systems work equally well.
  • Develop only. Many users want Oracle XE just to learn Oracle or to test an application with Oracle. If that's your requirement, then Oracle Enterprise Edition (including support for 64-bit Windows) is free "only for the purpose of developing, testing, prototyping and demonstrating your application".

Function to calculate R2 (R-squared) in R

You need a little statistical knowledge to see this. R squared between two vectors is just the square of their correlation. So you can define you function as:

rsq <- function (x, y) cor(x, y) ^ 2

Sandipan's answer will return you exactly the same result (see the following proof), but as it stands it appears more readable (due to the evident $r.squared).


Let's do the statistics

Basically we fit a linear regression of y over x, and compute the ratio of regression sum of squares to total sum of squares.

lemma 1: a regression y ~ x is equivalent to y - mean(y) ~ x - mean(x)

lemma 1

lemma 2: beta = cov(x, y) / var(x)

lemma 2

lemma 3: R.square = cor(x, y) ^ 2

lemma 3


Warning

R squared between two arbitrary vectors x and y (of the same length) is just a goodness measure of their linear relationship. Think twice!! R squared between x + a and y + b are identical for any constant shift a and b. So it is a weak or even useless measure on "goodness of prediction". Use MSE or RMSE instead:

I agree with 42-'s comment:

The R squared is reported by summary functions associated with regression functions. But only when such an estimate is statistically justified.

R squared can be a (but not the best) measure of "goodness of fit". But there is no justification that it can measure the goodness of out-of-sample prediction. If you split your data into training and testing parts and fit a regression model on the training one, you can get a valid R squared value on training part, but you can't legitimately compute an R squared on the test part. Some people did this, but I don't agree with it.

Here is very extreme example:

preds <- 1:4/4
actual <- 1:4

The R squared between those two vectors is 1. Yes of course, one is just a linear rescaling of the other so they have a perfect linear relationship. But, do you really think that the preds is a good prediction on actual??


In reply to wordsforthewise

Thanks for your comments 1, 2 and your answer of details.

You probably misunderstood the procedure. Given two vectors x and y, we first fit a regression line y ~ x then compute regression sum of squares and total sum of squares. It looks like you skip this regression step and go straight to the sum of square computation. That is false, since the partition of sum of squares does not hold and you can't compute R squared in a consistent way.

As you demonstrated, this is just one way for computing R squared:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] 0.25

But there is another:

regss <- sum((preds - mean(preds)) ^ 2) ## regression sum of squares
regss / tss
#[1] 0.75

Also, your formula can give a negative value (the proper value should be 1 as mentioned above in the Warning section).

preds <- 1:4 / 4
actual <- 1:4
rss <- sum((preds - actual) ^ 2)  ## residual sum of squares
tss <- sum((actual - mean(actual)) ^ 2)  ## total sum of squares
rsq <- 1 - rss/tss
#[1] -2.375

Final remark

I had never expected that this answer could eventually be so long when I posted my initial answer 2 years ago. However, given the high views of this thread, I feel obliged to add more statistical details and discussions. I don't want to mislead people that just because they can compute an R squared so easily, they can use R squared everywhere.

How do I find out what License has been applied to my SQL Server installation?

This shows the licence type and number of licences:

SELECT SERVERPROPERTY('LicenseType'), SERVERPROPERTY('NumLicenses')

How to sleep the thread in node.js without affecting other threads?

If you are referring to the npm module sleep, it notes in the readme that sleep will block execution. So you are right - it isn't what you want. Instead you want to use setTimeout which is non-blocking. Here is an example:

setTimeout(function() {
  console.log('hello world!');
}, 5000);

For anyone looking to do this using es7 async/await, this example should help:

const snooze = ms => new Promise(resolve => setTimeout(resolve, ms));

const example = async () => {
  console.log('About to snooze without halting the event loop...');
  await snooze(1000);
  console.log('done!');
};

example();

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Actually, You are blocked by SSMS not the SQL Server.

So the solution are either change setting of SSMS or use a SQL query.

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

adding multiple entries to a HashMap at once in one statement

Java has no map literal, so there's no nice way to do exactly what you're asking.

If you need that type of syntax, consider some Groovy, which is Java-compatible and lets you do:

def map = [name:"Gromit", likes:"cheese", id:1234]

Dynamic variable names in Bash

for varname=$prefix_suffix format, just use:

varname=${prefix}_suffix

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

Is there a Pattern Matching Utility like GREP in Windows?

We have recently used PowerGREP for some fairly advanced bulk operations on thousands of files. Including regex searching in content of PDF files, and altering PDF documents in largescale.

Its worth the money if you want to save time from manuel labour. You can try it before you buy i think.

powershell - extract file name and extension

PS C:\Users\joshua> $file = New-Object System.IO.FileInfo('file.type')
PS C:\Users\joshua> $file.BaseName, $file.Extension
file
.type

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

Why does sudo change the PATH?

Looks like this bug has been around for quite a while! Here are some bug references you may find helpful (and may want to subscribe to / vote up, hint, hint...):


Debian bug #85123 ("sudo: SECURE_PATH still can't be overridden") (from 2001!)

It seems that Bug#20996 is still present in this version of sudo. The changelog says that it can be overridden at runtime but I haven't yet discovered how.

They mention putting something like this in your sudoers file:

Defaults secure_path="/bin:/usr/bin:/usr/local/bin"

but when I do that in Ubuntu 8.10 at least, it gives me this error:

visudo: unknown defaults entry `secure_path' referenced near line 10

Ubuntu bug #50797 ("sudo built with --with-secure-path is problematic")

Worse still, as far as I can tell, it is impossible to respecify secure_path in the sudoers file. So if, for example, you want to offer your users easy access to something under /opt, you must recompile sudo.


Yes. There needs to be a way to override this "feature" without having to recompile. Nothing worse then security bigots telling you what's best for your environment and then not giving you a way to turn it off.


This is really annoying. It might be wise to keep current behavior by default for security reasons, but there should be a way of overriding it other than recompiling from source code! Many people ARE in need of PATH inheritance. I wonder why no maintainers look into it, which seems easy to come up with an acceptable solution.


I worked around it like this:

mv /usr/bin/sudo /usr/bin/sudo.orig

then create a file /usr/bin/sudo containing the following:

#!/bin/bash
/usr/bin/sudo.orig env PATH=$PATH "$@"

then your regular sudo works just like the non secure-path sudo


Ubuntu bug #192651 ("sudo path is always reset")

Given that a duplicate of this bug was originally filed in July 2006, I'm not clear how long an ineffectual env_keep has been in operation. Whatever the merits of forcing users to employ tricks such as that listed above, surely the man pages for sudo and sudoers should reflect the fact that options to modify the PATH are effectively redundant.

Modifying documentation to reflect actual execution is non destabilising and very helpful.


Ubuntu bug #226595 ("impossible to retain/specify PATH")

I need to be able to run sudo with additional non-std binary folders in the PATH. Having already added my requirements to /etc/environment I was surprised when I got errors about missing commands when running them under sudo.....

I tried the following to fix this without sucess:

  1. Using the "sudo -E" option - did not work. My existing PATH was still reset by sudo

  2. Changing "Defaults env_reset" to "Defaults !env_reset" in /etc/sudoers -- also did not work (even when combined with sudo -E)

  3. Uncommenting env_reset (e.g. "#Defaults env_reset") in /etc/sudoers -- also did not work.

  4. Adding 'Defaults env_keep += "PATH"' to /etc/sudoers -- also did not work.

Clearly - despite the man documentation - sudo is completely hardcoded regarding PATH and does not allow any flexibility regarding retaining the users PATH. Very annoying as I can't run non-default software under root permissions using sudo.

Manually Triggering Form Validation using jQuery

TL;DR: Not caring about old browsers? Use form.reportValidity().

Need legacy browser support? Read on.


It actually is possible to trigger validation manually.

I'll use plain JavaScript in my answer to improve reusability, no jQuery is needed.


Assume the following HTML form:

<form>
  <input required>
  <button type="button">Trigger validation</button>
</form>

And let's grab our UI elements in JavaScript:

var form = document.querySelector('form')
var triggerButton = document.querySelector('button')

Don't need support for legacy browsers like Internet Explorer? This is for you.

All modern browsers support the reportValidity() method on form elements.

triggerButton.onclick = function () {
    form.reportValidity()
}

That's it, we're done. Also, here's a simple CodePen using this approach.


Approach for older browsers

Below is a detailed explanation how reportValidity() can be emulated in older browsers.

However, you don't need to copy&paste those code blocks into your project yourself — there is a ponyfill/polyfill readily available for you.

Where reportValidity() is not supported, we need to trick the browser a little bit. So, what will we do?

  1. Check validity of the form by calling form.checkValidity(). This will tell us if the form is valid, but not show the validation UI.
  2. If the form is invalid, we create a temporary submit button and trigger a click on it. Since the form is not valid, we know it won't actually submit, however, it will show validation hints to the user. We'll remove the temporary submit button immedtiately, so it will never be visible to the user.
  3. If the form is valid, we don't need to interfere at all and let the user proceed.

In code:

triggerButton.onclick = function () {
  // Form is invalid!
  if (!form.checkValidity()) {
    // Create the temporary button, click and remove it
    var tmpSubmit = document.createElement('button')
    form.appendChild(tmpSubmit)
    tmpSubmit.click()
    form.removeChild(tmpSubmit)

  } else {
    // Form is valid, let the user proceed or do whatever we need to
  }
}

This code will work in pretty much any common browser (I've tested it successfully down to IE11).

Here's a working CodePen example.

How to Remove Line Break in String

Replace(yourString, vbNewLine, "", , , vbTextCompare)

Function to check if a string is a date

I use this function as a parameter to the PHP filter_var function.

  • It checks for dates in yyyy-mm-dd hh:mm:ss format
  • It rejects dates that match the pattern but still invalid (e.g. Apr 31)

function filter_mydate($s) {
    if (preg_match('@^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$@', $s, $m) == false) {
        return false;
    }
    if (checkdate($m[2], $m[3], $m[1]) == false || $m[4] >= 24 || $m[5] >= 60 || $m[6] >= 60) {
        return false;
    }
    return $s;
}

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

You should use Java's built in serialization mechanism. To use it, you need to do the following:

  1. Declare the Club class as implementing Serializable:

    public class Club implements Serializable {
        ...
    }
    

    This tells the JVM that the class can be serialized to a stream. You don't have to implement any method, since this is a marker interface.

  2. To write your list to a file do the following:

    FileOutputStream fos = new FileOutputStream("t.tmp");
    ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(clubs);
    oos.close();
    
  3. To read the list from a file, do the following:

    FileInputStream fis = new FileInputStream("t.tmp");
    ObjectInputStream ois = new ObjectInputStream(fis);
    List<Club> clubs = (List<Club>) ois.readObject();
    ois.close();
    

Invariant Violation: Objects are not valid as a React child

Something like this has just happened to me...

I wrote:

{response.isDisplayOptions &&
{element}
}

Placing it inside a div fixed it:

{response.isDisplayOptions &&
    <div>
        {element}
    </div>
}

How to use jQuery in AngularJS

Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/

  angular.module('App', [])
    .controller('AppCtrl', function ($scope) {

      $scope.model = 0;

      $scope.initSlider = function () {
          $(function () {
            // wait till load event fires so all resources are available
              $scope.$slider = $('#slider').slider({
                  slide: $scope.onSlide
              });
          });

          $scope.onSlide = function (e, ui) {
             $scope.model = ui.value;
             $scope.$digest();
          };
      };

      $scope.initSlider();
  });

The directive approach:

HTML

<div slider></div>

JS

  angular.module('App', [])
    .directive('slider', function (DataModel) {
      return {
         restrict: 'A',
         scope: true,
         controller: function ($scope, $element, $attrs) {
            $scope.onSlide = function (e, ui) {
              $scope.model = ui.value;
              // or set it on the model
              // DataModel.model = ui.value;
              // add to angular digest cycle
              $scope.$digest();
            };
         },
         link: function (scope, el, attrs) {

            var options = {
              slide: scope.onSlide  
            };

            // set up slider on load
            angular.element(document).ready(function () {
              scope.$slider = $(el).slider(options);
            });
         }
      }
  });

I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js

You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.

How to set a session variable when clicking a <a> link

Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.

So the link looks like this:

<a href="home.php?variable=value" name="home">home</a>

And the homge page would parse the query string and set the session variable.

How to check if a given directory exists in Ruby

You could use Kernel#test:

test ?d, 'some directory'

it gets it's origins from https://ss64.com/bash/test.html you will notice bash test has this flag -d to test if a directory exists -d file True if file is a Directory. [[ -d demofile ]]

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

Invalid URI: The format of the URI could not be determined

Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx

EDIT:

You need to put the protocol prefix in front the address, i.e. in your case "ftp://"

What's is the difference between train, validation and test set, in neural networks?

We create a validation set to

  • Measure how well a model generalizes, during training
  • Tell us when to stop training a model;When the validation loss stops decreasing (and especially when the validation loss starts increasing and the training loss is still decreasing)

Why validation set used:

Why validation set used

Pause in Python

An external WConio module can help here: http://newcenturycomputers.net/projects/wconio.html

import WConio
WConio.getch()

Show datalist labels but submit the actual value

When clicking on the button for search you can find it without a loop.
Just add to the option an attribute with the value you need (like id) and search for it specific.

$('#search_wrapper button').on('click', function(){
console.log($('option[value="'+ 
$('#autocomplete_input').val() +'"]').data('value'));
})

jquery, find next element by class

You cannot use next() in this scenario, if you look at the documentation it says:
Next() Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling that matches the selector.

so if the second DIV was in the same TD then you could code:


// Won't work in your case
$(obj).next().filter('.class');

But since it's not, I don't see a point to use next(). You can instead code:

$(obj).parents('table').find('.class')

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

How to generate sample XML documents from their DTD or XSD?

The OpenXSD library mentions that they have support for generating XML instances based on the XSD. Check that out.

How do I print the percent sign(%) in c

Use "%%". The man page describes this requirement:

% A '%' is written. No argument is converted. The complete conversion specification is '%%'.

How to remove the Flutter debug banner?

how to remove debug banner in flutter

Just add debugShowCheckedModeBanner: false in MaterialApp.

3 ways - Remove Debug Banner In Flutter

CSS list-style-image size

Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.

ul li:first-child:before {
    content: '';
    display: inline-block;
    height: 25px;
    width: 35px;
    background-image: url('../images/Money.png');
    background-size: contain;
    background-repeat: no-repeat;
    margin-left: -35px;
}

This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps

The property 'value' does not exist on value of type 'HTMLElement'

If you have dynamic element ID where you need to assign the dynamic value, you may use this:

//element_id = you dynamic id.
//dynamic_val = you dynamic value.
let _el = document.getElementById(element_id);
_el.value = dynamic_val.toString();

This works for me.

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x

p <- ggplot(plot, aes(x = pred, y = value)) +
     geom_point(size = 2.5) +
     theme_bw()+
     coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p

enter image description here

What are NR and FNR and what does "NR==FNR" imply?

There are awk built-in variables.

NR - It gives the total number of records processed.

FNR - It gives the total number of records for each input file.

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

I had this same problem using the Windows XAMPP 1.7.4 -- after setting a password for mysql, I could no longer access phpMyAdmin. I changed the password in config.inc.php from ' ' to the new mysql password, and changed AllowNoPassword from true to false. I still couldn't log in.

However, I saw that there is also a config.inc.php.safe file, and when I also edited the password settings in THAT file I was subsequently able to log in to phpMyAdmin.

Difference between MEAN.js and MEAN.io

Here is a side-by-side comparison of several application starters/generators and other technologies including MEAN.js, MEAN.io, and cleverstack. I keep adding alternatives as I find time and as that happens, the list of potentially provided benefits keeps growing too. Today it's up to around 1600. If anyone wants to help improve its accuracy or completeness, click the next link and do a questionnaire about something you know.

Compare app technologies project

From this database, the system generates reports like the following:

MeanJS vs MeanIO trade-off report

Renaming files in a folder to sequential numbers

with "rename" command

rename -N 0001 -X 's/.*/$N/' *.jpg

or

rename -N 0001 's/.*/$N.jpg/' *.jpg

how to add value to a tuple?

Tuples are immutable and not supposed to be changed - that is what the list type is for. You could replace each tuple by originalTuple + (newElement,), thus creating a new tuple. For example:

t = (1,2,3)
t = t + (1,)
print t
(1,2,3,1)

But I'd rather suggest to go with lists from the beginning, because they are faster for inserting items.

And another hint: Do not overwrite the built-in name list in your program, rather call the variable l or some other name. If you overwrite the built-in name, you can't use it anymore in the current scope.

Using two CSS classes on one element

If you have 2 classes i.e. .indent and .font, class="indent font" works.

You dont have to have a .indent.font{} in css.

You can have the classes separate in css and still call both just using the class="class1 class2" in the html. You just need a space between one or more class names.

Is it safe to store a JWT in localStorage with ReactJS?

Isn't neither localStorage or httpOnly cookie acceptable? In regards to a compromised 3rd party library, the only solution I know of that will reduce / prevent sensitive information from being stolen would be enforced Subresource Integrity.

Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match.

As long as the compromised 3rd party library is active on your website, a keylogger can start collecting info like username, password, and whatever else you input into the site.

An httpOnly cookie will prevent access from another computer but will do nothing to prevent the hacker from manipulating the user's computer.

How to assign Php variable value to Javascript variable?

Essentially:

<?php
//somewhere set a value
$var = "a value";
?>

<script>
// then echo it into the js/html stream
// and assign to a js variable
spge = '<?php echo $var ;?>';

// then
alert(spge);

</script>

Python spacing and aligning strings

Try %*s and %-*s and prefix each string with the column width:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

Check if value is zero or not null in python

If number could be None or a number, and you wanted to include 0, filter on None instead:

if number is not None:

If number can be any number of types, test for the type; you can test for just int or a combination of types with a tuple:

if isinstance(number, int):  # it is an integer
if isinstance(number, (int, float)):  # it is an integer or a float

or perhaps:

from numbers import Number

if isinstance(number, Number):

to allow for integers, floats, complex numbers, Decimal and Fraction objects.

Differences between Octave and MATLAB?

There is not much which I would like to add to Rody Oldenhuis answer. I usually follow the strategy that all functions which I write should run in Matlab.

Some specific functions I test on both systems, for the following use cases:

a) octave does not need a license server - e.g. if your institution does not support local licenses. I used it once in a situation where the system I used a script on had no connection to the internet and was going to run for a very long time (in a corner in the lab) and used by many different users. Remark: that is not about the license cost, but about the technical issues related.

b) Octave supports other platforms, for example, the Rasberry Pi (http://wiki.octave.org/Rasperry_Pi) - which may come in handy.

Copying formula to the next row when inserting a new row

Make the area with your data and formulas a Table:

enter image description here

Then adding new information in the next line will copy all formulas in that table for the new line. Data validation will also be applied for the new row as it was for the whole column. This is indeed Excel being smarter with your data.

NO VBA required...