Programs & Examples On #Containers

A container is a class, a data structure, or an abstract data type whose instances are collections of other objects. Containers typically make use of generics or templates so that a wide variety of objects can be added.

What are the complexity guarantees of the standard containers?

I'm not aware of anything like a single table that lets you compare all of them in at one glance (I'm not sure such a table would even be feasible).

Of course the ISO standard document enumerates the complexity requirements in detail, sometimes in various rather readable tables, other times in less readable bullet points for each specific method.

Also the STL library reference at http://www.cplusplus.com/reference/stl/ provides the complexity requirements where appropriate.

What's the difference between ClusterIP, NodePort and LoadBalancer service types in Kubernetes?

And do not forget the "new" service type (from the k8s docu):

ExternalName: Maps the Service to the contents of the externalName field (e.g. foo.bar.example.com), by returning a CNAME record with its value. No proxying of any kind is set up.

Note: You need either kube-dns version 1.7 or CoreDNS version 0.0.8 or higher to use the ExternalName type.

How to get IP address of running docker container

You can not access the docker's IP from outside of that host machine. If your browser is on another machine better to map the host port to container port by passing -p 8080:8080 to run command.

Passing -p you can map host port to container port and a proxy is set to forward all traffix for said host port to designated container port.

List only stopped Docker containers

Only stopped containers can be listed using:

docker ps --filter "status=exited"

or

docker ps -f "status=exited"

Singleton design pattern vs Singleton beans in Spring container

There is a very fundamental difference between the two. In case of Singleton design pattern, only one instance of a class will be created per classLoader while that is not the case with Spring singleton as in the later one shared bean instance for the given id per IoC container is created.

For example, if I have a class with the name "SpringTest" and my XML file looks something like this :-

<bean id="test1" class="com.SpringTest" scope="singleton">
        --some properties here
</bean>    
<bean id="test2" class="com.SpringTest" scope="singleton">
        --some properties here   
</bean>

So now in the main class if you will check the reference of the above two it will return false as according to Spring documentation:-

When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container

So as in our case, the classes are the same but the id's that we have provided are different hence resulting in two different instances being created.

How can I keep a container running on Kubernetes?

A container exits when its main process exits. Doing something like:

docker run -itd debian

to hold the container open is frankly a hack that should only be used for quick tests and examples. If you just want a container for testing for a few minutes, I would do:

docker run -d debian sleep 300

Which has the advantage that the container will automatically exit if you forget about it. Alternatively, you could put something like this in a while loop to keep it running forever, or just run an application such as top. All of these should be easy to do in Kubernetes.

The real question is why would you want to do this? Your container should be providing a service, whose process will keep the container running in the background.

Copy map values to vector in STL

If you are using the boost libraries, you can use boost::bind to access the second value of the pair as follows:

#include <string>
#include <map>
#include <vector>
#include <algorithm>
#include <boost/bind.hpp>

int main()
{
   typedef std::map<std::string, int> MapT;
   typedef std::vector<int> VecT;
   MapT map;
   VecT vec;

   map["one"] = 1;
   map["two"] = 2;
   map["three"] = 3;
   map["four"] = 4;
   map["five"] = 5;

   std::transform( map.begin(), map.end(),
                   std::back_inserter(vec),
                   boost::bind(&MapT::value_type::second,_1) );
}

This solution is based on a post from Michael Goldshteyn on the boost mailing list.

Returning a pointer to a vector element in c++

It is not a good idea to return iterators. Iterators become invalid when modifications to the vector (inversion\deletion ) happens. Also, the iterator is a local object created on stack and hence returning the address of the same is not at all safe. I'd suggest you to work with myObject rather than vector iterators.

EDIT: If the object is lightweight then its better you return the object itself. Otheriwise return pointers to myObject stored in the vector.

How do I stretch an image to fit the whole background (100% height x 100% width) in Flutter?

Your Question contains the first step, but you need width and height. you can get the width and height of the screen. Here is a small edit

//gets the screen width and height
double Width = MediaQuery.of(context).size.width;
double Height = MediaQuery.of(context).size.height;

Widget background = new Image.asset(
  asset.background,
  fit: BoxFit.fill,
  width: Width,
  height: Height,
);

return new Stack(
  children: <Widget>[
    background,
    foreground,
  ],
);

You can also use Width and Height to size other objects based on screen size.

ex: width: Height/2, height: Height/2 //using height for both keeps aspect ratio

docker: "build" requires 1 argument. See 'docker build --help'

Use the following command

docker build -t mytag .

Note that mytag and dot has a space between them . This dot represents the present working directory .

Docker error cannot delete docker container, conflict: unable to remove repository reference

If you want to cleanup docker images and containers

CAUTION: this will flush everything

stop all containers

docker stop $(docker ps -a -q)

remove all containers

docker rm $(docker ps -a -q)

remove all images

docker rmi -f $(docker images -a -q)

Connect to docker container as user other than root

For docker-compose. In the docker-compose.yml:

version: '3'
services:
    app:
        image: ...
        user: ${UID:-0}
...

In .env:

UID=1000

How to SSH into Docker?

I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.

However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.

How to set min-height for bootstrap container

Usually, if you are using bootstrap you can do this to set a min-height of 100%.

 <div class="container-fluid min-vh-100"></div>

this will also solve the footer not sticking at the bottom.

you can also do this from CSS with the following class

.stickDamnFooter{min-height: 100vh;}

if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.

How to change the size of the font of a JLabel to take the maximum size

Source Code for Label - How to change Color and Font (in Netbeans)

jLabel1.setFont(new Font("Serif", Font.BOLD, 12));


jLabel1.setForeground(Color.GREEN);

How is Docker different from a virtual machine?

I like Ken Cochrane's answer.

But I want to add additional point of view, not covered in detail here. In my opinion Docker differs also in whole process. In contrast to VMs, Docker is not (only) about optimal resource sharing of hardware, moreover it provides a "system" for packaging application (preferable, but not a must, as a set of microservices).

To me it fits in the gap between developer-oriented tools like rpm, Debian packages, Maven, npm + Git on one side and ops tools like Puppet, VMware, Xen, you name it...

Why is deploying software to a docker image (if that's the right term) easier than simply deploying to a consistent production environment?

Your question assumes some consistent production environment. But how to keep it consistent? Consider some amount (>10) of servers and applications, stages in the pipeline.

To keep this in sync you'll start to use something like Puppet, Chef or your own provisioning scripts, unpublished rules and/or lot of documentation... In theory servers can run indefinitely, and be kept completely consistent and up to date. Practice fails to manage a server's configuration completely, so there is considerable scope for configuration drift, and unexpected changes to running servers.

So there is a known pattern to avoid this, the so called immutable server. But the immutable server pattern was not loved. Mostly because of the limitations of VMs that were used before Docker. Dealing with several gigabytes big images, moving those big images around, just to change some fields in the application, was very very laborious. Understandable...

With a Docker ecosystem, you will never need to move around gigabytes on "small changes" (thanks aufs and Registry) and you don't need to worry about losing performance by packaging applications into a Docker container at runtime. You don't need to worry about versions of that image.

And finally you will even often be able to reproduce complex production environments even on your Linux laptop (don't call me if doesn't work in your case ;))

And of course you can start Docker containers in VMs (it's a good idea). Reduce your server provisioning on the VM level. All the above could be managed by Docker.

P.S. Meanwhile Docker uses its own implementation "libcontainer" instead of LXC. But LXC is still usable.

How to run a cron job inside a docker container?

When you deploy your container on another host, just note that it won't start any processes automatically. You need to make sure that 'cron' service is running inside your container. In our case, I am using Supervisord with other services to start cron service.

[program:misc]
command=/etc/init.d/cron restart
user=root
autostart=true
autorestart=true
stderr_logfile=/var/log/misc-cron.err.log
stdout_logfile=/var/log/misc-cron.out.log
priority=998

How to move Docker containers between different hosts?

What eventually worked for me, after lot's of confusing manuals and confusing tutorials, since Docker is obviously at time of my writing at peek of inflated expectations, is:

  1. Save the docker image into archive:
    docker save image_name > image_name.tar
  2. copy on another machine
  3. on that other docker machine, run docker load in a following way:
    cat image_name.tar | docker load

Export and import, as proposed in another answers does not export ports and variables, which might be required for your container to run. And you might end up with stuff like "No command specified" etc... When you try to load it on another machine.

So, difference between save and export is that save command saves whole image with history and metadata, while export command exports only files structure (without history or metadata).

Needless to say is that, if you already have those ports taken on the docker hyper-visor you are doing import, by some other docker container, you will end-up in conflict, and you will have to reconfigure exposed ports.

Note: In order to move data with docker, you might be having persistent storage somewhere, which should also be moved alongside with containers.

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

How can I use std::maps with user-defined types as key?

Keys must be comparable, but you haven't defined a suitable operator< for your custom class.

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

When to use MyISAM and InnoDB?

Use MyISAM for very unimportant data or if you really need those minimal performance advantages. The read performance is not better in every case for MyISAM.

I would personally never use MyISAM at all anymore. Choose InnoDB and throw a bit more hardware if you need more performance. Another idea is to look at database systems with more features like PostgreSQL if applicable.

EDIT: For the read-performance, this link shows that innoDB often is actually not slower than MyISAM: https://www.percona.com/blog/2007/01/08/innodb-vs-myisam-vs-falcon-benchmarks-part-1/

How to delete columns in numpy.array

In your situation, you can extract the desired data with:

a[:, -z]

"-z" is the logical negation of the boolean array "z". This is the same as:

a[:, logical_not(z)]

File being used by another process after using File.Create()

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

jQuery count child elements

fastest one:

$("div#selected ul li").length

HTML img tag: title attribute vs. alt attribute?

I would ALWAYS go with both the alt and the title attributes. Many developers have been using this pattern now for over 20 years to deal with IE and other issues. So this is not new knowledge. Its just been rediscovered by new developers that didn't bother to learn from the past.

In addition, in HTML5 you should start using the new HTML5 picture element wrapped in figure with full WPA-ARIA attributes for greater accessibility, as well as support of assistive technologies, screen readers, and the like. Because this element is not supported in many older browsers...BUT degrades gracefully...I recommend the following HTML design pattern now for images in HTML:

<figure aria-labelledby="picturecaption2">
    <picture id="picture2">
        <source srcset="image.webp" type="image/webp" media="(min-width: 800px)" />
        <source srcset="image.gif" type="image/gif" />
        <img id="image2" style="height:auto;max-width: 100%;" src="image.jpg" width="255" height="200" alt="image:The World Wide Web" title="The World Wide Web" loading="lazy" no-referrer="no-referrer" onerror="this.onerror=null;" />
    </picture>
    <figcaption id="picturecaption2"><small>"My Cool Picture" [<a href="http://creativecommons.org/licenses/" target="_blank">A License</a>] , via <a href="https://commons.wikimedia.org/wiki/" target="_blank">Wikimedia Commons</a></small></figcaption>
</figure>

The code above has many extra "goodies" beside alt and title, including ARIA attributes, support for WebP, a media query supporting higher resolution imagery, and a nice fallback pattern supporting older image formats. It shows a fully decorated image example that uses new technologies while still supporting old ones with progressive design patterns.

REMEMBER...ALWAYS SUPPORT THE OLD BROWSERS!

"Unknown class <MyClass> in Interface Builder file" error at runtime

I keep having this error with WatchKit over and over again and it seems to be when there is a user interface element that isn't tied to an outlet in code. I guess this is required in WatchKit.

class InterfaceController: WKInterfaceController {
    @IBOutlet weak var table: WKInterfaceTable!
}

Important note: just connect the outermost element. For instance if you try to also give a connection for something within the table like a label inside a row you will get a compiler error saying the outlet is invalid and cannot be connected to repeating content.

Is there a Public FTP server to test upload and download?

Tele2 provides ftp://speedtest.tele2.net , you can log in as anonymous and upload anything to test your upload speed. For download testing they provide fixed size files, you can choose which fits best to your test.

You can connect with username of anonymous and any password (e.g. anonymous ). You can upload files to upload folder. You can't create new folder here. Your file is deleted immediately after successful upload.

Found here: http://speedtest.tele2.net/

How can building a heap be O(n) time complexity?

think you're making a mistake. Take a look at this: http://golang.org/pkg/container/heap/ Building a heap isn'y O(n). However, inserting is O(lg(n). I'm assuming initialization is O(n) if you set a heap size b/c the heap needs to allocate space and set up the data structure. If you have n items to put into the heap then yes, each insert is lg(n) and there are n items, so you get n*lg(n) as u stated

Convert Python ElementTree to string

How do I convert ElementTree.Element to a String?

For Python 3:

xml_str = ElementTree.tostring(xml, encoding='unicode')

For Python 2:

xml_str = ElementTree.tostring(xml, encoding='utf-8')

The following is compatible with both Python 2 & 3, but only works for Latin characters:

xml_str = ElementTree.tostring(xml).decode()

Example usage

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
xml_str = ElementTree.tostring(xml).decode()
print(xml_str)

Output:

<Person Name="John" />

Explanation

Despite what the name implies, ElementTree.tostring() returns a bytestring by default in Python 2 & 3. This is an issue in Python 3, which uses Unicode for strings.

In Python 2 you could use the str type for both text and binary data. Unfortunately this confluence of two different concepts could lead to brittle code which sometimes worked for either kind of data, sometimes not. [...]

To make the distinction between text and binary data clearer and more pronounced, [Python 3] made text and binary data distinct types that cannot blindly be mixed together.

Source: Porting Python 2 Code to Python 3

If we know what version of Python is being used, we can specify the encoding as unicode or utf-8. Otherwise, if we need compatibility with both Python 2 & 3, we can use decode() to convert into the correct type.

For reference, I've included a comparison of .tostring() results between Python 2 and Python 3.

ElementTree.tostring(xml)
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml, encoding='unicode')
# Python 3: <Person Name="John" />
# Python 2: LookupError: unknown encoding: unicode

ElementTree.tostring(xml, encoding='utf-8')
# Python 3: b'<Person Name="John" />'
# Python 2: <Person Name="John" />

ElementTree.tostring(xml).decode()
# Python 3: <Person Name="John" />
# Python 2: <Person Name="John" />

Thanks to Martijn Peters for pointing out that the str datatype changed between Python 2 and 3.


Why not use str()?

In most scenarios, using str() would be the "cannonical" way to convert an object to a string. Unfortunately, using this with Element returns the object's location in memory as a hexstring, rather than a string representation of the object's data.

from xml.etree import ElementTree

xml = ElementTree.Element("Person", Name="John")
print(str(xml))  # <Element 'Person' at 0x00497A80>

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyController':

Exception clearly indicates the problem.

CompteDAOHib: No default constructor found

For spring to instantiate your bean, you need to provide a empty constructor for your class CompteDAOHib.

Python: Find index of minimum item in list of floats

I think it's worth putting a few timings up here for some perspective.

All timings done on OS-X 10.5.8 with python2.7

John Clement's answer:

python -m timeit -s 'my_list = range(1000)[::-1]; from operator import itemgetter' 'min(enumerate(my_list),key=itemgetter(1))'
1000 loops, best of 3: 239 usec per loop    

David Wolever's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'min((val, idx) for (idx, val) in enumerate(my_list))
1000 loops, best of 3: 345 usec per loop

OP's answer:

python -m timeit -s 'my_list = range(1000)[::-1]' 'my_list.index(min(my_list))'
10000 loops, best of 3: 96.8 usec per loop

Note that I'm purposefully putting the smallest item last in the list to make .index as slow as it could possibly be. It would be interesting to see at what N the iterate once answers would become competitive with the iterate twice answer we have here.

Of course, speed isn't everything and most of the time, it's not even worth worrying about ... choose the one that is easiest to read unless this is a performance bottleneck in your code (and then profile on your typical real-world data -- preferably on your target machines).

Inline style to act as :hover in CSS

If that <p> tag is created from JavaScript, then you do have another option: use JSS to programmatically insert stylesheets into the document head. It does support '&:hover'. https://cssinjs.org/

Can I force a UITableView to hide the separator between empty cells?

I use the following:

UIView *view = [[UIView alloc] init];
myTableView.tableFooterView = view;
[view release];

Doing it in viewDidLoad. But you can set it anywhere.

Can you nest html forms?

Even if you could get it to work in one browser, there's no guarantee that it would work the same in all browsers. So while you might be able to get it to work some of the time, you certainly wouldn't be able to get it to work all of the time.

Phone mask with jQuery and Masked Input Plugin

Actually the correct answer is on http://jsfiddle.net/HDakN/

Zoltan answer will allow user entry "(99) 9999" and then leave the field incomplete

$("#phone").mask("(99) 9999-9999?9");


$("#phone").on("blur", function() {
    var last = $(this).val().substr( $(this).val().indexOf("-") + 1 );

    if( last.length == 5 ) {
        var move = $(this).val().substr( $(this).val().indexOf("-") + 1, 1 );

        var lastfour = last.substr(1,4);

        var first = $(this).val().substr( 0, 9 );

        $(this).val( first + move + '-' + lastfour );
    }
});?

Can you Run Xcode in Linux?

I think you need MonoTouch (not free!) for that plugin.

And no, there is no way to run Xcode on Linux.

Sorry for all the bad news. :)

Artificially create a connection timeout error

You can use the Python REPL to simulate a timeout while receiving data (i.e. after a connection has been established successfully). Nothing but a standard Python installation is needed.

Python 2.7.4 (default, Apr  6 2013, 19:54:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)        
>>> s.bind(('localhost', 9000))
>>> s.listen(0)
>>> (clientsocket, address) = s.accept()

Now it waits for an incoming connection. Connect whatever you want to test to localhost:9000. When you do, Python will accept the connection and accept() will return it. Unless you send any data through the clientsocket, the caller's socket should time out during the next recv().

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

How to print the number of characters in each line of a text file

Try this:

while read line    
do    
    echo -e |wc -m      
done <abc.txt    

What's the difference between SortedList and SortedDictionary?

Index access (mentioned here) is the practical difference. If you need to access the successor or predecessor, you need SortedList. SortedDictionary cannot do that so you are fairly limited with how you can use the sorting (first / foreach).

Visual Studio can't 'see' my included header files

Delete the .sdf file that is in your solution directory. It's just the Intellisense database, and Visual Studio will recreate it the next time you open that solution. This db can get corrupted and cause the IDE to not be able to find things, and since the compiler generates this information for itself on the fly, it wouldn't be affected.

In Windows cmd, how do I prompt for user input and use the result in another command?

Just added the

set /p NetworkLocation= Enter name for network?

echo %NetworkLocation% >> netlist.txt

sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.

How can I check if the current date/time is past a set date/time?

Since PHP >= 5.2.2 you can use the DateTime class as such:

if (new DateTime() > new DateTime("2010-05-15 16:00:00")) {
    # current time is greater than 2010-05-15 16:00:00
    # in other words, 2010-05-15 16:00:00 has passed
}

The string passed to the DateTime constructor is parsed according to these rules.


Note that it is also possible to use time and strtotime functions. See original answer.

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

You could simply use

return

which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.

How to change the color of an image on hover

Use the background-color property instead of the background property in your CSS. So your code will look like this:
.fb-icon:hover {
background: blue;
}

WAMP Cannot access on local network 403 Forbidden

I got this answer from here. and its works for me

Require local

Change to

Require all granted
Order Deny,Allow
Allow from all

How do I pass variables and data from PHP to JavaScript?

There are actually several approaches to do this. Some require more overhead than others, and some are considered better than others.

In no particular order:

  1. Use AJAX to get the data you need from the server.
  2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM.
  3. Echo the data directly to JavaScript.

In this post, we'll examine each of the above methods, and see the pros and cons of each, as well as how to implement them.

1. Use AJAX to get the data you need from the server

This method is considered the best, because your server side and client side scripts are completely separate.

Pros

  • Better separation between layers - If tomorrow you stop using PHP, and want to move to a servlet, a REST API, or some other service, you don't have to change much of the JavaScript code.
  • More readable - JavaScript is JavaScript, PHP is PHP. Without mixing the two, you get more readable code on both languages.
  • Allows for asynchronous data transfer - Getting the information from PHP might be time/resources expensive. Sometimes you just don't want to wait for the information, load the page, and have the information reach whenever.
  • Data is not directly found on the markup - This means that your markup is kept clean of any additional data, and only JavaScript sees it.

Cons

  • Latency - AJAX creates an HTTP request, and HTTP requests are carried over network and have network latencies.
  • State - Data fetched via a separate HTTP request won't include any information from the HTTP request that fetched the HTML document. You may need this information (e.g., if the HTML document is generated in response to a form submission) and, if you do, will have to transfer it across somehow. If you have ruled out embedding the data in the page (which you have if you are using this technique) then that limits you to cookies/sessions which may be subject to race conditions.

Implementation Example

With AJAX, you need two pages, one is where PHP generates the output, and the second is where JavaScript gets that output:

get-data.php

/* Do some operation here, like talk to the database, the file-session
 * The world beyond, limbo, the city of shimmers, and Canada.
 *
 * AJAX generally uses strings, but you can output JSON, HTML and XML as well.
 * It all depends on the Content-type header that you send with your AJAX
 * request. */

echo json_encode(42); // In the end, you need to echo the result.
                      // All data should be json_encode()d.

                      // You can json_encode() any value in PHP, arrays, strings,
                      //even objects.

index.php (or whatever the actual page is named like)

<!-- snip -->
<script>
    function reqListener () {
      console.log(this.responseText);
    }

    var oReq = new XMLHttpRequest(); // New request object
    oReq.onload = function() {
        // This is where you handle what to do with the response.
        // The actual data is found on this.responseText
        alert(this.responseText); // Will alert: 42
    };
    oReq.open("get", "get-data.php", true);
    //                               ^ Don't block the rest of the execution.
    //                                 Don't wait until the request finishes to
    //                                 continue.
    oReq.send();
</script>
<!-- snip -->

The above combination of the two files will alert 42 when the file finishes loading.

Some more reading material

2. Echo the data into the page somewhere, and use JavaScript to get the information from the DOM

This method is less preferable to AJAX, but it still has its advantages. It's still relatively separated between PHP and JavaScript in a sense that there is no PHP directly in the JavaScript.

Pros

  • Fast - DOM operations are often quick, and you can store and access a lot of data relatively quickly.

Cons

  • Potentially Unsemantic Markup - Usually, what happens is that you use some sort of <input type=hidden> to store the information, because it's easier to get the information out of inputNode.value, but doing so means that you have a meaningless element in your HTML. HTML has the <meta> element for data about the document, and HTML 5 introduces data-* attributes for data specifically for reading with JavaScript that can be associated with particular elements.
  • Dirties up the Source - Data that PHP generates is outputted directly to the HTML source, meaning that you get a bigger and less focused HTML source.
  • Harder to get structured data - Structured data will have to be valid HTML, otherwise you'll have to escape and convert strings yourself.
  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

With this, the idea is to create some sort of element which will not be displayed to the user, but is visible to JavaScript.

index.php

<!-- snip -->
<div id="dom-target" style="display: none;">
    <?php
        $output = "42"; // Again, do some operation, get the output.
        echo htmlspecialchars($output); /* You have to escape because the result
                                           will not be valid HTML otherwise. */
    ?>
</div>
<script>
    var div = document.getElementById("dom-target");
    var myData = div.textContent;
</script>
<!-- snip -->

3. Echo the data directly to JavaScript

This is probably the easiest to understand.

Pros

  • Very easily implemented - It takes very little to implement this, and understand.
  • Does not dirty source - Variables are outputted directly to JavaScript, so the DOM is not affected.

Cons

  • Tightly couples PHP to your data logic - Because PHP is used in presentation, you can't separate the two cleanly.

Implementation Example

Implementation is relatively straightforward:

<!-- snip -->
<script>
    var data = <?php echo json_encode("42", JSON_HEX_TAG); ?>; // Don't forget the extra semicolon!
</script>
<!-- snip -->

Good luck!

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

How can I remove a key from a Python dictionary?

Single filter on key

  • return "key" and remove it from my_dict if "key" exists in my_dict
  • return None if "key" doesn't exist in my_dict

this will change my_dict in place (mutable)

my_dict.pop('key', None)

Multiple filters on keys

generate a new dict (immutable)

dic1 = {
    "x":1,
    "y": 2,
    "z": 3
}

def func1(item):
    return  item[0]!= "x" and item[0] != "y"

print(
    dict(
        filter(
            lambda item: item[0] != "x" and item[0] != "y", 
            dic1.items()
            )
    )
)

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

To trigger an event you basically just call the event handler for that element. Slight change from your code.

var a = document.getElementById("element");
var evnt = a["onclick"];

if (typeof(evnt) == "function") {
    evnt.call(a);
}

Configure Log4Net in web application

I also had the similar issue. Logs were not creating.

Please check logger attribute name should match with your LogManager.GetLogger("name")

<logger name="Mylog">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>



private static readonly ILog Log = LogManager.GetLogger("Mylog");

how to customize `show processlist` in mysql?

You can just capture the output and pass it through a filter, something like:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | sort -n -k12

The two greps strip out the header and trailer lines (others may be needed if there are other lines not containing useful information) and the sort is done based on the numeric field number 12 (I think that's right).

This one works for your immediate output:

mysql show processlist
    | grep -v '^\+\-\-'
    | grep -v '^| Id'
    | grep -v  '^[0-9][0-9]* rows in set '
    | grep -v '^ '
    | sort -n -k12

How to serve .html files with Spring

You can still continue to use the same View resolver but set the suffix to empty.

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
    p:prefix="/WEB-INF/jsp/" p:suffix="" />

Now your code can choose to return either index.html or index.jsp as shown in below sample -

@RequestMapping(value="jsp", method = RequestMethod.GET )
public String startJsp(){
    return "/test.jsp";
}

@RequestMapping(value="html", method = RequestMethod.GET )
public String startHtml(){
    return "/test.html";
}   

Android eclipse DDMS - Can't access data/data/ on phone to pull files

Much simpler than messing around with permissions in the android FS (which always feels like
a hack for me - because i believe there must be a kind of integrated way) is just to:

Allow ADB root access and Restart the deamon with root permissions.

  1. First be sure that ADB can have root access on your device (or emulator):
    (Settings -> Developer Options -> Root-Access for ADB or Apps & ADB.
  2. Restart the ADB-Service with root-permissions:
    Open a command prompt and type: adb.exe root
  3. Restart ADM (Android Device Manager):
    Enjoy browsing all files
  4. To negate this process:
    Type adb.exe unroot in your command prompt.

What is the use of the init() usage in JavaScript?

In JavaScript when you create any object through a constructor call like below

step 1 : create a function say Person..

function Person(name){
this.name=name;
}
person.prototype.print=function(){
console.log(this.name);
}

step 2 : create an instance for this function..

var obj=new Person('venkat')

//above line will instantiate this function(Person) and return a brand new object called Person {name:'venkat'}

if you don't want to instantiate this function and call at same time.we can also do like below..

var Person = {
  init: function(name){
    this.name=name;
  },
  print: function(){
    console.log(this.name);
  }
};
var obj=Object.create(Person);
obj.init('venkat');
obj.print();

in the above method init will help in instantiating the object properties. basically init is like a constructor call on your class.

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

Send POST data on redirect with JavaScript/jQuery?

var myRedirect = function(redirectUrl) {
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="parameter1" value="sample" />' +
'<input type="hidden" name="parameter2" value="Sample data 2" />' +
'</form>');
$('body').append(form);
$(form).submit();
};

Found code at http://www.prowebguru.com/2013/10/send-post-data-while-redirecting-with-jquery/

Going to try this and other suggestions for my work.

Is there any other way to do the same ?

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

A few years ago it was said that update() and digest() were legacy methods and the new streaming API approach was introduced. Now the docs say that either method can be used. For example:

var crypto    = require('crypto');
var text      = 'I love cupcakes';
var secret    = 'abcdeg'; //make this your secret!!
var algorithm = 'sha1';   //consider using sha256
var hash, hmac;

// Method 1 - Writing to a stream
hmac = crypto.createHmac(algorithm, secret);    
hmac.write(text); // write in to the stream
hmac.end();       // can't read from the stream until you call end()
hash = hmac.read().toString('hex');    // read out hmac digest
console.log("Method 1: ", hash);

// Method 2 - Using update and digest:
hmac = crypto.createHmac(algorithm, secret);
hmac.update(text);
hash = hmac.digest('hex');
console.log("Method 2: ", hash);

Tested on node v6.2.2 and v7.7.2

See https://nodejs.org/api/crypto.html#crypto_class_hmac. Gives more examples for using the streaming approach.

Using jQuery to center a DIV on the screen

I would like to correct one issue.

this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px");

Above code won't work in cases when this.height (lets assume that user resizes the screen and content is dynamic) and scrollTop() = 0, example:

window.height is 600
this.height is 650

600 - 650 = -50  

-50 / 2 = -25

Now the box is centered -25 offscreen.

Programmatically set image to UIImageView with Xcode 6.1/Swift

This code is in the wrong place:

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

You must place it inside a function. I recommend moving it inside the viewDidLoad function.

In general, the only code you can add within the class that's not inside of a function are variable declarations like:

@IBOutlet weak var bgImage: UIImageView!

How do I share variables between different .c files?

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

Number format in excel: Showing % value without multiplying with 100

_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_ 

Passing variables, creating instances, self, The mechanics and usage of classes: need explanation

So here is a simple example of how to use classes: Suppose you are a finance institute. You want your customer's accounts to be managed by a computer. So you need to model those accounts. That is where classes come in. Working with classes is called object oriented programming. With classes you model real world objects in your computer. So, what do we need to model a simple bank account? We need a variable that saves the balance and one that saves the customers name. Additionally, some methods to in- and decrease the balance. That could look like:

class bankaccount():
    def __init__(self, name, money):
        self.name = name
        self.money = money

    def earn_money(self, amount):
        self.money += amount

    def withdraw_money(self, amount):
        self.money -= amount

    def show_balance(self):
        print self.money

Now you have an abstract model of a simple account and its mechanism. The def __init__(self, name, money) is the classes' constructor. It builds up the object in memory. If you now want to open a new account you have to make an instance of your class. In order to do that, you have to call the constructor and pass the needed parameters. In Python a constructor is called by the classes's name:

spidermans_account = bankaccount("SpiderMan", 1000)

If Spiderman wants to buy M.J. a new ring he has to withdraw some money. He would call the withdraw method on his account:

spidermans_account.withdraw_money(100)

If he wants to see the balance he calls:

spidermans_account.show_balance()

The whole thing about classes is to model objects, their attributes and mechanisms. To create an object, instantiate it like in the example. Values are passed to classes with getter and setter methods like `earn_money()´. Those methods access your objects variables. If you want your class to store another object you have to define a variable for that object in the constructor.

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

As I think if system is connected to the internet then it's may be an issue of proxy

Do this to delete proxy

npm config delete proxy

CodeIgniter: How to use WHERE clause and OR clause

You can use or_where() for that - example from the CI docs:

$this->db->where('name !=', $name);

$this->db->or_where('id >', $id); 

// Produces: WHERE name != 'Joe' OR id > 50

Best way to parse command line arguments in C#?

I like that one, because you can "define rules" for the arguments, needed or not,...

or if you're a Unix guy, than you might like the GNU Getopt .NET port.

How to use sed to remove all double quotes within a file

Are you sure you need to use sed? How about:

tr -d "\""

HTML/Javascript Button Click Counter

    <!DOCTYPE html>
<html>
<head>
<script>
     var clicks = 0;
    function myFunction() {

        clicks += 1;
        document.getElementById("demo").innerHTML = clicks;


    }
</script>
</head>
<body>

<p>Click the button to trigger a function.</p>

<button onclick="myFunction()">Click me</button>

<p id="demo"></p>

</body>
</html>

This should work for you :) Yes var should be used

How to add column if not exists on PostgreSQL?

CREATE OR REPLACE function f_add_col(_tbl regclass, _col  text, _type regtype)
  RETURNS bool AS
$func$
BEGIN
   IF EXISTS (SELECT 1 FROM pg_attribute
              WHERE  attrelid = _tbl
              AND    attname = _col
              AND    NOT attisdropped) THEN
      RETURN FALSE;
   ELSE
      EXECUTE format('ALTER TABLE %s ADD COLUMN %I %s', _tbl, _col, _type);
      RETURN TRUE;
   END IF;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT f_add_col('public.kat', 'pfad1', 'int');

Returns TRUE on success, else FALSE (column already exists).
Raises an exception for invalid table or type name.

Why another version?

  • This could be done with a DO statement, but DO statements cannot return anything. And if it's for repeated use, I would create a function.

  • I use the object identifier types regclass and regtype for _tbl and _type which a) prevents SQL injection and b) checks validity of both immediately (cheapest possible way). The column name _col has still to be sanitized for EXECUTE with quote_ident(). More explanation in this related answer:

  • format() requires Postgres 9.1+. For older versions concatenate manually:

    EXECUTE 'ALTER TABLE ' || _tbl || ' ADD COLUMN ' || quote_ident(_col) || ' ' || _type;
    
  • You can schema-qualify your table name, but you don't have to.
    You can double-quote the identifiers in the function call to preserve camel-case and reserved words (but you shouldn't use any of this anyway).

  • I query pg_catalog instead of the information_schema. Detailed explanation:

  • Blocks containing an EXCEPTION clause like the currently accepted answer are substantially slower. This is generally simpler and faster. The documentation:

Tip: A block containing an EXCEPTION clause is significantly more expensive to enter and exit than a block without one. Therefore, don't use EXCEPTION without need.

Detect and exclude outliers in Pandas data frame

Since I am in a very early stage of my data science journey, I am treating outliers with the code below.

#Outlier Treatment

def outlier_detect(df):
    for i in df.describe().columns:
        Q1=df.describe().at['25%',i]
        Q3=df.describe().at['75%',i]
        IQR=Q3 - Q1
        LTV=Q1 - 1.5 * IQR
        UTV=Q3 + 1.5 * IQR
        x=np.array(df[i])
        p=[]
        for j in x:
            if j < LTV or j>UTV:
                p.append(df[i].median())
            else:
                p.append(j)
        df[i]=p
    return df

How to reference a local XML Schema file correctly?

Add one more slash after file:// in the value of xsi:schemaLocation. (You have two; you need three. Think protocol://host/path where protocol is 'file' and host is empty here, yielding three slashes in a row.) You can also eliminate the double slashes along the path. I believe that the double slashes help with file systems that allow spaces in file and directory names, but you wisely avoided that complication in your path naming.

xsi:schemaLocation="http://www.w3schools.com file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd"

Still not working? I suggest that you carefully copy the full file specification for the XSD into the address bar of Chrome or Firefox:

file:///C:/environment/workspace/maven-ws/ProjextXmlSchema/email.xsd

If the XSD does not display in the browser, delete all but the last component of the path (email.xsd) and see if you can't display the parent directory. Continue in this manner, walking up the directory structure until you discover where the path diverges from the reality of your local filesystem.

If the XSD does displayed in the browser, state what XML processor you're using, and be prepared to hear that it's broken or that you must work around some limitation. I can tell you that the above fix will work with my Xerces-J-based validator.

MySQL "between" clause not inclusive?

Set the upper date to date + 1 day, so in your case, set it to 2011-02-01.

How to trigger checkbox click event even if it's checked through Javascript code?

no gQuery

document.getElementById('your_box').onclick();

I used certain class on my checkboxes.

var x = document.getElementsByClassName("box_class");
var i;
for (i = 0; i < x.length; i++) {
    if(x[i].checked) x[i].checked = false;
    else x[i].checked = true;
    x[i].onclick();
   }

Microsoft SQL Server 2005 service fails to start

To solve this problem, you may need to repair your SQL Server 2005

Simple steps can be

  1. Update/Install .Net 2.0 framework. Windows Installer 3.1 available online recommended
  2. Download the setup files from Microsoft website : http://www.microsoft.com/en-in/download/details.aspx?id=184
  3. Follow the steps mentioned below from the Symantec website: http://www.symantec.com/connect/articles/install-and-configure-sql-server-2005-express

Hope this helps!

Should import statements always be at the top of a module?

Readability

In addition to startup performance, there is a readability argument to be made for localizing import statements. For example take python line numbers 1283 through 1296 in my current first python project:

listdata.append(['tk font version', font_version])
listdata.append(['Gtk version', str(Gtk.get_major_version())+"."+
                 str(Gtk.get_minor_version())+"."+
                 str(Gtk.get_micro_version())])

import xml.etree.ElementTree as ET

xmltree = ET.parse('/usr/share/gnome/gnome-version.xml')
xmlroot = xmltree.getroot()
result = []
for child in xmlroot:
    result.append(child.text)
listdata.append(['Gnome version', result[0]+"."+result[1]+"."+
                 result[2]+" "+result[3]])

If the import statement was at the top of file I would have to scroll up a long way, or press Home, to find out what ET was. Then I would have to navigate back to line 1283 to continue reading code.

Indeed even if the import statement was at the top of the function (or class) as many would place it, paging up and back down would be required.

Displaying the Gnome version number will rarely be done so the import at top of file introduces unnecessary startup lag.

How to start a background process in Python?

Both capture output and run on background with threading

As mentioned on this answer, if you capture the output with stdout= and then try to read(), then the process blocks.

However, there are cases where you need this. For example, I wanted to launch two processes that talk over a port between them, and save their stdout to a log file and stdout.

The threading module allows us to do that.

First, have a look at how to do the output redirection part alone in this question: Python Popen: Write to stdout AND log file simultaneously

Then:

main.py

#!/usr/bin/env python3

import os
import subprocess
import sys
import threading

def output_reader(proc, file):
    while True:
        byte = proc.stdout.read(1)
        if byte:
            sys.stdout.buffer.write(byte)
            sys.stdout.flush()
            file.buffer.write(byte)
        else:
            break

with subprocess.Popen(['./sleep.py', '0'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc1, \
     subprocess.Popen(['./sleep.py', '10'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) as proc2, \
     open('log1.log', 'w') as file1, \
     open('log2.log', 'w') as file2:
    t1 = threading.Thread(target=output_reader, args=(proc1, file1))
    t2 = threading.Thread(target=output_reader, args=(proc2, file2))
    t1.start()
    t2.start()
    t1.join()
    t2.join()

sleep.py

#!/usr/bin/env python3

import sys
import time

for i in range(4):
    print(i + int(sys.argv[1]))
    sys.stdout.flush()
    time.sleep(0.5)

After running:

./main.py

stdout get updated every 0.5 seconds for every two lines to contain:

0
10
1
11
2
12
3
13

and each log file contains the respective log for a given process.

Inspired by: https://eli.thegreenplace.net/2017/interacting-with-a-long-running-child-process-in-python/

Tested on Ubuntu 18.04, Python 3.6.7.

How do you check if a string is not equal to an object or other string value in java?

Change your code to:

System.out.println("AM or PM?"); 
Scanner TimeOfDayQ = new Scanner(System.in);
TimeOfDayStringQ = TimeOfDayQ.next();

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) { // <--
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

...

if(Hours == 13){
    if (TimeOfDayStringQ.equals("AM")) {
        TimeOfDayStringQ = "PM"; // <--
    } else {
        TimeOfDayStringQ = "AM"; // <--
    }
            Hours = 1;
    }
 }

jQuery function after .append

Yes you can add a callback function to any DOM insertion:
$myDiv.append( function(index_myDiv, HTML_myDiv){ //.... return child })

Check on JQuery documentation: http://api.jquery.com/append/
And here's a practical, similar, example: http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_html_prepend_func

How can I exclude $(this) from a jQuery selector?

Try using the not() method instead of the :not() selector.

$(".content a").click(function() {
    $(".content a").not(this).hide("slow");
});

Differences between "java -cp" and "java -jar"?

With the -cp argument you provide the classpath i.e. path(s) to additional classes or libraries that your program may require when being compiled or run. With -jar you specify the executable JAR file that you want to run.

You can't specify them both. If you try to run java -cp folder/myexternallibrary.jar -jar myprogram.jar then it won't really work. The classpath for that JAR should be specified in its Manifest, not as a -cp argument.

You can find more about this here and here.

PS: -cp and -classpath are synonyms.

Error in launching AVD with AMD processor

You need to read (and post) the output of

sc query intelhaxm

as stated on http://developer.android.com/tools/devices/emulator.html#accel-vm

You open a command prompt window by right click on the start menu, choose execute and write 'cmd'.

See also Android Emulator Doesn't Use HAXM .

If you cannot get the emulator to work you might want to try out an easier alternative: Genymotion - http://genymotion.com/

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

How do I get TimeSpan in minutes given two Dates?

See TimeSpan.TotalMinutes:

Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.

What is the benefit of zerofill in MySQL?

It's a feature for disturbed personalities who like square boxes.

You insert

1
23
123 

but when you select, it pads the values

000001
000023
000123

sorting dictionary python 3

dict does not keep its elements' order. What you need is an OrderedDict: http://docs.python.org/library/collections.html#collections.OrderedDict

edit

Usage example:

>>> from collections import OrderedDict
>>> a = {'foo': 1, 'bar': 2}
>>> a
{'foo': 1, 'bar': 2}
>>> b = OrderedDict(sorted(a.items()))
>>> b
OrderedDict([('bar', 2), ('foo', 1)])
>>> b['foo']
1
>>> b['bar']
2

Rounded Corners Image in Flutter

Output:

enter image description here

Using BoxDecoration

Container(
              margin: EdgeInsets.all(8),
              width: 86,
              height: 86,
              decoration: BoxDecoration(
                shape: BoxShape.circle,
                image: DecorationImage(
                    image: NetworkImage('https://i.stack.imgur.com/0VpX0.png'),
                    fit: BoxFit.cover
                ),
              ), 
           ),

Create a zip file and download it

// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);

I found this soludtion here and it work for me

How to include a class in PHP

Include a class example with the use keyword from Command Line Interface:

PHP Namespaces don't work on the commandline unless you also include or require the php file. When the php file is sitting in the webspace where it is interpreted by the php daemon then you don't need the require line. All you need is the 'use' line.

  1. Create a new directory /home/el/bin

  2. Make a new file called namespace_example.php and put this code in there:

    <?php
        require '/home/el/bin/mylib.php';
        use foobarwhatever\dingdong\penguinclass;
    
        $mypenguin = new penguinclass();
        echo $mypenguin->msg();
    ?>
    
  3. Make another file called mylib.php and put this code in there:

    <?php
    namespace foobarwhatever\dingdong;
    class penguinclass 
    {
        public function msg() {
            return "It's a beautiful day chris, come out and play! " . 
                   "NO!  *SLAM!*  taka taka taka taka."; 
        }   
    }
    ?>   
    
  4. Run it from commandline like this:

    el@apollo:~/bin$ php namespace_example.php 
    
  5. Which prints:

    It's a beautiful day chris, come out and play!
    NO!  *SLAM!*  taka taka taka taka
    

See notes on this in the comments here: http://php.net/manual/en/language.namespaces.importing.php

How to iterate (keys, values) in JavaScript?

I think the fast and easy way is

Object.entries(event).forEach(k => {
    console.log("properties ... ", k[0], k[1]); });

just check the documentation https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

How do I redirect output to a variable in shell?

TL;DR

To store "abc" into $foo:

echo "abc" | read foo

But, because pipes create forks, you have to use $foo before the pipe ends, so...

echo "abc" | ( read foo; date +"I received $foo on %D"; )

Sure, all these other answers show ways to not do what the OP asked, but that really screws up the rest of us who searched for the OP's question.

The answer to the question is to use the read command.

Here's how you do it

# I would usually do this on one line, but for readability...
series | of | commands \
| \
(
  read string;
  mystic_command --opt "$string" /path/to/file
) \
| \
handle_mystified_file

Here is what it is doing and why it is important:

  1. Let's pretend that the series | of | commands is a very complicated series of piped commands.

  2. mystic_command can accept the content of a file as stdin in lieu of a file path, but not the --opt arg therefore it must come in as a variable. The command outputs the modified content and would commonly be redirected into a file or piped to another command. (E.g. sed, awk, perl, etc.)

  3. read takes stdin and places it into the variable $string

  4. Putting the read and the mystic_command into a "sub shell" via parenthesis is not necessary but makes it flow like a continuous pipe as if the 2 commands where in a separate script file.

There is always an alternative, and in this case the alternative is ugly and unreadable compared to my example above.

# my example above as a oneliner
series | of | commands | (read string; mystic_command --opt "$string" /path/to/file) | handle_mystified_file

# ugly and unreadable alternative
mystic_command --opt "$(series | of | commands)" /path/to/file | handle_mystified_file

My way is entirely chronological and logical. The alternative starts with the 4th command and shoves commands 1, 2, and 3 into command substitution.

I have a real world example of this in this script but I didn't use it as the example above because it has some other crazy/confusing/distracting bash magic going on also.

How to secure an ASP.NET Web API

Update:

I have added this link to my other answer how to use JWT authentication for ASP.NET Web API here for anyone interested in JWT.


We have managed to apply HMAC authentication to secure Web API, and it worked okay. HMAC authentication uses a secret key for each consumer which both consumer and server both know to hmac hash a message, HMAC256 should be used. Most of the cases, hashed password of the consumer is used as a secret key.

The message normally is built from data in the HTTP request, or even customized data which is added to HTTP header, the message might include:

  1. Timestamp: time that request is sent (UTC or GMT)
  2. HTTP verb: GET, POST, PUT, DELETE.
  3. post data and query string,
  4. URL

Under the hood, HMAC authentication would be:

Consumer sends a HTTP request to web server, after building the signature (output of hmac hash), the template of HTTP request:

User-Agent: {agent}   
Host: {host}   
Timestamp: {timestamp}
Authentication: {username}:{signature}

Example for GET request:

GET /webapi.hmac/api/values

User-Agent: Fiddler    
Host: localhost    
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

The message to hash to get signature:

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n

Example for POST request with query string (signature below is not correct, just an example)

POST /webapi.hmac/api/values?key2=value2

User-Agent: Fiddler    
Host: localhost    
Content-Type: application/x-www-form-urlencoded
Timestamp: Thursday, August 02, 2012 3:30:32 PM 
Authentication: cuongle:LohrhqqoDy6PhLrHAXi7dUVACyJZilQtlDzNbLqzXlw=

key1=value1&key3=value3

The message to hash to get signature

GET\n
Thursday, August 02, 2012 3:30:32 PM\n
/webapi.hmac/api/values\n
key1=value1&key2=value2&key3=value3

Please note that form data and query string should be in order, so the code on the server get query string and form data to build the correct message.

When HTTP request comes to the server, an authentication action filter is implemented to parse the request to get information: HTTP verb, timestamp, uri, form data and query string, then based on these to build signature (use hmac hash) with the secret key (hashed password) on the server.

The secret key is got from the database with the username on the request.

Then server code compares the signature on the request with the signature built; if equal, authentication is passed, otherwise, it failed.

The code to build signature:

private static string ComputeHash(string hashedPassword, string message)
{
    var key = Encoding.UTF8.GetBytes(hashedPassword.ToUpper());
    string hashString;

    using (var hmac = new HMACSHA256(key))
    {
        var hash = hmac.ComputeHash(Encoding.UTF8.GetBytes(message));
        hashString = Convert.ToBase64String(hash);
    }

    return hashString;
}

So, how to prevent replay attack?

Add constraint for the timestamp, something like:

servertime - X minutes|seconds  <= timestamp <= servertime + X minutes|seconds 

(servertime: time of request coming to server)

And, cache the signature of the request in memory (use MemoryCache, should keep in the limit of time). If the next request comes with the same signature with the previous request, it will be rejected.

The demo code is put as here: https://github.com/cuongle/Hmac.WebApi

Get current date in DD-Mon-YYY format in JavaScript/Jquery

There is no native format in javascript for DD-Mon-YYYY.

You will have to put it all together manually.

The answer is inspired from : How to format a JavaScript date

_x000D_
_x000D_
// Attaching a new function  toShortFormat()  to any instance of Date() class_x000D_
_x000D_
Date.prototype.toShortFormat = function() {_x000D_
_x000D_
    let monthNames =["Jan","Feb","Mar","Apr",_x000D_
                      "May","Jun","Jul","Aug",_x000D_
                      "Sep", "Oct","Nov","Dec"];_x000D_
    _x000D_
    let day = this.getDate();_x000D_
    _x000D_
    let monthIndex = this.getMonth();_x000D_
    let monthName = monthNames[monthIndex];_x000D_
    _x000D_
    let year = this.getFullYear();_x000D_
    _x000D_
    return `${day}-${monthName}-${year}`;  _x000D_
}_x000D_
_x000D_
// Now any Date object can be declared _x000D_
let anyDate = new Date(1528578000000);_x000D_
_x000D_
// and it can represent itself in the custom format defined above._x000D_
console.log(anyDate.toShortFormat());    // 10-Jun-2018_x000D_
_x000D_
let today = new Date();_x000D_
console.log(today.toShortFormat());     // today's date
_x000D_
_x000D_
_x000D_

Console.WriteLine does not show up in Output window

If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.

If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.

If you absolutely must use the console, then you can attach a console in the program's Main method.

Find all stored procedures that reference a specific column in some table

You can use the system views contained in information_schema to search in tables, views and (unencrypted) stored procedures with one script. I developed such a script some time ago because I needed to search for field names everywhere in the database.

The script below first lists the tables/views containing the column name you're searching for, and then the stored procedures source code where the column is found. It displays the result in one table distinguishing "BASE TABLE", "VIEW" and "PROCEDURE", and (optionally) the source code in a second table:

DECLARE @SearchFor nvarchar(max)='%CustomerID%' -- search for this string
DECLARE @SearchSP bit = 1 -- 1=search in SPs as well
DECLARE @DisplaySPSource bit = 1 -- 1=display SP source code

-- tables
if (@SearchSP=1) begin  
  (
  select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object], 
            t.table_type 
  from information_schema.columns c
  left join information_schema.Tables t on c.table_name=t.table_name
  where column_name like @SearchFor 
  union
  select '['+routine_Schema+'].['+routine_Name+']' [schema_object], 
         'PROCEDURE' as table_type from information_schema.routines
  where routine_definition like @SearchFor
        and routine_type='procedure'
  )
  order by table_type, schema_object
end else begin
  select '['+c.table_Schema+'].['+c.table_Name+'].['+c.column_name+']' [schema_object], 
         t.table_type 
  from information_schema.columns c
  left join information_schema.Tables t on c.table_name=t.table_name
  where column_name like @SearchFor 
  order by c.table_Name, c.column_name
end     
-- stored procedure (source listing)
if (@SearchSP=1) begin      
    if (@DisplaySPSource=1) begin
      select '['+routine_Schema+'].['+routine_Name+']' [schema.sp], routine_definition 
      from information_schema.routines
      where routine_definition like @SearchFor
      and routine_type='procedure'
      order by routine_name
    end
end

If you run the query, use the "result as text" option - then you can use "find" to locate the search text in the result set (useful for long source code).

Note that you can set @DisplaySPSource to 0 if you just want to display the SP names, and if you're just looking for tables/views, but not for SPs, you can set @SearchSP to 0.

Example result (find CustomerID in the Northwind database, results displayed via LinqPad):

Sample Result

Note that I've verfied this script with a test view dbo.TestOrders and it found the CustomerID in this view even though c.* was used in the SELECT statement (referenced table Customers contains the CustomerIDand hence the view is showing this column).


Note for LinqPad users: In C#, you can use dc.ExecuteQueryDynamic(sqlQueryStr, new object[] {... parameters ...} ).Dump(); and have the parameters as @p0 ... @pn inside the query string. Then you can write a static extension class and save it under My Extensions to be used in your LinqPad queries. The data context can be passed from the query window as DataContextBase dc via parameter, i.e. public static void SearchDialog(this DataContextBase dc, string searchString = "%") inside a public static extension class (in LinqPad 6, it is DataContext). Then you can rewrite the SQL query above as a string with parameters and invoke it from the C# context.

Make a dictionary in Python from input values

for i in range(n):
    data = input().split(' ')
    d[data[0]] = data[1]
for keys,values in d.items():
    print(keys)
    print(values)

What is the difference between DTR/DSR and RTS/CTS flow control?

The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.

ComboBox: Adding Text and Value to an Item (no Binding Source)

If anyone is still interested in this, here is a simple and flexible class for a combobox item with a text and a value of any type (very similar to Adam Markowitz's example):

public class ComboBoxItem<T>
{
    public string Name;
    public T value = default(T);

    public ComboBoxItem(string Name, T value)
    {
        this.Name = Name;
        this.value = value;
    }

    public override string ToString()
    {
        return Name;
    }
}

Using the <T> is better than declaring the value as an object, because with object you'd then have to keep track of the type you used for each item, and cast it in your code to use it properly.

I've been using it on my projects for quite a while now. It is really handy.

How to create an installer for a .net Windows Service using Visual Studio

Nor Kelsey, nor Brendan solutions does not works for me in Visual Studio 2015 Community.

Here is my brief steps how to create service with installer:

  1. Run Visual Studio, Go to File->New->Project
  2. Select .NET Framework 4, in 'Search Installed Templates' type 'Service'
  3. Select 'Windows Service'. Type Name and Location. Press OK.
  4. Double click Service1.cs, right click in designer and select 'Add Installer'
  5. Double click ProjectInstaller.cs. For serviceProcessInstaller1 open Properties tab and change 'Account' property value to 'LocalService'. For serviceInstaller1 change 'ServiceName' and set 'StartType' to 'Automatic'.
  6. Double click serviceInstaller1. Visual Studio creates serviceInstaller1_AfterInstall event. Write code:

    private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
    {
        using (System.ServiceProcess.ServiceController sc = new 
        System.ServiceProcess.ServiceController(serviceInstaller1.ServiceName))
        {
            sc.Start();
        }
    }
    
  7. Build solution. Right click on project and select 'Open Folder in File Explorer'. Go to bin\Debug.

  8. Create install.bat with below script:

    :::::::::::::::::::::::::::::::::::::::::
    :: Automatically check & get admin rights
    :::::::::::::::::::::::::::::::::::::::::
    @echo off
    CLS 
    ECHO.
    ECHO =============================
    ECHO Running Admin shell
    ECHO =============================
    
    :checkPrivileges 
    NET FILE 1>NUL 2>NUL
    if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges ) 
    
    :getPrivileges 
    if '%1'=='ELEV' (shift & goto gotPrivileges)  
    ECHO. 
    ECHO **************************************
    ECHO Invoking UAC for Privilege Escalation 
    ECHO **************************************
    
    setlocal DisableDelayedExpansion
    set "batchPath=%~0"
    setlocal EnableDelayedExpansion
    ECHO Set UAC = CreateObject^("Shell.Application"^) > "%temp%\OEgetPrivileges.vbs" 
    ECHO UAC.ShellExecute "!batchPath!", "ELEV", "", "runas", 1 >> "%temp%\OEgetPrivileges.vbs" 
    "%temp%\OEgetPrivileges.vbs" 
    exit /B 
    
    :gotPrivileges 
    ::::::::::::::::::::::::::::
    :START
    ::::::::::::::::::::::::::::
    setlocal & pushd .
    
    cd /d %~dp0
    %windir%\Microsoft.NET\Framework\v4.0.30319\InstallUtil /i "WindowsService1.exe"
    pause
    
  9. Create uninstall.bat file (change in pen-ult line /i to /u)
  10. To install and start service run install.bat, to stop and uninstall run uninstall.bat

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

Firebase FCM notifications click_action payload

If your app is in background, Firebase will not trigger onMessageReceived(). onMessageReceived() is called when app is in foreground . When app is in background,onMessageReceived() method will be called only if the body of https://fcm.googleapis.com/fcm/send contain only data payload.Here ,i just created a method to build custom notification with intent having ur your required activity . and called this method in onMessageRecevied() .

In PostMan:

uri: https://fcm.googleapis.com/fcm/send

header:Authorization:key=ur key

body --->>

{  "data" : {
      "Nick" : "Mario",
      "Room" : "PoSDenmark",

    },

  "to" : "xxxxxxxxx"

}

in your application.

class MyFirebaseMessagingService  extends FirebaseMessagingService {

 public void onMessageReceived(RemoteMessage remoteMessage) {
       if (remoteMessage.getData().size() > 0) {
           sendNotification("ur message body") ;
        }
    }
private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, Main2Activity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }

 }

when the data payload comes to the mobile,then onMessageReceived() method will be called.. inside that method ,i just made a custom notification. this will work even if ur app is background or foreground.

What's a quick way to comment/uncomment lines in Vim?

This solution maps / to commenting and ? to uncommenting (comment toggling using the single mapping is too complex to implement properly). It takes comment strings from VIM's builtin commentstring option which is populated from files like /usr/share/vim/vim*/ftplugin/*.vim if filetype plugin on is declared.

filetype plugin on
autocmd FileType * let b:comment = split(&commentstring, '%s', 1)
autocmd FileType * execute "map <silent> <Leader>/ :normal 0i" . b:comment[0] . "<C-O>$" . b:comment[1] . "<C-O>0<CR>"
autocmd FileType * execute "map <silent> <Leader>? :normal $" . repeat('x', strlen(b:comment[1])) . "0" . strlen(b:comment[0]) . "x<CR>"

How can I make a list of lists in R?

As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:

> str(list_all)
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

And the most simple construction would be this:

> str(list(list(1, 2), list("a", "b")))
List of 2
 $ :List of 2
  ..$ : num 1
  ..$ : num 2
 $ :List of 2
  ..$ : chr "a"
  ..$ : chr "b"

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

Excerpt from PostgreSQL documentation:

Restricting and cascading deletes are the two most common options. [...] CASCADE specifies that when a referenced row is deleted, row(s) referencing it should be automatically deleted as well.

This means that if you delete a category – referenced by books – the referencing book will also be deleted by ON DELETE CASCADE.

Example:

CREATE SCHEMA shire;

CREATE TABLE shire.clans (
    id serial PRIMARY KEY,
    clan varchar
);

CREATE TABLE shire.hobbits (
    id serial PRIMARY KEY,
    hobbit varchar,
    clan_id integer REFERENCES shire.clans (id) ON DELETE CASCADE
);

DELETE FROM clans will CASCADE to hobbits by REFERENCES.

sauron@mordor> psql
sauron=# SELECT * FROM shire.clans;
 id |    clan    
----+------------
  1 | Baggins
  2 | Gamgi
(2 rows)

sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  1 | Bilbo    |       1
  2 | Frodo    |       1
  3 | Samwise  |       2
(3 rows)

sauron=# DELETE FROM shire.clans WHERE id = 1 RETURNING *;
 id |  clan   
----+---------
  1 | Baggins
(1 row)

DELETE 1
sauron=# SELECT * FROM shire.hobbits;
 id |  hobbit  | clan_id 
----+----------+---------
  3 | Samwise  |       2
(1 row)

If you really need the opposite (checked by the database), you will have to write a trigger!

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

Try to download binary zip (for ex. Maven 3.0.5 (Binary zip)) instead of complete source in official maven site. Also make sure that command line recognizes java and javac commands. I noticed that Maven Source zip didn't include any libraries at lib folder however Binary zip had them + in boot folder it had plexus-classworlds-2.4.jar. Perhaps the problem was with the absence of these libraries. Anyway it helped me so my M2_HOME is: C:\Program Files\Java\apache-maven-3.0.5 and at PATH I put: C:\Program Files\Java\apache-maven-3.0.5\bin.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

So For my case I noticed hibernate is trying to update the record rather than inserting it and that thrown the exception mentioned.

I finally came to find that my entity had an updatedAt timestamp column:

<timestamp name="updatedDate" column="updated_date" />

and when I was trying to initialize the object i found that the code was setting this field explicitly.

after removing that setUpdateDate(new Date()) it worked and did an insert instead.

val() doesn't trigger change() in jQuery

It looks like the events are not bubbling. Try this:

$("#mybutton").click(function(){
  var oldval=$("#mytext").val();
  $("#mytext").val('Changed by button');
  var newval=$("#mytext").val();
  if (newval != oldval) {
    $("#mytext").trigger('change');
  }
});

I hope this helps.

I tried just a plain old $("#mytext").trigger('change') without saving the old value, and the .change fires even if the value didn't change. That is why I saved the previous value and called $("#mytext").trigger('change') only if it changes.

Can you use CSS to mirror/flip text?

Real mirror:

_x000D_
_x000D_
.mirror{_x000D_
    display: inline-block; _x000D_
    font-size: 30px;_x000D_
_x000D_
    -webkit-transform: matrix(-1, 0, 0, 1, 0, 0);_x000D_
    -moz-transform: matrix(-1, 0, 0, 1, 0, 0);_x000D_
    -o-transform: matrix(-1, 0, 0, 1, 0, 0);_x000D_
    transform: matrix(-1, 0, 0, 1, 0, 0);_x000D_
}
_x000D_
<span class='mirror'>Mirror Text<span>
_x000D_
_x000D_
_x000D_

Clear form fields with jQuery

Most easy and best solution is-
$("#form")[0].reset();

Don't use here -
$(this)[0].reset();

Simple Android RecyclerView example

The following is a minimal example that will look like the following image.

RecyclerView with a list of animal names

Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the RecyclerView row
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

You can update the version numbers to whatever is the most current. Use compile rather than implementation if you are still using Android Studio 2.x.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create row layout

Each row in our RecyclerView is only going to have a single TextView. Create a new layout resource file.

recyclerview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">

    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each row with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
    }

    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvAnimalName);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the rows. This was available in the old ListViews and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

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

        // data to populate the RecyclerView with
        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyRecyclerViewAdapter(this, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle row click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Adding a divider between rows

You can add a simple divider like this

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
    layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

If you want something a little more complex, see the following answers:

Changing row color on click

See this answer for how to change the background color and add the Ripple Effect when a row is clicked.

Insert single item

Updating rows

See this answer for how to add, remove, and update rows.

Insert single item

Further reading

How to get a product's image in Magento?

Here is the way I've found to load all image data for all products in a collection. I am not sure at the moment why its needed to switch from Mage::getModel to Mage::helper and reload the product, but it must be done. I've reverse engineered this code from the magento image soap api, so I'm pretty sure its correct.

I have it set to load products with a vendor code equal to '39' but you could change that to any attribute, or just load all the products, or load whatever collection you want (including the collections in the phtml files showing products currently on the screen!)

$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addFieldToFilter(array(
    array('attribute'=>'vendor_code','eq'=>'39'),
));

$collection->addAttributeToSelect('*');

foreach ($collection as $product) {

    $prod = Mage::helper('catalog/product')->getProduct($product->getId(), null, null);

    $attributes = $prod->getTypeInstance(true)->getSetAttributes($prod);

    $galleryData = $prod->getData('media_gallery');

    foreach ($galleryData['images'] as &$image) {
        var_dump($image);
    }

}

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

.Net System.Mail.Message adding multiple "To" addresses

You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas

Using a remote repository with non-standard port

SSH based git access method can be specified in <repo_path>/.git/config using either a full URL or an SCP-like syntax, as specified in http://git-scm.com/docs/git-clone:

URL style:

url = ssh://[user@]host.xz[:port]/path/to/repo.git/

SCP style:

url = [user@]host.xz:path/to/repo.git/

Notice that the SCP style does not allow a direct port change, relying instead on an ssh_config host definition in your ~/.ssh/config such as:

Host my_git_host
HostName git.some.host.org
Port 24589
User not_a_root_user

Then you can test in a shell with:

ssh my_git_host

and alter your SCP-style URI in <repo_path>/.git/config as:

url = my_git_host:path/to/repo.git/

How to query between two dates using Laravel and Eloquent?

And I have created the model scope

More about scopes:

Code:

   /**
     * Scope a query to only include the last n days records
     *
     * @param  \Illuminate\Database\Eloquent\Builder $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereDateBetween($query,$fieldName,$fromDate,$todate)
    {
        return $query->whereDate($fieldName,'>=',$fromDate)->whereDate($fieldName,'<=',$todate);
    }

And in the controller, add the Carbon Library to top

use Carbon\Carbon;

OR

use Illuminate\Support\Carbon;

To get the last 10 days record from now

 $lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(10)->toDateString(),(new Carbon)->now()->toDateString() )->get();

To get the last 30 days record from now

 $lastTenDaysRecord = ModelName::whereDateBetween('created_at',(new Carbon)->subDays(30)->toDateString(),(new Carbon)->now()->toDateString() )->get();

What is the size of column of int(11) in mysql in bytes?

A good explanation for this can be found here

To summarize : The number N in int(N) is often confused by the maximum size allowed for the column, as it does in the case of varchar(N).

But this is not the case with Integer data types- the number N in the parentheses is not the maximum size for the column, but simply a parameter to tell MySQL what width to display the column at when the table's data is being viewed via the MySQL console (when you're using the ZEROFILL attribute).

The number in brackets will tell MySQL how many zeros to pad incoming integers with. For example: If you're using ZEROFILL on a column that is set to INT(5) and the number 78 is inserted, MySQL will pad that value with zeros until the number satisfies the number in brackets. i.e. 78 will become 00078 and 127 will become 00127. To sum it up: The number in brackets is used for display purposes.
In a way, the number in brackets is kind of usless unless you're using the ZEROFILL attribute.

So the size for the int would remain same i.e., -2147483648 to 2147483648 for signed and 0 to 4294967295 for unsigned (~ 2.15 billions and 4.2 billions, which is one of the reasons why developers remain unaware of the story behind the Number N in parentheses, as it hardly affects the database unless it contains over 2 billions of rows), and in terms of bytes it would be 4 bytes.

For more information on Integer Types size/range, refer to MySQL Manual

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

Including another class in SCSS

@extend .myclass;
@extend #{'.my-class'};

Python functions call by reference

Hope the following description sums it up well:

There are two things to consider here - variables and objects.

  1. If you are passing a variable, then it's pass by value, which means the changes made to the variable within the function are local to that function and hence won't be reflected globally. This is more of a 'C' like behavior.

Example:

def changeval( myvar ):
   myvar = 20; 
   print "values inside the function: ", myvar
   return

myvar = 10;
changeval( myvar );
print "values outside the function: ", myvar

O/P:

values inside the function:  20 
values outside the function:  10
  1. If you are passing the variables packed inside a mutable object, like a list, then the changes made to the object are reflected globally as long as the object is not re-assigned.

Example:

def changelist( mylist ):
   mylist2=['a'];
   mylist.append(mylist2);
   print "values inside the function: ", mylist
   return

mylist = [1,2,3];
changelist( mylist );
print "values outside the function: ", mylist

O/P:

values inside the function:  [1, 2, 3, ['a']]
values outside the function:  [1, 2, 3, ['a']]
  1. Now consider the case where the object is re-assigned. In this case, the object refers to a new memory location which is local to the function in which this happens and hence not reflected globally.

Example:

def changelist( mylist ):
   mylist=['a'];
   print "values inside the function: ", mylist
   return

mylist = [1,2,3];
changelist( mylist );
print "values outside the function: ", mylist

O/P:

values inside the function:  ['a']
values outside the function:  [1, 2, 3]

React JSX: selecting "selected" on selected <select> option

I've had a problem with <select> tags not updating to the correct <option> when the state changes. My problem seemed to be that if you render twice in quick succession, the first time with no pre-selected <option> but the second time with one, then the <select> tag doesn't update on the second render, but stays on the default first .

I found a solution to this using refs. You need to get a reference to your <select> tag node (which might be nested in some component), and then manually update the value property on it, in the componentDidUpdate hook.

componentDidUpdate(){
  let selectNode = React.findDOMNode(this.refs.selectingComponent.refs.selectTag);
  selectNode.value = this.state.someValue;
}

ParseError: not well-formed (invalid token) using cElementTree

After lots of searching through the entire WWW, I only found out that you have to escape certain characters if you want your XML parser to work! Here's how I did it and worked for me:

escape_illegal_xml_characters = lambda x: re.sub(u'[\x00-\x08\x0b\x0c\x0e-\x1F\uD800-\uDFFF\uFFFE\uFFFF]', '', x)

And use it like you'd normally do:

ET.XML(escape_illegal_xml_characters(my_xml_string)) #instead of ET.XML(my_xml_string)

JNI and Gradle in Android Studio

In the module build.gradle, in the task field, I get an error unless I use:

def ndkDir = plugins.getPlugin('com.android.application').sdkHandler.getNdkFolder()

I see people using

def ndkDir = android.plugin.ndkFolder

and

def ndkDir = plugins.getPlugin('com.android.library').sdkHandler.getNdkFolder()

but neither of those worked until I changed it to the plugin I was actually importing.

MaxLength Attribute not generating client-side validation attributes

StringLength works great, i used it this way:

[StringLength(25,MinimumLength=1,ErrorMessage="Sorry only 25 characters allowed for 
              ProductName")]
public string ProductName { get; set; }

or Just Use RegularExpression without StringLength:

[RegularExpression(@"^[a-zA-Z0-9'@&#.\s]{1,25}$", ErrorMessage = "Reg Says Sorry only 25 
                   characters allowed for ProductName")]    
public string ProductName { get; set; }

but for me above methods gave error in display view, cause i had already ProductName field in database which had more than 25 characters

so finally i came across this and this post and tried to validate without model like this:

 <div class="editor-field">
 @Html.TextBoxFor(model => model.ProductName, new
 {
 @class = "form-control",
 data_val = "true",
 data_val_length = "Sorry only 25 characters allowed for ProductName",
 data_val_length_max = "25",
 data_val_length_min = "1"
 })
 <span class="validation"> @Html.ValidationMessageFor(model => model.ProductName)</span>
 </div>

this solved my issue, you can also do validation manually using jquery or using ModelState.AddModelError

hope helps someone.

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

You can also specify the range with the coord_cartesian command to set the y-axis range that you want, an like in the previous post use scales = free_x

p <- ggplot(plot, aes(x = pred, y = value)) +
     geom_point(size = 2.5) +
     theme_bw()+
     coord_cartesian(ylim = c(-20, 80))
p <- p + facet_wrap(~variable, scales = "free_x")
p

enter image description here

How to export all collections in MongoDB?

I wrote bash script for that. Just run it with 2 parameters (database name, dir to store files).

#!/bin/bash

if [ ! $1 ]; then
        echo " Example of use: $0 database_name [dir_to_store]"
        exit 1
fi
db=$1
out_dir=$2
if [ ! $out_dir ]; then
        out_dir="./"
else
        mkdir -p $out_dir
fi

tmp_file="fadlfhsdofheinwvw.js"
echo "print('_ ' + db.getCollectionNames())" > $tmp_file
cols=`mongo $db $tmp_file | grep '_' | awk '{print $2}' | tr ',' ' '`
for c in $cols
do
    mongoexport -d $db -c $c -o "$out_dir/exp_${db}_${c}.json"
done
rm $tmp_file

SQL Not Like Statement not working

If WPP.COMMENT contains NULL, the condition will not match.

This query:

SELECT  1
WHERE   NULL NOT LIKE '%test%'

will return nothing.

On a NULL column, both LIKE and NOT LIKE against any search string will return NULL.

Could you please post relevant values of a row which in your opinion should be returned but it isn't?

Fastest way to check if a value exists in a list

The original question was:

What is the fastest way to know if a value exists in a list (a list with millions of values in it) and what its index is?

Thus there are two things to find:

  1. is an item in the list, and
  2. what is the index (if in the list).

Towards this, I modified @xslittlegrass code to compute indexes in all cases, and added an additional method.

Results

enter image description here

Methods are:

  1. in--basically if x in b: return b.index(x)
  2. try--try/catch on b.index(x) (skips having to check if x in b)
  3. set--basically if x in set(b): return b.index(x)
  4. bisect--sort b with its index, binary search for x in sorted(b). Note mod from @xslittlegrass who returns the index in the sorted b, rather than the original b)
  5. reverse--form a reverse lookup dictionary d for b; then d[x] provides the index of x.

Results show that method 5 is the fastest.

Interestingly the try and the set methods are equivalent in time.


Test Code

import random
import bisect
import matplotlib.pyplot as plt
import math
import timeit
import itertools

def wrapper(func, *args, **kwargs):
    " Use to produced 0 argument function for call it"
    # Reference https://www.pythoncentral.io/time-a-python-function/
    def wrapped():
        return func(*args, **kwargs)
    return wrapped

def method_in(a,b,c):
    for i,x in enumerate(a):
        if x in b:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_try(a,b,c):
    for i, x in enumerate(a):
        try:
            c[i] = b.index(x)
        except ValueError:
            c[i] = -1

def method_set_in(a,b,c):
    s = set(b)
    for i,x in enumerate(a):
        if x in s:
            c[i] = b.index(x)
        else:
            c[i] = -1
    return c

def method_bisect(a,b,c):
    " Finds indexes using bisection "

    # Create a sorted b with its index
    bsorted = sorted([(x, i) for i, x in enumerate(b)], key = lambda t: t[0])

    for i,x in enumerate(a):
        index = bisect.bisect_left(bsorted,(x, ))
        c[i] = -1
        if index < len(a):
            if x == bsorted[index][0]:
                c[i] = bsorted[index][1]  # index in the b array

    return c

def method_reverse_lookup(a, b, c):
    reverse_lookup = {x:i for i, x in enumerate(b)}
    for i, x in enumerate(a):
        c[i] = reverse_lookup.get(x, -1)
    return c

def profile():
    Nls = [x for x in range(1000,20000,1000)]
    number_iterations = 10
    methods = [method_in, method_try, method_set_in, method_bisect, method_reverse_lookup]
    time_methods = [[] for _ in range(len(methods))]

    for N in Nls:
        a = [x for x in range(0,N)]
        random.shuffle(a)
        b = [x for x in range(0,N)]
        random.shuffle(b)
        c = [0 for x in range(0,N)]

        for i, func in enumerate(methods):
            wrapped = wrapper(func, a, b, c)
            time_methods[i].append(math.log(timeit.timeit(wrapped, number=number_iterations)))

    markers = itertools.cycle(('o', '+', '.', '>', '2'))
    colors = itertools.cycle(('r', 'b', 'g', 'y', 'c'))
    labels = itertools.cycle(('in', 'try', 'set', 'bisect', 'reverse'))

    for i in range(len(time_methods)):
        plt.plot(Nls,time_methods[i],marker = next(markers),color=next(colors),linestyle='-',label=next(labels))

    plt.xlabel('list size', fontsize=18)
    plt.ylabel('log(time)', fontsize=18)
    plt.legend(loc = 'upper left')
    plt.show()

profile()

python dict to numpy structured array

Similarly to the approved answer. If you want to create an array from dictionary keys:

np.array( tuple(dict.keys()) )

If you want to create an array from dictionary values:

np.array( tuple(dict.values()) )

How to display length of filtered ng-repeat data

The easiest way if you have

<div ng-repeat="person in data | filter: query"></div>

Filtered data length

<div>{{ (data | filter: query).length }}</div>

.attr("disabled", "disabled") issue

Thank you all for your contribution! I found the problem:

ITS A FIREBUG BUG !!!

My code works. I have asked the PHP Dev to change the input types hidden in to input type text. The disabled feature works. But the firebug console does not update this status!

you can test out this firebug bug by your self here http://jsbin.com/uneti3/3#. Thx to aSeptik for the example page.

update: 2. June 2012: Firebug in FF11 still has this bug.

How do I get the last inserted ID of a MySQL table in PHP?

What you wrote would get you the greatest id assuming they were unique and auto-incremented that would be fine assuming you are okay with inviting concurrency issues.
Since you're using MySQL as your database, there is the specific function LAST_INSERT_ID() which only works on the current connection that did the insert.
PHP offers a specific function for that too called mysql_insert_id.

How to check if an element is visible with WebDriver

Verifying ele is visible.

public static boolean isElementVisible(final By by)
    throws InterruptedException {
        boolean value = false;

        if (driver.findElements(by).size() > 0) {
            value = true;
        }
        return value;
    }

Renaming files in a folder to sequential numbers

To renumber 6000, files in one folder you could use the 'Rename' option of the ACDsee program.

For defining a prefix use this format: ####"*"

Then set the start number and press Rename and the program will rename all 6000 files with sequential numbers.

How could I create a function with a completion handler in Swift?

We can use Closures for this purpose. Try the following

func loadHealthCareList(completionClosure: (indexes: NSMutableArray)-> ()) {
      //some code here
      completionClosure(indexes: list)
}

At some point we can call this function as given below.

healthIndexManager.loadHealthCareList { (indexes) -> () in
            print(indexes)
}

Please refer the following link for more information regarding Closures.

https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html

How to check queue length in Python

it is simple just use .qsize() example:

a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue

The above snippet applies for Queue() class of python. Thanks @rayryeng for the update.

for deque from collections we can use len() as stated here by K Z.

What does the fpermissive flag do?

Right from the docs:

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Bottom line: don't use it unless you know what you are doing!

How to convert string values from a dictionary, into int/float datatypes?

To handle the possibility of int, float, and empty string values, I'd use a combination of a list comprehension, dictionary comprehension, along with conditional expressions, as shown:

dicts = [{'a': '1' , 'b': '' , 'c': '3.14159'},
         {'d': '4' , 'e': '5' , 'f': '6'}]

print [{k: int(v) if v and '.' not in v else float(v) if v else None
            for k, v in d.iteritems()}
               for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

However dictionary comprehensions weren't added to Python 2 until version 2.7. It can still be done in earlier versions as a single expression, but has to be written using the dict constructor like the following:

# for pre-Python 2.7

print [dict([k, int(v) if v and '.' not in v else float(v) if v else None]
            for k, v in d.iteritems())
                for d in dicts]

# [{'a': 1, 'c': 3.14159, 'b': None}, {'e': 5, 'd': 4, 'f': 6}]

Note that either way this creates a new dictionary of lists, instead of modifying the original one in-place (which would need to be done differently).

Running an Excel macro via Python?

I did some modification to the SMNALLY's code so it can run in Python 3.5.2. This is my result:

#Import the following library to make use of the DispatchEx to run the macro
import win32com.client as wincl

def runMacro():

    if os.path.exists("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm"):

    # DispatchEx is required in the newest versions of Python.
    excel_macro = wincl.DispatchEx("Excel.application")
    excel_path = os.path.expanduser("C:\\Users\\Dev\\Desktop\\Development\\completed_apps\\My_Macr_Generates_Data.xlsm")
    workbook = excel_macro.Workbooks.Open(Filename = excel_path, ReadOnly =1)
    excel_macro.Application.Run\
        ("ThisWorkbook.Template2G")
    #Save the results in case you have generated data
    workbook.Save()
    excel_macro.Application.Quit()  
    del excel_macro

writing integer values to a file using out.write()

i = Your_int_value

Write bytes value like this for example:

the_file.write(i.to_bytes(2,"little"))

Depend of you int value size and the bit order your prefer

Uncompress tar.gz file

Use -C option of tar:

tar zxvf <yourfile>.tar.gz -C /usr/src/

and then, the content of the tar should be in:

/usr/src/<yourfile>

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

They aren't the same though, are they? One is a copy, the other is a swap. Hence the function names.

My favourite is:

a = b;

Where a and b are vectors.

mongodb/mongoose findMany - find all documents with IDs listed in array

Use this format of querying

let arr = _categories.map(ele => new mongoose.Types.ObjectId(ele.id));

Item.find({ vendorId: mongoose.Types.ObjectId(_vendorId) , status:'Active'})
  .where('category')
  .in(arr)
  .exec();

How to use LINQ to select object with minimum or maximum property value

public class Foo {
    public int bar;
    public int stuff;
};

void Main()
{
    List<Foo> fooList = new List<Foo>(){
    new Foo(){bar=1,stuff=2},
    new Foo(){bar=3,stuff=4},
    new Foo(){bar=2,stuff=3}};

    Foo result = fooList.Aggregate((u,v) => u.bar < v.bar ? u: v);
    result.Dump();
}

Changing image on hover with CSS/HTML

Change the img tag to a div and give it a background in CSS.

PostgreSQL: Drop PostgreSQL database through command line

Try this. Note there's no database specified - it just runs "on the server"

psql -U postgres -c "drop database databasename"

If that doesn't work, I have seen a problem with postgres holding onto orphaned prepared statements.
To clean them up, do this:

SELECT * FROM pg_prepared_xacts;

then for every id you see, run this:

ROLLBACK PREPARED '<id>';

How to show SVG file on React Native?

Note: Svg does not work for android release versions so do not consider for android. It will work for android in debug mode only. But it works fine for ios.

Use https://github.com/vault-development/react-native-svg-uri

Install

npm install react-native-svg-uri --save
react-native link react-native-svg # not react-native-svg-uri

Usage

import SvgUri from 'react-native-svg-uri';


<SvgUri source={require('./path_to_image/image.svg')} />

Convert ascii value to char

To convert an int ASCII value to character you can also use:

int asciiValue = 65;
char character = char(asciiValue);
cout << character; // output: A
cout << char(90); // output: Z

Create a Maven project in Eclipse complains "Could not resolve archetype"

Add your MAVEN_HOME environment variable, edit your Path to include %MAVEN_HOME%/bin then try creating the project manually with Maven:

mvn archetype:generate -DgroupId=com.program -DartifactId=Program -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false

Then import the existing Maven project to Eclipse.

'Linker command failed with exit code 1' when using Google Analytics via CocoaPods

This worked for me:

you have to remove libPods.a library from Linked Frameworks and Libraries section of target.

jQuery call function after load

In regards to the question in your comment:

Assuming that you've previously bound your function to the click event of the radio button, add this to your $(document).ready function:

$('#[radioButtonOptionID]').click()

Without a parameter, that simulates the click event.

how to change text box value with jQuery?

Use ready event of document :

$(document).ready(function(){ /* the click code */ });

And it is better to use bind method for event handeling. because you don't want to call click action in every load of page

  $(':submit').bind('click' , function () { /* ... */ });

What is JNDI? What is its basic use? When is it used?

JNDI in layman's terms is basically an Interface for being able to get instances of internal/External resources such as

  javax.sql.DataSource, 
  javax.jms.Connection-Factory,
  javax.jms.QueueConnectionFactory,
  javax.jms.TopicConnectionFactory,
  javax.mail.Session, java.net.URL,
  javax.resource.cci.ConnectionFactory,

or any other type defined by a JCA resource adapter. It provides a syntax in being able to create access whether they are internal or external. i.e (comp/env in this instance means where component/environment, there are lots of other syntax):

jndiContext.lookup("java:comp/env/persistence/customerDB");

Can't create project on Netbeans 8.2

I had the same issue,

  • Quit Netbeans.
  • Delete the JDK9 file in : /Library/Java/JavaVirtualMachines
  • Install the JDK8 : Download link

Good luck :)

Add / remove input field dynamically with jQuery

enter image description here You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.

How to view kafka message

On server where your admin run kafka find kafka-console-consumer.sh by command find . -name kafka-console-consumer.sh then go to that directory and run for read message from your topic

./kafka-console-consumer.sh --bootstrap-server localhost:9092 --topic test --from-beginning --max-messages 10

note that in topic may be many messages in that case I use --max-messages key

textarea character limit

I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.

Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:

HTML:

<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>

Javascript:

function maxLength(el) {    
    if (!('maxLength' in el)) {
        var max = el.attributes.maxLength.value;
        el.onkeypress = function () {
            if (this.value.length >= max) return false;
        };
    }
}

maxLength(document.getElementById("text"));

Demo

There is no such thing as a minlength attribute in HTML5.
For the following input types: number, range, date, datetime, datetime-local, month, time, and week (which aren't fully supported yet) use the min and max attributes.

How to print React component on click of a button?

The solution provided by Emil Ingerslev is working fine, but CSS is not applied to the output. Here I found a good solution given by Andrewlimaza. It prints the contents of a given div, as it uses the window object's print method, the CSS is not lost. And there is no need for an extra iframe also.

var printContents = document.getElementById("divcontents").innerHTML;
var originalContents = document.body.innerHTML;
document.body.innerHTML = printContents;
window.print();
document.body.innerHTML = originalContents;

Update 1: There is unusual behavior, in chrome/firefox/opera/edge, the print or other buttons stopped working after the execution of this code.

Update 2: The solution given is there on the above link in comments:

.printme { display: none;}
@media print { 
    .no-printme  { display: none;}
    .printme  { display: block;}
}

<h1 class = "no-printme"> do not print this </h1>    
<div class='printme'>
  Print this only 
</div>    
<button onclick={window.print()}>Print only the above div</button>

Classes residing in App_Code is not accessible

Put this at the top of the other files where you want to access the class:

using CLIck10.App_Code;

OR access the class from other files like this:

CLIck10.App_Code.Glob

Not sure if that's your issue or not but if you were new to C# then this is an easy one to get tripped up on.

Update: I recently found that if I add an App_Code folder to a project, then I must close/reopen Visual Studio for it to properly recognize this "special" folder.

C# MessageBox dialog result

You can also do it in one row:

if (MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo) == DialogResult.Yes)

And if you want to show a messagebox on top:

if (MessageBox.Show(new Form() { TopMost = true }, "Text", "Text", MessageBoxButtons.YesNo) == DialogResult.Yes)

What is TypeScript and why would I use it in place of JavaScript?

"TypeScript Fundamentals" -- a Pluralsight video-course by Dan Wahlin and John Papa is a really good, presently (March 25, 2016) updated to reflect TypeScript 1.8, introduction to Typescript.

For me the really good features, beside the nice possibilities for intellisense, are the classes, interfaces, modules, the ease of implementing AMD, and the possibility to use the Visual Studio Typescript debugger when invoked with IE.

To summarize: If used as intended, Typescript can make JavaScript programming more reliable, and easier. It can increase the productivity of the JavaScript programmer significantly over the full SDLC.

How to change ViewPager's page?

slide to right

viewPager.arrowScroll(View.FOCUS_RIGHT);

slide to left

viewPager.arrowScroll(View.FOCUS_LEFT);

How to change the default background color white to something else in twitter bootstrap

You can simply add this line into your bootstrap_and_overides.css.less file

body { background: #000000 !important;}

that's it

MySQL - sum column value(s) based on row from the same table

This might be seen as a little complex but does exactly what you want

SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(pl.CashAmount) AS Cash,
  SUM(pr.CashAmount) AS `Check`,
  SUM(px.CashAmount) AS `Credit Card`,
  SUM(pl.CashAmount) + SUM(pr.CashAmount) +SUM(px.CashAmount) AS Amount
FROM
  `payments` AS p 
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Cash' GROUP BY ProductID , PaymentMethod ) AS pl 
    ON pl.`PaymentMethod` = p.`PaymentMethod` AND pl.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID,PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Check' GROUP BY ProductID , PaymentMethod) AS pr 
    ON pr.`PaymentMethod` = p.`PaymentMethod` AND pr.ProductID = p.`ProductID`
  LEFT JOIN (SELECT ProductID, PaymentMethod , IFNULL(Amount,0) AS CashAmount FROM payments WHERE PaymentMethod = 'Credit Card' GROUP BY ProductID , PaymentMethod) AS px 
    ON px.`PaymentMethod` = p.`PaymentMethod` AND px.ProductID = p.`ProductID`
GROUP BY p.`ProductID` ;

Output

ProductID | Cash | Check | Credit Card | Amount
-----------------------------------------------
    3     | 20   |  15   |   25        |  60
    4     | 5    |  6    |   7         |  18

SQL Fiddle Demo

How can I show/hide component with JSF?

One obvious solution would be to use javascript (which is not JSF). To implement this by JSF you should use AJAX. In this example, I use a radio button group to show and hide two set of components. In the back bean, I define a boolean switch.

private boolean switchComponents;

public boolean isSwitchComponents() {
    return switchComponents;
}

public void setSwitchComponents(boolean switchComponents) {
    this.switchComponents = switchComponents;
}

When the switch is true, one set of components will be shown and when it is false the other set will be shown.

 <h:selectOneRadio value="#{backbean.switchValue}">
   <f:selectItem itemLabel="showComponentSetOne" itemValue='true'/>
   <f:selectItem itemLabel="showComponentSetTwo" itemValue='false'/>
   <f:ajax event="change" execute="@this" render="componentsRoot"/>
 </h:selectOneRadio>


<H:panelGroup id="componentsRoot">
     <h:panelGroup rendered="#{backbean.switchValue}">
       <!--switchValue to be shown on switch value == true-->
     </h:panelGroup>

   <h:panelGroup rendered="#{!backbean.switchValue}">
      <!--switchValue to be shown on switch value == false-->
   </h:panelGroup>
</H:panelGroup>

Note: on the ajax event we render components root. because components which are not rendered in the first place can't be re-rendered on the ajax event.

Also, note that if the "componentsRoot" and radio buttons are under different component hierarchy. you should reference it from the root (form root).

How to set default text for a Tkinter Entry widget

Use Entry.insert. For example:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
e = Entry(root)
e.insert(END, 'default text')
e.pack()
root.mainloop()

Or use textvariable option:

try:
    from tkinter import *  # Python 3.x
except Import Error:
    from Tkinter import *  # Python 2.x

root = Tk()
v = StringVar(root, value='default text')
e = Entry(root, textvariable=v)
e.pack()
root.mainloop()

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

You are repeating the y,m,d.

Instead of

gmdate('yyyy-mm-dd hh:mm:ss \G\M\T', time());  

You should use it like

gmdate('Y-m-d h:m:s \G\M\T', time());

How do you grep a file and get the next 5 lines

Some awk version.

awk '/19:55/{c=5} c-->0'
awk '/19:55/{c=5} c && c--'

When pattern found, set c=5
If c is true, print and decrease number of c

How to set and reference a variable in a Jenkinsfile

The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

So in your case:

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.FILENAME = readFile 'output.txt'
                }
                echo "${env.FILENAME}"
            }
        }
    }
}

Input group - two inputs close to each other

My solution requires no additional css and works with any combination of input-addon, input-btn and form-control. It just uses pre-existing bootstrap classes

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
    <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MinVal">_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="MaxVal">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

This will be inline if there is space and wrap for smaller screens.

Full Example ( input-addon, input-btn and form-control. )

jsfiddle

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" type="text/css" rel="stylesheet" />_x000D_
<form style="padding:10px; margin:10px" action="" class=" form-inline">_x000D_
  <div class="form-group">_x000D_
    <div class="input-group">_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <span class="input-group-addon" id="basic-addon1">@</span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <br>_x000D_
_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
          <span></span>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="form-group">_x000D_
        <div class="input-group">_x000D_
          <span></span>_x000D_
          <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to use workbook.saveas with automatic Overwrite

To hide the prompt set xls.DisplayAlerts = False

ConflictResolution is not a true or false property, it should be xlLocalSessionChanges

Note that this has nothing to do with displaying the Overwrite prompt though!

Set xls = CreateObject("Excel.Application")    
xls.DisplayAlerts = False
Set wb = xls.Workbooks.Add
fullFilePath = importFolderPath & "\" & "A.xlsx"

wb.SaveAs fullFilePath, AccessMode:=xlExclusive,ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges    
wb.Close (True)

What is .Net Framework 4 extended?

Got this from Bing. Seems Microsoft has removed some features from the core framework and added it to a separate optional(?) framework component.

To quote from MSDN (http://msdn.microsoft.com/en-us/library/cc656912.aspx)

The .NET Framework 4 Client Profile does not include the following features. You must install the .NET Framework 4 to use these features in your application:

* ASP.NET
* Advanced Windows Communication Foundation (WCF) functionality
* .NET Framework Data Provider for Oracle
* MSBuild for compiling

Smooth scroll to div id jQuery

Here is my solution to smooth scroll to div / anchor using jQuery in case you have a fixed header so that it doesn't scroll underneath it. Also it works if you link it from other page.

Just replace ".site-header" to div that contains your header.

$(function() {

$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');

  if (target.length) {
    $('html, body').animate({
      scrollTop: (target.offset().top - headerheight)
    }, 1000);
    return false;
  }
}
});

//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
  var target = $('#'+location.href.split("#")[1]);
  if (target.length) {
    $('html,body').animate({
      scrollTop: target.offset().top - headerheight
    }, 1);
    return false;
  }
}
});

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

Removing X-Powered-By

if (function_exists('header_remove')) {
    header_remove('X-Powered-By'); // PHP 5.3+
} else {
    @ini_set('expose_php', 'off');
}

"unexpected token import" in Nodejs5 and babel?

It may be that you're running uncompiled files. Let's start clean!

In your work directory create:

  • Two folders. One for precompiled es2015 code. The other for babel's output. We'll name them "src" and "lib" respectively.
  • A package.json file with the following object:

    { 
      "scripts": {
          "transpile-es2015": "babel src -d lib"
      },
      "devDependencies": {
          "babel-cli": "^6.18.0",
          "babel-preset-latest": "^6.16.0"
      }
    }
    
  • A file named ".babelrc" with the following instructions: {"presets": ["latest"]}

  • Lastly, write test code in your src/index.js file. In your case: import co from 'co'.

Through your console:

  • Install your packages: npm install
  • Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json: npm run transpile-es2015
  • Run your code from the output directory! node lib/index.js

How to sort by Date with DataTables jquery plugin?

Just in case someone is having trouble where they have blank spaces either in the date values or in cells, you will have to handle those bits. Sometimes an empty space is not handled by trim function coming from html it's like "$nbsp;". If you don't handle these, your sorting will not work properly and will break where ever there is a blank space.

I got this bit of code from jquery extensions here too and changed it a little bit to suit my requirement. You should do the same:) cheers!

function trim(str) {
    str = str.replace(/^\s+/, '');
    for (var i = str.length - 1; i >= 0; i--) {
        if (/\S/.test(str.charAt(i))) {
            str = str.substring(0, i + 1);
            break;
        }
    }
    return str;
}

jQuery.fn.dataTableExt.oSort['uk-date-time-asc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000; // = l'an 1000 ...
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }
    var z = ((x < y) ? -1 : ((x > y) ? 1 : 0));
    return z;
};

jQuery.fn.dataTableExt.oSort['uk-date-time-desc'] = function(a, b) {
    if (trim(a) != '' && a!="&nbsp;") {
        if (a.indexOf(' ') == -1) {
            var frDatea = trim(a).split(' ');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0]) * 1;
        }
        else {
            var frDatea = trim(a).split(' ');
            var frTimea = frDatea[1].split(':');
            var frDatea2 = frDatea[0].split('/');
            var x = (frDatea2[2] + frDatea2[1] + frDatea2[0] + frTimea[0] + frTimea[1] + frTimea[2]) * 1;
        }
    } else {
        var x = 10000000;
    }

    if (trim(b) != '' && b!="&nbsp;") {
        if (b.indexOf(' ') == -1) {
            var frDateb = trim(b).split(' ');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0]) * 1;
        }
        else {
            var frDateb = trim(b).split(' ');
            var frTimeb = frDateb[1].split(':');
            frDateb = frDateb[0].split('/');
            var y = (frDateb[2] + frDateb[1] + frDateb[0] + frTimeb[0] + frTimeb[1] + frTimeb[2]) * 1;
        }
    } else {
        var y = 10000000;
    }

    var z = ((x < y) ? 1 : ((x > y) ? -1 : 0));
    return z;
};

Converting Epoch time into the datetime

Try this:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'

Also in MySQL, you can FROM_UNIXTIME like:

INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))

For your 2nd question, it is probably because getbbb_class.end_time is a string. You can convert it to numeric like: float(getbbb_class.end_time)

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

How to output JavaScript with PHP

The error you get if because you need to escape the quotes (like other answers said).

To avoid that, you can use an alternative syntax for you strings declarations, called "Heredoc"

With this syntax, you can declare a long string, even containing single-quotes and/or double-quotes, whithout having to escape thoses ; it will make your Javascript code easier to write, modify, and understand -- which is always a good thing.

As an example, your code could become :

$str = <<<MY_MARKER
<script type="text/javascript">
  document.write("Hello World!");
</script>
MY_MARKER;

echo $str;

Note that with Heredoc syntax (as with string delimited by double-quotes), variables are interpolated.

Facebook OAuth "The domain of this URL isn't included in the app's domain"

In case someone comes across this and is looking for these settings (like I was)

You have to

  1. On the left hand side, click "+Add Product" and select "Facebook Login" (it was at the top for me)
  2. See the new settings available on the left hand side
  3. You will now have these OAuth settings on that "Product Settings"

enter image description here

Additional Info: Make sure to add the Callback URL like http://localhost:3000 to the Valid OAuth redirect URIs field on the settings page of Facebook Login

downloading all the files in a directory with cURL

If you're not bound to curl, you might want to use wget in recursive mode but restricting it to one level of recursion, try the following;

wget --no-verbose --no-parent --recursive --level=1\
--no-directories --user=login --password=pass ftp://ftp.myftpsite.com/
  • --no-parent : Do not ever ascend to the parent directory when retrieving recursively.
  • --level=depth : Specify recursion maximum depth level depth. The default maximum depth is five layers.
  • --no-directories : Do not create a hierarchy of directories when retrieving recursively.

Trying to merge 2 dataframes but get ValueError

I found that my dfs both had the same type column (str) but switching from join to merge solved the issue.

Classpath including JAR within a JAR

Not without writing your own class loader. You can add jars to the jar's classpath, but they must be co-located, not contained in the main jar.

SQL Error: ORA-00922: missing or invalid option

The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)

Generally, there is no benefit to declaring a column as CHAR(3) rather than VARCHAR2(3). Declaring a column as CHAR(3) doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3) and then add a CHECK constraint that LENGTH(takeoff_at) = 3.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)

Since both takeoff_at and destination are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight table and this new airport_code table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.

And from a naming convention standpoint, since both takeoff_at and destination are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code and arrival_airport_code, for example, would be much more meaningful.

importing jar libraries into android-studio

If the code for your jar library is on GitHub then importing into Android Studio is easy with JitPack.

Your will just need to add the repository to build.gradle:

allprojects{
 repositories {
    jcenter()
    maven { url "https://jitpack.io" }
 }
}

and then the library's GitHub repository as a dependency:

dependencies {
    // ...
    compile 'com.github.YourUsername:LibraryRepo:ReleaseTag'
}

JitPack acts as a maven repository and can be used like Maven Central. The nice thing is that you don't have to upload the jar manually. Behind the scenes JitPack will check out the code from GitHub and compile it. Therefore it works only if the repo has a build file in it (build.gradle).

There is also a guide on how to prepare an Android project.

Laravel 5: Retrieve JSON array from $request

As of Laravel 5.2+, you can fetch it directly with $request->input('item') as well.

Retrieving JSON Input Values

When sending JSON requests to your application, you may access the JSON data via the input method as long as the Content-Type header of the request is properly set to application/json. You may even use "dot" syntax to dig deeper into JSON arrays:

$name = $request->input('user.name');

https://laravel.com/docs/5.2/requests

As noted above, the content-type header must be set to application/json so the jQuery ajax call would need to include contentType: "application/json",

$.ajax({
    type: "POST",
    url: "/people",
    data: '[{ "name": "John", "location": "Boston" }, { "name": "Dave", "location": "Lancaster" }]',
    dataType: "json",
    contentType: "application/json",
    success:function(data) {
        $('#save_message').html(data.message);
    } 
});

By fixing the AJAX call, $request->all() should work.

How can I add shadow to the widget in flutter?

Before you start reinventing the wheel with one of these answers, check out the Material Card widget. It also allows you to define a global style via the app theme directly:

example

Java: Get month Integer from Date

Date mDate = new Date(System.currentTimeMillis());
mDate.getMonth() + 1

The returned value starts from 0, so you should add one to the result.

How to hide command output in Bash

You should not use bash in this case to get rid of the output. Yum does have an option -q which suppresses the output.

You'll most certainly also want to use -y

echo "Installing nano..."
yum -y -q install nano

To see all the options for yum, use man yum.

Using sendmail from bash script for multiple recipients

to use sendmail from the shell script

subject="mail subject"
body="Hello World"
from="[email protected]"
to="[email protected],[email protected]"
echo -e "Subject:${subject}\n${body}" | sendmail -f "${from}" -t "${to}"

CSS3 selector to find the 2nd div of the same class

What exactly is the structure of your HTML?

The previous CSS will work if the HTML is as such:

CSS

.foo:nth-child(2)

HTML

<div>
 <div class="foo"></div>
 <div class="foo">Find me</div>
...
</div>

But if you have the following HTML it will not work.

<div>
 <div class="other"></div>
 <div class="foo"></div>
 <div class="foo">Find me</div>
 ...
</div>

Simple put, there is no selector for the getting the index of the matches from the rest of the selector before it.

How to add content to html body using JS?

You can use

document.getElementById("parentID").appendChild(/*..your content created using DOM methods..*/)

or

document.getElementById("parentID").innerHTML+= "new content"

Using Google Text-To-Speech in Javascript

You can use the SpeechSynthesisUtterance with a function like say:

function say(m) {
  var msg = new SpeechSynthesisUtterance();
  var voices = window.speechSynthesis.getVoices();
  msg.voice = voices[10];
  msg.voiceURI = "native";
  msg.volume = 1;
  msg.rate = 1;
  msg.pitch = 0.8;
  msg.text = m;
  msg.lang = 'en-US';
  speechSynthesis.speak(msg);
}

Then you only need to call say(msg) when using it.

Update: Look at Google's Developer Blog that is about Voice Driven Web Apps Introduction to the Web Speech API.

How to remove close button on the jQuery UI dialog?

The best way to hide the button is to filter it with it's data-icon attribute:

$('#dialog-id [data-icon="delete"]').hide();

Eclipse add Tomcat 7 blank server name

It is a bug in Eclipse. I had exactly the same problem, also on Ubuntu with Eclipse Java EE Juno.

Here is the workaround that worked for me:

  1. Close Eclipse
  2. In {workspace-directory}/.metadata/.plugins/org.eclipse.core.runtime/.settings delete the following two files:
    • org.eclipse.wst.server.core.prefs
    • org.eclipse.jst.server.tomcat.core.prefs
  3. Restart Eclipse

Source: eclipse.org Forum

Rollback to an old Git commit in a public repo

Well, I guess the question is, what do you mean by 'roll back'? If you can't reset because it's public and you want to keep the commit history intact, do you mean you just want your working copy to reflect a specific commit? Use git checkout and the commit hash.

Edit: As was pointed out in the comments, using git checkout without specifying a branch will leave you in a "no branch" state. Use git checkout <commit> -b <branchname> to checkout into a branch, or git checkout <commit> . to checkout into the current branch.

Using Gradle to build a jar with dependencies

I use task shadowJar by plugin . com.github.jengelman.gradle.plugins:shadow:5.2.0

Usage just run ./gradlew app::shadowJar result file will be at MyProject/app/build/libs/shadow.jar

top level build.gradle file :

 apply plugin: 'kotlin'

buildscript {
    ext.kotlin_version = '1.3.61'

    repositories {
        mavenLocal()
        mavenCentral()
        jcenter()
    }

    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.github.jengelman.gradle.plugins:shadow:5.2.0'
    }
}

app module level build.gradle file

apply plugin: 'java'
apply plugin: 'kotlin'
apply plugin: 'kotlin-kapt'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'

sourceCompatibility = 1.8

kapt {
    generateStubs = true
}

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

    implementation "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"
    shadow "org.seleniumhq.selenium:selenium-java:4.0.0-alpha-4"

    implementation project(":module_remote")
    shadow project(":module_remote")
}

jar {
    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
    manifest {
        attributes(
                'Main-Class': 'com.github.kolyall.TheApplication',
                'Class-Path': configurations.compile.files.collect { "lib/$it.name" }.join(' ')
        )
    }
}

shadowJar {
    baseName = 'shadow'
    classifier = ''
    archiveVersion = ''
    mainClassName = 'com.github.kolyall.TheApplication'

    mergeServiceFiles()
}

What does "async: false" do in jQuery.ajax()?

  • async:false = Code paused. (Other code waiting for this to finish.)
  • async:true = Code continued. (Nothing gets paused. Other code is not waiting.)

As simple as this.

LINQ query to find if items in a list are contained in another list

var test2NotInTest1 = test2.Where(t2 => test1.Count(t1 => t2.Contains(t1))==0);

Faster version as per Tim's suggestion:

var test2NotInTest1 = test2.Where(t2 => !test1.Any(t1 => t2.Contains(t1)));

Postgresql 9.2 pg_dump version mismatch

I had same error and this is how I solved it in my case. This means your postgresql version is 9.2.1 but you have started postgresql service of 9.1.6.

If you run psql postgres you will see:

psql (9.2.1, server 9.1.6)

What I did to solve this problem is:

  1. brew services stop [email protected]
  2. brew services restart [email protected]

Now run psql postgres and you should have: psql (9.2.1)

You can also run brew services list to see the status of your postgres.

Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

Different names of JSON property during serialization and deserialization

You can use a combination of @JsonSetter, and @JsonGetter to control the deserialization, and serialization of your property, respectively. This will also allow you to keep standardized getter and setter method names that correspond to your actual field name.

import com.fasterxml.jackson.annotation.JsonSetter;    
import com.fasterxml.jackson.annotation.JsonGetter;

class Coordinates {
    private int red;

    //# Used during serialization
    @JsonGetter("r")
    public int getRed() {
        return red;
    }

    //# Used during deserialization
    @JsonSetter("red")
    public void setRed(int red) {
        this.red = red;
    }
}

Python def function: How do you specify the end of the function?

In my opinion, it's better to explicitly mark the end of the function by comment

def func():
     # funcbody
     ## end of subroutine func ##

The point is that some subroutine is very long and is not convenient to scroll up the editor to check for which function is ended. In addition, if you use Sublime, you can right click -> Goto Definition and it will automatically jump to the subroutine declaration.

Empty brackets '[]' appearing when using .where

You can use the lower function:

Guide.where("lower(title)='attack'") 

As a comment: Work on your question. The title isn't terribly informative, and you drop a big chunk of code at the end that is irrelevant to your question.

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

How do I remove the top margin in a web page?

Is your first element h1 or similar? That element's margin-top could be causing what seems like a margin on body.

Adding files to a GitHub repository

You can use Git GUI on Windows, see instructions:

  1. Open the Git Gui (After installing the Git on your computer).

enter image description here

  1. Clone your repository to your local hard drive:

enter image description here

  1. After cloning, GUI opens, choose: "Rescan" for changes that you made:

enter image description here

  1. You will notice the scanned files:

enter image description here

  1. Click on "Stage Changed":

enter image description here

  1. Approve and click "Commit":

enter image description here

  1. Click on "Push":

enter image description here

  1. Click on "Push":

enter image description here

  1. Wait for the files to upload to git:

enter image description here

enter image description here

Not able to change TextField Border Color

The new way to do it is to use enabledBorder like this:

new TextField(
  decoration: new InputDecoration(
    enabledBorder: const OutlineInputBorder(
      borderSide: const BorderSide(color: Colors.grey, width: 0.0),
    ),
    focusedBorder: ...
    border: ...
  ),
)

How to run composer from anywhere?

For running it from other location you can use the composer program that come with the program. It is basically a bash script. If you don't have it you can create one by simply copying the following code into a text file

#!/bin/sh

dir=$(d=$(dirname "$0"); cd "$d" && pwd)

if command -v 'cygpath' >/dev/null 2>&1; then
  dir=$(cygpath -m $dir);
fi

dir=$(echo $dir | sed 's/ /\ /g')
php "${dir}/composer.phar" $*

Then save the file inside your bin folder and name it composer without any file extension. Then add the bin folder to your environment variable f

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

Multiple inheritance for an anonymous class

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

For example:

Runnable r = new Runnable() {
   public void run() { ... }
};

Here, r is an object of an anonymous class which implements Runnable.

An anonymous class can extend another class using the same syntax:

SomeClass x = new SomeClass() {
   ...
};

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

How to add anything in <head> through jquery/javascript?

With jquery you have other option:

$('head').html($('head').html() + '...');

anyway it is working. JavaScript option others said, thats correct too.

CSS table layout: why does table-row not accept a margin?

Add spacer span between two elements, then make it unvisible:

<img src="#" />
<span class="spacer">---</span>
<span>Text TEXT</span>

.spacer {
    visibility: hidden
}

Android Studio AVD - Emulator: Process finished with exit code 1

In AVD Manager -> Edit -> Show Advanced Settings -> Boot Options (Selct Cold boot). That fixed my issue

How to generate List<String> from SQL query?

Where the data returned is a string; you could cast to a different data type:

(from DataRow row in dataTable.Rows select row["columnName"].ToString()).ToList();