Programs & Examples On #Monetdb

MonetDB is an open-source implementation of a column-oriented database. It is focused on analytical applications on a main memory resident database. MonetDB is a relational database and provides an SQL top-level interface. It is actively developed at CWI in Amsterdam, The Netherlands.

How to mkdir only if a directory does not already exist?

Use the -p flag.

man mkdir
mkdir -p foo

Redirect all output to file in Bash

All POSIX operating systems have 3 streams: stdin, stdout, and stderr. stdin is the input, which can accept the stdout or stderr. stdout is the primary output, which is redirected with >, >>, or |. stderr is the error output, which is handled separately so that any exceptions do not get passed to a command or written to a file that it might break; normally, this is sent to a log of some kind, or dumped directly, even when the stdout is redirected. To redirect both to the same place, use:

command &> /some/file

EDIT: thanks to Zack for pointing out that the above solution is not portable--use instead:

*command* > file 2>&1 

If you want to silence the error, do:

*command* 2> /dev/null

Using LINQ to concatenate strings

I blogged about this a while ago, what I did seams to be exactly what you're looking for:

http://ondevelopment.blogspot.com/2009/02/string-concatenation-made-easy.html

In the blog post describe how to implement extension methods that works on IEnumerable and are named Concatenate, this will let you write things like:

var sequence = new string[] { "foo", "bar" };
string result = sequence.Concatenate();

Or more elaborate things like:

var methodNames = typeof(IFoo).GetMethods().Select(x => x.Name);
string result = methodNames.Concatenate(", ");

How do I make a comment in a Dockerfile?

Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):

# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.

FROM ubuntu
MAINTAINER Kimbro Staken

RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen

#RUN echo "" >> /etc/mongodb.conf

CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"] 

Any way to limit border length?

for horizontal lines you can use hr tag:

hr { width: 90%; }

but its not possible to limit border height. only element height.

How to name Dockerfiles

Dockerfile (custom name and folder):

   docker/app.Dockerfile
   docker/nginx.Dockerfile

Build:

   docker build  -f ./docker/app.Dockerfile .
   docker build  -f ./docker/nginx.Dockerfile .

Angular get object from array by Id

You can use .filter() or .find(). One difference that filter will iterate over all items and returns any which passes the condition as array while find will return the first matched item and break the iteration.

Example

_x000D_
_x000D_
var questions = [_x000D_
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},_x000D_
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},_x000D_
      {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},_x000D_
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},_x000D_
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},_x000D_
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},_x000D_
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},_x000D_
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},_x000D_
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},_x000D_
      {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},_x000D_
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},_x000D_
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},_x000D_
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},_x000D_
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},_x000D_
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}_x000D_
];_x000D_
_x000D_
function getDimensionsByFilter(id){_x000D_
  return questions.filter(x => x.id === id);_x000D_
}_x000D_
_x000D_
function getDimensionsByFind(id){_x000D_
  return questions.find(x => x.id === id);_x000D_
}_x000D_
_x000D_
var test = getDimensionsByFilter(10);_x000D_
console.log(test);_x000D_
_x000D_
test = getDimensionsByFind(10);_x000D_
console.log(test);
_x000D_
_x000D_
_x000D_

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

How do I write a Python dictionary to a csv file?

You are using DictWriter.writerows() which expects a list of dicts, not a dict. You want DictWriter.writerow() to write a single row.

You will also want to use DictWriter.writeheader() if you want a header for you csv file.

You also might want to check out the with statement for opening files. It's not only more pythonic and readable but handles closing for you, even when exceptions occur.

Example with these changes made:

import csv

my_dict = {"test": 1, "testing": 2}

with open('mycsvfile.csv', 'w') as f:  # You will need 'wb' mode in Python 2.x
    w = csv.DictWriter(f, my_dict.keys())
    w.writeheader()
    w.writerow(my_dict)

Which produces:

test,testing
1,2

How can I select random files from a directory in bash?

How about a Perl solution slightly doctored from Mr. Kang over here:
How can I shuffle the lines of a text file on the Unix command line or in a shell script?

$ ls | perl -MList::Util=shuffle -e '@lines = shuffle(<>); print @lines[0..4]'

What causes this error? "Runtime error 380: Invalid property value"

Looks like the answers above are for when you are writing and compiling a program, but I'm using a Vendor's software, Catalog.exe, part of the Voyager card catalog by "Ex Libris" and I'm getting the error as well:

catalog-error.png http://img805.imageshack.us/img805/8275/catalogerror.png

I have two Windows 7 32-bit machines. The newer one is giving me the error but on the older one it runs fine. I have done a lot of research with Google and here are some of the things I've found that people are saying related to this issue. Maybe one of these things will help fix the error for you, although they didn't work for me:

From what others are saying (like David M) I think it could be related to the MSVBM60.DLL library - but it appears that on both of my computers this file is the exact same (same version, size, date, etc).

Since that file wasn't different I tried to find what other (dll) files the application could be using, so I launched Process Explorer by Sysinternals and took a look at the application (it loads and then crashes when you tell it to "connect"), and the screenshots below are what I found.

screen1.png http://img195.imageshack.us/img195/2231/screen1oo.png

screen2.png http://img88.imageshack.us/img88/2153/screen2ao.png

screen3.png

Now, I'm not a Windows / VB programmer, just a power user, and so I'm about at the end of my knowledge for what to do. I've talked to the software vendor and they recommend reinstalling Windows. That will probably work, but it just bugs me that this program can run on Windows 7, but something on this particular system is causing errors. Finally, this is an image that has been deployed on multiple machines already and so while re-installing Windows once is not a big deal it would save me some serious time if I could figure out a fix or workaround.

Compile to stand alone exe for C# app in Visual Studio 2010

Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

After submitting a POST form open a new window showing the result

I know this basic method:

1)

<input type=”image” src=”submit.png”> (in any place)

2)

<form name=”print”>
<input type=”hidden” name=”a” value=”<?= $a ?>”>
<input type=”hidden” name=”b” value=”<?= $b ?>”>
<input type=”hidden” name=”c” value=”<?= $c ?>”>
</form>

3)

<script>
$(‘#submit’).click(function(){
    open(”,”results”);
    with(document.print)
    {
        method = “POST”;
        action = “results.php”;
        target = “results”;
        submit();
    }
});
</script>

Works!

How do I URL encode a string

Use NSURLComponents to encode HTTP GET parameters:

    var urlComponents = NSURLComponents(string: "https://www.google.de/maps/")!
    urlComponents.queryItems = [
        NSURLQueryItem(name: "q", value: String(51.500833)+","+String(-0.141944)),
        NSURLQueryItem(name: "z", value: String(6))
    ]
    urlComponents.URL     // returns https://www.google.de/maps/?q=51.500833,-0.141944&z=6

http://www.ralfebert.de/snippets/ios/encoding-nsurl-get-parameters/

Virtualbox "port forward" from Guest to Host

That's not possible. localhost always defaults to the loopback device on the local operating system.
As your virtual machine runs its own operating system it has its own loopback device which you cannot access from the outside.

If you want to access it e.g. in a browser, connect to it using the local IP instead:

http://192.168.180.1:8000

This is just an example of course, you can find out the actual IP by issuing an ifconfig command on a shell in the guest operating system.

Choose folders to be ignored during search in VS Code

The short answer is to comma-separate the folders you want to ignore in "files to exclude".

  1. Start workspace wide search: CTRL+SHIFT+f
  2. Expand the global search with the three-dot button
  3. Enter your search term
  4. As an example, in the files to exclude-input field write babel,concat to exclude the folder "babel" and the folder "concat" in the search (make sure the exclude button is enabled).
  5. Press enter to get the results.

Dismissing a Presented View Controller

You can Close your super view window

self.view.superview?.window?.close()

How to enable CORS in ASP.net Core WebAPI

In my case I fixed with UseCors before UserRouting..

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to get a user's client IP address in ASP.NET?

If is c# see this way, is very simple

string clientIp = (Request.ServerVariables["HTTP_X_FORWARDED_FOR"] ?? 
                   Request.ServerVariables["REMOTE_ADDR"]).Split(',')[0].Trim();

Integer value in TextView

TextView tv = new TextView(this);
tv.setText("" + 4);

Use the auto keyword in C++ STL

auto keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.

Select elements by attribute

I have created npm package with intended behaviour as described above in question.

Link to [npm] and [github]

Usage is very simple. For example:

<p id="test" class="test">something</p>
$("#test").hasAttr("class")

returns true.

Works with camelcase too.

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

How to fill color in a cell in VBA?

You need to use cell.Text = "#N/A" instead of cell.Value = "#N/A". The error in the cell is actually just text stored in the cell.

How do I download a file with Angular2 or greater

I was facing this same case today, I had to download a pdf file as an attachment (the file shouldn't be rendered in the browser, but downloaded instead). To achieve that I discovered I had to get the file in an Angular Blob, and, at the same time, add a Content-Disposition header in the response.

This was the simplest I could get (Angular 7):

Inside the service:

getFile(id: String): Observable<HttpResponse<Blob>> {
  return this.http.get(`./file/${id}`, {responseType: 'blob', observe: 'response'});
}

Then, when I need to download the file in a component, I can simply:

fileService.getFile('123').subscribe((file: HttpResponse<Blob>) => window.location.href = file.url);

UPDATE:

Removed unnecessary header setting from service

Use of document.getElementById in JavaScript

document.getElementById("demo").innerHTML = voteable finds the element with the id demo and then places the voteable value into it; either too young or old enough.

So effectively <p id="demo"></p> becomes for example <p id="demo">Old Enough</p>

How to vertically align text in input type="text"?

The <textarea> element automatically aligns text at the top of a textbox, if you don't want to use CSS to force it.

javascript, for loop defines a dynamic variable name

You cannot create different "variable names" but you can create different object properties. There are many ways to do whatever it is you're actually trying to accomplish. In your case I would just do

for (var i = myArray.length - 1; i >= 0; i--) {    console.log(eval(myArray[i])); }; 

More generally you can create object properties dynamically, which is the type of flexibility you're thinking of.

var result = {}; for (var i = myArray.length - 1; i >= 0; i--) {     result[myArray[i]] = eval(myArray[i]);   }; 

I'm being a little handwavey since I don't actually understand language theory, but in pure Javascript (including Node) references (i.e. variable names) are happening at a higher level than at runtime. More like at the call stack; you certainly can't manufacture them in your code like you produce objects or arrays. Browsers do actually let you do this anyway though it's terrible practice, via

window['myVarName'] = 'namingCollisionsAreFun';  

(per comment)

How to retrieve GET parameters from JavaScript

If you are using AngularJS, you can use $routeParams using ngRoute module

You have to add a module to your app

angular.module('myApp', ['ngRoute'])

Now you can use service $routeParams:

.controller('AppCtrl', function($routeParams) {
  console.log($routeParams); // JSON object
}

Convert Data URI to File then append to FormData

toDataURL gives you a string and you can put that string to a hidden input.

Auto Generate Database Diagram MySQL

This http://code.google.com/p/database-diagram/ will reverse engineer your database. Just do an export 'structure only' then paste the SQL into the tool.

excel plot against a date time x series

You will need to specify TimeSeries in Excel to be plotted. Have a look at this

Plotting Time Series

Using a PagedList with a ViewModel ASP.Net MVC

For anyone who is trying to do it without modifying your ViewModels AND not loading all your records from the database.

Repository

    public List<Order> GetOrderPage(int page, int itemsPerPage, out int totalCount)
    {
        List<Order> orders = new List<Order>();
        using (DatabaseContext db = new DatabaseContext())
        {
            orders = (from o in db.Orders
                      orderby o.Date descending //use orderby, otherwise Skip will throw an error
                      select o)
                      .Skip(itemsPerPage * page).Take(itemsPerPage)
                      .ToList();
            totalCount = db.Orders.Count();//return the number of pages
        }
        return orders;//the query is now already executed, it is a subset of all the orders.
    }

Controller

    public ActionResult Index(int? page)
    {
        int pagenumber = (page ?? 1) -1; //I know what you're thinking, don't put it on 0 :)
        OrderManagement orderMan = new OrderManagement(HttpContext.ApplicationInstance.Context);
        int totalCount = 0;
        List<Order> orders = orderMan.GetOrderPage(pagenumber, 5, out totalCount);
        List<OrderViewModel> orderViews = new List<OrderViewModel>();
        foreach(Order order in orders)//convert your models to some view models.
        {
            orderViews.Add(orderMan.GenerateOrderViewModel(order));
        }
        //create staticPageList, defining your viewModel, current page, page size and total number of pages.
        IPagedList<OrderViewModel> pageOrders = new StaticPagedList<OrderViewModel>(orderViews, pagenumber + 1, 5, totalCount);
        return View(pageOrders);
    }

View

@using PagedList.Mvc;
@using PagedList; 

@model IPagedList<Babywatcher.Core.Models.OrderViewModel>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<div class="container-fluid">
    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    @if (Model.Count > 0)
    {


        <table class="table">
          <tr>
            <th>
                @Html.DisplayNameFor(model => model.First().orderId)
            </th>
            <!--rest of your stuff-->
        </table>

    }
    else
    {
        <p>No Orders yet.</p>
    }
    @Html.PagedListPager(Model, page => Url.Action("Index", new { page }))
</div>

Bonus

Do above first, then perhaps use this!

Since this question is about (view) models, I'm going to give away a little solution for you that will not only be useful for paging, but for the rest of your application if you want to keep your entities separate, only used in the repository, and have the rest of the application deal with models (which can be used as view models).

Repository

In your order repository (in my case), add a static method to convert a model:

public static OrderModel ConvertToModel(Order entity)
{
    if (entity == null) return null;
    OrderModel model = new OrderModel
    {
        ContactId = entity.contactId,
        OrderId = entity.orderId,
    }
    return model;
}

Below your repository class, add this:

public static partial class Ex
{
    public static IEnumerable<OrderModel> SelectOrderModel(this IEnumerable<Order> source)
    {
        bool includeRelations = source.GetType() != typeof(DbQuery<Order>);
        return source.Select(x => new OrderModel
        {
            OrderId = x.orderId,
            //example use ConvertToModel of some other repository
            BillingAddress = includeRelations ? AddressRepository.ConvertToModel(x.BillingAddress) : null,
            //example use another extension of some other repository
            Shipments = includeRelations && x.Shipments != null ? x.Shipments.SelectShipmentModel() : null
        });
    }
}

And then in your GetOrderPage method:

    public IEnumerable<OrderModel> GetOrderPage(int page, int itemsPerPage, string searchString, string sortOrder, int? partnerId,
        out int totalCount)
    {
        IQueryable<Order> query = DbContext.Orders; //get queryable from db
        .....//do your filtering, sorting, paging (do not use .ToList() yet)

        return queryOrders.SelectOrderModel().AsEnumerable();
        //or, if you want to include relations
        return queryOrders.Include(x => x.BillingAddress).ToList().SelectOrderModel();
        //notice difference, first ToList(), then SelectOrderModel().
    }

Let me explain:

The static ConvertToModel method can be accessed by any other repository, as used above, I use ConvertToModel from some AddressRepository.

The extension class/method lets you convert an entity to a model. This can be IQueryable or any other list, collection.

Now here comes the magic: If you have executed the query BEFORE calling SelectOrderModel() extension, includeRelations inside the extension will be true because the source is NOT a database query type (not an linq-to-sql IQueryable). When this is true, the extension can call other methods/extensions throughout your application for converting models.

Now on the other side: You can first execute the extension and then continue doing LINQ filtering. The filtering will happen in the database eventually, because you did not do a .ToList() yet, the extension is just an layer of dealing with your queries. Linq-to-sql will eventually know what filtering to apply in the Database. The inlcudeRelations will be false so that it doesn't call other c# methods that SQL doesn't understand.

It looks complicated at first, extensions might be something new, but it's really useful. Eventually when you have set this up for all repositories, simply an .Include() extra will load the relations.

Environment variables for java installation

Set java Environment variable in Centos / Linux

/home/ vi .bashrc

export JAVA_HOME=/opt/oracle/product/java/jdk1.8.0_45

export PATH=$JAVA_HOME/bin:$PATH

java -version

Broken references in Virtualenvs

This occurred when I updated to Mac OS X Mavericks from Snow Leopard. I had to re-install brew beforehand too. Hopefully you ran the freeze command for your project with pip.

To resolve, you have to update the paths that the virtual environment points to.

  • Install a version of python with brew:

brew install python

  • Re-install virtualenvwrapper.

pip install --upgrade virtualenvwrapper

  • Removed the old virtual environment:

rmvirtualenv old_project

  • Create a new virtual environment:

mkvirtualenv new_project

  • Work on new virtual environment

workon new_project

  • Use pip to install the requirements for the new project.

pip install -r requirements.txt

This should leave the project as it was before.

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

I tried all the other suggestions in the answers here, none of which worked. Eventually I used Process Monitor to discover that my .exe that VS2010 was failing to build was locked by the System process (PID=4). Searching SO for situations involving this yielded this answer.

Summarised: if you have the Application Experience service disabled (as I did) then re-enable and start it. Two years of aggravation ended.

How to compile for Windows on Linux with gcc/g++?

I've used mingw on Linux to make Windows executables in C, I suspect C++ would work as well.

I have a project, ELLCC, that packages clang and other things as a cross compiler tool chain. I use it to compile clang (C++), binutils, and GDB for Windows. Follow the download link at ellcc.org for pre-compiled binaries for several Linux hosts.

Why does Java have an "unreachable statement" compiler error?

I only just noticed this question, and wanted to add my $.02 to this.

In case of Java, this is not actually an option. The "unreachable code" error doesn't come from the fact that JVM developers thought to protect developers from anything, or be extra vigilant, but from the requirements of the JVM specification.

Both Java compiler, and JVM, use what is called "stack maps" - a definite information about all of the items on the stack, as allocated for the current method. The type of each and every slot of the stack must be known, so that a JVM instruction doesn't mistreat item of one type for another type. This is mostly important for preventing having a numeric value ever being used as a pointer. It's possible, using Java assembly, to try to push/store a number, but then pop/load an object reference. However, JVM will reject this code during class validation,- that is when stack maps are being created and tested for consistency.

To verify the stack maps, the VM has to walk through all the code paths that exist in a method, and make sure that no matter which code path will ever be executed, the stack data for every instruction agrees with what any previous code has pushed/stored in the stack. So, in simple case of:

Object a;
if (something) { a = new Object(); } else { a = new String(); }
System.out.println(a);

at line 3, JVM will check that both branches of 'if' have only stored into a (which is just local var#0) something that is compatible with Object (since that's how code from line 3 and on will treat local var#0).

When compiler gets to an unreachable code, it doesn't quite know what state the stack might be at that point, so it can't verify its state. It can't quite compile the code anymore at that point, as it can't keep track of local variables either, so instead of leaving this ambiguity in the class file, it produces a fatal error.

Of course a simple condition like if (1<2) will fool it, but it's not really fooling - it's giving it a potential branch that can lead to the code, and at least both the compiler and the VM can determine, how the stack items can be used from there on.

P.S. I don't know what .NET does in this case, but I believe it will fail compilation as well. This normally will not be a problem for any machine code compilers (C, C++, Obj-C, etc.)

How to convert buffered image to image and vice-versa?

BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:

Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;

Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.

What is Android keystore file, and what is it used for?

The answer I would provide is that a keystore file is to authenticate yourself to anyone who is asking. It isn't restricted to just signing .apk files, you can use it to store personal certificates, sign data to be transmitted and a whole variety of authentication.

In terms of what you do with it for Android and probably what you're looking for since you mention signing apk's, it is your certificate. You are branding your application with your credentials. You can brand multiple applications with the same key, in fact, it is recommended that you use one certificate to brand multiple applications that you write. It easier to keep track of what applications belong to you.

I'm not sure what you mean by implications. I suppose it means that no one but the holder of your certificate can update your application. That means that if you release it into the wild, lose the cert you used to sign the application, then you cannot release updates so keep that cert safe and backed up if need be.

But apart from signing apks to release into the wild, you can use it to authenticate your device to a server over SSL if you so desire, (also Android related) among other functions.

Case insensitive comparison of strings in shell script

For zsh the syntax is slightly different, but still shorter than most answers here:

> str1='mAtCh'
> str2='MaTcH'
> [[ "$str1:u" = "$str2:u" ]] && echo 'Strings Match!'
Strings Match!
>

This will convert both strings to uppercase before the comparison.


Another method makes use zsh's globbing flags, which allows us to directly make use of case-insensitive matching by using the i glob flag:

setopt extendedglob
[[ $str1 = (#i)$str2 ]] && echo "Match success"
[[ $str1 = (#i)match ]] && echo "Match success"

Get type of a generic parameter in Java with reflection

As pointed out by @bertolami, it's not possible to us a variable type and get its future value (the content of typeOfList variable).

Nevertheless, you can pass the class as parameter on it like this:

public final class voodoo {
    public static void chill(List<T> aListWithTypeSpiderMan, Class<T> clazz) {
        // Here I'd like to get the Class-Object 'SpiderMan'
        Class typeOfTheList = clazz;
    }

    public static void main(String... args) {
        chill(new List<SpiderMan>(), Spiderman.class );
    }
}

That's more or less what Google does when you have to pass a class variable to the constructor of ActivityInstrumentationTestCase2.

How to open an elevated cmd using command line for Windows?

Can use a temporary environment variable to use with an elevated shortcut (

start.cmd

setx valueName_betterSpecificForEachCase %~dp0
"%~dp0ascladm.lnk"

ascladm.lnk (shortcut)

_ properties\advanced\"run as administrator"=yes

(to make path changes you'll need to temporarily create the env.Variable)

_ properties\target="%valueName_betterSpecificForEachCase%\ascladm.cmd"

_ properties\"start in"="%valueName_betterSpecificForEachCase%"

ascladm.cmd

setx valueName_betterSpecificForEachCase=
reg delete HKEY_CURRENT_USER\Environment /F /V valueName_betterSpecificForEachCase
"%~dp0fileName_targetedCmd.cmd"

) (targetedCmd gets executed in elevated cmd window)

Although it is 3 files ,you can place everything (including targetedCmd) in some subfolder (do not forget to add the folderName to the patches) and rename "start.cmd" to targeted's one name

For me it looks like most native way of doing this ,whilst cmd doesn't have the needed command

Rotating x axis labels in R for barplot

EDITED ANSWER PER DAVID'S RESPONSE:

Here's a kind of hackish way. I'm guessing there's an easier way. But you could suppress the bar labels and the plot text of the labels by saving the bar positions from barplot and do a little tweaking up and down. Here's an example with the mtcars data set:

x <- barplot(table(mtcars$cyl), xaxt="n")
labs <- paste(names(table(mtcars$cyl)), "cylinders")
text(cex=1, x=x-.25, y=-1.25, labs, xpd=TRUE, srt=45)

What is lazy loading in Hibernate?

Lazy loading is a design pattern commonly used in computer programming to defer initialization of an object until the point at which it is needed. It can contribute to efficiency in the program's operation if properly and appropriately used

Wikipedia

Link of Lazy Loading from hibernate.org

Convert Python dict into a dataframe

In my case I wanted keys and values of a dict to be columns and values of DataFrame. So the only thing that worked for me was:

data = {'adjust_power': 'y', 'af_policy_r_submix_prio_adjust': '[null]', 'af_rf_info': '[null]', 'bat_ac': '3500', 'bat_capacity': '75'} 

columns = list(data.keys())
values = list(data.values())
arr_len = len(values)

pd.DataFrame(np.array(values, dtype=object).reshape(1, arr_len), columns=columns)

How to configure the web.config to allow requests of any length

If you run into this issue when running an IIS 8.5 web server you can use the following method.

First, find the "Request Filtering" module in the IIS site you are working on, then double click it...

enter image description here

Next, you need to right click in the white area shown below then click the context menu option called "Edit Feature Settings".

enter image description here

Then the last thing to do is change the "Maximum query string (Bytes)" value from 2048 to something more appropriate such as 5000 for your needs.

enter image description here

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

Easiest way to open a download window without navigating away from the page

Using HTML5 Blob Object-URL File API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file_x000D_
 * @param fileName String_x000D_
 * @param fileContents String JSON String_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
var saveBlobAsFile = function(fileName, fileContents) {_x000D_
  if (typeof(Blob) != 'undefined') { // using Blob_x000D_
    var textFileAsBlob = new Blob([fileContents], {_x000D_
      type: 'text/plain'_x000D_
    });_x000D_
    var downloadLink = document.createElement("a");_x000D_
    downloadLink.download = fileName;_x000D_
    if (window.webkitURL != null) {_x000D_
      downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
    } else {_x000D_
      downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
      downloadLink.onclick = document.body.removeChild(event.target);_x000D_
      downloadLink.style.display = "none";_x000D_
      document.body.appendChild(downloadLink);_x000D_
    }_x000D_
    downloadLink.click();_x000D_
  } else {_x000D_
    var pp = document.createElement('a');_x000D_
    pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));_x000D_
    pp.setAttribute('download', fileName);_x000D_
    pp.onclick = document.body.removeChild(event.target);_x000D_
    pp.click();_x000D_
  }_x000D_
} //saveBlobAsFile_x000D_
_x000D_
var jsonObject = {_x000D_
  "name": "John",_x000D_
  "age": 31,_x000D_
  "city": "New York"_x000D_
};_x000D_
var fileContents = JSON.stringify(jsonObject, null, 2);_x000D_
var fileName = "data.json";_x000D_
_x000D_
saveBlobAsFile(fileName, fileContents)
_x000D_
_x000D_
_x000D_

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Another solution : navigate to

\sdk\extras\android\m2repository\com\android\support\appcompat-v7\23.x.x

open .aar file with 7-zip or winrar , in res folder remove values-23 folder and save changes .

How to check is Apache2 is stopped in Ubuntu?

In the command line type service apache2 status then hit enter. The result should say:

Apache2 is running (pid xxxx)

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Properties -> FormBorderStyle -> FixedSingle

if you can not find your Properties tool. Go to View -> Properties Window

Two constructors

The first line of a constructor is always an invocation to another constructor. You can choose between calling a constructor from the same class with "this(...)" or a constructor from the parent clas with "super(...)". If you don't include either, the compiler includes this line for you: super();

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Java naming convention for static final variables

In my opinion a variable being "constant" is often an implementation detail and doesn't necessarily justify different naming conventions. It may help readability, but it may as well hurt it in some cases.

Get Public URL for File - Google Cloud Storage - App Engine (Python)

You need to use get_serving_url from the Images API. As that page explains, you need to call create_gs_key() first to get the key to pass to the Images API.

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

How can I pause setInterval() functions?

While @Jonas Giuro is right when saying that:

You cannot PAUSE the setInterval function, you can either STOP it (clearInterval), or let it run

On the other hand this behavior can be simulated with approach @VitaliyG suggested:

You shouldn't measure time in interval function. Instead just save time when timer was started and measure difference when timer was stopped/paused. Use setInterval only to update displayed value.

_x000D_
_x000D_
var output = $('h1');_x000D_
var isPaused = false;_x000D_
var time = new Date();_x000D_
var offset = 0;_x000D_
var t = window.setInterval(function() {_x000D_
  if(!isPaused) {_x000D_
    var milisec = offset + (new Date()).getTime() - time.getTime();_x000D_
    output.text(parseInt(milisec / 1000) + "s " + (milisec % 1000));_x000D_
  }_x000D_
}, 10);_x000D_
_x000D_
//with jquery_x000D_
$('.toggle').on('click', function(e) {_x000D_
  e.preventDefault();_x000D_
  isPaused = !isPaused;_x000D_
  if (isPaused) {_x000D_
    offset += (new Date()).getTime() - time.getTime();_x000D_
  } else {_x000D_
    time = new Date();_x000D_
  }_x000D_
_x000D_
});
_x000D_
h1 {_x000D_
    font-family: Helvetica, Verdana, sans-serif;_x000D_
    font-size: 12px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<h1>Seconds: 0</h1>_x000D_
<button class="toggle">Toggle</button>
_x000D_
_x000D_
_x000D_

List tables in a PostgreSQL schema

For those coming across this in the future:

If you would like to see a list of relations for several schemas:

$psql mydatabase
mydatabase=# SET search_path TO public, usa;   #schema examples
SET
mydatabase=# \dt
              List of relations
 Schema |      Name       | Type  |  Owner
--------+-----------------+-------+----------
 public | counties        | table | postgres
 public | spatial_ref_sys | table | postgres
 public | states          | table | postgres
 public | us_cities       | table | postgres
 usa    | census2010      | table | postgres

How can I add numbers in a Bash script?

 #!/bin/bash
read X
read Y
echo "$(($X+$Y))"

Append an int to a std::string

The std::string::append() method expects its argument to be a NULL terminated string (char*).

There are several approaches for producing a string containg an int:

  • std::ostringstream

    #include <sstream>
    
    std::ostringstream s;
    s << "select logged from login where id = " << ClientID;
    std::string query(s.str());
    
  • std::to_string (C++11)

    std::string query("select logged from login where id = " +
                      std::to_string(ClientID));
    
  • boost::lexical_cast

    #include <boost/lexical_cast.hpp>
    
    std::string query("select logged from login where id = " +
                      boost::lexical_cast<std::string>(ClientID));
    

Unable to set default python version to python3 in ubuntu

As it says, update-alternatives --install needs <link> <name> <path> and <priority> arguments.

You have link (/usr/bin/python), name (python), and path (/usr/bin/python3), you're missing priority.

update-alternatives --help says:

<priority> is an integer; options with higher numbers have higher priority in automatic mode.

So just put a 100 or something at the end

ImportError: No module named six

I did the following to solve the mentioned problem. I got the mentioned problem when I was trying to run the built exe, even I successfully built the exe using pyinstaller. I did this on Windows 10.

  1. go to https://pypi.org/project/six/#files
  2. download "six-1.14.0.tar.gz (33.9 kB)"
  3. unzip it, copy and paste "six.py" into your source directory.
  4. import "six" module into your source code (import six)
  5. run source script.

Converting XML to JSON using Python?

There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to do with the results.

That being said, Python's standard library has several modules for parsing XML (including DOM, SAX, and ElementTree). As of Python 2.6, support for converting Python data structures to and from JSON is included in the json module.

So the infrastructure is there.

How to find sum of several integers input by user using do/while, While statement or For statement

#include<iostream>
int main()
{//initialize variables
    int limit;
    int num;
    int sum=0;
    int counter=0;

    cout<<"Enter limit of numbers you wish to see"<<" ";
    cin>>limit;
    cout<<endl;

while(counter<limit)
{

   cout<<"Enter number "<<endl;
  cin>>num;

  sum=sum+num;
  counter++;
}
cout<<"The sum of numbers is "<<" "<<endl

return 0;
}

Gradle: Could not determine java version from '11.0.2'

In my case, I was trying to build and get APK for an old Unity 3D project (so that I can play the game in my Android phone). I was using the most recent Android Studio version, and all the SDK packages I could download via SDK Manager in Android Studio. SDK Packages was located in

C:/Users/Onat/AppData/Local/Android/Sdk 

And the error message I got was the same except the JDK (Java Development Kit) version "jdk-12.0.2" . JDK was located in

C:\Program Files\Java\jdk-12.0.2

And Environment Variable in Windows was JAVA_HOME : C:\Program Files\Java\jdk-12.0.2

After 3 hours of research, I found out that Unity does not support JDK 10. As told in https://forum.unity.com/threads/gradle-build-failed-error-could-not-determine-java-version-from-10-0-1.532169/ . My suggestion is:

  1. Uninstall unwanted JDK if you have one installed already. https://www.java.com/tr/download/help/uninstall_java.xml
  2. Head to http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
  3. Login to/Open a Oracle account if not already logged in.
  4. Download the older but functional JDK 8 for your computer set-up(32 bit/64 bit, Windows/Linux etc.)
  5. Install the JDK. Remember the installation path. (https://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/)
  6. If you are using Windows, Open Environment Variables and change Java Path via Right click My Computer/This PC>Properties>Advanced System Settings>Environment Variables>New>Variable Name: JAVA_HOME>Variable Value: [YOUR JDK Path, Mine was "C:\Program Files\Java\jdk1.8.0_221"]
  7. In Unity 3D, press Edit > Preferences > External Tools and fill in the JDK path (Mine was "C:\Program Files\Java\jdk1.8.0_221").
  8. Also, in the same pop-up, edit SDK Path. (Get it from Android Studio > SDK Manager > Android SDK > Android SDK Location.)
  9. If needed, restart your computer for changes to take effect.

No assembly found containing an OwinStartupAttribute Error

Check you have the correct startup project selected. I had a web api project as startup. That generated this error.

Convert INT to VARCHAR SQL

You can use CAST function:

SELECT CAST(your_column_name AS varchar(10)) FROM your_table_name

what is the difference between ajax and jquery and which one is better?

They aren't comparable.

Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.

jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

javascript /jQuery - For Loop

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}

overlay two images in android to set an imageview

You can use the code below to solve the problem or download demo here

Create two functions to handle each.

First, the canvas is drawn and the images are drawn on top of each other from point (0,0)

On button click

public void buttonMerge(View view) {

        Bitmap bigImage = BitmapFactory.decodeResource(getResources(), R.drawable.img1);
        Bitmap smallImage = BitmapFactory.decodeResource(getResources(), R.drawable.img2);
        Bitmap mergedImages = createSingleImageFromMultipleImages(bigImage, smallImage);

        img.setImageBitmap(mergedImages);
    }

Function to create an overlay.

private Bitmap createSingleImageFromMultipleImages(Bitmap firstImage, Bitmap secondImage){

    Bitmap result = Bitmap.createBitmap(firstImage.getWidth(), firstImage.getHeight(), firstImage.getConfig());
    Canvas canvas = new Canvas(result);
    canvas.drawBitmap(firstImage, 0f, 0f, null);
    canvas.drawBitmap(secondImage, 10, 10, null);
    return result;
}

Read more

Max length UITextField

I have been using this protocol / extension in one of my apps, and it's a little more readable. I like how it recognizes backspaces and explicitly tells you when a character is a backspace.

Some things to consider:

1.Whatever implements this protocol extension needs to specify a character limit. That's typically going to be your ViewController, but you could implement character limit as a computed property and return something else, for example a character limit on one of your models.

2. You will need to call this method inside of your text field's shouldChangeCharactersInRange delegate method. Otherwise you won't be able to block text entry by returning false, etc.

3. You will probably want to allow backspace characters through. That's why I added the extra function to detect backspaces. Your shouldChangeCharacters method can check for this and return 'true' early on so you always allow backspaces.

protocol TextEntryCharacterLimited{
    var characterLimit:Int { get } 
}

extension TextEntryCharacterLimited{

    func charactersInTextField(textField:UITextField, willNotExceedCharacterLimitWithReplacementString string:String, range:NSRange) -> Bool{

        let startingLength = textField.text?.characters.count ?? 0
        let lengthToAdd = string.characters.count
        let lengthToReplace = range.length

        let newLength = startingLength + lengthToAdd - lengthToReplace

        return newLength <= characterLimit

    }

    func stringIsBackspaceWith(string:String, inRange range:NSRange) -> Bool{
        if range.length == 1 && string.characters.count == 0 { return true }
        return false
    }

}

If any of you are interested, I have a Github repo where I've taken some of this character limit behavior and put into an iOS framework. There's a protocol you can implement to get a Twitter-like character limit display that shows you how far you've gone above the character limit.

CharacterLimited Framework on Github

How to append to the end of an empty list?

Note that you also can use insert in order to put number into the required position within list:

initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]

And also note that in python you can always get a list length using method len()

When should you use 'friend' in C++?

edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation

How would it break encapsulation?

You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:

class c1 {
public:
  int x;
};

class c2 {
public:
  int foo();
private:
  int x;
};

class c3 {
  friend int foo();
private:
  int x;
};

c1 is obviously not encapsulated. Anyone can read and modify x in it. We have no way to enforce any kind of access control.

c2 is obviously encapsulated. There is no public access to x. All you can do is call the foo function, which performs some meaningful operation on the class.

c3? Is that less encapsulated? Does it allow unrestricted access to x? Does it allow unknown functions access?

No. It allows precisely one function to access the private members of the class. Just like c2 did. And just like c2, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2, we can see, just by looking at the class definitions, a complete list of who has access.

So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.

friend does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.

First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.

Second, it is not restrictive enough. Consider a fourth class:

class c4 {
public:
  int getx();
  void setx(int x);
private:
  int x;
};

This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)

Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.

How to expand 'select' option width after the user wants to select an option

I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

How to change the font color in the textbox in C#?

Assuming WinForms, the ForeColor property allows to change all the text in the TextBox (not just what you're about to add):

TextBox.ForeColor = Color.Red;

To only change the color of certain words, look at RichTextBox.

Multi-Line Comments in Ruby?

=begin comment line 1 comment line 2 =end make sure =begin and =end is the first thing on that line (no spaces)

Stack Memory vs Heap Memory

It's a language abstraction - some languages have both, some one, some neither.

In the case of C++, the code is not run in either the stack or the heap. You can test what happens if you run out of heap memory by repeatingly calling new to allocate memory in a loop without calling delete to free it it. But make a system backup before doing this.

How to remove \xa0 from string in Python?

You can try string.strip()
It worked for me! :)

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

Test if remote TCP port is open from a shell script

check ports using bash

Example

$ ./test_port_bash.sh 192.168.7.7 22

the port 22 is open

Code

HOST=$1
PORT=$2
exec 3> /dev/tcp/${HOST}/${PORT}
if [ $? -eq 0 ];then echo "the port $2 is open";else echo "the port $2 is closed";fi

How to manually include external aar package using new Gradle Android Build System

I found this workaround in the Android issue tracker: https://code.google.com/p/android/issues/detail?id=55863#c21

The trick (not a fix) is to isolating your .aar files into a subproject and adding your libs as artifacts:

configurations.create("default")
artifacts.add("default", file('somelib.jar'))
artifacts.add("default", file('someaar.aar'))

More info: Handling-transitive-dependencies-for-local-artifacts-jars-and-aar

smtp configuration for php mail

PHP's mail() function does not have support for SMTP. You're going to need to use something like the PEAR Mail package.

Here is a sample SMTP mail script:

<?php
require_once("Mail.php");

$from = "Your Name <[email protected]>";
$to = "Their Name <[email protected]>";
$subject = "Subject";
$body = "Lorem ipsum dolor sit amet, consectetur adipiscing elit...";

$host = "mailserver.blahblah.com";
$username = "smtp_username";
$password = "smtp_password";

$headers = array('From' => $from, 'To' => $to, 'Subject' => $subject);

$smtp = Mail::factory('smtp', array ('host' => $host,
                                     'auth' => true,
                                     'username' => $username,
                                     'password' => $password));

$mail = $smtp->send($to, $headers, $body);

if ( PEAR::isError($mail) ) {
    echo("<p>Error sending mail:<br/>" . $mail->getMessage() . "</p>");
} else {
    echo("<p>Message sent.</p>");
}
?>

Best way to remove duplicate entries from a data table

There is a simple way using Linq GroupBy Method.

var duplicateValues = dt.AsEnumerable() 

        .GroupBy(row => row[0]) 

        .Where(group => (group.Count() == 1 || group.Count() > 1)) 

        .Select(g => g.Key); 



foreach (var d in duplicateValues)

        Console.WriteLine(d);

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

HashMap and int as key

Please use HashMap<Integer, myObject> myMap = new HashMap<Integer, myObject>();

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Convert String to int array in java

Using Java 8's stream library, we can make this a one-liner (albeit a long line):

String str = "[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]";
int[] arr = Arrays.stream(str.substring(1, str.length()-1).split(","))
    .map(String::trim).mapToInt(Integer::parseInt).toArray();
System.out.println(Arrays.toString(arr));

substring removes the brackets, split separates the array elements, trim removes any whitespace around the number, parseInt parses each number, and we dump the result in an array. I've included trim to make this the inverse of Arrays.toString(int[]), but this will also parse strings without whitespace, as in the question. If you only needed to parse strings from Arrays.toString, you could omit trim and use split(", ") (note the space).

HTML.ActionLink method

I think what you want is this:

ASP.NET MVC1

Html.ActionLink(article.Title, 
                "Login",  // <-- Controller Name.
                "Item",   // <-- ActionMethod
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string controllerName,
                                string actionName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC2

two arguments have been switched around

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { id = article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This uses the following method ActionLink signature:

public static string ActionLink(this HtmlHelper htmlHelper, 
                                string linkText,
                                string actionName,
                                string controllerName,
                                object values, 
                                object htmlAttributes)

ASP.NET MVC3+

arguments are in the same order as MVC2, however the id value is no longer required:

Html.ActionLink(article.Title, 
                "Item",   // <-- ActionMethod
                "Login",  // <-- Controller Name.
                new { article.ArticleID }, // <-- Route arguments.
                null  // <-- htmlArguments .. which are none. You need this value
                      //     otherwise you call the WRONG method ...
                      //     (refer to comments, below).
                )

This avoids hard-coding any routing logic into the link.

 <a href="/Item/Login/5">Title</a> 

This will give you the following html output, assuming:

  1. article.Title = "Title"
  2. article.ArticleID = 5
  3. you still have the following route defined

. .

routes.MapRoute(
    "Default",     // Route name
    "{controller}/{action}/{id}",                           // URL with parameters
    new { controller = "Home", action = "Index", id = "" }  // Parameter defaults
);

How do you cache an image in Javascript

Nowdays, there is a new technique suggested by google to cache and improve your image rendering process:

  1. Include the JavaScript Lazysizes file: lazysizes.js
  2. Add the file to the html file you want to use in: <script src="lazysizes.min.js" async></script>
  3. Add the lazyload class to your image: <img data-src="images/flower3.png" class="lazyload" alt="">

Bash if statement with multiple conditions throws an error

Please try following

if ([ $dateR -ge 234 ] && [ $dateR -lt 238 ]) || ([ $dateR -ge 834 ] && [ $dateR -lt 838 ]) || ([ $dateR -ge 1434 ] && [ $dateR -lt 1438 ]) || ([ $dateR -ge 2034 ] && [ $dateR -lt 2038 ]) ;
then
    echo "WORKING"
else
    echo "Out of range!"

Which is a better way to check if an array has more than one element?

Use count()

if (count($my_array) > 1) {
// do
}

this page explains it pretty well http://phparraylength.com/

Automatically run %matplotlib inline in IPython Notebook

The setting was disabled in Jupyter 5.X and higher by adding below code

pylab = Unicode('disabled', config=True,
    help=_("""
    DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib.
    """)
)

@observe('pylab')
def _update_pylab(self, change):
    """when --pylab is specified, display a warning and exit"""
    if change['new'] != 'warn':
        backend = ' %s' % change['new']
    else:
        backend = ''
    self.log.error(_("Support for specifying --pylab on the command line has been removed."))
    self.log.error(
        _("Please use `%pylab{0}` or `%matplotlib{0}` in the notebook itself.").format(backend)
    )
    self.exit(1)

And in previous versions it has majorly been a warning. But this not a big issue because Jupyter uses concepts of kernels and you can find kernel for your project by running below command

$ jupyter kernelspec list
Available kernels:
  python3    /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3

This gives me the path to the kernel folder. Now if I open the /Users/tarunlalwani/Documents/Projects/SO/notebookinline/bin/../share/jupyter/kernels/python3/kernel.json file, I see something like below

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
 ],
 "display_name": "Python 3",
 "language": "python"
}

So you can see what command is executed to launch the kernel. So if you run the below command

$ python -m ipykernel_launcher --help
IPython: an enhanced interactive Python shell.

Subcommands
-----------

Subcommands are launched as `ipython-kernel cmd [args]`. For information on
using subcommand 'cmd', do: `ipython-kernel cmd -h`.

install
    Install the IPython kernel

Options
-------

Arguments that take values are actually convenience aliases to full
Configurables, whose aliases are listed on the help line. For more information
on full configurables, see '--help-all'.

....
--pylab=<CaselessStrEnum> (InteractiveShellApp.pylab)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Pre-load matplotlib and numpy for interactive use, selecting a particular
    matplotlib backend and loop integration.
--matplotlib=<CaselessStrEnum> (InteractiveShellApp.matplotlib)
    Default: None
    Choices: ['auto', 'agg', 'gtk', 'gtk3', 'inline', 'ipympl', 'nbagg', 'notebook', 'osx', 'pdf', 'ps', 'qt', 'qt4', 'qt5', 'svg', 'tk', 'widget', 'wx']
    Configure matplotlib for interactive use with the default matplotlib
    backend.
...    
To see all available configurables, use `--help-all`

So now if we update our kernel.json file to

{
 "argv": [
  "python",
  "-m",
  "ipykernel_launcher",
  "-f",
  "{connection_file}",
  "--pylab",
  "inline"
 ],
 "display_name": "Python 3",
 "language": "python"
}

And if I run jupyter notebook the graphs are automatically inline

Auto Inline

Note the below approach also still works, where you create a file on below path

~/.ipython/profile_default/ipython_kernel_config.py

c = get_config()
c.IPKernelApp.matplotlib = 'inline'

But the disadvantage of this approach is that this is a global impact on every environment using python. You can consider that as an advantage also if you want to have a common behaviour across environments with a single change.

So choose which approach you would like to use based on your requirement

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

This error is occur,because the function is not defined. In my case i have called the datepicker function without including the datepicker js file that time I got this error.

How to remove an element from a list by index

Generally, I am using the following method:

>>> myList = [10,20,30,40,50]
>>> rmovIndxNo = 3
>>> del myList[rmovIndxNo]
>>> myList
[10, 20, 30, 50]

How can I push a specific commit to a remote, and not previous commits?

The other answers are lacking on the reordering descriptions.

git push <remotename> <commit SHA>:<remotebranchname>

will push a single commit, but that commit has to be the OLDEST of your local, non-pushed, commits, not to be confused with the top, first, or tip commit, which are all ambiguous descriptions in my opinion. The commit needs to the oldest of your commits, i.e. the furthest from your most recent commit. If it's not the oldest commit then all commits from your oldest, local, non-pushed SHA to the SHA specified will be pushed. To reorder the commits use:

git rebase -i HEAD~xxx

After reordering the commit you can safely push it to the remote repository.

To summarize, I used

git rebase -i HEAD~<number of commits to SHA>
git push origin <post-rebase SHA>:master

to push a single commit to my remote master branch.

References:

  1. http://blog.dennisrobinson.name/push-only-one-commit-with-git/
  2. http://blog.dennisrobinson.name/reorder-commits-with-git/

See also:

  1. git: Duplicate Commits After Local Rebase Followed by Pull
  2. git: Pushing Single Commits, Reordering with rebase, Duplicate Commits

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

Rotating a point about another point (2D)

This is the answer by Nils Pipenbrinck, but implemented in c# fiddle.

https://dotnetfiddle.net/btmjlG

using System;

public class Program
{
    public static void Main()
    {   
        var angle = 180 * Math.PI/180;
        Console.WriteLine(rotate_point(0,0,angle,new Point{X=10, Y=10}).Print());
    }

    static Point rotate_point(double cx, double cy, double angle, Point p)
    {
        double s = Math.Sin(angle);
        double c = Math.Cos(angle);
        // translate point back to origin:
        p.X -= cx;
        p.Y -= cy;
        // rotate point
        double Xnew = p.X * c - p.Y * s;
        double Ynew = p.X * s + p.Y * c;
        // translate point back:
        p.X = Xnew + cx;
        p.Y = Ynew + cy;
        return p;
    }

    class Point
    {
        public double X;
        public double Y;

        public string Print(){
            return $"{X},{Y}";
        }
    }
}

Ps: Apparently I can’t comment, so I’m obligated to post it as an answer ...

How to serve up a JSON response using Go?

You can do something like this in you getJsonResponse function -

jData, err := json.Marshal(Data)
if err != nil {
    // handle error
}
w.Header().Set("Content-Type", "application/json")
w.Write(jData)

How to access global variables

I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.

main.go

var StartTime = time.Now()
func main() {
   otherPackage.StartTime = StartTime
}

otherpackage.go

var StartTime time.Time

Create a custom View by inflating a layout?

Use the LayoutInflater as I shown below.

    public View myView() {
        View v; // Creating an instance for View Object
        LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        v = inflater.inflate(R.layout.myview, null);

        TextView text1 = v.findViewById(R.id.dolphinTitle);
        Button btn1 = v.findViewById(R.id.dolphinMinusButton);
        TextView text2 = v.findViewById(R.id.dolphinValue);
        Button btn2 = v.findViewById(R.id.dolphinPlusButton);

        return v;
    }

Get an OutputStream into a String

This worked nicely

OutputStream output = new OutputStream() {
    private StringBuilder string = new StringBuilder();

    @Override
    public void write(int b) throws IOException {
        this.string.append((char) b );
    }

    //Netbeans IDE automatically overrides this toString()
    public String toString() {
        return this.string.toString();
    }
};

method call =>> marshaller.marshal( (Object) toWrite , (OutputStream) output);

then to print the string or get it just reference the "output" stream itself As an example, to print the string out to console =>> System.out.println(output);

FYI: my method call marshaller.marshal(Object,Outputstream) is for working with XML. It is irrelevant to this topic.

This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls.

And the world lives on another day....

CSS disable text selection

Don't apply these properties to the whole body. Move them to a class and apply that class to the elements you want to disable select:

.disable-select {
  -webkit-user-select: none;  
  -moz-user-select: none;    
  -ms-user-select: none;      
  user-select: none;
}

Foreign Key to multiple tables

The first option in @Nathan Skerl's list is what was implemented in a project I once worked with, where a similar relationship was established between three tables. (One of them referenced two others, one at a time.)

So, the referencing table had two foreign key columns, and also it had a constraint to guarantee that exactly one table (not both, not neither) was referenced by a single row.

Here's how it could look when applied to your tables:

CREATE TABLE dbo.[Group]
(
    ID int NOT NULL CONSTRAINT PK_Group PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.[User]
(
    ID int NOT NULL CONSTRAINT PK_User PRIMARY KEY,
    Name varchar(50) NOT NULL
);

CREATE TABLE dbo.Ticket
(
    ID int NOT NULL CONSTRAINT PK_Ticket PRIMARY KEY,
    OwnerGroup int NULL
      CONSTRAINT FK_Ticket_Group FOREIGN KEY REFERENCES dbo.[Group] (ID),
    OwnerUser int NULL
      CONSTRAINT FK_Ticket_User  FOREIGN KEY REFERENCES dbo.[User]  (ID),
    Subject varchar(50) NULL,
    CONSTRAINT CK_Ticket_GroupUser CHECK (
      CASE WHEN OwnerGroup IS NULL THEN 0 ELSE 1 END +
      CASE WHEN OwnerUser  IS NULL THEN 0 ELSE 1 END = 1
    )
);

As you can see, the Ticket table has two columns, OwnerGroup and OwnerUser, both of which are nullable foreign keys. (The respective columns in the other two tables are made primary keys accordingly.) The CK_Ticket_GroupUser check constraint ensures that only one of the two foreign key columns contains a reference (the other being NULL, that's why both have to be nullable).

(The primary key on Ticket.ID is not necessary for this particular implementation, but it definitely wouldn't harm to have one in a table like this.)

What is Node.js?

I think the advantages are:

  1. Web development in a dynamic language (JavaScript) on a VM that is incredibly fast (V8). It is much faster than Ruby, Python, or Perl.

  2. Ability to handle thousands of concurrent connections with minimal overhead on a single process.

  3. JavaScript is perfect for event loops with first class function objects and closures. People already know how to use it this way having used it in the browser to respond to user initiated events.

  4. A lot of people already know JavaScript, even people who do not claim to be programmers. It is arguably the most popular programming language.

  5. Using JavaScript on a web server as well as the browser reduces the impedance mismatch between the two programming environments which can communicate data structures via JSON that work the same on both sides of the equation. Duplicate form validation code can be shared between server and client, etc.

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

How can I clear an HTML file input with JavaScript?

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.

Regular expression for number with length of 4, 5 or 6

[0-9]{4,6} can be shortened to \d{4,6}

Struct like objects in Java

To address mutability concerns you can declare x and y as final. For example:

class Data {
  public final int x;
  public final int y;
  public Data( int x, int y){
    this.x = x;
    this.y = y;
  }
}

Calling code that attempts to write to these fields will get a compile time error of "field x is declared final; cannot be assigned".

The client code can then have the 'short-hand' convenience you described in your post

public class DataTest {
    public DataTest() {
        Data data1 = new Data(1, 5);
        Data data2 = new Data(2, 4);
        System.out.println(f(data1));
        System.out.println(f(data2));
    }

    public int f(Data d) {
        return (3 * d.x) / d.y;
    }

    public static void main(String[] args) {
        DataTest dataTest = new DataTest();
    }
}

Auto-redirect to another HTML page

<meta http-equiv="refresh" content="5; url=http://example.com/">

Disposing WPF User Controls

My scenario is little different, but the intent is same i would like to know when the parent window hosting my user control is closing/closed as The view(i.e my usercontrol) should invoke the presenters oncloseView to execute some functionality and perform clean up. ( well we are implementing a MVP pattern on a WPF PRISM application).

I just figured that in the Loaded event of the usercontrol, i can hook up my ParentWindowClosing method to the Parent windows Closing event. This way my Usercontrol can be aware when the Parent window is being closed and act accordingly!

Java Set retain order?

There are 2 different things.

  1. Sort the elements in a set. For which we have SortedSet and similar implementations.
  2. Maintain insertion order in a set. For which LinkedHashSet and CopyOnWriteArraySet (thread-safe) can be used.

Convert XLS to CSV on command line

A small expansion on ScottF's groovy VB script: this batch file will loop through the .xlsx files in a directory and dump them into *.csv files:

FOR /f "delims=" %%i IN ('DIR *.xlsx /b') DO ExcelToCSV.vbs "%%i" "%%i.csv"

Note: You may change extension .xlsx to .xls andname of script ExcelToCSV to XlsToCsv

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

Bumped into same warning. If you specified goals and built project using "Run as -> Maven build..." option check and remove pom.xml from Profiles: just below Goals:

How do I print the content of a .txt file in Python?

Just do this:

>>> with open("path/to/file") as f: # The with keyword automatically closes the file when you are done
...     print f.read()

This will print the file in the terminal.

batch file to copy files to another location?

@echo off cls echo press any key to continue backup ! pause xcopy c:\users\file*.* e:\backup*.* /s /e echo backup complete pause


file = name of file your wanting to copy

backup = where u want the file to be moved to

Hope this helps

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

Rails DB Migration - How To Drop a Table?

the best way you can do is

rails g migration Drop_table_Users

then do the following

rake db:migrate

How to make JQuery-AJAX request synchronous

try this

the solution is, work with callbacks like this

$(function() {

    var jForm = $('form[name=form]');
    var jPWField = $('#employee_password');

    function getCheckedState() {
        return jForm.data('checked_state');
    };

    function setChecked(s) {
        jForm.data('checked_state', s);
    };


    jPWField.change(function() {
        //reset checked thing
        setChecked(null);
    }).trigger('change');

    jForm.submit(function(){
        switch(getCheckedState()) {
            case 'valid':
                return true;
            case 'invalid':
                //invalid, don submit
                return false;
            default:
                //make your check
                var password = $.trim(jPWField.val());

                $.ajax({
                    type: "POST",
                    async: "false",
                    url: "checkpass.php",
                    data: {
                        "password": $.trim(jPWField.val);
                    }
                    success: function(html) {
                        var arr=$.parseJSON(html);
                        setChecked(arr == "Successful" ? 'valid': 'invalid');
                        //submit again
                        jForm.submit();
                    }
                    });
                return false;
        }

    });
 });

json_decode returns NULL after webservice call

In Notepad++, select Encoding (from the top menu) and then ensure that "Encode in UTF-8" is selected.

This will display any characters that shouldn't be in your json that would cause json_decode to fail.

What is the difference between <section> and <div>?

<div> Vs <Section>

Round 1

<div>: The HTML element (or HTML Document Division Element) is the generic container for flow content, which does not inherently represent anything. It can be used to group elements for styling purposes (using the class or id attributes), or because they share attribute values, such as lang. It should be used only when no other semantic element (such as <article> or <nav>) is appropriate.

<section>: The HTML Section element (<section>) represents a generic section of a document, i.e., a thematic grouping of content, typically with a heading.


Round 2

<div>: Browser Support enter image description here

<section>: Browser Support

The numbers in the table specifies the first browser version that fully supports the element. enter image description here

In that vein, a div is relevant only from a pure CSS or DOM perspective, whereas a section is relevant also for semantics and, in a near future, for indexing by search engines.

How to pass anonymous types as parameters?

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

Double precision floating values in Python?

Here is my solution. I first create random numbers with random.uniform, format them in to string with double precision and then convert them back to float. You can adjust the precision by changing '.2f' to '.3f' etc..

import random
from decimal import Decimal

GndSpeedHigh = float(format(Decimal(random.uniform(5, 25)), '.2f'))
GndSpeedLow = float(format(Decimal(random.uniform(2, GndSpeedHigh)), '.2f'))
GndSpeedMean = float(Decimal(format(GndSpeedHigh + GndSpeedLow) / 2, '.2f')))
print(GndSpeedMean)

How to convert from int to string in objective c: example code

If you just need an int to a string as you suggest, I've found the easiest way is to do as below:

[NSString stringWithFormat:@"%d",numberYouAreTryingToConvert]

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

In case you recently updated to Xcode 11 beta 3 and try to run an older SwiftUI project, you have to make some changes in the SceneDelegate where the views are loaded, otherwise the screens will remain black on devices running iOS 13 beta 3 which of course includes all simulators.

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
    // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
    // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

    // Use a UIHostingController as window root view controller
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView())
        self.window = window
        window.makeKeyAndVisible()
    }
}

The behavior not strictly limited to the simulators, but since most people will run beta software exclusively on simulators it will only occur in this context. It baffled me for quite a while, so hope it helps.

How to set a timeout on a http.request() in Node?

Just to clarify the answer above:

Now it is possible to use timeout option and the corresponding request event:

// set the desired timeout in options
const options = {
    //...
    timeout: 3000,
};

// create a request
const request = http.request(options, response => {
    // your callback here
});

// use its "timeout" event to abort the request
request.on('timeout', () => {
    request.abort();
});

Setting a width and height on an A tag

All these suggestions work unless you put the anchors inside an UL list.

<ul>
    <li>
        <a>click me</a>>
    </li>
</ul>

Then any cascade style sheet rules are overridden in the Chrome browser. The width becomes auto. Then you must use inline CSS rules directly on the anchor itself.

CheckBox in RecyclerView keeps on checking different items

this is due to again and again creating view ,best option is clear cache before setting adapter

recyclerview.setItemViewCacheSize(your array.size());

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

Using /proc/tty/drivers only indicates which tty drivers are loaded. If you're looking for a list of the serial ports check out /dev/serial, it will have two subdirectories: by-id and by-path.

EX:

# find . -type l
./by-path/usb-0:1.1:1.0-port0
./by-id/usb-Prolific_Technology_Inc._USB-Serial_Controller-if00-port0

Thanks to this post: https://superuser.com/questions/131044/how-do-i-know-which-dev-ttys-is-my-serial-port

Ignore .pyc files in git repository

You should add a line with:

*.pyc 

to the .gitignore file in the root folder of your git repository tree right after repository initialization.

As ralphtheninja said, if you forgot to to do it beforehand, if you just add the line to the .gitignore file, all previously committed .pyc files will still be tracked, so you'll need to remove them from the repository.

If you are on a Linux system (or "parents&sons" like a MacOSX), you can quickly do it with just this one line command that you need to execute from the root of the repository:

find . -name "*.pyc" -exec git rm -f "{}" \;

This just means:

starting from the directory i'm currently in, find all files whose name ends with extension .pyc, and pass file name to the command git rm -f

After *.pyc files deletion from git as tracked files, commit this change to the repository, and then you can finally add the *.pyc line to the .gitignore file.

(adapted from http://yuji.wordpress.com/2010/10/29/git-remove-all-pyc/)

how to delete the content of text file without deleting itself

Just write:

FileOutputStream writer = new FileOutputStream("file.txt");

case-insensitive matching in xpath?

You mentioned that PHP solutions were acceptable, and PHP does offer a way to accomplish this even though it only supports XPath v1.0. You can extend the XPath support to allow PHP function calls.

$xpathObj = new DOMXPath($docObj);
$xpathObj->registerNamespace('php','http://php.net/xpath'); // (required)
$xpathObj->registerPhpFunctions("strtolower"); // (leave empty to allow *any* PHP function)
$xpathObj->query('//CD[php:functionString("strtolower",@title) = "empire burlesque"]');

See the PHP registerPhpFunctions documentation for more examples. It basically demonstrates that "php:function" is for boolean evaluation and "php:functionString" is for string evaluation.

Find a value anywhere in a database

Database client tools (like DBeaver or phpMyAdmin) often support means of fulltext search through entire database.

Connection refused on docker container

In Docker Quickstart Terminal run following command: $ docker-machine ip 192.168.99.100

Is there a function to copy an array in C/C++?

As others have mentioned, in C you would use memcpy. Note however that this does a raw memory copy, so if your data structures have pointer to themselves or to each other, the pointers in the copy will still point to the original objects.

In C++ you can also use memcpy if your array members are POD (that is, essentially types which you could also have used unchanged in C), but in general, memcpy will not be allowed. As others mentioned, the function to use is std::copy.

Having said that, in C++ you rarely should use raw arrays. Instead you should either use one of the standard containers (std::vector is the closest to a built-in array, and also I think the closest to Java arrays — closer than plain C++ arrays, indeed —, but std::deque or std::list may be more appropriate in some cases) or, if you use C++11, std::array which is very close to built-in arrays, but with value semantics like other C++ types. All the types I mentioned here can be copied by assignment or copy construction. Moreover, you can "cross-copy" from opne to another (and even from a built-in array) using iterator syntax.

This gives an overview of the possibilities (I assume all relevant headers have been included):

int main()
{
  // This works in C and C++
  int a[] = { 1, 2, 3, 4 };
  int b[4];
  memcpy(b, a, 4*sizeof(int)); // int is a POD

  // This is the preferred method to copy raw arrays in C++ and works with all types that can be copied:
  std::copy(a, a+4, b);

  // In C++11, you can also use this:
  std::copy(std::begin(a), std::end(a), std::begin(b));

  // use of vectors
  std::vector<int> va(a, a+4); // copies the content of a into the vector
  std::vector<int> vb = va;    // vb is a copy of va

  // this initialization is only valid in C++11:
  std::vector<int> vc { 5, 6, 7, 8 }; // note: no equal sign!

  // assign vc to vb (valid in all standardized versions of C++)
  vb = vc;

  //alternative assignment, works also if both container types are different
  vb.assign(vc.begin(), vc.end());

  std::vector<int> vd; // an *empty* vector

  // you also can use std::copy with vectors
  // Since vd is empty, we need a `back_inserter`, to create new elements:
  std::copy(va.begin(), va.end(), std::back_inserter(vd));

  // copy from array a to vector vd:
  // now vd already contains four elements, so this new copy doesn't need to
  // create elements, we just overwrite the existing ones.
  std::copy(a, a+4, vd.begin());

  // C++11 only: Define a `std::array`:
  std::array<int, 4> sa = { 9, 10, 11, 12 };

  // create a copy:
  std::array<int, 4> sb = sa;

  // assign the array:
  sb = sa;
}

Adding Buttons To Google Sheets and Set value to Cells on clicking

It is possible to insert an image in a Google Spreadsheet using Google Apps Script. However, the image should have been hosted publicly over internet. At present, it is not possible to insert private images from Google Drive.

You can use following code to insert an image through script.

  function insertImageOnSpreadsheet() {
  var SPREADSHEET_URL = 'INSERT_SPREADSHEET_URL_HERE';
  // Name of the specific sheet in the spreadsheet.
  var SHEET_NAME = 'INSERT_SHEET_NAME_HERE';

  var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
  var sheet = ss.getSheetByName(SHEET_NAME);

  var response = UrlFetchApp.fetch(
      'https://developers.google.com/adwords/scripts/images/reports.png');
  var binaryData = response.getContent();

  // Insert the image in cell A1.
  var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
  sheet.insertImage(blob, 1, 1);
}

Above example has been copied from this link. Check noogui's reply for details.

In case you need to insert image from Google Drive, please check this link for current updates.

the getSource() and getActionCommand()

I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").

I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:

public class SeleccionListener implements ActionListener, FocusListener {}

So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:

public void actionPerformed(ActionEvent event) {
    if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
        System.out.println("Aceptar pressed");
    }

In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).

public void focusGained(FocusEvent focusEvent) {
    if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
        System.out.println("Data radio button");
    }

In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)

C# Pass Lambda Expression as Method Parameter

Lambda expressions have a type of Action<parameters> (in case they don't return a value) or Func<parameters,return> (in case they have a return value). In your case you have two input parameters, and you need to return a value, so you should use:

Func<FullTimeJob, Student, FullTimeJob>

Action Image MVC3 Razor

To add to all the Awesome work started by Luke I am posting one more that takes a css class value and treats class and alt as optional parameters (valid under ASP.NET 3.5+). This will allow more functionality but reduct the number of overloaded methods needed.

// Extension method
    public static MvcHtmlString ActionImage(this HtmlHelper html, string action,
        string controllerName, object routeValues, string imagePath, string alt = null, string cssClass = null)
    {
        var url = new UrlHelper(html.ViewContext.RequestContext);

        // build the <img> tag
        var imgBuilder = new TagBuilder("img");
        imgBuilder.MergeAttribute("src", url.Content(imagePath));
        if(alt != null)
            imgBuilder.MergeAttribute("alt", alt);
        if (cssClass != null)
            imgBuilder.MergeAttribute("class", cssClass);

        string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

        // build the <a> tag
        var anchorBuilder = new TagBuilder("a");

        anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
        anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
        string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(anchorHtml);
    }

How to implement DrawerArrowToggle from Android appcompat v7 21 library

I created a small application which had similar functionality

MainActivity

public class MyActivity extends ActionBarActivity {

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

        DrawerLayout drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
        android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.toolbar);
        ActionBarDrawerToggle actionBarDrawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                toolbar,
                R.string.open,
                R.string.close
        )

        {
            public void onDrawerClosed(View view)
            {
                super.onDrawerClosed(view);
                invalidateOptionsMenu();
                syncState();
            }

            public void onDrawerOpened(View drawerView)
            {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu();
                syncState();
            }
        };
        drawerLayout.setDrawerListener(actionBarDrawerToggle);

        //Set the custom toolbar
        if (toolbar != null){
            setSupportActionBar(toolbar);
        }

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        actionBarDrawerToggle.syncState();
    }
}

My XML of that Activity

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MyActivity"
    android:id="@+id/drawer"
    >

    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        <include layout="@layout/toolbar_custom"/>
    </FrameLayout>
    <!-- The navigation drawer -->
    <ListView
        android:layout_marginTop="?attr/actionBarSize"
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#457C50"/>


</android.support.v4.widget.DrawerLayout>

My Custom Toolbar XML

<?xml version="1.0" encoding="utf-8"?>

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/toolbar"
    android:background="?attr/colorPrimaryDark">
    <TextView android:text="U titel"
        android:textAppearance="@android:style/TextAppearance.Theme"
        android:textColor="@android:color/white"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />
</android.support.v7.widget.Toolbar>

My Theme Style

<resources>
    <style name="AppTheme" parent="Base.Theme.AppCompat"/>

    <style name="AppTheme.Base" parent="Theme.AppCompat">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDarker</item>
        <item name="android:windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>

    <style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
        <item name="spinBars">true</item>
        <item name="color">@android:color/white</item>
    </style>

    <color name="primary">#457C50</color>
    <color name="primaryDarker">#580C0C</color>
</resources>

My Styles in values-v21

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:windowContentTransitions">true</item>
        <item name="android:windowAllowEnterTransitionOverlap">true</item>
        <item name="android:windowAllowReturnTransitionOverlap">true</item>
        <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
        <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
    </style>
</resources>

How to add a file to the last commit in git?

If you didn't push the update in remote then the simple solution is remove last local commit using following command: git reset HEAD^. Then add all files and commit again.

XAMPP installation on Win 8.1 with UAC Warning

You can solve the issue by

  1. Ignore the warning and Install XAMPP directly under C:/ folder. It will solve your issue
  2. You can deactivate the UAC which i don't recommend. It's makes your PC less secure.

Declare global variables in Visual Studio 2010 and VB.NET

The various answers in this blog seem to be defined by SE's who promote strict adherence to the usual rules of object-oriented programming (use a Public Class with public shared (aka static), and fully-qualified class references, or SE's who promote using the backward-compatibility feature (Module) for which the compiler obviously needs to do the same thing to make it work.

As a SE with 30+ years of experience, I would propose the following guidelines:

  1. If you are writing all new code (not attempting to convert a legacy app) that you avoid using these forms altogether except in the rare instance that you really DO need to have a static variable because they can cause terrible consequences (and really hard-to-find bugs). (Multithread and multiprocessing code requires semaphores around static variables...)

  2. If you are modifying a small application that already has a few global variables, then formulate them so they are not obscured by Modules, that is, use the standard rules of object-oriented programming to re-create them as public static and access them by full qualification so others can figure out what is going on.

  3. If you have a huge legacy application with dozens or hundreds of global variables, by all means, use Modules to define them. There is no reason to waste time when getting the application working, because you are probably already behind the 8-ball in time spent on Properties, etc.

Reversing a linked list in Java, recursively

void reverse(node1,node2){
if(node1.next!=null)
      reverse(node1.next,node1);
   node1.next=node2;
}
call this method as reverse(start,null);

Expand a random range from 1–5 to 1–7

function rand7() {
    while (true) { //lowest base 5 random number > 7 reduces memory
        int num = (rand5()-1)*5 + rand5()-1;
    if (num < 21)  // improves performance
        return 1 + num%7;
    }
}

Python code:

from random import randint
def rand7():
    while(True):
        num = (randint(1, 5)-1)*5 + randint(1, 5)-1
        if num < 21:
                return 1 + num%7

Test distribution for 100000 runs:

>>> rnums = []
>>> for _ in range(100000):
    rnums.append(rand7())
>>> {n:rnums.count(n) for n in set(rnums)}
{1: 15648, 2: 15741, 3: 15681, 4: 15847, 5: 15642, 6: 15806, 7: 15635}

Correct way to use Modernizr to detect IE?

I agree we should test for capabilities, but it's hard to find a simple answer to "what capabilities are supported by 'modern browsers' but not 'old browsers'?"

So I fired up a bunch of browsers and inspected Modernizer directly. I added a few capabilities I definitely require, and then I added "inputtypes.color" because that seems to cover all the major browsers I care about: Chrome, Firefox, Opera, Edge...and NOT IE11. Now I can gently suggest the user would be better off with Chrome/Opera/Firefox/Edge.

This is what I use - you can edit the list of things to test for your particular case. Returns false if any of the capabilities are missing.

/**
 * Check browser capabilities.
 */
public CheckBrowser(): boolean
{
    let tests = ["csstransforms3d", "canvas", "flexbox", "webgl", "inputtypes.color"];

    // Lets see what each browser can do and compare...
    //console.log("Modernizr", Modernizr);

    for (let i = 0; i < tests.length; i++)
    {
        // if you don't test for nested properties then you can just use
        // "if (!Modernizr[tests[i]])" instead
        if (!ObjectUtils.GetProperty(Modernizr, tests[i]))
        {
            console.error("Browser Capability missing: " + tests[i]);
            return false;
        }
    }

    return true;
}

And here is that GetProperty method which is needed for "inputtypes.color".

/**
 * Get a property value from the target object specified by name.
 * 
 * The property name may be a nested property, e.g. "Contact.Address.Code".
 * 
 * Returns undefined if a property is undefined (an existing property could be null).
 * If the property exists and has the value undefined then good luck with that.
 */
public static GetProperty(target: any, propertyName: string): any
{
    if (!(target && propertyName))
    {
        return undefined;
    }

    var o = target;

    propertyName = propertyName.replace(/\[(\w+)\]/g, ".$1");
    propertyName = propertyName.replace(/^\./, "");

    var a = propertyName.split(".");

    while (a.length)
    {
        var n = a.shift();

        if (n in o)
        {
            o = o[n];

            if (o == null)
            {
                return undefined;
            }
        }
        else
        {
            return undefined;
        }
    }

    return o;
}

How to limit file upload type file size in PHP?

If you are looking for a hard limit across all uploads on the site, you can limit these in php.ini by setting the following:

`upload_max_filesize = 2M` `post_max_size = 2M`

that will set the maximum upload limit to 2 MB

How to use AND in IF Statement

Brief syntax lesson

Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)

.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:

With ActiveSheet
  :
  .Cells(Row,Column)
  :
End With

If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:

With ActiveSheet
  :
  .Range.  
  :
End With

Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:

With Sheets("xxxx")
  :
  .Range.  
  :
End With

because my code only works on sheet xxxx.

Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.

Cells(Row,Column) like "*Miami*" will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.

Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:

Lcase(Cells(Row,Column).Value) = "miami"  

My suggestions

Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.

Use

If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
  Cells(i, "C").Value = "BA"

if you want to accept, for example, "South Miami" and "Miami, North".

Use

If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
  Cells(i, "C").Value = "BA"

if you want to accept, exactly, "Miami" and "Florida".

Use

If Lcase(Cells(i, "A").Value) = "miami" And _
   Lcase(Cells(i, "D").Value) = "florida" Then
  Cells(i, "C").Value = "BA"

if you don't care about case.

Get file from project folder java

These lines worked in my case,

ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());

provided test.txt file inside src

Get User's Current Location / Coordinates

here is a copy-paste example that worked for me.

http://swiftdeveloperblog.com/code-examples/determine-users-current-location-example-in-swift/

import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager:CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

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

        determineMyCurrentLocation()
    }


    func determineMyCurrentLocation() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation

        // Call stopUpdatingLocation() to stop listening for location updates,
        // other wise this function will be called every time when user location changes.

       // manager.stopUpdatingLocation()

        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Error \(error)")
    }
}

What is sys.maxint in Python 3?

If you are looking for a number that is bigger than all others:

Method 1:

float('inf')

Method 2:

import sys
max = sys.maxsize

If you are looking for a number that is smaller than all others:

Method 1:

float('-inf')

Method 2:

import sys
min = -sys.maxsize - 1

Method 1 works in both Python2 and Python3. Method 2 works in Python3. I have not tried Method 2 in Python2.

top align in html table?

Some CSS :

table td, table td * {
    vertical-align: top;
}

Convert UTC date time to local date time

I believe this is the best solution:

  let date = new Date(objDate);
  date.setMinutes(date.getTimezoneOffset());

This will update your date by the offset appropriately since it is presented in minutes.

Tracking the script execution time in PHP

Shorter version of talal7860's answer

<?php
// At start of script
$time_start = microtime(true); 

// Anywhere else in the script
echo 'Total execution time in seconds: ' . (microtime(true) - $time_start);

As pointed out, this is 'wallclock time' not 'cpu time'

Scrolling an iframe with JavaScript?

Based on Chris's comment

CSS
.amazon-rating {
  width: 55px;
  height: 12px;
  overflow: hidden;
}

.rating-stars {
  left: -18px;
  top: -102px;
  position: relative;
}
HAML
.amazon-rating
  %iframe.rating-stars{src: $item->ratingURL, seamless: 'seamless', frameborder: 0, scrolling: 'no'}

When should I use the new keyword in C++?

Which method should I use?

This is almost never determined by your typing preferences but by the context. If you need to keep the object across a few stacks or if it's too heavy for the stack you allocate it on the free store. Also, since you are allocating an object, you are also responsible for releasing the memory. Lookup the delete operator.

To ease the burden of using free-store management people have invented stuff like auto_ptr and unique_ptr. I strongly recommend you take a look at these. They might even be of help to your typing issues ;-)

Display special characters when using print statement

Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r: r"Hello\tWorld\nHello World".

>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World

Also, \s is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

Removing padding gutter from grid columns in Bootstrap 4

You can use the mixin make-col-ready and set the gutter width to zero:

@include make-col-ready(0);

JQuery Event for user pressing enter in a textbox?

   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

Swift GET request with parameters

When building a GET request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also use URLComponents.

var url = URLComponents(string: "https://www.google.com/search/")!

url.queryItems = [
    URLQueryItem(name: "q", value: "War & Peace")
]

The only trick is that most web services need + character percent escaped (because they'll interpret that as a space character as dictated by the application/x-www-form-urlencoded specification). But URLComponents will not percent escape it. Apple contends that + is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning in application/x-www-form-urlencoded requests and really should not be passed unescaped.

Apple acknowledges that we have to percent escaping the + characters, but advises that we do it manually:

var url = URLComponents(string: "https://www.wolframalpha.com/input/")!

url.queryItems = [
    URLQueryItem(name: "i", value: "1+2")
]

url.percentEncodedQuery = url.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")

This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a + character and you have a server that interprets them as spaces.

So, combining that with your sendRequest routine, you end up with something like:

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
    var components = URLComponents(string: url)!
    components.queryItems = parameters.map { (key, value) in 
        URLQueryItem(name: key, value: value) 
    }
    components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
    let request = URLRequest(url: components.url!)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data,                            // is there data
            let response = response as? HTTPURLResponse,  // is there HTTP response
            (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX
            error == nil else {                           // was there no error, otherwise ...
                completion(nil, error)
                return
        }

        let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
        completion(responseObject, nil)
    }
    task.resume()
}

And you'd call it like:

sendRequest("someurl", parameters: ["foo": "bar"]) { responseObject, error in
    guard let responseObject = responseObject, error == nil else {
        print(error ?? "Unknown error")
        return
    }

    // use `responseObject` here
}

Personally, I'd use JSONDecoder nowadays and return a custom struct rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.


See previous revision of this answer for Swift 2 and manual percent escaping renditions.

Append to the end of a Char array in C++

If you are not allowed to use C++'s string class (which is terrible teaching C++ imho), a raw, safe array version would look something like this.

#include <cstring>
#include <iostream>

int main()
{
    char array1[] ="The dog jumps ";
    char array2[] = "over the log";
    char * newArray = new char[std::strlen(array1)+std::strlen(array2)+1];
    std::strcpy(newArray,array1);
    std::strcat(newArray,array2);
    std::cout << newArray << std::endl;
    delete [] newArray;
    return 0;
}

This assures you have enough space in the array you're doing the concatenation to, without assuming some predefined MAX_SIZE. The only requirement is that your strings are null-terminated, which is usually the case unless you're doing some weird fixed-size string hacking.

Edit, a safe version with the "enough buffer space" assumption:

#include <cstring>
#include <iostream>

int main()
{
    const unsigned BUFFER_SIZE = 50;
    char array1[BUFFER_SIZE];
    std::strncpy(array1, "The dog jumps ", BUFFER_SIZE-1); //-1 for null-termination
    char array2[] = "over the log";
    std::strncat(array1,array2,BUFFER_SIZE-strlen(array1)-1); //-1 for null-termination
    std::cout << array1 << std::endl;
    return 0;
}

Force an Android activity to always use landscape mode

Press CTRL+F11 to rotate the screen.

how to convert rgb color to int in java

Color has a getRGB() method that returns the color as an int.

Change route params without reloading in Angular 2

Use attribute queryParamsHandling: 'merge' while changing the url.

this.router.navigate([], {
        queryParams: this.queryParams,
        queryParamsHandling: 'merge',
        replaceUrl: true,
});

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

Change span text?

document.getElementById("serverTime").innerHTML = ...;

How to restrict SSH users to a predefined set of commands after login?

You can also restrict keys to permissible commands (in the authorized_keys file).

I.e. the user would not log in via ssh and then have a restricted set of commands but rather would only be allowed to execute those commands via ssh (e.g. "ssh somehost bin/showlogfile")

How to include !important in jquery

If you really need to override css that has !important rules in it, for instance, in a case I ran into recently, overriding a wordpress theme required !important scss rules to break the theme, but since I was transpiling my code with webpack and (I assume this is why --)my css came along in the chain after the transpiled javascript, you can add a separate class rule in your stylesheet that overrides the first !important rule in the cascade, and toggle the heavier-weighted class rather than adjusting css dynamically. Just a thought.

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

Pylint, PyChecker or PyFlakes?

Well, I am a bit curious, so I just tested the three myself right after asking the question ;-)

Ok, this is not a very serious review, but here is what I can say:

I tried the tools with the default settings (it's important because you can pretty much choose your check rules) on the following script:

#!/usr/local/bin/python
# by Daniel Rosengren modified by e-satis

import sys, time
stdout = sys.stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

class Iterator(object) :

    def __init__(self):

        print 'Rendering...'
        for y in xrange(-39, 39):
            stdout.write('\n')
            for x in xrange(-39, 39):
                if self.mandelbrot(x/40.0, y/40.0) :
                    stdout.write(' ')
                else:
                    stdout.write('*')


    def mandelbrot(self, x, y):
        cr = y - 0.5
        ci = x
        zi = 0.0
        zr = 0.0

        for i in xrange(MAX_ITERATIONS) :
            temp = zr * zi
            zr2 = zr * zr
            zi2 = zi * zi
            zr = zr2 - zi2 + cr
            zi = temp + temp + ci

            if zi2 + zr2 > BAILOUT:
                return i

        return 0

t = time.time()
Iterator()
print '\nPython Elapsed %.02f' % (time.time() - t)

As a result:

  • PyChecker is troublesome because it compiles the module to analyze it. If you don't want your code to run (e.g, it performs a SQL query), that's bad.
  • PyFlakes is supposed to be light. Indeed, it decided that the code was perfect. I am looking for something quite severe so I don't think I'll go for it.
  • PyLint has been very talkative and rated the code 3/10 (OMG, I'm a dirty coder !).

Strong points of PyLint:

  • Very descriptive and accurate report.
  • Detect some code smells. Here it told me to drop my class to write something with functions because the OO approach was useless in this specific case. Something I knew, but never expected a computer to tell me :-p
  • The fully corrected code run faster (no class, no reference binding...).
  • Made by a French team. OK, it's not a plus for everybody, but I like it ;-)

Cons of Pylint:

  • Some rules are really strict. I know that you can change it and that the default is to match PEP8, but is it such a crime to write 'for x in seq'? Apparently yes because you can't write a variable name with less than 3 letters. I will change that.
  • Very very talkative. Be ready to use your eyes.

Corrected script (with lazy doc strings and variable names):

#!/usr/local/bin/python
# by Daniel Rosengren, modified by e-satis
"""
Module doctring
"""


import time
from sys import stdout

BAILOUT = 16
MAX_ITERATIONS = 1000

def mandelbrot(dim_1, dim_2):
    """
    function doc string
    """
    cr1 = dim_1 - 0.5
    ci1 = dim_2
    zi1 = 0.0
    zr1 = 0.0

    for i in xrange(MAX_ITERATIONS) :
        temp = zr1 * zi1
        zr2 = zr1 * zr1
        zi2 = zi1 * zi1
        zr1 = zr2 - zi2 + cr1
        zi1 = temp + temp + ci1

        if zi2 + zr2 > BAILOUT:
            return i

    return 0

def execute() :
    """
    func doc string
    """
    print 'Rendering...'
    for dim_1 in xrange(-39, 39):
        stdout.write('\n')
        for dim_2 in xrange(-39, 39):
            if mandelbrot(dim_1/40.0, dim_2/40.0) :
                stdout.write(' ')
            else:
                stdout.write('*')


START_TIME = time.time()
execute()
print '\nPython Elapsed %.02f' % (time.time() - START_TIME)

Thanks to Rudiger Wolf, I discovered pep8 that does exactly what its name suggests: matching PEP8. It has found several syntax no-nos that Pylint did not. But Pylint found stuff that was not specifically linked to PEP8 but interesting. Both tools are interesting and complementary.

Eventually I will use both since there are really easy to install (via packages or setuptools) and the output text is so easy to chain.

To give you a little idea of their output:

pep8:

./python_mandelbrot.py:4:11: E401 multiple imports on one line
./python_mandelbrot.py:10:1: E302 expected 2 blank lines, found 1
./python_mandelbrot.py:10:23: E203 whitespace before ':'
./python_mandelbrot.py:15:80: E501 line too long (108 characters)
./python_mandelbrot.py:23:1: W291 trailing whitespace
./python_mandelbrot.py:41:5: E301 expected 1 blank line, found 3

Pylint:

************* Module python_mandelbrot
C: 15: Line too long (108/80)
C: 61: Line too long (85/80)
C:  1: Missing docstring
C:  5: Invalid name "stdout" (should match (([A-Z_][A-Z0-9_]*)|(__.*__))$)
C: 10:Iterator: Missing docstring
C: 15:Iterator.__init__: Invalid name "y" (should match [a-z_][a-z0-9_]{2,30}$)
C: 17:Iterator.__init__: Invalid name "x" (should match [a-z_][a-z0-9_]{2,30}$)

[...] and a very long report with useful stats like :

Duplication
-----------

+-------------------------+------+---------+-----------+
|                         |now   |previous |difference |
+=========================+======+=========+===========+
|nb duplicated lines      |0     |0        |=          |
+-------------------------+------+---------+-----------+
|percent duplicated lines |0.000 |0.000    |=          |
+-------------------------+------+---------+-----------+

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Getting the Username from the HKEY_USERS values

Done it, by a bit of creative programming,

  1. Enum the Keys in HKEY_USERS for those funny number keys...

  2. Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

and you will find the same numbers.... Now in those keys look at the String value: ProfileImagePath = "SomeValue" where the values are either:

"%systemroot%\system32\config\systemprofile"... not interested in this one... as its not a directory path...

%SystemDrive%\Documents and Settings\LocalService - "Local Services" %SystemDrive%\Documents and Settings\NetworkService "NETWORK SERVICE"

or

%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the "USERNAME" values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly...

matplotlib error - no module named tkinter

For windows users, re-run the installer. Select Modify. Check the box for tcl/tk and IDLE. The description for this says "Installs tkinter"

Video 100% width and height

We tried with the below code & it works on Samsung TV, Chrome, IE11, Safari...

<!DOCTYPE html>
<html>
<head>
    <title>Video</title>
    <meta charset="utf-8" />
    <style type="text/css" >

        html,body {
          height: 100%;
          text-align: center;
          margin: 0;
          padding:0;
        }

        video {
            width: 100vw; /*100% of horizontal viewport*/
            height:100vh; /*100% of vertical viewport*/
        }

    </style>
</head>
<body>
        <video preload="auto" class="videot" id="videot" preload>
            <source src="BESTANDEN/video/tible.mp4" type="video/mp4" >
            <object data="BESTANDEN/video/tible.mp4" height="1080">
                <param name="wmode" value="transparent">
                <param name="autoplay" value="false" >
                <param name="loop" value="false" >
            </object>
        </video>
</body>
</html>

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Components should start with capital letters. Also remember to change the first letter in the line to export!

How to Empty Caches and Clean All Targets Xcode 4 and later

I have been pulling out hair from my head because I thought that I had the same problem. When building the app I didn't get the same result on my iPhone as on the simulator.

The problem was that I had somehow made a localized version of the MainStoryboard.storyboard file. So when I ran the app on my phone it showed the danish version... and the simulator showed the english version.

Yeah I'm new! :)

Assign width to half available screen width declaratively

give width as 0dp to make sure its size is exactly as per its weight this will make sure that even if content of child views get bigger, they'll still be limited to exactly half(according to is weight)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:weightSum="1"
     >

    <Button
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="click me"
    android:layout_weight="0.5"/>


    <TextView
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="Hello World"
    android:layout_weight="0.5"/>
  </LinearLayout>

Python Requests - No connection adapters

You need to include the protocol scheme:

'http://192.168.1.61:8080/api/call'

Without the http:// part, requests has no idea how to connect to the remote server.

Note that the protocol scheme must be all lowercase; if your URL starts with HTTP:// for example, it won’t find the http:// connection adapter either.

Get current controller in view

You are still in the context of your CategoryController even though you're loading a PartialView from your Views/News folder.

Height of an HTML select box (dropdown)

Confirmed.

The part that drops down is set to either:

  1. The height needed to show all entries, or
  2. The height needed to show x entries (with scrollbars to see remaining), where x is
    • 20 in Firefox & Chrome
    • 30 in IE 6, 7, 8
    • 16 for Opera 10
    • 14 for Opera 11
    • 22 for Safari 4
    • 18 for Safari 5
    • 11 in IE 5.0, 5.5
  3. In IE/Edge, if there are no options, a stupidly high list of 11 blanks entries.

For (3) above you can see the results in this JSFiddle

referenced before assignment error in python

My Scenario

def example():
    cl = [0, 1]
    def inner():
        #cl = [1, 2] # access this way will throw `reference before assignment`
        cl[0] = 1 
        cl[1] = 2   # these won't

    inner()

Comparing two arrays & get the values which are not common

Look at Compare-Object

Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }

Or if you would like to know where the object belongs to, then look at SideIndicator:

$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1

Changing java platform on which netbeans runs

In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc . Thanks all.

How many characters can a Java String have?

Have you considered using BigDecimal instead of String to hold your numbers?

Calling dynamic function with dynamic number of parameters

Here's what you need:

function mainfunc (){
    window[Array.prototype.shift.call(arguments)].apply(null, arguments);
}

The first argument is used as the function name and all of the remaining ones are used as arguments to the called function...

We're able to use the shift method to return and then delete the first value from the arguments array. Note that we've called it from the Array prototype since, strictly speaking, 'arguments' is not a real array and so doesn't inherit the shift method like a regular array would.


You can also call the shift method like this:

[].shift.call(arguments);

Use PHP to create, edit and delete crontab jobs?

Check a cronjob

function cronjob_exists($command){

    $cronjob_exists=false;

    exec('crontab -l', $crontab);


    if(isset($crontab)&&is_array($crontab)){

        $crontab = array_flip($crontab);

        if(isset($crontab[$command])){

            $cronjob_exists=true;

        }

    }
    return $cronjob_exists;
}

Append a cronjob

function append_cronjob($command){

    if(is_string($command)&&!empty($command)&&cronjob_exists($command)===FALSE){

        //add job to crontab
        exec('echo -e "`crontab -l`\n'.$command.'" | crontab -', $output);


    }

    return $output;
}

Remove a crontab

exec('crontab -r', $crontab);

Example

exec('crontab -r', $crontab);

append_cronjob('* * * * * curl -s http://localhost/cron/test1.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test2.php');

append_cronjob('* * * * * curl -s http://localhost/cron/test3.php');

How can I check if my python object is a number?

That's not really how python works. Just use it like you would a number, and if someone passes you something that's not a number, fail. It's the programmer's responsibility to pass in the correct types.

URL encoding the space character: + or %20?

From Wikipedia (emphasis and link added):

When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.

So, the real percent encoding uses %20 while form data in URLs is in a modified form that uses +. So you're most likely to only see + in URLs in the query string after an ?.

Reading an Excel file in python using pandas

import pandas as pd

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

print (data)

MySQL: How to reset or change the MySQL root password?

for mysql 5.6 this command works and you can set password through the wizard:

sudo dpkg-reconfigure mysql-server-5.6

Round integers to the nearest 10

Slightly simpler:

def round_int(x):
    return 10 * ((x + 5) // 10)

Chrome: Uncaught SyntaxError: Unexpected end of input

In my case, i had low internet speed, when i turn off the other user's internet connection then error has gone, strange

How to check if a given directory exists in Ruby

All the other answers are correct, however, you might have problems if you're trying to check directory in a user's home directory. Make sure you expand the relative path before checking:

File.exists? '~/exists'
=> false
File.directory? '~/exists'
=> false
File.exists? File.expand_path('~/exists')
=> true

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

I got this error when running Visual Studio. By running Visual Studio as Administrator the application was able to access the Security logs as it then had sufficient permissions (thus preventing the error).