Programs & Examples On #Xcf

tqdm in Jupyter Notebook prints new progress bars repeatedly

None of the above works for me. I find that running the following sorts this issue after error (It just clears all the instances of progress bars in the background):

from tqdm import tqdm

# blah blah your code errored

tqdm._instances.clear()

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

The simple answer:

  • doing a MOV RBX, 3 and MUL RBX is expensive; just ADD RBX, RBX twice

  • ADD 1 is probably faster than INC here

  • MOV 2 and DIV is very expensive; just shift right

  • 64-bit code is usually noticeably slower than 32-bit code and the alignment issues are more complicated; with small programs like this you have to pack them so you are doing parallel computation to have any chance of being faster than 32-bit code

If you generate the assembly listing for your C++ program, you can see how it differs from your assembly.

"installation of package 'FILE_PATH' had non-zero exit status" in R

I was having a similar problem trying to install a package called AED. I tried using the install.packages() command:

install.packages('FILE_PATH', repos=NULL, type = "source")

but kept getting the following warning message:

Warning message:
In install.packages("/Users/blahblah/R-2.14.0/AED",  :
installation of package ‘/Users/blahblah/R-2.14.0/AED’ had
non-zero exit status

It turned out the folder 'AED' had another folder inside of it that hadn't been uncompressed. I just uncompressed it and tried installing the package again and it worked.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

# coding: utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

How can I get the sha1 hash of a string in node.js?

Please read and strongly consider my advice in the comments of your post. That being said, if you still have a good reason to do this, check out this list of crypto modules for Node. It has modules for dealing with both sha1 and base64.

Python CSV error: line contains NULL byte

Have you tried using gzip.open?

with gzip.open('my.csv', 'rb') as data_file:

I was trying to open a file that had been compressed but had the extension '.csv' instead of 'csv.gz'. This error kept showing up until I used gzip.open

How to check if a file is a valid image file?

I have just found the builtin imghdr module. From python documentation:

The imghdr module determines the type of image contained in a file or byte stream.

This is how it works:

>>> import imghdr
>>> imghdr.what('/tmp/bass')
'gif'

Using a module is much better than reimplementing similar functionality

ImportError: No module named 'google'

got this from cloud service documentation

pip install --upgrade google-cloud-translate

Worked for me !

How to insert the current timestamp into MySQL database using a PHP insert query

Your usage of now() is correct. However, you need to use one type of quotes around the entire query and another around the values.

You can modify your query to use double quotes at the beginning and end, and single quotes around $somename:

$update_query = "UPDATE db.tablename SET insert_time=now() WHERE username='$somename'";

How to iterate through a list of objects in C++

It is also worth to mention, that if you DO NOT intent to modify the values of the list, it is possible (and better) to use the const_iterator, as follows:

for (std::list<Student>::const_iterator it = data.begin(); it != data.end(); ++it){
    // do whatever you wish but don't modify the list elements
    std::cout << it->name;
}

What is the difference between an abstract function and a virtual function?

Abstract Function:

  1. It can be declared only inside abstract class.
  2. It contains only method declaration not the implementation in abstract class.
  3. It must be overridden in derived class.

Virtual Function:

  1. It can be declared inside abstract as well as non abstract class.
  2. It contains method implementation.
  3. It may be overridden.

Error: allowDefinition='MachineToApplication' beyond application level

I was having the same issue when I would publish the site, if I build the site I get no issues but while publishing I would get this awful error:

"It is an error to use a section registered as allowDefinition='MachineToApplication' beyond application level. This error can be caused by a virtual directory not being configured as an application in IIS"

I tried everything that has been stated here in this post to no resort, what worked for me was to just create a new publish profile with exactly the same as the one I've been using and that works well, don't get the error with the new profile but do with the old. Not sure what the difference is but at least I can publish my MVC project.

Hope this helps somebody!

Cloning specific branch

You may try this

git clone --single-branch --branch <branchname> host:/dir.git

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

As of R2017b, this is not officially possible. The relevant documentation states that:

Program files can contain multiple functions. If the file contains only function definitions, the first function is the main function, and is the function that MATLAB associates with the file name. Functions that follow the main function or script code are called local functions. Local functions are only available within the file.

However, workarounds suggested in other answers can achieve something similar.

WCF gives an unsecured or incorrectly secured fault error

Just for the sake of sharing... I had a rare case that got me scratching the back of my head for a few minutes. Even tho the time skew solution was very accurate, and I had that problem solved before, this time was different. I was on a new Win8.1 machine which I remember having a timezone issue and I had manually adjusted the time. Well, I kept getting the error, despite the time displayed in both server and client had only a diference in seconds. What I did is activate "summer saving option" (note that I am indeed under summer saving time, but had the time setup manually) in "date and time setup" then went to the internet time section and refreshed... the time in my pc kept exactly the same, but the error dissapeared.

Hope this is useful to anybody!

Turning multiple lines into one comma separated line

sed -n 's/.*/&,/;H;$x;$s/,\n/,/g;$s/\n\(.*\)/\1/;$s/\(.*\),/\1/;$p'

How can I update a row in a DataTable in VB.NET?

Dim myRow() As Data.DataRow
myRow = dt.Select("MyColumnName = 'SomeColumnTitle'")
myRow(0)("SomeOtherColumnTitle") = strValue

Code above instantiates a DataRow. Where "dt" is a DataTable, you get a row by selecting any column (I know, sounds backwards). Then you can then set the value of whatever row you want (I chose the first row, or "myRow(0)"), for whatever column you want.

Creating custom function in React component

Another way:

export default class Archive extends React.Component { 

  saySomething = (something) => {
    console.log(something);
  }

  handleClick = (e) => {
    this.saySomething("element clicked");
  }

  componentDidMount() {
    this.saySomething("component did mount");
  }

  render() {
    return <button onClick={this.handleClick} value="Click me" />;
  }
}

In this format you don't need to use bind

What does the @Valid annotation indicate in Spring?

Adding to above answers, take a look at following. AppointmentForm's date column is annotated with couple of annotations. By having @Valid annotation that triggers validations on the AppointmentForm (in this case @NotNull and @Future). These annotations could come from different JSR-303 providers (e.g, Hibernate, Spring..etc).

    @RequestMapping(value = "/appointments", method = RequestMethod.POST)
    public String add(@Valid AppointmentForm form, BindingResult result) {
        ....
    }

    static class AppointmentForm {

        @NotNull @Future
        private Date date;
    }

Invalid date in safari

For me implementing a new library just because Safari cannot do it correctly is too much and a regex is overkill. Here is the oneliner:

console.log (new Date('2011-04-12'.replace(/-/g, "/")));

Is there a way to access the "previous row" value in a SELECT statement?

The selected answer will only work if there are no gaps in the sequence. However if you are using an autogenerated id, there are likely to be gaps in the sequence due to inserts that were rolled back.

This method should work if you have gaps

declare @temp (value int, primaryKey int, tempid int identity)
insert value, primarykey from mytable order by  primarykey

select t1.value - t2.value from @temp  t1
join @temp  t2 
on t1.tempid = t2.tempid - 1

How do you create different variable names while in a loop?

I would use a list:

string = []
for i in range(0, 9):
  string.append("Hello")

This way, you would have 9 "Hello" and you could get them individually like this:

string[x]

Where x would identify which "Hello" you want.

So, print(string[1]) would print Hello.

How to calculate time difference in java?

    /*
 * Total time calculation.
 */
private void getTotalHours() {
    try {
        // TODO Auto-generated method stub
        if (tfTimeIn.getValue() != null && tfTimeOut.getValue() != null) {
            Long min1 = tfTimeOut.getMinutesValue();
            Long min2 = tfTimeIn.getMinutesValue();
            Long hr1 = tfTimeOut.getHoursValue();
            Long hr2 = tfTimeIn.getHoursValue();
            Long hrsTotal = new Long("0");
            Long minTotal = new Long("0");
            if ((hr2 - hr1) == 1) {
                hrsTotal = (long) 1;
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    hrsTotal++;
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) > 0) {
                hrsTotal = (hr2 - hr1);
                if (min1 != 0 && min2 == 0) {
                    minTotal = (long) 60 - min1;
                } else if (min1 == 0 && min2 != 0) {
                    minTotal = min2;
                } else if (min1 != 0 && min2 != 0) {
                    minTotal = min2;
                    Long minOne = (long) 60 - min1;
                    Long minTwo = min2;
                    minTotal = minOne + minTwo;
                }
                if (minTotal >= 60) {
                    minTotal = minTotal % 60;
                }
            } else if ((hr2 - hr1) == 0) {
                if (min1 != 0 || min2 != 0) {
                    if (min2 > min1) {
                        hrsTotal = (long) 0;
                        minTotal = min2 - min1;
                    } else {
                        Notification.show("Enter A Valid Time");
                        tfTotalTime.setValue("00.00");
                    }
                }
            } else {
                Notification.show("Enter A Valid Time");
                tfTotalTime.setValue("00.00");
            }
            String hrsTotalString = hrsTotal.toString();
            String minTotalString = minTotal.toString();
            if (hrsTotalString.trim().length() == 1) {
                hrsTotalString = "0" + hrsTotalString;
            }
            if (minTotalString.trim().length() == 1) {
                minTotalString = "0" + minTotalString;
            }
            tfTotalTime.setValue(hrsTotalString + ":" + minTotalString);
        } else {
            tfTotalTime.setValue("00.00");
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }
}

Linux Process States

While waiting for read() or write() to/from a file descriptor return, the process will be put in a special kind of sleep, known as "D" or "Disk Sleep". This is special, because the process can not be killed or interrupted while in such a state. A process waiting for a return from ioctl() would also be put to sleep in this manner.

An exception to this is when a file (such as a terminal or other character device) is opened in O_NONBLOCK mode, passed when its assumed that a device (such as a modem) will need time to initialize. However, you indicated block devices in your question. Also, I have never tried an ioctl() that is likely to block on a fd opened in non blocking mode (at least not knowingly).

How another process is chosen depends entirely on the scheduler you are using, as well as what other processes might have done to modify their weights within that scheduler.

Some user space programs under certain circumstances have been known to remain in this state forever, until rebooted. These are typically grouped in with other "zombies", but the term would not be correct as they are not technically defunct.

Copying PostgreSQL database to another server

You don't need to create an intermediate file. You can do

pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname

or

pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname

using psql or pg_dump to connect to a remote host.

With a big database or a slow connection, dumping a file and transfering the file compressed may be faster.

As Kornel said there is no need to dump to a intermediate file, if you want to work compressed you can use a compressed tunnel

pg_dump -C dbname | bzip2 | ssh  remoteuser@remotehost "bunzip2 | psql dbname"

or

pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"

but this solution also requires to get a session in both ends.

Note: pg_dump is for backing up and psql is for restoring. So, the first command in this answer is to copy from local to remote and the second one is from remote to local. More -> https://www.postgresql.org/docs/9.6/app-pgdump.html

Failed to connect to mysql at 127.0.0.1:3306 with user root access denied for user 'root'@'localhost'(using password:YES)

MySQL Installer Community -> MySQL Server Reconfigure -> Next -> Next -> Connection Name [Local instance or any other name] -> Click on Password - Store in Vault... and add a password and then -> Test connection. It works for me :)

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

Answer seems to be a little old, What I did was to use this mapper to convert a MAP

      ObjectMapper mapper = new ObjectMapper().configure(SerializationConfig.Feature.WRITE_NULL_MAP_VALUES, false);

a simple Map:

          Map<String, Object> user = new HashMap<String,Object>();
            user.put( "id",  teklif.getAccount().getId() );
            user.put( "fname", teklif.getAccount().getFname());
            user.put( "lname", teklif.getAccount().getLname());
            user.put( "email", teklif.getAccount().getEmail());
            user.put( "test", null);

Use it like this for example:

      String json = mapper.writeValueAsString(user);

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

Property '...' has no initializer and is not definitely assigned in the constructor

When you upgrade using [email protected] , its compiler strict the rules follows for array type declare inside the component class constructor.

For fix this issue either change the code where are declared in the code or avoid to compiler to add property "strictPropertyInitialization": false in the "tsconfig.json" file and run again npm start .

Angular web and mobile Application Development you can go to www.jtechweb.in

Comparing Java enum members: == or equals()?

Both are technically correct. If you look at the source code for .equals(), it simply defers to ==.

I use ==, however, as that will be null safe.

Python method for reading keypress?

See the MSDN getch docs. Specifically:

The _getch and_getwch functions read a single character from the console without echoing the character. None of these functions can be used to read CTRL+C. When reading a function key or an arrow key, each function must be called twice; the first call returns 0 or 0xE0, and the second call returns the actual key code.

The Python function returns a character. you can use ord() to get an integer value you can test, for example keycode = ord(msvcrt.getch()).

So if you read an 0x00 or 0xE0, read it a second time to get the key code for an arrow or function key. From experimentation, 0x00 precedes F1-F10 (0x3B-0x44) and 0xE0 precedes arrow keys and Ins/Del/Home/End/PageUp/PageDown.

How to understand nil vs. empty vs. blank in Ruby

Don't forget any? which is generally !empty?. In Rails I typically check for the presence of something at the end of a statement with if something or unless something then use blank? where needed since it seems to work everywhere.

What is reflection and why is it useful?

Reflection is a key mechanism to allow an application or framework to work with code that might not have even been written yet!

Take for example your typical web.xml file. This will contain a list of servlet elements, which contain nested servlet-class elements. The servlet container will process the web.xml file, and create new a new instance of each servlet class through reflection.

Another example would be the Java API for XML Parsing (JAXP). Where an XML parser provider is 'plugged-in' via well-known system properties, which are used to construct new instances through reflection.

And finally, the most comprehensive example is Spring which uses reflection to create its beans, and for its heavy use of proxies

100% width table overflowing div container

From a purely "make it fit in the div" perspective, add the following to your table class (jsfiddle):

table-layout: fixed;
width: 100%;

Set your column widths as desired; otherwise, the fixed layout algorithm will distribute the table width evenly across your columns.

For quick reference, here are the table layout algorithms, emphasis mine:

  • Fixed (source)
    With this (fast) algorithm, the horizontal layout of the table does not depend on the contents of the cells; it only depends on the table's width, the width of the columns, and borders or cell spacing.
  • Automatic (source)
    In this algorithm (which generally requires no more than two passes), the table's width is given by the width of its columns [, as determined by content] (and intervening borders).

    [...] This algorithm may be inefficient since it requires the user agent to have access to all the content in the table before determining the final layout and may demand more than one pass.

Click through to the source documentation to see the specifics for each algorithm.

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You should replace WebDriver wb = new FirefoxDriver(); with driver = new FirefoxDriver(); in your @Before Annotation.

As you are accessing driver object with null or you can make wb reference variable as global variable.

Don't change link color when a link is clicked

you are looking for this:

a:visited{
  color:blue;
}

Links have several states you can alter... the way I remember them is LVHFA (Lord Vader's Handle Formerly Anakin)

Each letter stands for a pseudo class: (Link,Visited,Hover,Focus,Active)

a:link{
  color:blue;
}
a:visited{
  color:purple;
}
a:hover{
  color:orange;
}
a:focus{
  color:green;
}
a:active{
  color:red;
}

If you want the links to always be blue, just change all of them to blue. I would note though on a usability level, it would be nice if the mouse click caused the color to change a little bit (even if just a lighter/darker blue) to help indicate that the link was actually clicked (this is especially important in a touchscreen interface where you're not always sure the click was actually registered)

If you have different types of links that you want to all have the same color when clicked, add a class to the links.

a.foo, a.foo:link, a.foo:visited, a.foo:hover, a.foo:focus, a.foo:active{
  color:green;
}
a.bar, a.bar:link, a.bar:visited, a.bar:hover, a.bar:focus, a.bar:active{
  color:orange;
}

It should be noted that not all browsers respect each of these options ;-)

Can two Java methods have same name with different return types?

No. C++ and Java both disallow overloading on a functions's return type. The reason is that overloading on return-type can be confusing (it can be hard for developers to predict which overload will be called). In fact, there are those who argue that any overloading can be confusing in this respect and recommend against it, but even those who favor overloading seem to agree that this particular form is too confusing.

DateTime's representation in milliseconds?

Using the answer of Andoma, this is what I'm doing

You can create a Struct or a Class like this one

struct Date
    {
        public static double GetTime(DateTime dateTime)
        {
            return dateTime.ToUniversalTime().Subtract(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
        }

        public static DateTime DateTimeParse(double milliseconds)
        {
            return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds(milliseconds).ToLocalTime();
        }

    }

And you can use this in your code as following

DateTime dateTime = DateTime.Now;

double total = Date.GetTime(dateTime);

dateTime = Date.DateTimeParse(total);

I hope this help you

How does HTTP file upload work?

An HTTP message may have a body of data sent after the header lines. In a response, this is where the requested resource is returned to the client (the most common use of the message body), or perhaps explanatory text if there's an error. In a request, this is where user-entered data or uploaded files are sent to the server.

http://www.tutorialspoint.com/http/http_messages.htm

jQuery Dialog Box

<script type="text/javascript">
// Increase the default animation speed to exaggerate the effect
$.fx.speeds._default = 1000;
$(function() {
    $('#dialog1').dialog({
        autoOpen: false,
        show: 'blind',
        hide: 'explode'
    });

    $('#Wizard1_txtEmailID').click(function() {
        $('#dialog1').dialog('open');
        return false;
    });
    $('#Wizard1_txtEmailID').click(function() {
        $('#dialog2').dialog('close');
        return false;
    });
    //mouseover
    $('#Wizard1_txtPassword').click(function() {
        $('#dialog1').dialog('close');
        return false;
    });

});



/////////////////////////////////////////////////////
 <div id="dialog1" title="Email ID">
                                                                                                                <p>
                                                                                                                    (Enter your Email ID here.)
                                                                                                                    <br />
                                                                                                                </p>
                                                                                             </div>
 ////////////////////////////////////////////////////////

<div id="dialog2" title="Password">
                                                                                                                <p>
                                                                                                                    (Enter your Passowrd here.)
                                                                                                                    <br />
                                                                                                                </p>
                                                                                              </div>

How do I move a table into a schema in T-SQL

ALTER SCHEMA TargetSchema 
    TRANSFER SourceSchema.TableName;

If you want to move all tables into a new schema, you can use the undocumented (and to be deprecated at some point, but unlikely!) sp_MSforeachtable stored procedure:

exec sp_MSforeachtable "ALTER SCHEMA TargetSchema TRANSFER ?"

Ref.: ALTER SCHEMA

SQL 2008: How do I change db schema to dbo

What is function overloading and overriding in php?

Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).

If you define your function like this:

function f($p=0)
{
  if($p)
  {
    //implement functionality #1 here
  }
  else
  {
    //implement functionality #2 here
  }
}

When you call this function like:

f();

you'll get one functionality (#1), but if you call it with parameter like:

f(1);

you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).

I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).

How do you normalize a file path in Bash?

Based on @Andre's answer, I might have a slightly better version, in case someone is after a loop-free, completely string-manipulation based solution. It is also useful for those who don't want to dereference any symlinks, which is the downside of using realpath or readlink -f.

It works on bash versions 3.2.25 and higher.

shopt -s extglob

normalise_path() {
    local path="$1"
    # get rid of /../ example: /one/../two to /two
    path="${path//\/*([!\/])\/\.\./}"
    # get rid of /./ and //* example: /one/.///two to /one/two
    path="${path//@(\/\.\/|\/+(\/))//}"
    # remove the last '/.'
    echo "${path%%/.}"
}

$ normalise_path /home/codemedic/../codemedic////.config
/home/codemedic/.config

Using an index to get an item, Python

What you show, ('A','B','C','D','E'), is not a list, it's a tuple (the round parentheses instead of square brackets show that). Nevertheless, whether it to index a list or a tuple (for getting one item at an index), in either case you append the index in square brackets.

So:

thetuple = ('A','B','C','D','E')
print thetuple[0]

prints A, and so forth.

Tuples (differently from lists) are immutable, so you couldn't assign to thetuple[0] etc (as you could assign to an indexing of a list). However you can definitely just access ("get") the item by indexing in either case.

SQL error "ORA-01722: invalid number"

An ORA-01722 error occurs when an attempt is made to convert a character string into a number, and the string cannot be converted into a number.

Without seeing your table definition, it looks like you're trying to convert the numeric sequence at the end of your values list to a number, and the spaces that delimit it are throwing this error. But based on the information you've given us, it could be happening on any field (other than the first one).

Setting focus to iframe contents

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

Why Does OAuth v2 Have Both Access and Refresh Tokens?

The link to discussion, provided by Catchdave, has another valid point (original, dead link) made by Dick Hardt, which I believe is worth to be mentioned here in addition to what's been written above:

My recollection of refresh tokens was for security and revocation. <...>

revocation: if the access token is self contained, authorization can be revoked by not issuing new access tokens. A resource does not need to query the authorization server to see if the access token is valid.This simplifies access token validation and makes it easier to scale and support multiple authorization servers. There is a window of time when an access token is valid, but authorization is revoked.

Indeed, in the situation where Resource Server and Authorization Server is the same entity, and where the connection between user and either of them is (usually) equally secure, there is not much sense to keep refresh token separate from the access token.

Although, as mentioned in the quote, another role of refresh tokens is to ensure the access token can be revoked at any time by the User (via the web-interface in their profiles, for example) while keeping the system scalable at the same time.

Generally, tokens can either be random identifiers pointing to the specific record in the Server's database, or they can contain all information in themselves (certainly, this information have to be signed, with MAC, for example).

How the system with long-lived access tokens should work

The server allows the Client to get access to User's data within a pre-defined set of scopes by issuing a token. As we want to keep the token revocable, we must store in the database the token along with the flag "revoked" being set or unset (otherwise, how would you do that with self-contained token?) Database can contain as much as len(users) x len(registered clients) x len(scopes combination) records. Every API request then must hit the database. Although it's quite trivial to make queries to such database performing O(1), the single point of failure itself can have negative impact on the scalability and performance of the system.

How the system with long-lived refresh token and short-lived access token should work

Here we issue two keys: random refresh token with the corresponding record in the database, and signed self-contained access token, containing among others the expiration timestamp field.

As the access token is self-contained, we don't have to hit the database at all to check its validity. All we have to do is to decode the token and to validate the signature and the timestamp.

Nonetheless, we still have to keep the database of refresh tokens, but the number of requests to this database is generally defined by the lifespan of the access token (the longer the lifespan, the lower the access rate).

In order to revoke the access of Client from a particular User, we should mark the corresponding refresh token as "revoked" (or remove it completely) and stop issuing new access tokens. It's obvious though that there is a window during which the refresh token has been revoked, but its access token may still be valid.

Tradeoffs

Refresh tokens partially eliminate the SPoF (Single Point of Failure) of Access Token database, yet they have some obvious drawbacks.

  1. The "window". A timeframe between events "user revokes the access" and "access is guaranteed to be revoked".

  2. The complication of the Client logic.

    without refresh token

    • send API request with access token
    • if access token is invalid, fail and ask user to re-authenticate

    with refresh token

    • send API request with access token
    • If access token is invalid, try to update it using refresh token
    • if refresh request passes, update the access token and re-send the initial API request
    • If refresh request fails, ask user to re-authenticate

I hope this answer does make sense and helps somebody to make more thoughtful decision. I'd like to note also that some well-known OAuth2 providers, including github and foursquare adopt protocol without refresh tokens, and seem happy with that.

Redirecting new tab on button click.(Response.Redirect) in asp.net C#

I think your code should work just remove one thing from here but it'll do redirection from current page within existing window

<asp:Button ID="btn" runat="Server" Text="SUBMIT" 

 OnClick="btnNewEntry_Click"/>    



protected void btnNewEntry_Click(object sender, EventArgs e)
 {
    Response.Redirect("CMS_1.aspx");
 }

And if u wanna do the this via client side scripting Use this way

<asp:Button ID="BTN" runat="server" Text="Submit" OnClientClick="window.open('Default2.aspx')" />

According to me you should prefer the Client Side Scripting because just to open a new window server side will take a post back and that will be useless..

Grep for beginning and end of line?

It should be noted that not only will the caret (^) behave differently within the brackets, it will have the opposite result of placing it outside of the brackets. Placing the caret where you have it will search for all strings NOT beginning with the content you placed within the brackets. You also would want to place a period before the asterisk in between your brackets as with grep, it also acts as a "wildcard".

grep ^[.rwx].*[0-9]$

This should work for you, I noticed that some posters used a character class in their expressions which is an effective method as well, but you were not using any in your original expression so I am trying to get one as close to yours as possible explaining every minor change along the way so that it is better understood. How can we learn otherwise?

How to convert DataSet to DataTable

Here is my solution:

DataTable datatable = (DataTable)dataset.datatablename;

How do I make bootstrap table rows clickable?

There is a javascript plugin that adds this feature to bootstrap.

When rowlink.js is included you can do:

<table data-link="row">
  <tr><td><a href="foo.html">Foo</a></td><td>This is Foo</td></tr>
  <tr><td><a href="bar.html">Bar</a></td><td>Bar is good</td></tr>
</table>

The table will be converted so that the whole row can be clicked instead of only the first column.

Why is git push gerrit HEAD:refs/for/master used instead of git push origin master

The documentation for Gerrit, in particular the "Push changes" section, explains that you push to the "magical refs/for/'branch' ref using any Git client tool".

The following image is taken from the Intro to Gerrit. When you push to Gerrit, you do git push gerrit HEAD:refs/for/<BRANCH>. This pushes your changes to the staging area (in the diagram, "Pending Changes"). Gerrit doesn't actually have a branch called <BRANCH>; it lies to the git client.

Internally, Gerrit has its own implementation for the Git and SSH stacks. This allows it to provide the "magical" refs/for/<BRANCH> refs.

When a push request is received to create a ref in one of these namespaces Gerrit performs its own logic to update the database, and then lies to the client about the result of the operation. A successful result causes the client to believe that Gerrit has created the ref, but in reality Gerrit hasn’t created the ref at all. [Link - Gerrit, "Gritty Details"].

The Gerrit workflow

After a successful patch (i.e, the patch has been pushed to Gerrit, [putting it into the "Pending Changes" staging area], reviewed, and the review has passed), Gerrit pushes the change from the "Pending Changes" into the "Authoritative Repository", calculating which branch to push it into based on the magic it did when you pushed to refs/for/<BRANCH>. This way, successfully reviewed patches can be pulled directly from the correct branches of the Authoritative Repository.

Why do we have to specify FromBody and FromUri?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.

There is a lot more information on the web if you google "web api parameter binding".

How to "crop" a rectangular image into a square with CSS?

Using background-size:cover - http://codepen.io/anon/pen/RNyKzB

CSS:

.image-container {
  background-image: url('http://i.stack.imgur.com/GA6bB.png');
  background-size:cover;
  background-repeat:no-repeat;
  width:250px;
  height:250px;
}  

Markup:

<div class="image-container"></div>

PHP: How to remove specific element from an array?

unset($array[array_search('strawberry', $array)]);

How to call a method after bean initialization is complete?

Have you tried implementing InitializingBean? It sounds like exactly what you're after.

The downside is that your bean becomes Spring-aware, but in most applications that's not so bad.

Using Powershell to stop a service remotely without WMI or remoting

This worked for me, but I used it as start. powershell outputs, waiting for service to finshing starting a few times then finishes and then a get-service on the remote server shows the service started.

**start**-service -inputobject $(get-service -ComputerName remotePC -Name Spooler)

Determine whether a Access checkbox is checked or not

Checkboxes are a control type designed for one purpose: to ensure valid entry of Boolean values.

In Access, there are two types:

  1. 2-state -- can be checked or unchecked, but not Null. Values are True (checked) or False (unchecked). In Access and VBA, the value of True is -1 and the value of False is 0. For portability with environments that use 1 for True, you can always test for False or Not False, since False is the value 0 for all environments I know of.

  2. 3-state -- like the 2-state, but can be Null. Clicking it cycles through True/False/Null. This is for binding to an integer field that allows Nulls. It is of no use with a Boolean field, since it can never be Null.

Minor quibble with the answers:

There is almost never a need to use the .Value property of an Access control, as it's the default property. These two are equivalent:

  ?Me!MyCheckBox.Value
  ?Me!MyCheckBox

The only gotcha here is that it's important to be careful that you don't create implicit references when testing the value of a checkbox. Instead of this:

  If Me!MyCheckBox Then

...write one of these options:

  If (Me!MyCheckBox) Then  ' forces evaluation of the control

  If Me!MyCheckBox = True Then

  If (Me!MyCheckBox = True) Then

  If (Me!MyCheckBox = Not False) Then

Likewise, when writing subroutines or functions that get values from a Boolean control, always declare your Boolean parameters as ByVal unless you actually want to manipulate the control. In that case, your parameter's data type should be an Access control and not a Boolean value. Anything else runs the risk of implicit references.

Last of all, if you set the value of a checkbox in code, you can actually set it to any number, not just 0 and -1, but any number other than 0 is treated as True (because it's Not False). While you might use that kind of thing in an HTML form, it's not proper UI design for an Access app, as there's no way for the user to be able to see what value is actually be stored in the control, which defeats the purpose of choosing it for editing your data.

How to add text to a WPF Label in code?

Label myLabel = new Label (); myLabel.Content = "Hello World!";

Select count(*) from result query

select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)select count(*) from(select count(SID) from Test where Date = '2012-12-10' group by SID)

should works

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

SSIS how to set connection string dynamically from a config file

Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:

  • XML configuration file
  • Environment variable
  • Registry entry
  • Parent package variable
  • SQL Server

Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.

How to make <input type="file"/> accept only these types?

The value of the accept attribute is, as per HTML5 LC, a comma-separated list of items, each of which is a specific media type like image/gif, or a notation like image/* that refers to all image types, or a filename extension like .gif. IE 10+ and Chrome support all of these, whereas Firefox does not support the extensions. Thus, the safest way is to use media types and notations like image/*, in this case

<input type="file" name="foo" accept=
"application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint,
text/plain, application/pdf, image/*">

if I understand the intents correctly. Beware that browsers might not recognize the media type names exactly as specified in the authoritative registry, so some testing is needed.

Add class to an element in Angular 4

you can try this without any java script you can do that just by using CSS

img:active,
img:focus,
img:hover{ 
border: 10px solid red !important
}

of if your case is to add any other css class by clicking you can use query selector like

<img id="image1" ng-click="changeClass(id)" >
<img id="image2" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >
<img id="image3" ng-click="changeClass(id)" >

in controller first search for any image with red border and remove it then by passing the image id add the border class to that image

$scope.changeClass = function(id){
angular.element(document.querySelector('.some-class').removeClass('.some-class');
angular.element(document.querySelector(id)).addClass('.some-class');
}

Checking length of dictionary object

What I do is use Object.keys() to return a list of all the keys and then get the length of that

Object.keys(dictionary).length

how to get multiple checkbox value using jquery

You can get them like this

$('#save_value').click(function() {
    $('.ads_Checkbox:checked').each(function() {
        alert($(this).val());
    });
});

jsfiddle

Ruby Array find_first object?

Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:

found_object = my_array.find { |e| e.satisfies_condition? }

otherwise you can use any?

found_it = my_array.any?  { |e| e.satisfies_condition? }

The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.

How to implement the --verbose or -v option into a script?

I stole the logging code from virtualenv for a project of mine. Look in main() of virtualenv.py to see how it's initialized. The code is sprinkled with logger.notify(), logger.info(), logger.warn(), and the like. Which methods actually emit output is determined by whether virtualenv was invoked with -v, -vv, -vvv, or -q.

Accessing a value in a tuple that is in a list

You can also use sequence unpacking with zip:

L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]

_, res = zip(*L)

print(res)

# (2, 3, 5, 4, 7, 7, 8)

This also creates a tuple _ from the discarded first elements. Extracting only the second is possible, but more verbose:

from itertools import islice

res = next(islice(zip(*L), 1, None))

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

Consider the following servlet conf:

   <servlet>
        <servlet-name>NewServlet</servlet-name>
        <servlet-class>NewServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>NewServlet</servlet-name>
        <url-pattern>/NewServlet/*</url-pattern>
    </servlet-mapping>

Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi, it will invoke NewServlet as it is mapped with the pattern described above.

Here:

getRequestURI() =  /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi

We have those ones:

  • getPathInfo()

    returns
    a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information

  • getRequestURI()

    returns
    a String containing the part of the URL from the protocol name up to the query string

SQL Server: Invalid Column Name

There can be many things:
First attempt, make a select of this field in its source table;
Check the instance of the sql script window, you may be in a different instance;
Check if your join is correct;
Verify query ambiguity, maybe you are making a wrong table reference
Of these checks, run the T-sql script again

[Image of the script SQL][1]
  [1]: https://i.stack.imgur.com/r59ZY.png`enter code here

Get Month name from month number

For Abbreviated Month Names : "Aug"

DateTimeFormatInfo.GetAbbreviatedMonthName Method (Int32)

Returns the culture-specific abbreviated name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(8)

For Full Month Names : "August"

DateTimeFormatInfo.GetMonthName Method (Int32)

Returns the culture-specific full name of the specified month based on the culture associated with the current DateTimeFormatInfo object.

string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(8);

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to fix C++ error: expected unqualified-id

As a side note, consider passing strings in setWord() as const references to avoid excess copying. Also, in displayWord, consider making this a const function to follow const-correctness.

void setWord(const std::string& word) {
  theWord = word;
}

When to use single quotes, double quotes, and backticks in MySQL

Backticks are generally used to indicate an identifier and as well be safe from accidentally using the Reserved Keywords.

For example:

Use `database`;

Here the backticks will help the server to understand that the database is in fact the name of the database, not the database identifier.

Same can be done for the table names and field names. This is a very good habit if you wrap your database identifier with backticks.

Check this answer to understand more about backticks.


Now about Double quotes & Single Quotes (Michael has already mentioned that).

But, to define a value you have to use either single or double quotes. Lets see another example.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, title1);

Here I have deliberately forgotten to wrap the title1 with quotes. Now the server will take the title1 as a column name (i.e. an identifier). So, to indicate that it's a value you have to use either double or single quotes.

INSERT INTO `tablename` (`id, `title`) VALUES ( NULL, 'title1');

Now, in combination with PHP, double quotes and single quotes make your query writing time much easier. Let's see a modified version of the query in your question.

$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

Now, using double quotes in the PHP, you will make the variables $val1, and $val2 to use their values thus creating a perfectly valid query. Like

$val1 = "my value 1";
$val2 = "my value 2";
$query = "INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, '$val1', '$val2')";

will make

INSERT INTO `table` (`id`, `col1`, `col2`) VALUES (NULL, 'my value 1', 'my value 2')

anaconda - graphviz - can't import after installation

For ubuntu users I recommend this way:

sudo apt-get install -y graphviz libgraphviz-dev

Declaring static constants in ES6 classes?

Here is one more way you can do

_x000D_
_x000D_
/*
one more way of declaring constants in a class,
Note - the constants have to be declared after the class is defined
*/
class Auto{
   //other methods
}
Auto.CONSTANT1 = "const1";
Auto.CONSTANT2 = "const2";

console.log(Auto.CONSTANT1)
console.log(Auto.CONSTANT2);
_x000D_
_x000D_
_x000D_

Note - the Order is important, you cannot have the constants above

Usage

console.log(Auto.CONSTANT1);

How can strings be concatenated?

Just a comment, as someone may find it useful - you can concatenate more than one string in one go:

>>> a='rabbit'
>>> b='fox'
>>> print '%s and %s' %(a,b)
rabbit and fox

npm behind a proxy fails with status 403

If you need to provide a username and password to authenticate at your proxy, this is the syntax to use:

npm config set proxy http://usr:pwd@host:port
npm config set https-proxy http://usr:pwd@host:port

grep using a character vector with multiple patterns

Have you tried the match() or charmatch() functions?

Example use:

match(c("A1", "A9", "A6"), myfile$Letter)

Group by & count function in sqlalchemy

If you are using Table.query property:

from sqlalchemy import func
Table.query.with_entities(Table.column, func.count(Table.column)).group_by(Table.column).all()

If you are using session.query() method (as stated in miniwark's answer):

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Dynamically change color to lighter or darker by percentage CSS (Javascript)

At the time of writing, here's the best pure CSS implementation for color manipulation I found:

Use CSS variables to define your colors in HSL instead of HEX/RGB format, then use calc() to manipulate them.

Here's a basic example:

_x000D_
_x000D_
:root {_x000D_
  --link-color-h: 211;_x000D_
  --link-color-s: 100%;_x000D_
  --link-color-l: 50%;_x000D_
  --link-color-hsl: var(--link-color-h), var(--link-color-s), var(--link-color-l);_x000D_
_x000D_
  --link-color: hsl(var(--link-color-hsl));_x000D_
  --link-color-10: hsla(var(--link-color-hsl), .1);_x000D_
  --link-color-20: hsla(var(--link-color-hsl), .2);_x000D_
  --link-color-30: hsla(var(--link-color-hsl), .3);_x000D_
  --link-color-40: hsla(var(--link-color-hsl), .4);_x000D_
  --link-color-50: hsla(var(--link-color-hsl), .5);_x000D_
  --link-color-60: hsla(var(--link-color-hsl), .6);_x000D_
  --link-color-70: hsla(var(--link-color-hsl), .7);_x000D_
  --link-color-80: hsla(var(--link-color-hsl), .8);_x000D_
  --link-color-90: hsla(var(--link-color-hsl), .9);_x000D_
_x000D_
  --link-color-warm: hsl(calc(var(--link-color-h) + 80), var(--link-color-s), var(--link-color-l));_x000D_
  --link-color-cold: hsl(calc(var(--link-color-h) - 80), var(--link-color-s), var(--link-color-l));_x000D_
_x000D_
  --link-color-low: hsl(var(--link-color-h), calc(var(--link-color-s) / 2), var(--link-color-l));_x000D_
  --link-color-lowest: hsl(var(--link-color-h), calc(var(--link-color-s) / 4), var(--link-color-l));_x000D_
_x000D_
  --link-color-light: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) / .9));_x000D_
  --link-color-dark: hsl(var(--link-color-h), var(--link-color-s), calc(var(--link-color-l) * .9));_x000D_
}_x000D_
_x000D_
.flex {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.flex > div {_x000D_
  flex: 1;_x000D_
  height: calc(100vw / 10);_x000D_
}
_x000D_
<h3>Color Manipulation (alpha)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-10)"></div>_x000D_
  <div style="background-color: var(--link-color-20)"></div>_x000D_
  <div style="background-color: var(--link-color-30)"></div>_x000D_
  <div style="background-color: var(--link-color-40)"></div>_x000D_
  <div style="background-color: var(--link-color-50)"></div>_x000D_
  <div style="background-color: var(--link-color-60)"></div>_x000D_
  <div style="background-color: var(--link-color-70)"></div>_x000D_
  <div style="background-color: var(--link-color-80)"></div>_x000D_
  <div style="background-color: var(--link-color-90)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Hue)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-warm)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-cold)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Saturation)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-low)"></div>_x000D_
  <div style="background-color: var(--link-color-lowest)"></div>_x000D_
</div>_x000D_
_x000D_
<h3>Color Manipulation (Lightness)</h3>_x000D_
_x000D_
<div class="flex">_x000D_
  <div style="background-color: var(--link-color-light)"></div>_x000D_
  <div style="background-color: var(--link-color)"></div>_x000D_
  <div style="background-color: var(--link-color-dark)"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

I also created a CSS framework (still in early stage) to provide basic CSS variables support called root-variables.

Javascript: best Singleton pattern

Extending the above post by Tom, if you need a class type declaration and access the singleton instance using a variable, the code below might be of help. I like this notation as the code is little self guiding.

function SingletonClass(){
    if ( arguments.callee.instance )
        return arguments.callee.instance;
    arguments.callee.instance = this;
}


SingletonClass.getInstance = function() {
    var singletonClass = new SingletonClass();
    return singletonClass;
};

To access the singleton, you would

var singleTon = SingletonClass.getInstance();

How to scroll to bottom in react?

If you want to do this with React Hooks, this method can be followed. For a dummy div has been placed at the bottom of the chat. useRef Hook is used here.

Hooks API Reference : https://reactjs.org/docs/hooks-reference.html#useref

import React, { useEffect, useRef } from 'react';

const ChatView = ({ ...props }) => {
const el = useRef(null);

useEffect(() => {
    el.current.scrollIntoView({ block: 'end', behavior: 'smooth' });
});

 return (
   <div>
     <div className="MessageContainer" >
       <div className="MessagesList">
         {this.renderMessages()}
       </div>
       <div id={'el'} ref={el}>
       </div>
     </div>
    </div>
  );
}

getting file size in javascript

You can't get the file size of local files with javascript in a standard way using a web browser.

But if the file is accessible from a remote path, you might be able to send a HEAD request using Javascript, and read the Content-length header, depending on the webserver

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

Read line with Scanner

next() and nextLine() methods are associated with Scanner and is used for getting String inputs. Their differences are...

next() can read the input only till the space. It can't read two words separated by space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

Read article :Difference between next() and nextLine()

Replace your while loop with :

while(r.hasNext()) {
                scan = r.next();
                System.out.println(scan);
                if(scan.length()==0) {continue;}
                //treatment
            }

Using hasNext() and next() methods will resolve the issue.

How do I cancel form submission in submit button onclick event?

You need to return false;:

<input type='submit' value='submit request' onclick='return btnClick();' />

function btnClick() {
    return validData();
}

SqlBulkCopy - The given value of type String from the data source cannot be converted to type money of the specified target column

Since I don't believe "Please use..." plus some random code that is unrelated to the question is a good answer, but I do believe the spirit was correct, I decided to answer this correctly.

When you are using Sql Bulk Copy, it attempts to align your input data directly with the data on the server. So, it takes the Server Table and performs a SQL statement similar to this:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES

Therefore, if you give it Columns 1, 3, and 2, EVEN THOUGH your names may match (e.g.: col1, col3, col2). It will insert like so:

INSERT INTO [schema].[table] (col1, col2, col3) VALUES
                          ('col1', 'col3', 'col2')

It would be extra work and overhead for the Sql Bulk Insert to have to determine a Column Mapping. So it instead allows you to choose... Either ensure your Code and your SQL Table columns are in the same order, or explicitly state to align by Column Name.

Therefore, if your issue is mis-alignment of the columns, which is probably the majority of the cause of this error, this answer is for you.

TLDR

using System.Data;
//...
myDataTable.Columns.Cast<DataColumn>().ToList().ForEach(x => 
    bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(x.ColumnName, x.ColumnName)));

This will take your existing DataTable, which you are attempt to insert into your created BulkCopy object, and it will just explicitly map name to name. Of course if, for some reason, you decided to name your DataTable Columns differently than your SQL Server Columns... that's on you.

Can the Android layout folder contain subfolders?

Check Bash Flatten Folder script that converts folder hierarchy to a single folder

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

How to change colour of blue highlight on select box dropdown

To both style the hover color and avoid the OS default color in Firefox, you need to add a box-shadow to both the select option and select option:hover declarations, setting the color of the box-shadow on "select option" to the menu background color.

select option {
  background: #f00; 
  color: #fff; 
  box-shadow: inset 20px 20px #f00
} 

select option:hover {
  color: #000; 
  box-shadow: inset 20px 20px #00f;
}

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

c++ Read from .csv file

Your csv is malformed. The output is not three loopings but just one output. To ensure that this is a single loop, add a counter and increment it with every loop. It should only count to one.

This is what your code sees

0,Filipe,19,M\n1,Maria,20,F\n2,Walter,60,M

Try this

0,Filipe,19,M
1,Maria,20,F
2,Walter,60,M


while(file.good())
{

    getline(file, ID, ',');
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero) ; \\ diff
    cout << "Sexo: " <<  genero;\\diff


}

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Use shell=True if you're passing a string to subprocess.call.

From docs:

If passing a single string, either shell must be True or else the string must simply name the program to be executed without specifying any arguments.

subprocess.call(crop, shell=True)

or:

import shlex
subprocess.call(shlex.split(crop))

Finding whether a point lies inside a rectangle or not

Assuming the rectangle is represented by three points A,B,C, with AB and BC perpendicular, you only need to check the projections of the query point M on AB and BC:

0 <= dot(AB,AM) <= dot(AB,AB) &&
0 <= dot(BC,BM) <= dot(BC,BC)

AB is vector AB, with coordinates (Bx-Ax,By-Ay), and dot(U,V) is the dot product of vectors U and V: Ux*Vx+Uy*Vy.

Update. Let's take an example to illustrate this: A(5,0) B(0,2) C(1,5) and D(6,3). From the point coordinates, we get AB=(-5,2), BC=(1,3), dot(AB,AB)=29, dot(BC,BC)=10.

For query point M(4,2), we have AM=(-1,2), BM=(4,0), dot(AB,AM)=9, dot(BC,BM)=4. M is inside the rectangle.

For query point P(6,1), we have AP=(1,1), BP=(6,-1), dot(AB,AP)=-3, dot(BC,BP)=3. P is not inside the rectangle, because its projection on side AB is not inside segment AB.

git: Your branch is ahead by X commits

If you get this message after doing a commit in order to untrack file in the branch, try making some change in any file and perform commit. Apparently you can't make single commit which includes only untracking previously tracked file. Finally this post helped me solve whole problem https://help.github.com/articles/removing-files-from-a-repository-s-history/. I just had to remove file from repository history.

JavaScript before leaving the page

This will alert on leaving current page

<script type='text/javascript'>
function goodbye(e) {
    if(!e) e = window.event;
    //e.cancelBubble is supported by IE - this will kill the bubbling process.
    e.cancelBubble = true;
    e.returnValue = 'You sure you want to leave?'; //This is displayed on the dialog

    //e.stopPropagation works in Firefox.
    if (e.stopPropagation) {
        e.stopPropagation();
        e.preventDefault();
    }
}
window.onbeforeunload=goodbye; 

</script>

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

How do I split a string, breaking at a particular character?

If Spliter is found then only

Split it

else return the same string

function SplitTheString(ResultStr) {
    if (ResultStr != null) {
        var SplitChars = '~';
        if (ResultStr.indexOf(SplitChars) >= 0) {
            var DtlStr = ResultStr.split(SplitChars);
            var name  = DtlStr[0];
            var street = DtlStr[1];
        }
    }
}

What's the difference between Git Revert, Checkout and Reset?

If you broke the tree but didn't commit the code, you can use git reset, and if you just want to restore one file, you can use git checkout.

If you broke the tree and committed the code, you can use git revert HEAD.

http://book.git-scm.com/4_undoing_in_git_-_reset,_checkout_and_revert.html

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

This works as well:

<dependency>
    <scope>compile</scope>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

so used jstl 1.2 instead of standard.jar together with jstl-api 1.2

.setAttribute("disabled", false); changes editable attribute to false

the disabled attributes value is actally not considered.. usually if you have noticed the attribute is set as disabled="disabled" the "disabled" here is not necessary persay.. thus the best thing to do is to remove the attribute.

element.removeAttribute("disabled");     

also you could do

element.disabled=false;

Better way to shuffle two numpy arrays in unison

X = np.array([[1., 0.], [2., 1.], [0., 0.]])
y = np.array([0, 1, 2])
from sklearn.utils import shuffle
X, y = shuffle(X, y, random_state=0)

To learn more, see http://scikit-learn.org/stable/modules/generated/sklearn.utils.shuffle.html

Google Map API v3 ~ Simply Close an infowindow?

Or you can share/reuse the same infoWindow object. See this google demo for reference.

Same code from demo

var Demo = { map: null,  infoWindow: null
};

/**
 * Called when clicking anywhere on the map and closes the info window.
 */
Demo.closeInfoWindow = function() {
  Demo.infoWindow.close();
};

/**
 * Opens the shared info window, anchors it to the specified marker, and
 * displays the marker's position as its content.
 */
Demo.openInfoWindow = function(marker) {
  var markerLatLng = marker.getPosition();
  Demo.infoWindow.setContent([
    '<b>Marker position is:</b><br/>',
    markerLatLng.lat(),
    ', ',
    markerLatLng.lng()
  ].join(''));
  Demo.infoWindow.open(Demo.map, marker);
},

/**
 * Called only once on initial page load to initialize the map.
 */
Demo.init = function() {
  // Create single instance of a Google Map.
  var centerLatLng = new google.maps.LatLng(37.789879, -122.390442);
  Demo.map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 13,
    center: centerLatLng,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  // Create a single instance of the InfoWindow object which will be shared
  // by all Map objects to display information to the user.
  Demo.infoWindow = new google.maps.InfoWindow();

  // Make the info window close when clicking anywhere on the map.
  google.maps.event.addListener(Demo.map, 'click', Demo.closeInfoWindow);

  // Add multiple markers in a few random locations around San Francisco.
  // First random marker
  var marker1 = new google.maps.Marker({
    map: Demo.map,
    position: centerLatLng
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker1, 'click', function() {
    Demo.openInfoWindow(marker1);
  });

  // Second random marker
  var marker2 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.787814,-122.40764),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker2, 'click', function() {
    Demo.openInfoWindow(marker2);
  });

  // Third random marker
  var marker3 = new google.maps.Marker({
    map: Demo.map,
    position: new google.maps.LatLng(37.767568,-122.391665),
    draggable: true
  });

  // Register event listeners to each marker to open a shared info
  // window displaying the marker's position when clicked or dragged.
  google.maps.event.addListener(marker3, 'click', function() {
    Demo.openInfoWindow(marker3);
  });
}

cout is not a member of std

add #include <iostream> to the start of io.cpp too.

How to create an empty R vector to add new items

You can create an empty vector like so

vec <- numeric(0)

And then add elements using c()

vec <- c(vec, 1:5)

However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Update for python 3.0 and later. Try the following in the python editor:

locale-gen en_US.UTF-8
export LANG=en_US.UTF-8 LANGUAGE=en_US.en
LC_ALL=en_US.UTF-8

This sets the system`s default locale encoding to the UTF-8 format.

More can be read here at PEP 538 -- Coercing the legacy C locale to a UTF-8 based locale.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

How to read file with async/await properly?

Since Node v11.0.0 fs promises are available natively without promisify:

const fs = require('fs').promises;
async function loadMonoCounter() {
    const data = await fs.readFile("monolitic.txt", "binary");
    return new Buffer(data);
}

GROUP BY having MAX date

Fast and easy with HAVING:

SELECT * FROM tblpm n 
FROM tblpm GROUP BY control_number 
HAVING date_updated=MAX(date_updated);

In the context of HAVING, MAX finds the max of each group. Only the latest entry in each group will satisfy date_updated=max(date_updated). If there's a tie for latest within a group, both will pass the HAVING filter, but GROUP BY means that only one will appear in the returned table.

Excel: Creating a dropdown using a list in another sheet?

Excel has a very powerful feature providing for a dropdown select list in a cell, reflecting data from a named region. It'a a very easy configuration, once you have done it before. Two steps are to follow:

Create a named region,
Setup the dropdown in a cell.

There is a detailed explanation of the process HERE.

Save file/open file dialog box, using Swing & Netbeans GUI editor

I think you face three problems:

  1. understanding the FileChooser
  2. writing/reading files
  3. understanding extensions and file formats

ad 1. Are you sure you've connected the FileChooser to a correct panel/container? I'd go for a simple tutorial on this matter and see if it works. That's the best way to learn - by making small but large enough steps forward. Breaking down an issue into such parts might be tricky sometimes ;)

ad. 2. After you save or open the file you should have methods to write or read the file. And again there are pretty neat examples on this matter and it's easy to understand topic.

ad. 3. There's a difference between a file having extension and file format. You can change the format of any file to anything you want but that doesn't affect it's contents. It might just render the file unreadable for the application associated with such extension. TXT files are easy - you read what you write. XLS, DOCX etc. require more work and usually framework is the best way to tackle these.

How do I convert NSInteger to NSString datatype?

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

Why does the C preprocessor interpret the word "linux" as the constant "1"?

Because linux is a built-in macro defined when the compiler is running on, or compiling for (if it is a cross-compiler), Linux.

There are a lot of such predefined macros. With GCC, you can use:

cp /dev/null emptyfile.c
gcc -E -dM emptyfile.c

to get a list of macros. (I've not managed to persuade GCC to accept /dev/null directly, but the empty file seems to work OK.) With GCC 4.8.1 running on Mac OS X 10.8.5, I got the output:

#define __DBL_MIN_EXP__ (-1021)
#define __UINT_LEAST16_MAX__ 65535
#define __ATOMIC_ACQUIRE 2
#define __FLT_MIN__ 1.17549435082228750797e-38F
#define __UINT_LEAST8_TYPE__ unsigned char
#define __INTMAX_C(c) c ## L
#define __CHAR_BIT__ 8
#define __UINT8_MAX__ 255
#define __WINT_MAX__ 2147483647
#define __ORDER_LITTLE_ENDIAN__ 1234
#define __SIZE_MAX__ 18446744073709551615UL
#define __WCHAR_MAX__ 2147483647
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 1
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 1
#define __DBL_DENORM_MIN__ ((double)4.94065645841246544177e-324L)
#define __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 1
#define __GCC_ATOMIC_CHAR_LOCK_FREE 2
#define __FLT_EVAL_METHOD__ 0
#define __GCC_ATOMIC_CHAR32_T_LOCK_FREE 2
#define __x86_64 1
#define __UINT_FAST64_MAX__ 18446744073709551615ULL
#define __SIG_ATOMIC_TYPE__ int
#define __DBL_MIN_10_EXP__ (-307)
#define __FINITE_MATH_ONLY__ 0
#define __GNUC_PATCHLEVEL__ 1
#define __UINT_FAST8_MAX__ 255
#define __DEC64_MAX_EXP__ 385
#define __INT8_C(c) c
#define __UINT_LEAST64_MAX__ 18446744073709551615ULL
#define __SHRT_MAX__ 32767
#define __LDBL_MAX__ 1.18973149535723176502e+4932L
#define __UINT_LEAST8_MAX__ 255
#define __GCC_ATOMIC_BOOL_LOCK_FREE 2
#define __APPLE_CC__ 1
#define __UINTMAX_TYPE__ long unsigned int
#define __DEC32_EPSILON__ 1E-6DF
#define __UINT32_MAX__ 4294967295U
#define __LDBL_MAX_EXP__ 16384
#define __WINT_MIN__ (-__WINT_MAX__ - 1)
#define __SCHAR_MAX__ 127
#define __WCHAR_MIN__ (-__WCHAR_MAX__ - 1)
#define __INT64_C(c) c ## LL
#define __DBL_DIG__ 15
#define __GCC_ATOMIC_POINTER_LOCK_FREE 2
#define __SIZEOF_INT__ 4
#define __SIZEOF_POINTER__ 8
#define __USER_LABEL_PREFIX__ _
#define __STDC_HOSTED__ 1
#define __LDBL_HAS_INFINITY__ 1
#define __FLT_EPSILON__ 1.19209289550781250000e-7F
#define __LDBL_MIN__ 3.36210314311209350626e-4932L
#define __DEC32_MAX__ 9.999999E96DF
#define __strong 
#define __INT32_MAX__ 2147483647
#define __SIZEOF_LONG__ 8
#define __APPLE__ 1
#define __UINT16_C(c) c
#define __DECIMAL_DIG__ 21
#define __LDBL_HAS_QUIET_NAN__ 1
#define __DYNAMIC__ 1
#define __GNUC__ 4
#define __MMX__ 1
#define __FLT_HAS_DENORM__ 1
#define __SIZEOF_LONG_DOUBLE__ 16
#define __BIGGEST_ALIGNMENT__ 16
#define __DBL_MAX__ ((double)1.79769313486231570815e+308L)
#define __INT_FAST32_MAX__ 2147483647
#define __DBL_HAS_INFINITY__ 1
#define __DEC32_MIN_EXP__ (-94)
#define __INT_FAST16_TYPE__ short int
#define __LDBL_HAS_DENORM__ 1
#define __DEC128_MAX__ 9.999999999999999999999999999999999E6144DL
#define __INT_LEAST32_MAX__ 2147483647
#define __DEC32_MIN__ 1E-95DF
#define __weak 
#define __DBL_MAX_EXP__ 1024
#define __DEC128_EPSILON__ 1E-33DL
#define __SSE2_MATH__ 1
#define __ATOMIC_HLE_RELEASE 131072
#define __PTRDIFF_MAX__ 9223372036854775807L
#define __amd64 1
#define __tune_core2__ 1
#define __ATOMIC_HLE_ACQUIRE 65536
#define __LONG_LONG_MAX__ 9223372036854775807LL
#define __SIZEOF_SIZE_T__ 8
#define __SIZEOF_WINT_T__ 4
#define __GXX_ABI_VERSION 1002
#define __FLT_MIN_EXP__ (-125)
#define __INT_FAST64_TYPE__ long long int
#define __DBL_MIN__ ((double)2.22507385850720138309e-308L)
#define __LP64__ 1
#define __DEC128_MIN__ 1E-6143DL
#define __REGISTER_PREFIX__ 
#define __UINT16_MAX__ 65535
#define __DBL_HAS_DENORM__ 1
#define __UINT8_TYPE__ unsigned char
#define __NO_INLINE__ 1
#define __FLT_MANT_DIG__ 24
#define __VERSION__ "4.8.1"
#define __UINT64_C(c) c ## ULL
#define __GCC_ATOMIC_INT_LOCK_FREE 2
#define __FLOAT_WORD_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __INT32_C(c) c
#define __DEC64_EPSILON__ 1E-15DD
#define __ORDER_PDP_ENDIAN__ 3412
#define __DEC128_MIN_EXP__ (-6142)
#define __INT_FAST32_TYPE__ int
#define __UINT_LEAST16_TYPE__ short unsigned int
#define __INT16_MAX__ 32767
#define __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ 1080
#define __SIZE_TYPE__ long unsigned int
#define __UINT64_MAX__ 18446744073709551615ULL
#define __INT8_TYPE__ signed char
#define __FLT_RADIX__ 2
#define __INT_LEAST16_TYPE__ short int
#define __LDBL_EPSILON__ 1.08420217248550443401e-19L
#define __UINTMAX_C(c) c ## UL
#define __SSE_MATH__ 1
#define __k8 1
#define __SIG_ATOMIC_MAX__ 2147483647
#define __GCC_ATOMIC_WCHAR_T_LOCK_FREE 2
#define __SIZEOF_PTRDIFF_T__ 8
#define __x86_64__ 1
#define __DEC32_SUBNORMAL_MIN__ 0.000001E-95DF
#define __INT_FAST16_MAX__ 32767
#define __UINT_FAST32_MAX__ 4294967295U
#define __UINT_LEAST64_TYPE__ long long unsigned int
#define __FLT_HAS_QUIET_NAN__ 1
#define __FLT_MAX_10_EXP__ 38
#define __LONG_MAX__ 9223372036854775807L
#define __DEC128_SUBNORMAL_MIN__ 0.000000000000000000000000000000001E-6143DL
#define __FLT_HAS_INFINITY__ 1
#define __UINT_FAST16_TYPE__ short unsigned int
#define __DEC64_MAX__ 9.999999999999999E384DD
#define __CHAR16_TYPE__ short unsigned int
#define __PRAGMA_REDEFINE_EXTNAME 1
#define __INT_LEAST16_MAX__ 32767
#define __DEC64_MANT_DIG__ 16
#define __INT64_MAX__ 9223372036854775807LL
#define __UINT_LEAST32_MAX__ 4294967295U
#define __GCC_ATOMIC_LONG_LOCK_FREE 2
#define __INT_LEAST64_TYPE__ long long int
#define __INT16_TYPE__ short int
#define __INT_LEAST8_TYPE__ signed char
#define __DEC32_MAX_EXP__ 97
#define __INT_FAST8_MAX__ 127
#define __INTPTR_MAX__ 9223372036854775807L
#define __LITTLE_ENDIAN__ 1
#define __SSE2__ 1
#define __LDBL_MANT_DIG__ 64
#define __CONSTANT_CFSTRINGS__ 1
#define __DBL_HAS_QUIET_NAN__ 1
#define __SIG_ATOMIC_MIN__ (-__SIG_ATOMIC_MAX__ - 1)
#define __code_model_small__ 1
#define __k8__ 1
#define __INTPTR_TYPE__ long int
#define __UINT16_TYPE__ short unsigned int
#define __WCHAR_TYPE__ int
#define __SIZEOF_FLOAT__ 4
#define __pic__ 2
#define __UINTPTR_MAX__ 18446744073709551615UL
#define __DEC64_MIN_EXP__ (-382)
#define __INT_FAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_TEST_AND_SET_TRUEVAL 1
#define __FLT_DIG__ 6
#define __UINT_FAST64_TYPE__ long long unsigned int
#define __INT_MAX__ 2147483647
#define __MACH__ 1
#define __amd64__ 1
#define __INT64_TYPE__ long long int
#define __FLT_MAX_EXP__ 128
#define __ORDER_BIG_ENDIAN__ 4321
#define __DBL_MANT_DIG__ 53
#define __INT_LEAST64_MAX__ 9223372036854775807LL
#define __GCC_ATOMIC_CHAR16_T_LOCK_FREE 2
#define __DEC64_MIN__ 1E-383DD
#define __WINT_TYPE__ int
#define __UINT_LEAST32_TYPE__ unsigned int
#define __SIZEOF_SHORT__ 2
#define __SSE__ 1
#define __LDBL_MIN_EXP__ (-16381)
#define __INT_LEAST8_MAX__ 127
#define __SIZEOF_INT128__ 16
#define __LDBL_MAX_10_EXP__ 4932
#define __ATOMIC_RELAXED 0
#define __DBL_EPSILON__ ((double)2.22044604925031308085e-16L)
#define _LP64 1
#define __UINT8_C(c) c
#define __INT_LEAST32_TYPE__ int
#define __SIZEOF_WCHAR_T__ 4
#define __UINT64_TYPE__ long long unsigned int
#define __INT_FAST8_TYPE__ signed char
#define __DBL_DECIMAL_DIG__ 17
#define __FXSR__ 1
#define __DEC_EVAL_METHOD__ 2
#define __UINT32_C(c) c ## U
#define __INTMAX_MAX__ 9223372036854775807L
#define __BYTE_ORDER__ __ORDER_LITTLE_ENDIAN__
#define __FLT_DENORM_MIN__ 1.40129846432481707092e-45F
#define __INT8_MAX__ 127
#define __PIC__ 2
#define __UINT_FAST32_TYPE__ unsigned int
#define __CHAR32_TYPE__ unsigned int
#define __FLT_MAX__ 3.40282346638528859812e+38F
#define __INT32_TYPE__ int
#define __SIZEOF_DOUBLE__ 8
#define __FLT_MIN_10_EXP__ (-37)
#define __INTMAX_TYPE__ long int
#define __DEC128_MAX_EXP__ 6145
#define __ATOMIC_CONSUME 1
#define __GNUC_MINOR__ 8
#define __UINTMAX_MAX__ 18446744073709551615UL
#define __DEC32_MANT_DIG__ 7
#define __DBL_MAX_10_EXP__ 308
#define __LDBL_DENORM_MIN__ 3.64519953188247460253e-4951L
#define __INT16_C(c) c
#define __STDC__ 1
#define __PTRDIFF_TYPE__ long int
#define __ATOMIC_SEQ_CST 5
#define __UINT32_TYPE__ unsigned int
#define __UINTPTR_TYPE__ long unsigned int
#define __DEC64_SUBNORMAL_MIN__ 0.000000000000001E-383DD
#define __DEC128_MANT_DIG__ 34
#define __LDBL_MIN_10_EXP__ (-4931)
#define __SIZEOF_LONG_LONG__ 8
#define __GCC_ATOMIC_LLONG_LOCK_FREE 2
#define __LDBL_DIG__ 18
#define __FLT_DECIMAL_DIG__ 9
#define __UINT_FAST16_MAX__ 65535
#define __GNUC_GNU_INLINE__ 1
#define __GCC_ATOMIC_SHORT_LOCK_FREE 2
#define __SSE3__ 1
#define __UINT_FAST8_TYPE__ unsigned char
#define __ATOMIC_ACQ_REL 4
#define __ATOMIC_RELEASE 3

That's 236 macros from an empty file. When I added #include <stdio.h> to the file, the number of macros defined went up to 505. These includes all sorts of platform-identifying macros.

json_encode sparse PHP array as JSON array, not JSON object

json_decode($jsondata, true);

true turns all properties to array (sequential or not)

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

Using env variable in Spring Boot's application.properties

I faced the same issue as the author of the question. For our case answers in this question weren't enough since each of the members of my team had a different local environment and we definitely needed to .gitignore the file that had the different db connection string and credentials, so people don't commit the common file by mistake and break others' db connections.

On top of that when we followed the procedure below it was easy to deploy on different environments and as en extra bonus we didn't need to have any sensitive information in the version control at all.

Getting the idea from PHP Symfony 3 framework that has a parameters.yml (.gitignored) and a parameters.yml.dist (which is a sample that creates the first one through composer install),

I did the following combining the knowledge from answers below: https://stackoverflow.com/a/35534970/986160 and https://stackoverflow.com/a/35535138/986160.

Essentially this gives the freedom to use inheritance of spring configurations and choose active profiles through configuration at the top one plus any extra sensitive credentials as follows:

application.yml.dist (sample)

    spring:
      profiles:
        active: local/dev/prod
      datasource:
        username:
        password:
        url: jdbc:mysql://localhost:3306/db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on dev server)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: verysecretpassword
    url: jdbc:mysql://localhost:3306/real_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application.yml (.gitignore-d on local machine)

spring:
  profiles:
    active: dev
  datasource:
    username: root
    password: rootroot
    url: jdbc:mysql://localhost:3306/xampp_db?useSSL=false&useLegacyDatetimeCode=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8

application-dev.yml (extra environment specific properties not sensitive)

spring:
  datasource:
    testWhileIdle: true
    validationQuery: SELECT 1
  jpa:
    show-sql: true
    format-sql: true
    hibernate:
      ddl-auto: create-droop
      naming-strategy: org.hibernate.cfg.ImprovedNamingStrategy
    properties:
      hibernate:
        dialect: org.hibernate.dialect.MySQL57InnoDBDialect

Same can be done with .properties

To show error message without alert box in Java Script

Setting innerHtml of input value wont do anything good here, try with other element like span, or just display previously made and hidden error message. You can set value of name field tho.

<head>
    <script type="text/javascript">
        function validate() {
            if (myform.fname.value.length == 0) {
                document.getElementById("fname").value = "this is invalid name ";
                document.getElementById("errorMessage").style.display = "block";
            }
        }
    </script>
</head>

<body>
    <form name="myform">First_Name
        <input type="text" id="fname" name="fname" onblur="validate()"></input> <span id="errorMessage" style="display:none;">name field must not be empty</span>

        <br>
        <br>Last_Name
        <input type="text" id="lname" name="lname" onblur="validate()"></input>
        <br>
        <input type="button" value="check" />
    </form>
</body>

FIDDLE

how to customize `show processlist` in mysql?

...We don't have a newer version of MySQL yet, so I was able to do this (works only on UNIX):

 host=maindb

 echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Locked

The above will query for all locked sessions, and return the information and SQL that is involved.

...So- assuming you wanted to query for sessions that were sleeping:

  host=maindb

  echo "show full processlist\G" | mysql -h$host | grep -B 6 -A 1 Sleep

Or, assuming you needed to provide additional connection parameters for MySQL:

  host=maindb

  user=me

  password=mycoolpassword 

  echo "show full processlist\G" | mysql -h$host -u$user -p$password | grep -B 6 -A 1 Locked

With a couple of tweaks, I'm sure a shell script could be easily created to query the processlist the way you want it.

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

iOS / Android cross platform development

In case you do not want to use a full-fledged framework for cross-platform development, take a look at C++ as an option. iOS fully supports using C++ for your application logic via Objective-C++. I don't know how well Android's support for C++ via the NDK is suited for doing your business logic in C++ rather than just some performance-critical code snippets, but in case that use case is well supported, you could give it a try.

This approach of course only makes sense if your application logic constitutes the greatest part of your project, as the user interfaces will have to be written individually for each platform.

As a matter of fact, C++ is the single most widely supported programming language (with the exception of C), and is therefore the core language of most large cross-platform applications.

CSS3 Continuous Rotate Animation (Just like a loading sundial)

Your issue here is that you've supplied a -webkit-TRANSITION-timing-function when you want a -webkit-ANIMATION-timing-function. Your values of 0 to 360 will work properly.

How to print Unicode character in C++?

If you use Windows (note, we are using printf(), not cout):

//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
    SetConsoleOutputCP(65001); 
    printf("?\n");
}

Not Unicode but working - 1251 instead of UTF8:

//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
    SetConsoleOutputCP(1251); 
    cout << "?" << endl;
}

How to pause a YouTube player when hiding the iframe?

just remove src of iframe

$('button.close').click(function(){
    $('iframe').attr('src','');;
});

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

How to install PyQt5 on Windows?

If you're using Windows 10, if you use

    py -m pip install pyqt5

in the command prompt it should download fine. Depending on either the version of Python or Windows sometimes python -m pip install pyqt5 isn't accepted, so you have to use py instead. pip is a good way to download a lot of stuff, so I'd recommend that.

Error: Argument is not a function, got undefined

To fix this problem, I had to discover that I misspelled the name of the controller in the declaration of Angular routes:

.when('/todo',{
            templateUrl: 'partials/todo.html',
            controller: 'TodoCtrl'
        })

Jquery, Clear / Empty all contents of tbody element?

jQuery:

$("#tbodyid").empty();

HTML:

<table>
    <tbody id="tbodyid">
        <tr>
            <td>something</td>
        </tr>
    </tbody>
</table>

Works for me
http://jsfiddle.net/mbsh3/

Vue.js toggle class on click

Without the need of a method:

// html element, will display'active' class if showMobile is true
//clicking on the elment will toggle showMobileMenu to true and false alternatively
<div id="mobile-toggle"
 :class="{ active: showMobileMenu }"
 @click="showMobileMenu = !showMobileMenu">
</div>

//in your vue.js app
data: {
    showMobileMenu: false
}

How to display all methods of an object?

I believe there's a simple historical reason why you can't enumerate over methods of built-in objects like Array for instance. Here's why:

Methods are properties of the prototype-object, say Object.prototype. That means that all Object-instances will inherit those methods. That's why you can use those methods on any object. Say .toString() for instance.

So IF methods were enumerable, and I would iterate over say {a:123} with: "for (key in {a:123}) {...}" what would happen? How many times would that loop be executed?

It would be iterated once for the single key 'a' in our example. BUT ALSO once for every enumerable property of Object.prototype. So if methods were enumerable (by default), then any loop over any object would loop over all its inherited methods as well.

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

If you have date as a datetime.datetime (or a datetime.date) instance and want to combine it via a time from a datetime.time instance, then you can use the classmethod datetime.datetime.combine:

import datetime
dt = datetime.datetime(2020, 7, 1)
t = datetime.time(12, 34)
combined = datetime.datetime.combine(dt.date(), t)

How to check if a file exists before creating a new file

The easiest way to do this is using ios :: noreplace.

Get parent of current directory from Python script

import os def parent_directory(): # Create a relative path to the parent # of the current working directory path = os.getcwd() parent = os.path.dirname(path)

relative_parent = os.path.join(path, parent)

# Return the absolute path of the parent directory
return relative_parent

print(parent_directory())

Adb Devices can't find my phone

I have a Fascinate as well, and had to change the phone's USB communication mode from MODEM to PDA. Use:

  • enter **USBUI (**87284)

to change both USB and UART to PDA mode. I also had to disconnect and reconnect the USB cable. Once Windows re-recognized the device again, "adb devices" started returning my device.

BTW if you use CDMA workshop or the equivalent, you will need to switch the setting back to MODEM.

How to get the current time in Google spreadsheet using script editor?

The Date object is used to work with dates and times.

Date objects are created with new Date().

var date= new Date();

 function myFunction() {
        var currentTime = new Date();
        Logger.log(currentTime);
    }

How to copy a char array in C?

As others have noted, strings are copied with strcpy() or its variants. In certain cases, you could use snprintf() as well.

You can only assign arrays the way you want as part of a structure assignment:

typedef struct { char a[18]; } array;
array array1 = { "abcdefg" };
array array2;

array2 = array1;

If your arrays are passed to a function, it will appear that you are allowed to assign them, but this is just an accident of the semantics. In C, an array will decay to a pointer type with the value of the address of the first member of the array, and this pointer is what gets passed. So, your array parameter in your function is really just a pointer. The assignment is just a pointer assignment:

void foo (char x[10], char y[10]) {
    x = y;    /* pointer assignment! */
    puts(x);
}

The array itself remains unchanged after returning from the function.

This "decay to pointer value" semantic for arrays is the reason that the assignment doesn't work. The l-value has the array type, but the r-value is the decayed pointer type, so the assignment is between incompatible types.

char array1[18] = "abcdefg";
char array2[18];
array2 = array1; /* fails because array1 becomes a pointer type,
                    but array2 is still an array type */

As to why the "decay to pointer value" semantic was introduced, this was to achieve a source code compatibility with the predecessor of C. You can read The Development of the C Language for details.

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

This linker error usually (in my experience) means that you've overridden a virtual function in a child class with a declaration, but haven't given a definition for the method. For example:

class Base
{
    virtual void f() = 0;
}
class Derived : public Base
{
    void f();
}

But you haven't given the definition of f. When you use the class, you get the linker error. Much like a normal linker error, it's because the compiler knew what you were talking about, but the linker couldn't find the definition. It's just got a very difficult to understand message.

Python: Fetch first 10 results from a list

The itertools module has lots of great stuff in it. So if a standard slice (as used by Levon) does not do what you want, then try the islice function:

from itertools import islice
l = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
iterator = islice(l, 10)
for item in iterator:
    print item

Xcode build failure "Undefined symbols for architecture x86_64"

UPD

Apple requires to use arm64 architecture. Do not use x32 libraries in your project

So the answer below is not correct anymore!


Old answer

The new Xcode 5.1 sets the architecture armv7,armv7s,and arm64 as default.

And sometimes the error "build failure “Undefined symbols for architecture x86_64”" may be caused by this. Because, some libs (not Apple's) were compiled for x32 originally and doesn't support x64.

So what you need, is to change the "Architectures" for your project target like this

NB. If you're using Cocoapods - you should do the same for "Pods" target.

enter image description here

How to position the Button exactly in CSS

It seems some what center of the screen. So I would like to do like this

body { 
     background: url('http://oi44.tinypic.com/33tjudk.jpg') no-repeat center center fixed;    
     background-size:cover; 
     text-align: 0 auto; // Make the play button horizontal center
}

#play_button {
    position:absolute;  // absolutely positioned
    transition: .5s ease;
    top: 50%;  // Makes vertical center
} 

python paramiko ssh

The code of @ThePracticalOne is great for showing the usage except for one thing: Somtimes the output would be incomplete.(session.recv_ready() turns true after the if session.recv_ready(): while session.recv_stderr_ready() and session.exit_status_ready() turned true before entering next loop)

so my thinking is to retrieving the data when it is ready to exit the session.

while True:
if session.exit_status_ready():
while True:
    while True:
        print "try to recv stdout..."
        ret = session.recv(nbytes)
        if len(ret) == 0:
            break
        stdout_data.append(ret)

    while True:
        print "try to recv stderr..."
        ret = session.recv_stderr(nbytes)
        if len(ret) == 0:
            break
        stderr_data.append(ret)
    break

How can I find the last element in a List<>?

Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:

AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);

And in your for loop:

for (int cnt3 = 0 ; cnt3 < integerList.Count ; cnt3++) //<----PROBLEM HERE
{
   AllIntegerIDs ids = integerList[cnt3];
   Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n",
      ids.m_MessageID,ids.m_MessageType,ids.m_ClassID,ids.m_CategoryID, ids.m_MessageText);
}

Script for rebuilding and reindexing the fragmented index?

The real answer, in 2016 and 2017, is: Use Ola Hallengren's scripts:

https://ola.hallengren.com/sql-server-index-and-statistics-maintenance.html

That is all any of us need to know or bother with, at this point in our mutual evolution.

ValidateRequest="false" doesn't work in Asp.Net 4

Found solution on the error page itself. Just needed to add requestValidationMode="2.0" in web.config

<system.web>
    <compilation debug="true" targetFramework="4.0" />
    <httpRuntime requestValidationMode="2.0" />
</system.web>

MSDN information: HttpRuntimeSection.RequestValidationMode Property

Regex Match all characters between two strings

RegEx to match everything between two strings using the Java approach.

List<String> results = new ArrayList<>(); //For storing results
String example = "Code will save the world";

Let's use Pattern and Matcher objects to use RegEx (.?)*.

Pattern p = Pattern.compile("Code "(.*?)" world");   //java.util.regex.Pattern;
Matcher m = p.matcher(example);                      //java.util.regex.Matcher;

Since Matcher might contain more than one match, we need to loop over the results and store it.

while(m.find()){   //Loop through all matches
   results.add(m.group()); //Get value and store in collection.
}

This example will contain only "will save the" word, but in the bigger text it will probably find more matches.

Fastest way to convert a dict's keys & values from `unicode` to `str`?

>>> d = {u"a": u"b", u"c": u"d"}
>>> d
{u'a': u'b', u'c': u'd'}
>>> import json
>>> import yaml
>>> d = {u"a": u"b", u"c": u"d"}
>>> yaml.safe_load(json.dumps(d))
{'a': 'b', 'c': 'd'}

Flask SQLAlchemy query, specify column names

An example here:

movies = Movie.query.filter(Movie.rating != 0).order_by(desc(Movie.rating)).all()

I query the db for movies with rating <> 0, and then I order them by rating with the higest rating first.

Take a look here: Select, Insert, Delete in Flask-SQLAlchemy

Gridview get Checkbox.Checked value

Try this,

Using foreach Loop:

foreach (GridViewRow row in GridView1.Rows)
{
     CheckBox chk = row.Cells[0].Controls[0] as CheckBox;
     if (chk != null && chk.Checked)
     {
       // ...
     }
}

Use it in OnRowCommand event and get checked CheckBox value.

GridViewRow row = (GridViewRow)(((Control)e.CommandSource).NamingContainer);
int requisitionId = Convert.ToInt32(e.CommandArgument);
CheckBox cbox = (CheckBox)row.Cells[3].Controls[0];

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon()

is what you should use. the thing is behind the scenes asp.net will destroy the session but immediately give the user a brand new session on the next page request. So if you're checking to see if the session is gone right after calling abandon it will look like it didn't work.

Determine if variable is defined in Python

try:
    a # does a exist in the current namespace
except NameError:
    a = 10 # nope

How to run Maven from another directory (without cd to project dir)?

You can try this:

pushd ../
maven install [...]
popd

Pointer to class data member "::*"

I think you'd only want to do this if the member data was pretty large (e.g., an object of another pretty hefty class), and you have some external routine which only works on references to objects of that class. You don't want to copy the member object, so this lets you pass it around.

Remove excess whitespace from within a string

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.

function secureRip(string $str): string { /* Rips all whitespace securely. */
  $arr = str_split($str, 1);
  $retStr = '';
  foreach ($arr as $char) {
    $retStr .= trim($char);
  }
  return $retStr;
}

Java Calendar, getting current month value, clarification needed

import java.util.*;

class GetCurrentmonth
{
    public static void main(String args[])
    {
        int month;
        GregorianCalendar date = new GregorianCalendar();      
        month = date.get(Calendar.MONTH);
        month = month+1;
        System.out.println("Current month is  " + month);
    }
}

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

Hey! I'm the developer of wxMathPlot! The project is active: I just took a long time to get a new release, because the code needed a partial rewriting to introduce new features. Take a look to the new 0.1.0 release: it is a great improvement from old versions. Anyway, it doesn't provide 3D (even if I always thinking about it...).

Lambda function in list comprehensions

People gave good answers but forgot to mention the most important part in my opinion: In the second example the X of the list comprehension is NOT the same as the X of the lambda function, they are totally unrelated. So the second example is actually the same as:

[Lambda X: X*X for I in range(10)]

The internal iterations on range(10) are only responsible for creating 10 similar lambda functions in a list (10 separate functions but totally similar - returning the power 2 of each input).

On the other hand, the first example works totally different, because the X of the iterations DO interact with the results, for each iteration the value is X*X so the result would be [0,1,4,9,16,25, 36, 49, 64 ,81]

Location of WSDL.exe

If you have Windows 10 and VS2019, and the .NET Framework 4.8, below you can see the Location of WSDL.exe

Path in your pc C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.8 Tools

Html.BeginForm and adding properties

You can also use the following syntax for the strongly typed version:

<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), 
          FormMethod.Post, 
          new { enctype = "multipart/form-data" })) 
   { %>

Display MessageBox in ASP

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>

<script>
function myFunction()
{
    alert("Hello!");
}
</script>

</body>
</html>

Copy Paste this in an HTML file and run in any browser , this should show an alert using javascript.

axios post request to send form data

Check out querystring.

You can use it as follows:

var querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

Min/Max-value validators in asp.net mvc

A complete example of how this could be done. To avoid having to write client-side validation scripts, the existing ValidationType = "range" has been used.

public class MinValueAttribute : ValidationAttribute, IClientValidatable
{
    private readonly double _minValue;

    public MinValueAttribute(double minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;  
    }

    public MinValueAttribute(int minValue)
    {
        _minValue = minValue;
        ErrorMessage = "Enter a value greater than or equal to " + _minValue;
    }

    public override bool IsValid(object value)
    {
        return Convert.ToDouble(value) >= _minValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();
        rule.ErrorMessage = ErrorMessage;
        rule.ValidationParameters.Add("min", _minValue);
        rule.ValidationParameters.Add("max", Double.MaxValue);
        rule.ValidationType = "range";
        yield return rule;
    }

}

Trying to load local JSON file to show data in a html page using JQuery

app.js

$("button").click( function() {
 $.getJSON( "article.json", function(obj) {
  $.each(obj, function(key, value) {
         $("ul").append("<li>"+value.name+"'s age is : "+value.age+"</li>");
  });
 });
});

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Tax Calulator</title>
    <script src="jquery-3.2.0.min.js" type="text/javascript"></script>
  </head>
  <body>
    <ul></ul>
    <button>Users</button>
<script type="text/javascript" src="app.js"></script>
  </body>
</html>

article.json

{
"a": {
"name": "Abra",
"age": 125,
"company": "Dabra"
},
"b": {
"name": "Tudak tudak",
"age": 228,
"company": "Dhidak dhidak"
}
}

server.js

var http = require('http');
var fs = require('fs');

function onRequest(request,response){
  if(request.method == 'GET' && request.url == '/') {
          response.writeHead(200,{"Content-Type":"text/html"});
          fs.createReadStream("./index.html").pipe(response);
  } else if(request.method == 'GET' && request.url == '/jquery-3.2.0.min.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./jquery-3.2.0.min.js").pipe(response);
  } else if(request.method == 'GET' && request.url == '/app.js') {
          response.writeHead(200,{"Content-Type":"text/javascript"});
          fs.createReadStream("./app.js").pipe(response);
  }
  else if(request.method == 'GET' && request.url == '/article.json') {
          response.writeHead(200,{"Content-Type":"text/json"});
          fs.createReadStream("./article.json").pipe(response);
  }
}

http.createServer(onRequest).listen(2341);
console.log("Server is running ....");

Server.js will run a simple node http server in your local to process the data.

Note don't forget toa dd jQuery library in your folder structure and change the version number accordingly in server.js and index.html

This is my running one https://github.com/surya4/jquery-json.

Display unescaped HTML in Vue.js

You can read that here

If you use

{{<br />}}

it'll be escaped. If you want raw html, you gotta use

{{{<br />}}}

EDIT (Feb 5 2017): As @hitautodestruct points out, in vue 2 you should use v-html instead of triple curly braces.

How do I read a date in Excel format in Python?

Since there's a chance that your excel files are coming from different computers/people; there's a chance that the formatting is messy; so be extra cautious.

I just imported data from 50 odd excels where the dates were entered in DD/MM/YYYY or DD-MM-YYYY, but most of the Excel files stored them as MM/DD/YYYY (Probably because the PCs were setup with en-us instead of en-gb or en-in).

Even more irritating was the fact that dates above 13/MM/YYYY were in DD/MM/YYYY format still. So there was variations within the Excel files.

The most reliable solution I figured out was to manually set the Date column on each excel file to to be Plain Text -- then use this code to parse it:

if date_str_from_excel:
    try:
        return datetime.strptime(date_str_from_excel, '%d/%m/%Y')
    except ValueError:
        print("Unable to parse date")

How to sort an object array by date property?

I recommend GitHub: Array sortBy - a best implementation of sortBy method which uses the Schwartzian transform

But for now we are going to try this approach Gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.

Creating the sorting function

var sortBy = (function () {
  var toString = Object.prototype.toString,
      // default parser function
      parse = function (x) { return x; },
      // gets the item to be sorted
      getItem = function (x) {
        var isObject = x != null && typeof x === "object";
        var isProp = isObject && this.prop in x;
        return this.parser(isProp ? x[this.prop] : x);
      };
      
  /**
   * Sorts an array of elements.
   *
   * @param {Array} array: the collection to sort
   * @param {Object} cfg: the configuration options
   * @property {String}   cfg.prop: property name (if it is an Array of objects)
   * @property {Boolean}  cfg.desc: determines whether the sort is descending
   * @property {Function} cfg.parser: function to parse the items to expected type
   * @return {Array}
   */
  return function sortby (array, cfg) {
    if (!(array instanceof Array && array.length)) return [];
    if (toString.call(cfg) !== "[object Object]") cfg = {};
    if (typeof cfg.parser !== "function") cfg.parser = parse;
    cfg.desc = !!cfg.desc ? -1 : 1;
    return array.sort(function (a, b) {
      a = getItem.call(cfg, a);
      b = getItem.call(cfg, b);
      return cfg.desc * (a < b ? -1 : +(a > b));
    });
  };
  
}());

Setting unsorted data

var data = [
  {date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0,   type: "cash"},
  {date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
  {date: "2011-11-14T16:30:43Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T17:22:59Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:53:41Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:48:46Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},
  {date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T16:58:03Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
  {date: "2011-11-14T17:07:21Z", quantity: 2, total: 90,  tip: 0,   type: "tab"},
  {date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0,   type: "cash"}
];

Using it

Finally, we arrange the array, by "date" property as string

//sort the object by a property (ascending)
//sorting takes into account uppercase and lowercase
sortBy(data, { prop: "date" });

If you want to ignore letter case, set the "parser" callback:

//sort the object by a property (descending)
//sorting ignores uppercase and lowercase
sortBy(data, {
    prop: "date",
    desc: true,
    parser: function (item) {
        //ignore case sensitive
        return item.toUpperCase();
    }
});

If you want to treat the "date" field as Date type:

//sort the object by a property (ascending)
//sorting parses each item to Date type
sortBy(data, {
    prop: "date",
    parser: function (item) {
        return new Date(item);
    }
});

Here you can play with the above example:
jsbin.com/lesebi

Python: Adding element to list while iterating

Why don't you just do it the idiomatic C way? This ought to be bullet-proof, but it won't be fast. I'm pretty sure indexing into a list in Python walks the linked list, so this is a "Shlemiel the Painter" algorithm. But I tend not to worry about optimization until it becomes clear that a particular section of code is really a problem. First make it work; then worry about making it fast, if necessary.

If you want to iterate over all the elements:

i = 0  
while i < len(some_list):  
  more_elements = do_something_with(some_list[i])  
  some_list.extend(more_elements)  
  i += 1  

If you only want to iterate over the elements that were originally in the list:

i = 0  
original_len = len(some_list)  
while i < original_len:  
  more_elements = do_something_with(some_list[i])  
  some_list.extend(more_elements)  
  i += 1

link with target="_blank" does not open in new tab in Chrome

If you use React this should work:

_x000D_
_x000D_
<a href="#" onClick={()=>window.open("https://...")}</a>
_x000D_
_x000D_
_x000D_

How to store Emoji Character in MySQL Database

If you are inserting using PHP, and you have followed the various ALTER database and ALTER table options above, make sure your php connection's charset is utf8mb4.

Example of connection string:

$this->pdo = new PDO("mysql:host=$ip;port=$port;dbname=$db;charset=utf8mb4", etc etc

Notice the "charset" is utf8mb4, not just utf8!

How to check if a Ruby object is a Boolean

There is no Boolean class in Ruby, the only way to check is to do what you're doing (comparing the object against true and false or the class of the object against TrueClass and FalseClass). Can't think of why you would need this functionality though, can you explain? :)

If you really need this functionality however, you can hack it in:

module Boolean; end
class TrueClass; include Boolean; end
class FalseClass; include Boolean; end

true.is_a?(Boolean) #=> true
false.is_a?(Boolean) #=> true

ReactJS map through Object

When calling Object.keys it returns a array of the object's keys.

Object.keys({ test: '', test2: ''}) // ['test', 'test2']

When you call Array#map the function you pass will give you 2 arguments;

  1. the item in the array,
  2. the index of the item.

When you want to get the data, you need to use item (or in the example below keyName) instead of i

{Object.keys(subjects).map((keyName, i) => (
    <li className="travelcompany-input" key={i}>
        <span className="input-label">key: {i} Name: {subjects[keyName]}</span>
    </li>
))}

What's the "Content-Length" field in HTTP header?

From this page

The most common use of POST, by far, is to submit HTML form data to CGI scripts. In this case, the Content-Type: header is usually application/x-www-form-urlencoded, and the Content-Length: header gives the length of the URL-encoded form data (here's a note on URL-encoding). The CGI script receives the message body through STDIN, and decodes it. Here's a typical form submission, using POST:

POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32

Re-doing a reverted merge in Git

  1. create new branch at commit prior to the original merge - call it it 'develop-base'
  2. perform interactive rebase of 'develop' on top of 'develop-base' (even though it's already on top). During interactive rebase, you'll have the opportunity to remove both the merge commit, and the commit that reversed the merge, i.e. remove both events from git history

At this point you'll have a clean 'develop' branch to which you can merge your feature brach as you regularly do.

JavaScript math, round to two decimal places

To get the result with two decimals, you can do like this :

var discount = Math.round((100 - (price / listprice) * 100) * 100) / 100;

The value to be rounded is multiplied by 100 to keep the first two digits, then we divide by 100 to get the actual result.

npx command not found

I returned to a system after a while, and even though it had Node 12.x, there was no npx or even npm available. I had installed Node via nvm, so I removed it, reinstalled it and then installed the latest Node LTS. This got me both npm and npx.

For loop example in MySQL

drop table if exists foo;
create table foo
(
id int unsigned not null auto_increment primary key,
val smallint unsigned not null default 0
)
engine=innodb;

drop procedure if exists load_foo_test_data;

delimiter #
create procedure load_foo_test_data()
begin

declare v_max int unsigned default 1000;
declare v_counter int unsigned default 0;

  truncate table foo;
  start transaction;
  while v_counter < v_max do
    insert into foo (val) values ( floor(0 + (rand() * 65535)) );
    set v_counter=v_counter+1;
  end while;
  commit;
end #

delimiter ;

call load_foo_test_data();

select * from foo order by id;

How do I install the ext-curl extension with PHP 7?

Well I was able to install it by :

sudo apt-get install php-curl

on my system. This will install a dependency package, which depends on the default php version.

After that restart apache

sudo service apache2 restart

What does "int 0x80" mean in assembly code?

Keep in mind that 0x80 = 80h = 128

You can see here that INT is just one of the many instructions (actually the Assembly Language representation (or should I say 'mnemonic') of it) that exists in the x86 instruction set. You can also find more information about this instruction in Intel's own manual found here.

To summarize from the PDF:

INT n/INTO/INT 3—Call to Interrupt Procedure

The INT n instruction generates a call to the interrupt or exception handler specified with the destination operand. The destination operand specifies a vector from 0 to 255, encoded as an 8-bit unsigned intermediate value. The INT n instruction is the general mnemonic for executing a software-generated call to an interrupt handler.

As you can see 0x80 is the destination operand in your question. At this point the CPU knows that it should execute some code that resides in the Kernel, but what code? That is determined by the Interrupt Vector in Linux.

One of the most useful DOS software interrupts was interrupt 0x21. By calling it with different parameters in the registers (mostly ah and al) you could access various IO operations, string output and more.

Most Unix systems and derivatives do not use software interrupts, with the exception of interrupt 0x80, used to make system calls. This is accomplished by entering a 32-bit value corresponding to a kernel function into the EAX register of the processor and then executing INT 0x80.

Take a look at this please where other available values in the interrupt handler tables are shown:

enter image description here

As you can see the table points the CPU to execute a system call. You can find the Linux System Call table here.

So by moving the value 0x1 to EAX register and calling the INT 0x80 in your program, you can make the process go execute the code in Kernel which will stop (exit) the current running process (on Linux, x86 Intel CPU).

A hardware interrupt must not be confused with a software interrupt. Here is a very good answer on this regard.

This also is good source.

concat scope variables into string in angular directive expression

I've created a working CodePen example demonstrating how to do this.

Relevant HTML:

<section ng-app="app" ng-controller="MainCtrl">
  <a href="#" ng-click="doSomething('#/path/{{obj.val1}}/{{obj.val2}}')">Click Me</a><br>
  debug: {{debug.val}}
</section>

Relevant javascript:

var app = angular.module('app', []);

app.controller('MainCtrl', function($scope) {
  $scope.obj = {
    val1: 'hello',
    val2: 'world'
  };

  $scope.debug = {
    val: ''
  };

  $scope.doSomething = function(input) {
    $scope.debug.val = input;
  };
});

jquery fill dropdown with json data

This should do the trick:

$($.parseJSON(data.msg)).map(function () {
    return $('<option>').val(this.value).text(this.label);
}).appendTo('#combobox');

Here's the distinction between ajax and getJSON (from the jQuery documentation):

[getJSON] is a shorthand Ajax function, which is equivalent to:

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

EDIT: To be clear, part of the problem was that the server's response was returning a json object that looked like this:

{
    "msg": '[{"value":"1","label":"xyz"}, {"value":"2","label":"abc"}]'
}

...So that msg property needed to be parsed manually using $.parseJSON().

@UniqueConstraint and @Column(unique = true) in hibernate annotation

As said before, @Column(unique = true) is a shortcut to UniqueConstraint when it is only a single field.

From the example you gave, there is a huge difference between both.

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private ProductSerialMask mask;

@Column(unique = true)
@ManyToOne(optional = false, fetch = FetchType.EAGER)
private Group group;

This code implies that both mask and group have to be unique, but separately. That means that if, for example, you have a record with a mask.id = 1 and tries to insert another record with mask.id = 1, you'll get an error, because that column should have unique values. The same aplies for group.

On the other hand,

@Table(
   name = "product_serial_group_mask", 
   uniqueConstraints = {@UniqueConstraint(columnNames = {"mask", "group"})}
)

Implies that the values of mask + group combined should be unique. That means you can have, for example, a record with mask.id = 1 and group.id = 1, and if you try to insert another record with mask.id = 1 and group.id = 2, it'll be inserted successfully, whereas in the first case it wouldn't.

If you'd like to have both mask and group to be unique separately and to that at class level, you'd have to write the code as following:

@Table(
        name = "product_serial_group_mask",
        uniqueConstraints = {
                @UniqueConstraint(columnNames = "mask"),
                @UniqueConstraint(columnNames = "group")
        }
)

This has the same effect as the first code block.

Getting full JS autocompletion under Sublime Text

Check if the snippets have <tabTrigger> attributes that start with special characters. If they do, they won't show up in the autocomplete box. This is currently a problem on Windows with the available jQuery plugins.

See my answer on this thread for more details.

Text file in VBA: Open/Find Replace/SaveAs/Close File

Guess I'm too late...

Came across the same problem today; here is my solution using FileSystemObject:

Dim objFSO
Const ForReading = 1
Const ForWriting = 2
Dim objTS 'define a TextStream object
Dim strContents As String
Dim fileSpec As String

fileSpec = "C:\Temp\test.txt"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTS = objFSO.OpenTextFile(fileSpec, ForReading)
strContents = objTS.ReadAll
strContents = Replace(strContents, "XXXXX", "YYYY")
objTS.Close

Set objTS = objFSO.OpenTextFile(fileSpec, ForWriting)
objTS.Write strContents
objTS.Close

How to print a percentage value in python?

You are dividing integers then converting to float. Divide by floats instead.

As a bonus, use the awesome string formatting methods described here: http://docs.python.org/library/string.html#format-specification-mini-language

To specify a percent conversion and precision.

>>> float(1) / float(3)
[Out] 0.33333333333333331

>>> 1.0/3.0
[Out] 0.33333333333333331

>>> '{0:.0%}'.format(1.0/3.0) # use string formatting to specify precision
[Out] '33%'

>>> '{percent:.2%}'.format(percent=1.0/3.0)
[Out] '33.33%'

A great gem!

Histogram with Logarithmic Scale and custom breaks

It's not entirely clear from your question whether you want a logged x-axis or a logged y-axis. A logged y-axis is not a good idea when using bars because they are anchored at zero, which becomes negative infinity when logged. You can work around this problem by using a frequency polygon or density plot.

How to check whether an object has certain method/property?

Wouldn't it be better to not use any dynamic types for this, and let your class implement an interface. Then, you can check at runtime wether an object implements that interface, and thus, has the expected method (or property).

public interface IMyInterface
{
   void Somemethod();
}


IMyInterface x = anyObject as IMyInterface;
if( x != null )
{
   x.Somemethod();
}

I think this is the only correct way.

The thing you're referring to is duck-typing, which is useful in scenarios where you already know that the object has the method, but the compiler cannot check for that. This is useful in COM interop scenarios for instance. (check this article)

If you want to combine duck-typing with reflection for instance, then I think you're missing the goal of duck-typing.

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

linq where list contains any in list

Or like this

class Movie
{
  public string FilmName { get; set; }
  public string Genre { get; set; }
}

...

var listofGenres = new List<string> { "action", "comedy" };

var Movies = new List<Movie> {new Movie {Genre="action", FilmName="Film1"},
                new Movie {Genre="comedy", FilmName="Film2"},
                new Movie {Genre="comedy", FilmName="Film3"},
                new Movie {Genre="tragedy", FilmName="Film4"}};

var movies = Movies.Join(listofGenres, x => x.Genre, y => y, (x, y) => x).ToList();

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

How to create an empty DataFrame with a specified schema?

I had a special requirement wherein I already had a dataframe but given a certain condition I had to return an empty dataframe so I returned df.limit(0) instead.

How to add 30 minutes to a JavaScript Date object?

Use an existing library known to handle the quirks involved in dealing with time calculations. My current favorite is moment.js.

<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.js"></script>
<script>
 var now = moment(); // get "now"
 console.log(now.toDate()); // show original date
 var thirty = moment(now).add(30,"minutes"); // clone "now" object and add 30 minutes, taking into account weirdness like crossing DST boundries or leap-days, -minutes, -seconds.
 console.log(thirty.toDate()); // show new date
</script>

android TextView: setting the background color dynamically doesn't work

here is in little detail,

if you are in activity use this

textview.setBackground(ContextCompat.getColor(this,R.color.yourcolor));

if you are in fragment use below code

textview.setBackground(ContextCompat.getColor(getActivity(),R.color.yourcolor));

if you are in recyclerview adapter use below code

textview.setBackground(ContextCompat.getColor(context,R.color.yourcolor));

// use holder.textview if you are in onBindviewholder
//here context is passed from fragment

How do I sum values in a column that match a given condition using pandas?

The essential idea here is to select the data you want to sum, and then sum them. This selection of data can be done in several different ways, a few of which are shown below.

Boolean indexing

Arguably the most common way to select the values is to use Boolean indexing.

With this method, you find out where column 'a' is equal to 1 and then sum the corresponding rows of column 'b'. You can use loc to handle the indexing of rows and columns:

>>> df.loc[df['a'] == 1, 'b'].sum()
15

The Boolean indexing can be extended to other columns. For example if df also contained a column 'c' and we wanted to sum the rows in 'b' where 'a' was 1 and 'c' was 2, we'd write:

df.loc[(df['a'] == 1) & (df['c'] == 2), 'b'].sum()

Query

Another way to select the data is to use query to filter the rows you're interested in, select column 'b' and then sum:

>>> df.query("a == 1")['b'].sum()
15

Again, the method can be extended to make more complicated selections of the data:

df.query("a == 1 and c == 2")['b'].sum()

Note this is a little more concise than the Boolean indexing approach.

Groupby

The alternative approach is to use groupby to split the DataFrame into parts according to the value in column 'a'. You can then sum each part and pull out the value that the 1s added up to:

>>> df.groupby('a')['b'].sum()[1]
15

This approach is likely to be slower than using Boolean indexing, but it is useful if you want check the sums for other values in column a:

>>> df.groupby('a')['b'].sum()
a
1    15
2     8

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

Connection timeouts (assuming a local network and several client machines) typically result from

a) some kind of firewall on the way that simply eats the packets without telling the sender things like "No Route to host"

b) packet loss due to wrong network configuration or line overload

c) too many requests overloading the server

d) a small number of simultaneously available threads/processes on the server which leads to all of them being taken. This happens especially with requests that take a long time to run and may combine with c).

Hope this helps.

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Take a look at OAuth 2.0 playground.You will get an overview of the protocol.It is basically an environment(like any app) that shows you the steps involved in the protocol.

https://developers.google.com/oauthplayground/

What's the best UI for entering date of birth?

I think a date picker just make the move more complicated to enter one's birth date.

As already mentioned, a combination of drop lists for days and months with a text box for the year seems the most efficient for a user. It takes just less than 10 seconds to enter a birth date this way, which is far quicker than a date picker: thanks to the tab key (which all users should learn to use to complete a form), it's fast to go from one form element to the next one.

At least under Macintosh (I don't know about Windows), you also can use the keyboard to access date inside select boxes: thanks to the tab key, you get the focus onto the form element, then press the arrow key to drop down the list, then type for instance 1967 and you get there in the blink of an eye…

Switch case on type c#

Update C# 7

Yes: Source

switch(shape)
{
    case Circle c:
        WriteLine($"circle with radius {c.Radius}");
        break;
    case Rectangle s when (s.Length == s.Height):
        WriteLine($"{s.Length} x {s.Height} square");
        break;
    case Rectangle r:
        WriteLine($"{r.Length} x {r.Height} rectangle");
        break;
    default:
        WriteLine("<unknown shape>");
        break;
    case null:
        throw new ArgumentNullException(nameof(shape));
}

Prior to C# 7

No.

http://blogs.msdn.com/b/peterhal/archive/2005/07/05/435760.aspx

We get a lot of requests for addditions to the C# language and today I'm going to talk about one of the more common ones - switch on type. Switch on type looks like a pretty useful and straightforward feature: Add a switch-like construct which switches on the type of the expression, rather than the value. This might look something like this:

switch typeof(e) { 
        case int:    ... break; 
        case string: ... break; 
        case double: ... break; 
        default:     ... break; 
}

This kind of statement would be extremely useful for adding virtual method like dispatch over a disjoint type hierarchy, or over a type hierarchy containing types that you don't own. Seeing an example like this, you could easily conclude that the feature would be straightforward and useful. It might even get you thinking "Why don't those #*&%$ lazy C# language designers just make my life easier and add this simple, timesaving language feature?"

Unfortunately, like many 'simple' language features, type switch is not as simple as it first appears. The troubles start when you look at a more significant, and no less important, example like this:

class C {}
interface I {}
class D : C, I {}

switch typeof(e) {
case C: … break;
case I: … break;
default: … break;
}

Link: https://blogs.msdn.microsoft.com/peterhal/2005/07/05/many-questions-switch-on-type/

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

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

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

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

Static and dynamic libraries each have pros and cons.

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

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

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

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

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

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

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

Is there a java setting for disabling certificate validation?

Use cli utility keytool from java software distribution for import (and trust!) needed certificates

Sample:

  1. From cli change dir to jre\bin

  2. Check keystore (file found in jre\bin directory)
    keytool -list -keystore ..\lib\security\cacerts
    Enter keystore password: changeit

  3. Download and save all certificates chain from needed server.

  4. Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"

accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK

source: http://www.java-samples.com/showtutorial.php?tutorialid=210

How to convert webpage into PDF by using Python

You also can use pdfkit:

Usage

import pdfkit
pdfkit.from_url('http://google.com', 'out.pdf')

Install

MacOS: brew install Caskroom/cask/wkhtmltopdf

Debian/Ubuntu: apt-get install wkhtmltopdf

Windows: choco install wkhtmltopdf

See official documentation for MacOS/Ubuntu/other OS: https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf

base_url() function not working in codeigniter

If you don't want to use the url helper, you can get the same results by using the following variable:

$this->config->config['base_url']

It will return the base url for you with no extra steps required.