text:
Q: unittest in tensorflow, python session_test.py, got a exception I'm trying to run session_test.py from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/client/session_test.py, So in my anaconda, tensorflow virtual env, I went to the corresponding directory in tensorflow like ../master/tensorflow/python/client/.. and run
python session_test.py
I got exception info like this:

Traceback (most recent call last):
    File "session_test.py", line 32, in
      from tensorflow.core.protobuf import cluster_pb2
  ImportError: cannot import name 'cluster_pb2'

What package I should install or related documents that I could read about it. Is there anyone trying to do the same thing, run those unit test coming along with each module in tensorflow repo?
Please help me, thanks!

A: That line was added just a couple of weeks ago (see commit), and relates to a new feature being implemented in TensorFlow. Unless you have compiled and installed a very bleeding-edge version of TensorFlow you won't be able to run it. Instead, try to run the script corresponding to the version of TensorFlow that you have installed (for example, this is for version 1.1.0, the latest stable release at the time of writing).


text:
Q: Set backgroundColor of UITableViewCell in grouped UITableView Is it possible to set the backgroundColor of a UITableViewCell in a grouped UITableView and maintain the rounded corners of the cells?
All of my attempts results in a loss of the rounded corners.
mike

A: I asked the same question a few weeks ago, and you can see the valid answer here:
How to customize the background/border colors of a grouped table view cell?
It is indeed possible and the provided source code works great.

A: Unfortunately no. I believe the rounder corners are a background with the cell being transparent at the edges. When you try to use a custom color (or image) it draws over them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Publishing Container (external access) I started a nginx container, I can access it through the local ip (192.168.0.1).
I want to externally access mysite.dns.net
I did the port redirection on the router, but it didn't work.
access 192.168.0.1:8080 work
access mysite.dns.net:8080 didn't work
Note: Use linux VM.


text:
Q: Lua decompress gzip from string I have some trouble with decompress gzip from string in lua. (mb bad understanding)
Response of one web-services is base64-encoded gzip string, for sample I get some code on C#.
    public static string Decompress(byte[] value, Encoding Encoding = null)
    {
        if (value == null) return null;
        Encoding = Encoding ?? System.Text.Encoding.Unicode;
        using (var inputStream = new MemoryStream(value))
        using (var outputStream = new MemoryStream())
        {
            using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
            {
                byte[] bytes = new byte[4096];
                int n;
                while ((n = zip.Read(bytes, 0, bytes.Length)) != 0)
                {
                    outputStream.Write(bytes, 0, n);
                }
                zip.Close();
            }
            return Encoding.GetString(outputStream.ToArray());
        }
    }

    static void Main(string[] args)
    {
        const string encodedText = "H4sIAAAAAAAEAHMNCvIPUlRwzS0oqVQoLinKzEtXyC9SyCvNyYFxM/OAqKC0RKEgsSgxN7UktQgAwOaxgjUAAAA=";

        byte[] decodedBytes = Convert.FromBase64String(encodedText);

        var decodedString = Decompress(decodedBytes, Encoding.UTF8);

        Console.WriteLine(decodedString);

    }

I try to do this with lua (on nginx) and make from base64 string array of byte
local byte_table={};
base64.base64_decode(res_string):gsub(".", function(c){
 table.insert(byte_table, string.byte(c))
})

but have some problem with zlib.
Please help me understanding how can I use IO stream in lua and decompress gzip.

A:
I try to do this with lua (on nginx) and make from base64 string array of byte

No, you are making Lua table with bunch of numbers.
Decode base64 and feed to zlib the whole resulting string.
I'm use http://luaforge.net/projects/lzlib/ for gzip decompressing:
local result = zlib.decompress(str,31)


text:
Q: Powershell Copy item from Array to Array I would like to copy folders that have a DateTime format to a folder with the name of Weekday. The Folder D:\TEST\2015-06-23T2300+0000 should be copied to D:\TEST\Thursday.
Get-ChildItem $Path | Select FullName
D:\TEST\2015-06-23T2300+0000
D:\TEST\2016-01-07T2300+0000

Get-ChildItem $Path | ForEach {$_.LastWriteTime.DayOfWeek}
Thursday
Friday

Here is the code I have a the moment but it is not working. I am missing something.
$Path = "D:\TEST"
$source = Get-ChildItem $Path | Select FullName
$dest = Get-ChildItem $Path | ForEach {$_.LastWriteTime.DayOfWeek}
  foreach ($source in $sources)
    {
    Copy-Item -Path $source -Destination "D:\TEST2\$dest" -Recurse
    }

Any help welcome.

A: You're populating $dest with all possible Weekday values.
Retrieve the weekday on a per-item basis, as you go through them and copy:
$Sources = Get-ChildItem $Path
foreach($Source in $Sources)
{
    $Weekday = $Source.LastWriteTime.DayOfWeek
    $Destination = "D:\Test\$Weekday"

    Copy-Item $Source.FullName -Destination $Destination -Recurse
}

A: Try this code,
It is working, I have tested:
$Dir = "c:\files"
$Items = Get-ChildItem -Path $Dir
foreach ($Item in $Items)
{
    if (!($Item -is [System.IO.DirectoryInfo]))
    {
        Copy-Item -Path $Item.FullName -Destination .\Desktop\$($Item.LastAccessTime.DayOfWeek)
    }
}

*

*This directory c:\files should have a subdirectory foreach day of the week.


text:
Q: Why am I getting odd inductances from home made inductor? This question is related my my previous question: What to do about very hot planar inductor?
What I'm trying to do
I am trying to make a planar inductor (made from the tracks of the PCB, and surrounded by a 2 part a ferrite core). According to the datasheet of the ferrite core, the AL value is 1700nH, which means that with 12 turns around the core, I should get 12x12x1.7 = 244uH.
The problem
However, when I measure the inductance on my LC meter, it reads only 1.8uH. What's stranger is that if I create an inductor with the same core, but using stranded wire, and only 10 turns, I get 46uH!
I measured the resistance of the PCB tracks, and it's 0.25R, just as it should be, so I don't think there's a short in there.

My questions
What's going on? Is the AL value not sufficient for calculating inductance? How could it be that fewer turns gives a much higher inductance? Is the stranded wire massively better than PCB trace?

A: Brian has nailed it. Good shout. @Brian please take this picture and make your own answer. I'll delete this answer as soon as: -

NO VOTES PLEASE

A: If the stack height of your pcbs is such that the core is not completely mated then this will dramatically lower your inductance.


text:
Q: Como chamar uma ação de plugin pelo cronjobs Estou precisando executar um hook que desenvolvi dentro de um plugin em intervalos de 3 horas, eu gostaria de poder chamar esse comando em um arquivo externo parra assim adicionar no cron do servidor.

A: Oi, Victor.
Para esses casos eu uso o plugin WP Cron Control. Uma solução simples sem ter que re-inventar a roda.
Espero que ajude.


text:
Q: Why is libcurl sending packets between localhost ports? I have started working with libcurl, and simply tried running the basic code to get a file from an url. When I get this file using curl.exe, compiled with the same library, I get detect no random traffic on my localhost. However, when I run with my own executable, I get around 19 packets sent between two localhost ports.
I make sure to call curl_global_init(CURL_GLOBAL_WIN32) and curl_global_cleanup() after the method call.
What could be the cause of this traffic, and how could I make it go away?
int CurlFileDownloader::downloadSingleFile(const std::string& url, const std::string& destination) {
    CURLcode res = CURLE_READ_ERROR;

    mHandle = curl_easy_init();
    if(mHandle) {
        mData.destinationFolder = destination;
        // Get the file name from the url
        auto lastPos = url.find_last_of("/");
        mData.fileName = url.substr(lastPos + 1);

        curl_easy_setopt(mHandle, CURLOPT_URL, url.c_str());
        /* Define our callback to get called when there's data to be written */
        curl_easy_setopt(mHandle, CURLOPT_WRITEFUNCTION, &CurlFileDownloader::writeFileContent);
        /* Set a pointer to our struct to pass to the callback */
        curl_easy_setopt(mHandle, CURLOPT_WRITEDATA, &mData);

        /* Switch on full protocol/debug output */
        curl_easy_setopt(mHandle, CURLOPT_VERBOSE, 1L);

        mLastError = curl_easy_perform(mHandle);

        /* always cleanup */
        curl_easy_cleanup(mHandle);
        if (mData.fileStream.is_open()) {
            mData.fileStream.close();
        }

        if(CURLE_OK != mLastError) {
            std::cerr << "Curl error " << mLastError << std::endl;
        }
    }

    return mLastError;
}

size_t CurlFileDownloader::writeFileContent(char *buffer, size_t size, size_t nmemb, void *cb_data) {
    struct CurlCallbackData *data = (CurlCallbackData*)cb_data;
    size_t written = 0;
    if (data->fileStream.is_open()) {
        data->fileStream.write(buffer, nmemb);
    }
    else {
        /* listing output */
        if (data->destinationFolder != "") {
            data->fileStream.open(data->destinationFolder + "\\" + data->fileName, std::ios::out | std::ios::binary);
        }
        else {
            data->fileStream.open(data->fileName, std::ios::out | std::ios::binary);
        }
        data->fileStream.write(buffer, nmemb);
    }
    return nmemb;
}

Here is a sample of what RawCap.exe is capturing.

A: The source of the localhost communication was the use of a socket pair for IPV4 Loopback. When removing the #USE_SOCKETPAIR from libCURL's socketpair.h, the issue went away.


text:
Q: Scheduled Actions on Process Builder are not invoked I have created a process builder for sending email alerts 30 days before a date field on a record.
So I have added a criteria for activating only when the status__c field equals scheduled.
Then I have added Scheduled Actions to it - to send an email 30 days before the due_date__c field value.
For enabling Scheduled Actions I had to mark in the criteria, this section as true:

Do you want to execute the actions only when specified changes are made to the record

But because of that, this criteria does not always happen
My main use case is - if the status__c field does not change, and the due_date__c field only changes - then the schedule does not happen.
I have tried to add ISCHANGED to the due_date__c field to the criteria but that is not allowed.
Is there any way to trigger the Scheduled Actions always when the due_date__c field changes?
Here is a snap of my process:

UPDATE
The error when adding IS CHANGED to the due_date__c field:

A: So when you select yes when prompted "Do you want to execute the actions only when specified changes are made to the record?"(thus allowing you to create a scheduled action) you are only going to fire the event when you make a change and it explicitly makes all rule criteria true.
The reason you cannot use ISCHANGED is how scheduled actions work. At the time scheduled, if the rule criteria still evaluates to true, then the action will fire, which means that in order to use ISCHANGED, you would have to store the prior value of the field until at least the scheduled action executes - expensive and not supported.
I would recommend making your second rule criteria
due_date__c Not Equal to GlobalConstants.Null
This will allow your scheduled action to be scheduled upon change of due date.
It will also allow the action to be scheduled in the case where the status__c is populated but the due_date__c is not.


text:
Q: Determining Vo in a diode circuit using iterative analysis

simulate this circuit – Schematic created using CircuitLab
Say  we have this circuit. Then we were asked to find Vo using iterative analysis. We were told to stop when the estimate is accurate to within 15mV. I just want to confirm my understanding of the question.

*

*Is the 15mV the Vo that we should be aiming to get?

*And so,  if it is, we should be looking for the values of Id or Vd, right?

*What will be the right approach here? Could I first assume Vd to be 1/2Vout (Since I could find Id when I know Vd) and then just adjust it till I get to 15mV?

My KVL equation is: (Id is based from the exponential model of the diode)
$$ Vout = V1 - iD(R1) - 2Vd $$
The following are given:
Is (reverse sat. current) = 1fA
Ideality factor = 1
Operating temp = 27 C

A: *

*No, you're asked to find the output voltage within a tolerance of 15mV.

*See above.

*Initial assumption doesn't matter too much, it saves iterations if you are closer. If you assume a current (it will be fairly low in this case, maybe uA for a silicon diode), then calculate Vo, then you'll have a new current based on (1V-Vo)/R1. Calculate Vo again, repeat until it converges well enough.

A: To give you an idea of the iterative method let's assume a value of 4K ohms for R1

*

*And let's make an initial guess of 0.3V across each diode totalling 0.6V

*Given 1V - 0.6V = 0.4V drop across 4K ohms will provide a current of 0.1mA check using the Diode model the corresponding forward voltage (x2 for two diodes) and get a new estimate for the voltage across them.

*Plug the model calculated forward voltage into your original equation and recalculate the current i.e. (1V - 2*Vd)/4K and repeat step 2.
Stop when Vout changes between steps by <=15mV


text:
Q: Setting properties on ActiveModel::Base from an initializer Content of initializers/rails_defaults.rb
ActiveModel::Base.include_root_in_json = false

The error I get on startup:
NameError: uninitialized constant ActiveModel::Base

Anyone know of a remedy?
I'm using rails 3.1.RC4.

A: Rails 2.x? Change ActiveModel to ActiveRecord, and look in  initializers/new_rails_defaults.rb for the setting.
See:
http://apidock.com/rails/ActiveRecord/Serialization/to_json
Rails 3? Looks like for now you set it in the model directly instead:
class MyModel < ActiveRecord::Base
  self.include_root_in_json = true
end

Edit:
You may also want to look at this:
Rails 3.1 include_root_in_json


text:
Q: Rails 2 and unit testing I'm going to be working on upgrading a Rails 2 app to Rails 3. The app currently has no test coverage.
It's unclear to me if rspec-rails has a version that is compatible with Rails 2.
Any ideas?
Thanks.


text:
Q: Is there a difference between having a private setter OR only defining a getter? I need to make a class that wraps two dictionaries together, so that their values can be retrieved by a key of either an int or a string.
Properties seem to be the best approach here, but is there a difference between these two implementations?
public class Atlas<TValue>
{
    private Dictionary<int, TValue> _byIndex;
    private Dictionary<string, TValue> _byName;

    public Dictionary<int, TValue> ByIndex
    {
        get { return _byIndex; }
    }

    public Dictionary<string, TValue> ByName
    {
        get { return _byName; }
    }
}

And
public class Atlas<TValue>
{
    public Dictionary<int, TValue> ByIndex { get; private set; }
    public Dictionary<string, TValue> ByName { get; private set; }
}

In either case, the dictionary object is immutable and the elements can freely be changed, which is what I want. However, trying to change the dictionary object will result in either a ~ cannot be assigned to -- it is read only or a ~ cannot be used in this context because the set accessor is inaccessible. I realize the compiler will fluff out my auto properties into something similar to the top block of code anyways...
Does it actually matter which compiler error is raised?

A: The only difference is that in the second case the setter is inaccessible, but it is there, while in the firs case there is no accessor at all. This means that a program that uses reflection could potentially access the properties of the second example, while in case of the first example you would need to access fields instead.
As far as non-reflective use is concerned, there is no difference between the two code snippets: outside classes will not be able to set the dictionaries.
You may want to go further and hide the presence of the dictionaries from the users of your classes. Rather than providing two properties of Dictionary type, you may want to hide this detail of implementation from the users of your class by hiding it behind a pair of method:
public class Atlas<TValue> {
    public bool TryGetByIndex(int index, out TValue val);
    public void Add(int index, TValue val);
    public bool TryGetByName(string name, out TValue val);
    public void Add(string name, TValue val);
    public TValue this[string name] { get ... set ...}
    public TValue this[int index] { get ... set ...}
    // You may want to add more methods or properties here, for example to iterate atlas elements
}


text:
Q: Where is Windows XP's version of Minesweeper located? People have said that it's in C:\Program Files\Microsoft Games, but I don't have that directory. (I also don't have C:\mine)

A: Your's may be located under C:\Windows\System32\winmine.exe. Check there!


text:
Q: What are .mvfs_*** files in clearcase folder? When ever I make a change, an .mvfs_xxxx file gets created in my ClearCase folder.
I've a dynamic view.
I tried to remove these files and my system always get stuck.
What is the purpose of this file and how can I control MVFS from creating files in my clearcase folder?

A: See "About dot files in the view storage"
.mvfsxxxxxx files

Q: There are also files named .mvfsxxxxxxx in my view. They show up as view private files when I run cleartool lsprivate in my dynamic view. How did they get there and can I delete them?
A: These are files that were removed when another process still had them open.
  In order to allow the open process to continue reading the file after the file has been removed (UNIX semantics) the original file is renamed to some temporary unique name (just as in NFS).
The .MVFS files can be deleted using standard operating system remove commands (rm or del).

Example: cleartool lsprivate | fgrep '.mvfs' | rm"

In your case, a reboot might be in order before starting just the dynamic view and trying to remove them (without launching any other processes).

Apprently, (from this thread), they are called "silly renames":

has anyone ever seen view private files called something like

.mvfs_47e21162

with 0 byte size?

It is what is called a silly-renamed file.
  You get these in the MVFS if you delete a file while someone has it open.
In local filesystems deleting an open file causes the name to go away but the data is maintained in memory. On a distributed filesystem like the MVFS or NFS this doesn't work because the actual file is on a different system.
  Both the MVFS and the NFS get around this problem by renaming the file to something "silly"
  that is normally invisible and is unlikely to cause a naming conflict.

You get those also with ClearCase Multisite (for a different reason), where the term "silly rename" is (this time officially) mentioned.


text:
Q: How do I get the location of a box within an image in Flutter? I am writing a Flutter app to solve a Sudoku based on an picture taken with the camera.  Here is the source code: https://github.com/lachiejames/SudokuSolver
So far, I can do this if the Sudoku is in a precise location within the camera.  However if it is not in this precise location, it will not work.
I would like to improve this by using some kind of image-processing technique to detect the location of the Sudoku within the image.  But as of yet, I have not found a viable way to do this in Flutter.


text:
Q: vertical line chart (time series) in jqplot I'm trying to plot a time-series in a vertical line chart, something like this:
[EDIT The link is now a demos in the download archive which is available here:
https://www.rgraph.net/download.html#stable
And the demo is called demos/scatter-vertical-line.html ]
The reason is simple: mobile phones have a "vertical" aspect ratio, so a x-based chart is not as effective.
Is there any way I can do it with jqplot? I tried the "rotate" property in css, but it's not available in Opera Mini so I can't use it...

A: Adding this should do it :
seriesDefaults: {rendererOptions: {barDirection: 'horizontal'}}.


text:
Q: Bubble Sort method not working with Linked List in C I am trying to implement a bubble sort method into a linked list data structure, but when running it through a test harness, it doesn't do anything. Any suggestions?
Here is my source code:
void set_sort (set_t * the_set)
{
    assert (the_set);
    set_node_t *current;
    current = the_set->head;
    int sorted = 1;
    int x;
    for (x = 0; x < the_set->set_size; x++) {
        //we dont do it if this is the last value
        if (x + 1 == the_set->set_size) {
            continue;
        }
        if (current->data > current->next->data) {
            sorted = 0;
            int temp = &current->next->data;
            current->next->data = current->data;
            current->data = temp;
        }
        current = current->next;
    }
    if (!sorted) {
        set_sort (the_set);
    }

}

EDIT WITH HEADER FILE
#ifndef _set_h_
#define _set_h_

#include <stdbool.h>
#include "common.h"

/* Create a basic singly-linked list.*/
/*This code has been sourced from Mike Mcallistar, Assignment 5 Solutions*/

typedef struct _set_node_t {
        test_type_t *data;
        struct _set_node_t *next;
        struct _set_node_t *below;
} set_node_t;

/* the set itself keeps track of the head and the tail of the linked list */
typedef struct {

        int set_size;
        bool ready;
        set_node_t *head;
        set_node_t *tail;
        int set_level;
} set_t;

bool set_init(set_t *the_set);
void set_destroy(set_t *the_set);
bool set_add(set_t *the_set, test_type_t *item_to_add);
bool set_delete(set_t *the_set, test_type_t *item_to_remove);
bool set_find( set_t *the_set, test_type_t *item_to_find);
void set_sort(set_t *the_set);
void set_enumerate(set_t *the_set);
#endif

A: Something seems very wrong with this.
int temp = &current->next->data;     // Assignes a pointer into temp
current->next->data = current->data; // Copies current into next
current->data = temp;                // Copies the pointer into data

This is unlikely to do nothing. It's quite likely to corrupt your data.
Could it be as simple as to change the first of these lines to:
int temp = current->next->data;

Edit
Cleaning up your code a little I get to this:
void set_sort(set_t *the_set)
{
    assert(the_set);
    int sorted;
    int x;
    do {
        set_node_t *current = the_set->head;
        sorted = 1;
        for( x = 0; x < the_set->set_size - 1; x++){
            if(current->data > current->next->data){
                sorted = 0;
                int temp = current->next->data;
                current->next->data = current->data;
                current->data = temp;
            }
            current = current->next;
        }
    }
    while (!sorted);
}

Removing the use of unnecessary recursion removes the risk of causing a stack overflow.  Removing the continue makes the code marginally quicker (I believe).  Removing the spurious use of the pointer should fix your code.
If your code isn't fixed by this then then you will need to post the definition of set_node_t, its possible your comparison is not working (if (current->data > current->next->data)).
Edit 2
As comments and updated question has now pointed out you need to perform your comparison on the data itself and not the pointer to the data.
if(*(current->data) > *(current->next->data)){


text:
Q: How should I use django models from other applications? What is the proper way to use models from other django applications in my application? For example, should I simply go into the other application's models and add my functionality effectively coupling the two applications?
Should I subclass the models using a django proxy model to add my application specific functionality? This method, however, rules out ever using this added functionality in the parent application.
Should I simply import the model and create library functions to handle this additional functionality?
Thanks!
Pete

A: There are certain categories of apps that end up being coupled in other apps - a good example is the django.contrib.auth: if you are using the Django User model you depend on that app and your own apps are coupled with it.
There is nothing wrong with that scenario. I tend to think of it less as coupling and more as dependency. Your app depends on the django.contrib.auth being available. It is a natural thing because you need that functionality. You can always replace that app with some other app that provides the same interfaces you are currently using...
Now, if you have two of your own applications and they need knowledge of each other's models, I can think of two scenarios:

*

*You need a third application for your shared models

*They should be only one application (uncommon; you had a reason to make them separate to begin with!)
I usually have a core application of my own (just like there is a django.core) where I keep the code that is common across the apps in my project. If models of different applications are dependent on each other, they get moved to this app.
Now, it is also possible that your two applications really are only one application - but that should not be the default thinking. Monolithic apps are a very bad thing (TM).


text:
Q: What is difference between 'glad' and 'pleased'? I am studying English writing.
I am translated my language to English.
My book's answer is "I am pleased to meet you"
My answer was "I am glad to meet you"
Is this same sentence?
Does it have same meaning?
If my grammer is poor in this question, please correct my sentence.
If you correct my grammer, it will be very helpfull.
Thank you

A: "Glad" can have an element of relief about it.
If you meet someone who is (or you hope will be) pleasant and agreeable to talk to you can say "I am pleased to meet you".
If you have some problem and and you finally find someone who may be able to help you might say "I am glad to meet you".

A: Welcome to ELL!
Your grammar is not too bad! I've corrected some spelling mistakes and made it more continuous.

I am studying English writing and have translated (or am translating if you are still translating it!)  the sentence below
from my language into English.
According to my book it should be "I am pleased to meet you," but I
translated it as "I am glad to meet you." Do they both mean the same?
If the grammar in my question is poor, please correct it. If you do,
it will be very helpful.

I agree with Nemo about the words glad and pleased.

A: There is no difference in meaning.
You can use either.
But "I'm pleased to meet you" is the more common expression.
If you are learning English you should say "I'm pleased to meet you".


text:
Q: Bounded convex sets $A,B\subseteq\Bbb R^n,n\ge 2$ with a common point, but disjoint boundaries Motivation of my question is this answer.

Let $A,B\subseteq\Bbb R^n,n\ge 2$ be bounded convex sets such that $\exists a\in A,$ and $a\in B,$ too and $\partial A\cap\partial B=\emptyset.$ Does it hold that $A\subset B$ or $B\subset A$?

I assumed:

*

*$n\ge 2$ because, in $\Bbb R,$ segments $[0,2]$ and $[1,3]$ have disjoint boundaries, yet $2$ is an element of both. In $\Bbb R^2,$ however, their boundaries aren't disjoint.

*$A,B\subseteq\Bbb R^2$ bounded because the stripes $A=\{(x,y)\in\Bbb R^2\mid 0\le x\le 2\}$ and $B=\{(x,y)\in\Bbb R^2\mid 1\le x\le 3\}$ is a counterexample.

*$A,B\subseteq\Bbb R^2$ convex because $A=\{x\in\Bbb R^2\mid 0\le\|x\|\le 2\}$ and $B=\{x\in\Bbb R^2\mid 1\le\|x\|\le 3\}$ is a counterexample.

Now, if I'm not wrong, a convex set with more than $3$ non-collinear points (possible in $\Bbb R^n,n\ge 2$) should have a non-empty interior. Therefore one might consider two open balls of sufficiently smal radii (which are again convex) contained in $A$ and $B$ which the initial problem might boil down to, but I couldn't solve the problem that way.
I then tried to employ the boundedness of the boundaries (which with closedness make them compact) and try something with their distance, but to no avail.
Under what conditions does the statement hold and how can we prove it?

Edit:
I'm not sure if this is relevant to the question, but according to this ResearchGate post boundary $\partial A$ of a bounded convex set $A\subseteq\Bbb R^n$ is homeomorphic to the unit sphere $\Bbb S^{n-1}$, hence connected (because it is the image of the connected set $\Bbb S^{n-1}$ under the continuous inverse of a map $f:\partial A\to\Bbb S^{n-1}, f(x)=\frac{x}{\|x\|}$?)

A: Our proof strategy will be as follows. Suppose that none of $A\setminus B$, $B\setminus A$, or $A\cap B$ is empty. We will exhibit a point in $B$ and on the boundary of $A$, and another point outside $B$ and on the boundary of $A$. We can then travel from the former point to the latter along the boundary of $A$ in a continuous manner. While we do so, we are bound to cross the boundary of $B$ somewhere. See the figure below.

Formally: for the sake of contradiction, assume that $A\not\subseteq B$ and $B\not\subseteq A$. Since $A\cap B\neq\varnothing$, there exist $a\in A\cap B$ and $b\in B\setminus A$. Let $$\overline\lambda\equiv\sup\{\lambda\in[0,1]\,|\,(1-\lambda)a+\lambda b\in A\}.$$ I leave it as an exercise to show that $$x\equiv(1-\overline\lambda)a+\overline\lambda b\in \partial A\cap B.$$
Next, I claim that $\partial A\setminus B$ is not empty. If it is, then $\partial A\subseteq B$. Since every extreme point of $\overline A$ is also a boundary point (where $\overline A$ denotes the closure of $A$), the Krein–Milman theorem implies that $$A\subseteq\overline A=\overline{\operatorname{co}(\operatorname{extreme}(\overline A))}\subseteq\overline{\operatorname{co}(\partial(\overline A))}\subseteq\overline{\operatorname{co}(\partial A)}=\operatorname{co}(\partial A)\subseteq B,$$
contradicting $A\not\subseteq B$. Now take $y\in\partial A\setminus B$.
Since $\partial A$ is path connected for $n\geq 2$, one can find a continuous function $f:[0,1]\to\partial A$ such that $f(0)=x$ and $f(1)=y$. Let $$\overline c\equiv\sup\{c\in[0,1]\,|\,f(c)\in B\}.$$ Then, $z\equiv f(\overline c)\in\partial A\cap\partial B=\varnothing$, a contradiction.


text:
Q: Load html5 canvas publish of animate cc multiple times The publish output of Animate CC gives html file and js file. I want to draw the same drawing two times in the same canvas. From this example, i want to have output as
How can i change the javascript to achieve this without having two canvas tag? I want to have numerous instance of it in single canvas tag.

A: If you are trying to achieve the image above, you can simply create two instances of simple_canv class.
Try this:
var canvas, stage, exportRoot;

function init() {

 canvas = document.getElementById("canvas");
 exportRootLeft = new lib.simple_canv();
 exportRootRight = new lib.simple_canv();
 exportRootRight.x = 555;

 stage = new createjs.Stage(canvas);
 stage.addChild(exportRootLeft, exportRootRight);
 stage.update();
 stage.enableMouseOver();

 createjs.Ticker.setFPS(lib.properties.fps);
 createjs.Ticker.addEventListener("tick", stage);

 init_app()

}
Also, remember to increase the width of your canvas.

A: Is this what you are looking for?
<!DOCTYPE html>
<html>
    <body>

        <canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">
            Your browser does not support the canvas element.
        </canvas>

        <script>
            var canvas = document.getElementById("myCanvas");

            var ctx1 = canvas.getContext("2d");
            var ctx2 = canvas.getContext("2d");

            ctx1.fillStyle = "red";
            ctx1.fillRect(0,0,50,50);

            ctx2.fillStyle = "blue";
            ctx2.fillRect(50,0,50,50);
        </script>

    </body>
</html>

You can then change what you render.


text:
Q: Clear all widgets in a layout in pyqt Is there a way to clear (delete) all the widgets in a layout?
self.plot_layout = QtGui.QGridLayout()
self.plot_layout.setGeometry(QtCore.QRect(200,200,200,200))
self.root_layout.addLayout(self.plot_layout)
self.plot_layout.addWidget(MyWidget())

Now I want to replace the widget in plot_layout with a new widget. Is there an easy way to clear all the widgets in plot_layout? I don't see any method such.

A: I use:
    while layout.count() > 0:
        layout.itemAt(0).setParent(None)

A: Most of the existing answers don't account for nested layouts, so I made a recursive function, that given a layout it will recursively delete everything inside it, and all the layouts inside of it. here it is:
def clearLayout(layout):
    print("-- -- input layout: "+str(layout))
    for i in reversed(range(layout.count())):
        layoutItem = layout.itemAt(i)
        if layoutItem.widget() is not None:
            widgetToRemove = layoutItem.widget()
            print("found widget: " + str(widgetToRemove))
            widgetToRemove.setParent(None)
            layout.removeWidget(widgetToRemove)
        elif layoutItem.spacerItem() is not None:
            print("found spacer: " + str(layoutItem.spacerItem()))
        else:
            layoutToRemove = layout.itemAt(i)
            print("-- found Layout: "+str(layoutToRemove))
            clearLayout(layoutToRemove)

I might not have accounted for all UI types, not sure. Hope this helps!

A: This may be a bit too late but just wanted to add this for future reference:
def clearLayout(layout):
  while layout.count():
    child = layout.takeAt(0)
    if child.widget():
      child.widget().deleteLater()

Adapted from Qt docs http://doc.qt.io/qt-5/qlayout.html#takeAt. Remember that when you are removing children from the layout in a while or for loop, you are effectively modifying the index # of each child item in the layout. That's why you'll run into problems using a for i in range() loop.

A: My solution to this problem is to override the setLayout method of QWidget. The following code updates the layout to the new layout which may or may not contain items that are already displayed. You can simply create a new layout object, add whatever you want to it, then call setLayout. Of course, you can also just call clearLayout to remove everything.
def setLayout(self, layout):
    self.clearLayout()
    QWidget.setLayout(self, layout)

def clearLayout(self):
    if self.layout() is not None:
        old_layout = self.layout()
        for i in reversed(range(old_layout.count())):
            old_layout.itemAt(i).widget().setParent(None)
        import sip
        sip.delete(old_layout)

A: The answer from PALEN works well if you do not need to put new widgets to your layout.
for i in reversed(range(layout.count())):
    layout.itemAt(i).widget().setParent(None)

But you will get a "Segmentation fault      (core dumped)" at some point if you empty and fill the layout many times or with many widgets. It seems that the layout keeps a list of widget and that this list is limited in size.
If you remove the widgets that way:
for i in reversed(range(layout.count())):
    widgetToRemove = layout.itemAt(i).widget()
    # remove it from the layout list
    layout.removeWidget(widgetToRemove)
    # remove it from the gui
    widgetToRemove.setParent(None)

You won't get that problem.

A: From the docs:

To remove a widget from a layout, call removeWidget(). Calling QWidget.hide() on a widget also effectively removes the widget from the layout until QWidget.show() is called.

removeWidget is inherited from QLayout, that's why it's not listed among the QGridLayout methods.

A: I had issues with solutions previously mentioned. There were lingering widgets that were causing problems; I suspect deletion was scheduled, but not finihsed. I also had to set the widgets parent to None.
this was my solution:
def clearLayout(layout):
    while layout.count():
        child = layout.takeAt(0)
        childWidget = child.widget()
        if childWidget:
            childWidget.setParent(None)
            childWidget.deleteLater()

A: That's how I clear a layout :
def clearLayout(layout):
    if layout is not None:
        while layout.count():
            child = layout.takeAt(0)
            if child.widget() is not None:
                child.widget().deleteLater()
            elif child.layout() is not None:
                clearLayout(child.layout())

A: You can use the close() method of widget:
for i in range(layout.count()): layout.itemAt(i).widget().close()

A: After a lot of research (and this one took quite time, so I add it here for future reference), this is the way I found to really clear and delete the widgets in a layout:
for i in reversed(range(layout.count())):
    layout.itemAt(i).widget().setParent(None)

What the documentation says about the QWidget is that:

The new widget is deleted when its parent is deleted.

Important note: You need to loop backwards because removing things from the beginning shifts items and changes the order of items in the layout.
To test and confirm that the layout is empty:
for i in range(layout.count()): print i

There seems to be another way to do it. Instead of using the setParent function, use the deleteLater() function like this:
for i in reversed(range(layout.count())):
    layout.itemAt(i).widget().deleteLater()

The documentation says that QObject.deleteLater (self)

Schedules this object for deletion.

However, if you run the test code specified above, it prints some values. This indicates that the layout still has items, as opposed to the code with setParent.

A: A couple of solutions, if you are swapping between known views using a stacked widget and just flipping the shown index might be a lot easier than adding and removing single widgets from a layout.
If you want to replace all the children of a widget then the QObject functions findChildren should get you there e.g. I don't know how the template functions are wrapped in pyqt though. But you could also search for the widgets by name if you know them.

A: for i in reversed(range(layout.count())):
    if layout.itemAt(i).widget():
        layout.itemAt(i).widget().setParent(None)
    else:
        layout.removeItem(layout.itemAt(i))

A:         for i in reversed (range(layout.count())):
            layout.itemAt(i).widget().close()
            layout.takeAt(i)

or
        for i in range(layout.count()):
            layout.itemAt(0).widget().close()
            layout.takeAt(0)


text:
Q: Leaflet: route machine current position I would like to insert the current position of the device at the first waypoint. With a function onLocationFound I get the position but I can't add it to the waypoint. Does not work.
is there a best solution?
function onLocationFound(e) {
        var radius = e.accuracy / 2;
        var curr_latitude = e.latitude;
        var curr_longitude = e.longitude
        L.marker(e.latlng).addTo(map).bindPopup("You are within " + lat + " meters from this point").openPopup();
        L.circle(e.latlng, radius).addTo(map);
    }

function onLocationError(e) {
        alert(e.message);
    }

    map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);

    map.locate({setView: false, maxZoom: 16});

map.on('locationfound', onLocationFound);
    map.on('locationerror', onLocationError);

    map.locate({setView: false, maxZoom: 16});

L.Routing.control({

routeWhileDragging: false,
    draggableWaypoints: false,
    addWaypoints: false,
    waypoints: [
        L.latLng(curr_latitude, curr_longitude),
        L.latLng(45.5062563,9.1864641)
    ],
    language: 'it',
    showAlternatives: false,
    lineOptions: {
    styles:
            [
                {color: 'black', opacity: 0.15, weight: 9}, //sombra
                {color: 'white', opacity: 0.8, weight: 6}, // Contorno
                {color: 'blue', opacity: 1, weight: 4}] // Centro
   },
          summaryTemplate:  '
Percorso: {name}

Distanza: {distance}
',
          show: false,

}).addTo(map);


text:
Q: Unable to import external module in Angular2 with TypeScript I am trying to import marker-animate-unobtrusive library into my angular2 project. And since it already has a type definition, I have tried like this:
npm install marker-animate-unobtrusive  --save
npm install @types/marker-animate-unobtrusive --save
typings install dt~google.maps --global --save
typings install dt~marker-animate-unobtrusive --global --save

After successful installation, I am trying to import one of the modules like this:
import * as SlidingMarker from 'marker-animate-unobtrusive';
But at that moment, I am getting this error:
File '/Users/.../node_modules/@types/marker-animate-unobtrusive/index.d.ts' is not a module.

But I checked the index.d.ts and found that module is already declared.
What am I missing here or doing wrong?
EDIT 1:
Hash: 561cad2f71e8d09ae7cf
Version: webpack 2.1.0-beta.25
Time: 9538ms
           Asset       Size  Chunks             Chunk Names
  main.bundle.js    3.55 MB    0, 2  [emitted]  main
styles.bundle.js    10.2 kB    1, 2  [emitted]  styles
       inline.js    5.37 kB       2  [emitted]  inline
        main.map    3.63 MB    0, 2  [emitted]  main
      styles.map    14.1 kB    1, 2  [emitted]  styles
      inline.map    5.55 kB       2  [emitted]  inline
      index.html  478 bytes          [emitted]

ERROR in [default] /Users/.../src/app/trip/map-content-component/map-content-component.component.ts:6:26
File '/Users/.../node_modules/@types/marker-animate-unobtrusive/index.d.ts' is not a module.
Child html-webpack-plugin for "index.html":
         Asset     Size  Chunks       Chunk Names
    index.html  2.81 kB       0
webpack: bundle is now VALID.


text:
Q: I'm a beginner and I'm creating a C program to print numbers from 0 to n using while loop where n is input from user I'm a beginner and I'm creating a C program to print numbers from 0 to n using while loop where n is input from user.
//program to print numbers 0 to n where n is input from user

#include<stdio.h>
int main()
{
    int i=0,num;
    printf("Enter number: ");
    scanf("%d",&num);
    while(i<=num)
    {
        printf('%d',i);
        i++;
    }
    return 0;
}

Im getting error saying expected const char

I tried to get solution over several websites
since im new to this language I'm facing trouble in such simple code
I tried running this code on several online compilers but everywhere I get the same issue

A: In line 11 in the printf statement you have used single quotes - '%d' which does is giving you problems here, change it to a "%d". Hope that helps.


text:
Q: MySQL - Request to count periodically with accumulation Sorry if this is a duplicate but I never found an answer to this.
I have a User table which is as follows :
| id | pseudo      | inscription date |
|----|-------------|------------------|
| 1  | johndoe     | 01/01/1970       |
| 2  | janeyes     | 02/01/1970       |
| 3  | thirdpseudo | 05/01/1970       |

And I am searching for a query to do statistics of accumulation. I would like to retrieve, day by day, the number of users registered.
I made a query that retrieves only for the registering days, but I don't find how to accumulate every days...
SELECT DATE_FORMAT(date, "%d/%m/%Y") AS 'Day', COUNT(*) AS 'Number of registered users'
FROM User
GROUP BY DATE(date)
ORDER BY date DESC;

This query outputs :
| date       | number of registered users |
| ---------- | -------------------------- |
| 01/01/1970 | 1                          |
| 02/01/1970 | 1                          |
| 05/01/1970 | 1                          |

The output I would like for this example is :
| date       | number of registered users |
| ---------- | -------------------------- |
| 01/01/1970 | 1                          |
| 02/01/1970 | 2                          |
| 03/01/1970 | 2                          |
| 04/01/1970 | 2                          |
| 05/01/1970 | 3                          |
| 06/01/1970 | 3                          |

A: I would suggest to generate some dates data defined as range of dates. Then join all users available to these dates and count how many users were registered during such days.
Here is the code:
-- creating simple table
create table Users
(
    id int not null,
    pseudo varchar(15),
    date date
);

-- adding some data
insert into Users
values
(1,'jonh','1970-01-01'),
(2,'doe','1970-01-02'),
(3,'janeyes','1970-01-02'),
(4,'third','1970-01-03'),
(5,'pseudo','1970-01-03'),
(6,'title','1970-01-04'),
(7,'somename','1970-01-04'),
(8,'anothername','1970-01-04');

-- defines the start date and the end date
set @startDate = '1970-01-01';
set @endDate = '1970-02-01';

-- recursively geneterates all dates within the range
with RECURSIVE dateRange (Date) as
(
    select @startDate as Date
    union ALL
    select DATE_ADD(Date, INTERVAL 1 DAY)
    from dateRange
    where Date < @endDate
)
-- using SUM() over () would result in running total starting
-- from 1, it would count next day + all previous days
select Date, Sum(RegisteredUsersCount) over(order by RegisteredUsersCount asc
                                            rows between unbounded preceding and current row) as RegisteredUsersCount
from
(
  -- left join will join all users, if there is no users that correspond to the date of join, then it would be 0 for that date.
  select dr.Date, Count(u.id) as RegisteredUsersCount
  from dateRange as dr
  left join Users as u
  on dr.Date = u.date
  group by dr.Date
) as t
order by Date asc;

And working example to test: SQLize Online


text:
Q: I'm working on a convex hull project using processing3, could somebody tell me if there's anyway to quit a function (not the whole program)?     int currentPoint = 2;
    int direction = 1;
    PVector copyOf(PVector p){
        return new PVector(p.x, p.y);
    }

    void addPoint() {

        hull.add(points.get(currentPoint));

    // look at the turn direction in the last three points
    // (we have to work with copies of the points because Java)
        p1 = copyOf(hull.get(hull.size() - 3));
        p2 = copyOf(hull.get(hull.size() - 2));
        p3 = copyOf(hull.get(hull.size() - 1));

        while (!crossprod (p1, p2, p3) && hull.size() > 2) {
    // if crossproduct is <= 0, then remove the middle point
    // if crossproduct is >= 0, do nothing because we have add the point before
            hull.remove(hull.size() - 2);
            if (hull.size() >= 3) {
    //in case of null pointer error
                p1 = copyOf(hull.get(hull.size() - 3));
            }
            p2 = copyOf(hull.get(hull.size() - 2));
            p3 = copyOf(hull.get(hull.size() - 1));
        }
    //you'll see information in the console
        println("currentPoint: " + currentPoint + " numPoints: " + points.size() + " hullSize: " + hull.size()+" direction:"+direction);
        if (currentPoint == points.size() -1 || currentPoint == 0) {
    //when direction = 1, it's a traversal of all points with O(n)
    //when direction = -1, the construction of convex hull began which is O(nlogn)
            direction = direction * -1;
            if (currentPoint == 0){
    /****add code here*****/
            }
        }

        currentPoint+= direction;
    }

It's quite hard to explain my question clearly without code. I want to add some code so that when currentPoint = 0, it will quit the addpoint() function. exit() won't work, for it will quit the whole program and the animation already played will disappear. I can't think up any good solution to that, do anybody has ideas about that?

A: From the reference:

The keyword return may also be used to break out of a function, thus not allowing the program to the remaining statements.
void draw() {
  background(204);
  line(0, 0, width, height);
  if (mousePressed) {
    return;  // Break out of draw(), skipping the line statement below
  }
  line(0, height, width, 0);  // Executed only if mouse is not pressed
}

So in your case:

I want to add some code so that when currentPoint = 0, it will quit the addpoint() function.

if(currentPoint == 0){
  return;
}

Taking a step back, you should really get into the habit of doing some research. A quick google search of "java quit function" returns a bunch of results, including:

*

*How to break out or exit a method in Java?

*Which is the Best way to exit a method

A: Use
return;

or
return <optional object>;


text:
Q: Jquery Tree list I can add first tree list. But it does not work in next step. How can do it? I want to make tree larger.

$(".thisadd").click(function(){

      $(this).closest("li").append("

Company Maintenance<button class='thisadd'>+</button>

");
    });

TECH <button class="thisadd">+</button>

A: You are calling event on first method but not on dynamically generated buttons. Use .on() for this.

$(document).on("click", '.thisadd', function() {
      $(this).closest("li").append("

Company Maintenance<button class='thisadd'>+</button>

");
});

TECH
      <button class="thisadd">+</button>


text:
Q: What is bi-direction protocol in TChannel? I have read about TChannel which is a networking framing protocol used for general RPC.
https://github.com/uber/tchannel/blob/master/docs/protocol.md
But I misunderstand some concepts.
"Tchannel is a bi-directional request/response protocol. Each connection between peers is considered equivalent, regardless of which side initiated it. It's possible, perhaps even desirable, to have multiple connections between the same pair of peers. Message ids are scoped to a connection. It is not valid to send a request down one connection and a response down another."
What is bi-direction protocol?

A: Start considering the "request/response" part in the statement. It means that for every successful request sent by the host A there will be always a response sent back by host B.
This does not necessarly implies a syncronous behaviour (e.g. A block waiting for B's reply). Indeed TChannel works with an async behavior. Many requests can be sent in sequence, and the requester expects an out of order responses. In this way, the slow requests do not block faster requests.
How this work? Very simple. A specifies a message id when sending a request.  When B responds, it uses the same message id for the response. In this way A can easily correlate a response with the corresponding request.
Now look at the "bi-directional" part in the statement. It means that if host B wants to send a request to host A, it can re-use the same channel that was created originally by A. Despite there is a request/response logic, A and B are considered peers, and each connection between peers is considered equivalent, regardless of which host initiated it.


text:
Q: What's a good client tool to access Oracle RDBMS? I'm looking for a good client tool to replace "Oracle SQL Developer" (the tool I currently use) which supports:

*

*Oracle DB 10g, 10gR2, 11g

*Running SQL code

*Debugging SQL code (with walk-through... click error, jumps to error line)

Do you know of one, preferably free?

A: I haven't found anything 'free' that works as well as Oracle SQL Developer. In the past it was pretty buggy and frustrating. I am on a 3.0 Early Adopter release now and very happy with the improvements. I am a heavy user and have had no crashes in the 3 months since going to this release. I wasn't sold on the interface early on but I am familiar with it now and very productive with it. I also make great use of the User Defined Reports -- all the SQL Queries I had floating in text documents for troubleshooting I wrap into their own custom reports.
Toad is an option... but can be pricey. It satisfies your want-list. If you want to pay for all the bells and whistles and have to support a lot of differenct databases it might be worth it for you.
A lot of developers  here use AllRoundAutomations "PL/SQL Developer" tool, so many in fact that we bought a site license. Single seats can be had for US$180 per seat. It fits your requirements. I have not personally used the debugger but it is a mature product, I would expect it to work as advertised.

A: While I have grown quite fond of Oracles SQL Developer, have you considered trying Toad as an alternative for Oracle's SQL Developer? (You can download a 30 day trial from Quest's website.)
There is also SQuirrel and DbVisualizer which will work with Oracle (and other DBMS' platforms).

A: The product of Quest Software full fill all need and is easy to use. Currently I am running Toad version 11.
Here is a short demo
But as far is goes to the free software the "Oracle SQL Developer", IMHO the best software to connect with Oracle.

A: For a truly free editor and administrator , try http://www.silversash.com
it does have a debugger. not sure if does the jump to error line that you wanted.


text:
Q: how to convert value in array to be stringg and number to be a sentence how to convert this array ['myname', 'myhobby', 1] to be "myname", "hobby", 1
1 must be a number, is that possible ?? I want to create value for push it on database , sqlite
so when I call parameter of (name, hobby, age) and the value must be ('myname', 'myhobby', 1)
myname TEXT
hobby TEXT
age INTEGER
is that possible ??


text:
Q: IntelliJ IDEA 14 where can I get Android Designer? This question is related to IntelliJ IDEA 13 - missing Android UI designer?
I have IntelliJ IDEA 14.0.2 and the same problem as mentioned in above question, but I am not able to find Android Designer. What have been changed in new IntelliJ?

A: Android Designer is no longer a separate plugin; it's been merged into the main Android plugin. The UI designer functionality is available for projects that have an Android facet configured.

A: Grab Android Studio - it's IntelliJ IDEA with Android support, officially supported by Google.
http://developer.android.com/sdk/index.html


text:
Q: Считать несколько строк с клавиатуры в переменную У меня есть прибор, который работает в режиме клавиатуры. Он делает какие-то измерения и передает их по bluetooth на ПК. Проблема заключаются в том, что передается несколько строк, а с помощью стандартной функции Console.ReadLine() происходит следующее:

*

*Считывается первая строка

*Завершается выполнение функции и оставшийся текст вводится просто в VS.

Пробовал еще Console.In.ReadToEnd(). Не помогает. Возможно поможет перехват потока ввода.
EDIT: Console.In.ReadToEnd() работает, если текст руками вводить. а там прибор сам выплевывает значения в две строки. поэтому не помогает использование Console.In.ReadToEnd()


text:
Q: Petición POST a navegador nativo Necesito hacer una petición post al navegador nativo del móvil y mostrar el navegador. El paquete url_launcher permite hacer peticiones get y mostrar la url que le indiquemos en el navegador, pero no hay manera de hacer un post.
El paquete inAppWebView tampoco me sirve. Si que me hace la petición POST correctamente pero una vez dentro necesito descargar ficheros, y con este Widget no me lo permite, de ahí que necesite hacerlo en el navegador nativo.
¿Sabeis alguna solución?


text:
Q: Receive in C++ a Java generic object as a method return type using JNI I have a C++ wrapper that calls Java functions of a Java SDK using JNI.
In the Java code there is a generic class, for example let's call it MyClass, that is defined like this:
public class MyClass<T> extends HashMap<String, T> {
    ...
}

In the C++ code I am calling a Java function using JNI, for example let's call it getMyClass, that is defined like this:
public MyClass<String> getMyClass() {
    return myclassObject;
}

So, the Java function getMyClass returns an object of type MyClass and I'd like to read this object in the C++ code where it is returned.
I tried casting the returned Java object with JNI's parameter type jobject, but it doesn't seem to work as it always has a null value. In other words, I tried something like this which would work if the returned object Java was of type String for example.
auto jObjectMyClass = (jobject) env->CallObjectMethod(jObjectThatHasGetMyClassFunction, getMyClassMethod);

Questions:

*

*Is there any other casting that I could try when receiving the Java object in the C++ code, in order for this to work in a similar way?

*Is there any other better way in which I should approach this matter of receiving a generic class object using JNI?


text:
Q: Deserialize a value which can be an array or atomic I'm using Gson and want to deserialize the following JSON alternatives into the same class Values. In the latter case I would like to receive a List of just one element. Is there a way to accomplish this in Gson without having to write a custom deserializer?
//Array:
{
  "Value": [205.4, 13.5]
}

//Single value:
{
  "Value": 205.4
}

Deserialize both into:
public static class Values {
      private List<Double> Value;
}

A: There is no way to do this in Gson unless using custom TypeAdapter.
public class AwesomeType extends ArrayList<Double> {
    ...
}

public class AwesomeTypeAdapter extends TypeAdapter<AwesomeType> {
    @Override
    public void write(JsonWriter out, AwesomeType value) throws IOException {
        ...
    }

    @Override
    public AwesomeType read(JsonReader in) throws IOException {
        AwesomeType result = new AwesomeType();
        if (in.peek() == JsonToken.BEGIN_ARRAY) {
            in.beginArray();
            while (in.peek() != JsonToken.END_ARRAY)
                result.add(in.nextDouble());
            in.endArray();
        } else {
            result.add(in.nextDouble());
        }
        return result;
    }
}

Register this type adapter to your Gson and use this class in your model instead of List<Double>.

A: As @BornToCode mentioned the solution is to write a custom TypeAdapter and register it with the GsonBuilder:
public class ListTypeAdapter extends TypeAdapter<List<Double>> {

  @Override
  public void write(final JsonWriter writer, final List<Double> doubles) throws IOException {
    writer.beginArray();
    for (final double value : doubles) {
      writer.value(value);
    }
    writer.endArray();
  }

  @Override
  public List<Double> read(final JsonReader reader) throws IOException {
    final List<Double> doubles = new ArrayList<>();

    if (reader.peek() == JsonToken.BEGIN_ARRAY) {
      reader.beginArray();
      while (reader.hasNext()) {
        doubles.add(reader.nextDouble());
      }
      reader.endArray();
    } else {
      doubles.add(reader.nextDouble());
    }
    return doubles;
  }
}

Register it:
GSONBUILDER.registerTypeAdapter(new TypeToken<List<Double>>(){}.getType(),
    new ListTypeAdapter().nullSafe());


text:
Q: Regular expression for matching quantities and unit I need to extract the quantity and unit from strings like this
1 tbsp
1tbsp
300ml
300 ml
10grams
10 g

The quantities will always be numbers, then there may or may not be a space then the unit. They may be 15 - 20 different units which can come from a list that we define (perhaps an array)
The solution can be in either javascript or PHP as I need to split them before storing them in a database. ie they need to be stored separately.
Thanks
EDIT: Sorry to be clear. Each new line represents a new string. That is the string would only contain 10g OR 300ml - so we just need to split one unit and one quantity at a time.

A: Okay, what you can do is create an array of allowed units, and then use array_map to apply preg_quote on each unit in the array (so that if there are any characters in the unit that are special characters in a regular expression they will be escaped), and then construct a regular expression:
$units = array("tbsp", "ml", "g", "grams"); // add whatever other units are allowed
$pattern = '/^(\d+)\s*(' . join("|", array_map("preg_quote", $units)) . ')$/';

The $pattern will thus become something like /^(\d+)\s*(tbsp|ml|g|grams)$/, and then you can use it to detect things that look like units in your string:
$matches = array();
// assuming you have an array of measurement strings...
foreach ($measurement_strings as $measurement)
{
  preg_match($pattern, $measurement, $matches);
  list(, $quantity, $unit) = $matches;
  // ...
}

Because the pattern defines two capturing groups, for the quantity and unit respectively, you can then extract those out of the match and do what you want with them.
(I've updated my answer, based on the question update that each line is a separate string).

A: Regex:
/(\d+)\s*(\D+)/

Code:
preg_match_all('/(\d+)\s*(\D+)/', $ingredients, $m);

$quantities = $m[1];
$units = array_map('trim', $m[2]);

$quantities and $units are:
Array
(
    [0] => 1
    [1] => 1
    [2] => 300
    [3] => 300
    [4] => 10
    [5] => 10
)
Array
(
    [0] => tbsp
    [1] => tbsp
    [2] => ml
    [3] => ml
    [4] => grams
    [5] => g
)

See: http://ideone.com/MSH8t
If you use this you don't have to have a list of units ready. But this assumes your units will have no numeric characters on them, and your quantities are numbers only.

A: Mabye something simple is enough, just like that:
^([0-9]+)\s*([a-zA-Z]+)\s*$


text:
Q: I downloaded the dSYM-file but the Crashlytics does not see it I downloaded the dSYM-file but the Crashlytics does not see it. I took the file from App Store and downloaded it using "Fabric/upload-symbols". Please tell me what could be the reason
command for upload-symbols (terminal):
~/prjPath/ios/Pods/Fabric/upload-symbols -gsp ~/prjPath/ios/prj/GoogleService-Info.plist -p ios ~/dSYMPath/69c5e6e8-fbf8-3848-82db-96b1e29f594f.dSYM

response:
Successfully submitted symbols for architecture arm64 with UUID 69c5e6e8fbf8384882db96b1e29f594f in dSYM: /dSYMPath/69c5e6e8-fbf8-3848-82db-96b1e29f594f.dSYM

Successfully uploaded Crashlytics symbols
Terminal and Crashlytics console

A: When uploading the dSYMs through Fabric.io, they require you to compress/zip the folder first. If you haven't already, I'd give that a try first. If that fails, there is another option, if you need to proceed...
You can add your dSYM's through the Fabric Crashlytics dashboard at fabric.io. Click the Settings cog on the top right of the page and then select apps from the menu. From there select your App from your list of apps, and you'll see another tab bar menu on the page with Missing DSYMS on the right. Compress/zip your folder before uploading, and by the time you've navigated back to the dash, they'll be ready to go.


text:
Q: How to pass option when creating form I'm working on a form and want to pass to my form an array that would content all my projects so that my form would have a select with all of those project for option.
I already reed alot of answer, but I just can't figure this thing out. I know that I'm suppose to do something like:
$formulaire=$this->createForm(new ModifierSupprimerProjet(), null, $myArray);

but, I'm suppose to add all the content of my array to getDefaultOptions()...
I do I do that? An other thing, what is suppose to be the second parameters of the createForm method?
Here is the post that that came the closest to solve my probleme:
Accessing a variable through $options in the buildForm()

A: The best way to populate select form element with Project entities is to use entity form field. So you don't have to pass any options to form type class.
$builder
    ->add('project', 'entity', [
        'label'         => 'form.project',
        'class'         => 'AppBundle\Entity\Project',
        'property'      => 'name',
        'required'      => true,
        'empty_value'   => 'form.select_empty_value',
        'query_builder' => function($repository) {
            return $repository->createQueryBuilder('p')->add('orderBy', 'p.name ASC');
        },
    ])
;

If you need to populate choice field there is another best practice. You should define your form type class as service and inject Entity Manager into it. So you could fetch any data from the database and populate any choice fields.
services.xml
<service id="app.form.modifier_supprimer_projet" class="AdminBundle\Form\ModifierSupprimerProjet">
    <tag name="form.type" alias="app_modifier_supprimer_projet" />
    <argument type="service" id="doctrine.orm.entity_manager"/>
</service>

ModifierSupprimerProjet.php
<?php

namespace AppBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityManager;

class ModifierSupprimerProjet extends AbstractType
{
    /**
     * @var EntityManager
     */
    protected $em;

    /**
     * @param EntityManager $em
     */
    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    /**
     * @param FormBuilderInterface $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('project', 'choice', [
                'label'   => 'form.project',
                'choices' => $this->em->getRepository('AppBundle:Project')->getProjectsList(),
            ])
        ;
    }

    /**
     * @param OptionsResolverInterface $resolver
     */
    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults([
            'data_class' => 'AppBundle\Entity\ModifierSupprimerProjet',
        ]);
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'app_modifier_supprimer_projet';
    }
}

Controller
$modifierSupprimerProjet = new ModifierSupprimerProjet();

$form = $this->createForm('app_modifier_supprimer_projet', $modifierSupprimerProjet);

Second param of createForm method is Entity, if your form is mapped to any entity.

A: A while ago I had to do something similar, I had to get the list of icons and pass that to the form and this is how I achieved it.
inside my action
// my entity
$services = new Services();

$icons = the query for icons, in your case the projects

// creating form view, notice 'icons' being passed to the form
$form = $this->createForm(new AddServices(), $services, array('icons' => $icons));

Inside your form class
namespace Acme\YourBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class AddServices extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

//build your form here
        $builder->add('....');
        //form field linked with your dropdown options, in your case the projects
        $builder->add('icon', 'choice', array(
            'choices'   => $options['icons'],
            'required'  => false,
        ));

    }

    public function getName()
    {
        return 'addServices';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        //notice icons being set here as default options
        $resolver->setDefaults(array(
            'icons' => null,
        ));
    }
}

Then inside your twig
{{ form_widget(form.icon, { 'attr': {'class': ''}  }) }}
I am sure there might be other ways to achieve this but this is how I do it and seems to work perfectly fine

A: We assume that you've already read the documentation, but couldn't understand how to use it.. It's very simple, there are 3 important methods in form type, buildForm which builds the fields of your form, setDefaultOptions for versions <=2.6 or configureOptions for versions >2.6 where you specify options which are consumed by buildForm method (internally by Form Component), getName - unique name of your form (here is a simple clarification to this method).
You can solve your task like this if we go back to your problem:
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver
        ->setDefaults([
            'data_class' => 'YOUR_ENTITY' /* FormComponent autmatically maps the form fields with your entity if you set this option and pass an object as an 2-arguement to `createForm` method in your controller */
            'my_custom_option' => null /* here we specify our custom option and set its initial value as null */
        ])
        ->setRequired([ /* this is optional, which tells the 'my_custom_option' option is required */
            'my_custom_option'
        ])
        ->setAllowedTypes([ /* this one is also optional, which specify the type your 'my_custom_option' option */
            'my_custom_option' => 'Symfony\Component\HttpFoundation\Request' // this is an example, which allows only `request` object
        ])
     ;
}

public function buildForm(...)
{
    $myCustomOption = $options['my_custom_option']; // here we get our 'my_custom_option'

    ....
}

In your controller:
$formulaire=$this->createForm(new ModifierSupprimerProjet(), OBJECT_OR_NULL /* here we set our object which we've already assigned to `data_class` or we set to NULL */, [
     'my_custom_option' => $request
]);


text:
Q: Issue During Converting Array to XML i have an array list like this
    Array
(
    [351] => Array
        (
            [0] => Array
                (
                    [unit_id] => Array
                        (
                            [0] => 10192
                            [1] => 10192
                            [2] => 10192
                        )

                    [born_from] => Array
                        (
                            [0] => 1980-08-21
                        )

                    [born_to] => Array
                        (
                            [0] => 2010-08-18
                        )

                    [start_date] => Array
                        (
                            [0] => 2013-02-21 17:29:00
                        )

                    [sex] => Array
                        (
                            [0] => 3
                        )

                    [id] => 351
                    [product_id] => 1
                    [name] => test1
                )

        )

    [352] => Array
        (
            [0] => Array
                (
                    [unit_id] => Array
                        (
                            [0] => 10192
                            [1] => 10192
                            [2] => 10192
                        )

                    [born_from] => Array
                        (
                            [0] => 1985-01-01
                        )

                    [born_to] => Array
                        (
                            [0] => 2000-01-07
                        )

                    [sex] => Array
                        (
                            [0] => 2
                        )

                    [id] => 352
                    [product_id] => 2
                    [name] => Test2
                )

        )

)

now to convert this array in to xml i have this code
$product_info = array($myPHPArray);

// creating object of SimpleXMLElement
$xml_product_info = new SimpleXMLElement("<?xml version=\"1.0\"?><product_info></product_info>");

// function call to convert array to xml
array_to_xml($product_info,$xml_product_info);

//saving generated xml file
$xml_product_info->asXML('C:/product.xml');

// function defination to convert array to xml
function array_to_xml($product_info, &$xml_product_info) {
    foreach($product_info as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_product_info->addChild("$key");
                array_to_xml($value, $subnode);
            }
            else{
                array_to_xml($value, $xml_product_info);
            }
        }
        else {
            $xml_product_info->addChild("$key","$value");
        }
    }
}

this will give me output like this
<?xml version="1.0"?>
<product_info>
<unit_id>
    <0>10192</0>
    <1>10192</1>
    <2>10192</2>
</unit_id>
<born_from>
    <0>1980-08-21</0>
</born_from>
<born_to>
    <0>2010-08-18</0>
</born_to>
<individual_strdt>
    <0>2013-02-21 17:29:00</0>
</individual_strdt>
<elite_sex>
    <0>3</0>
</elite_sex>
<id>351</id>
<product_id>1</product_id>
<name>test1</name>

// here it stars for 352
<unit_id>
    <0>10192</0>
    <1>10192</1>
    <2>10192</2>
</unit_id>
.
.
.
.
</product_info>

here
1) i cant not identify particular element's value which is 351 and 352
it should like
<?xml version="1.0"?>
<product_info>
    <351>
    //data of 351
    </351>
    <352>
    //data of 352
    </352>
</product_info>

2) when a particular sub array is converted to xml then it is storing data with <0>1092</0> like that which increase my final file's size
3) can i use all this sub array's value as attribute??
4) any other smart way to arrange this data
i am new to xml so any of new idea most welcome


text:
Q: Encounter warning when add edge in OrientDB Here is my Code:
 OrientVertex luca = graph.addVertex(null);
 luca.setProperty("name", "John" + Integer.toString(i));

 OrientVertex marko = graph.addVertex(null);
 marko.setProperty("name", "Van Ness Ave." + Integer.toString(i + 1));

 OrientEdge lucaKnowsMarko = graph.addEdge(null, luca, marko, "knows");
 graph.commit();

Here is a snapshot of the same.
And then, I encountered this warning:

WARNING: The command 'create edge type 'knows' as subclass of 'E''
  must be executed outside an active transaction: the transaction will
  be committed and reopen right after it. To avoid this behavior execute
  it outside a transaction (db=test)

Googling this problem, it seems that this question is relevant to the not-transactional and transactional databases operations.

A: You are working schema less, so OrientDB creates classes for you the first time you create vertexes/edges. In this case it was for the Edge class 'knows'. You can avoid this by creating classes at the beginning, or however, outside the scope of transaction. Try to execute this before your code, only once:
OrientGraphNoTx graph = new OrientGraphNoTx(url);
graph.createEdgeType("knows");
graph.shutdown();


text:
Q: Can images containing single cell be used to train a model to detect and localize multiple cells in the test image I have a dataset containing images, each image has a single cell along with some smaller inconsequential cells in the background. Can this dataset be used to train a model to detect and recognize multiple target cells in a single test image?
Secondly will having a different size of cell in the training data to the size of cells in the test image affect the prediction?

A: This sounds like a multi object detection (MOD) problem. You will need to train a MOD-model such as YOLO or SSD with your images (required format and procedure varies by framework and network architecture), then they should be able to detect multiple instances of the data they were trained on. Whether you train with images containing only one instance or several instances should not make a fundamental difference. Note that the training and inference processes are not easy tasks, however, if you don't have a solid background in neural networks and some programming language (e.g. Python).
I would recommend looking for some blog or youtube tutorials on customized multi object detection and following those.


text:
Q: fatal error: pcap.h: No such file or directory remote: 34 | #include  I'm getting this issue and the most common solution (sudo apt-get install libpcap-dev) isn't working for me.
I'm on a mac and when I try to install it using Homebrew it gives me:
"Warning: No available formula with the name "libpcap-dev". Did you mean libpcap?"
How can I install libpcap-dev and it's dependencies on a mac or work around it?

A:
I'm getting this issue and the most common solution (sudo apt-get install libpcap-dev) isn't working for me.

That's the solution for Debian and Debian-derived Linux distributions such as Ubuntu.  If it's the most common solution, that's probably only because a lot of people use Debian, Ubuntu, or other Debian derivatives.
It is unlikely to work on most other Linux distributions, or on OSes that aren't Linux distributions, as they don't use the Debian package manager, which apt-get depends on.

I'm on a mac

Then you're probably running macOS, not Debian, so the Debian solution will not work for you.

when I try to install it using Homebrew

Note that if you have either Xcode or the command-line compiler tools installed on macOS, that should be sufficient to build software that uses libpcap - libpcap is bundled with macOS, and its header files are bundled with the software development kits that come with Xcode and the command-line compiler tools.
For example:
$ cat foo.c
#include <stdio.h>
#include <pcap.h>

int
main(void)
{
    printf("Hello, world!\n");
    return 0;
}
$ cc -o foo -Os -Wall -W foo.c
$ ./foo
Hello, world!

No "pcap.h: No such file or directory" error there.

when I try to install it using Homebrew it gives me: "Warning: No available formula with the name "libpcap-dev". Did you mean libpcap?"

Homebrew is a package manager that was originally designed for macOS, not for Linux, and doesn't make the same "there's the library package, which installs what's necessary to allow programs using a given library to work, and there's the developer package, which installs what's necessary to allow programs using a given library to be compiled" distinction that some Linux distributions make in their packages.
So it doesn't have separate "libpcap" and "libpcap-dev" packages, it just has a single "libpcap" package, that installs a version of libpcap.
Installing that package means you now have two versions of libpcap - the one Apple provides and the one Homebrew provides.  Unless you need some of the features from the latest version of libpcap that aren't in the version that's provided with the version of macOS you're using, that shouldn't be necessary.
Make sure you have Xcode, or the command-line tools, installed on your Mac, and then you shouldn't get an error reporting that it couldn't find pcap.h, unless there's an error in your program or in the way you're compiling it.  If you're getting an error like that, please indicate what you're compiling, and give the context of that error message, as:

*

*If pcap.h were missing, then Clang (the C compiler that Apple has provided with Xcode for the past several years) will says something such as
program.c:17:10: fatal error: 'pcap.h' file not found
#include <pcap.h>
^~~~~~~~
1 error generated.

*I don't know what the heck "remote: 34" means there, as "remote" isn't the name of a C or C++ or... source file.


text:
Q: Sort an object by the property in form of string Is there any way I can make this work. The portion that isn't working is bolded. Essentially, I am trying to figure out a way to get it to sort by the sortColumn which is passed as a string. It wants o => o.Field not o.String.
internal List<Apps> GetAllApps(string sortColumn)
{
    List<Apps> employeeList = new List<Apps>();

    // Some database operations that fill employeeList
    // with a bunch of objects from a database operations

    if (!string.IsNullOrEmpty(sortColumn))
    {
        employeeList.OrderBy(o => **o.sortColumn** ).ToList();

    }

    return employeeList;
}

A: You can try something like this:
var sortPropertyInfo = typeof(Apps).GetProperty(sortColumn);

employeeList
    .OrderBy(o => sortPropertyInfo.GetValue(o, null))
    .ToList();

Some sanity checks can be added. Alternatively, consider using Dynamic LINQ.

A: You can use reflection
employeeList.OrderBy(o => typeof(Apps).GetMethod(sortColumn).Invoke(o, null) ).ToList();

A: I would prefer using Dynamic LINQ:
internal List<Apps> GetAllApps(string sortColumn)
{
    List<Apps> employeeList = new List<Apps>();
    ...
    if (!string.IsNullOrEmpty(sortColumn))
    {
        employeeList = employeeList.AsQueryable<Apps>()
                                   .OrderBy(sortColumn)
                                   .Cast<Apps>()
                                   .ToList();
    }
    return employeeList;

}


text:
Q: DOMXPath/DOM - Check if can find the element in the DOM Here is my code:

$url = "http://www.sportsdirect.com/football-shirts/premier-league-football-shirts/arsenal-football-shirts";

libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);

$xpath = new DOMXpath($doc);

$n  = $xpath->query('//div[@class="s-producttext-top-wrapper"]');
$l  = $xpath->query('//div[@class="s-producttext-top-wrapper"]/a');
$p  = $xpath->query('//div[@class="s-largered"]');
$im  = $xpath->query('//a[@class="ProductImageList"]');
$ra = $xpath->query('//div[@class="s-producttext-review"]/div');

$nl = $xpath->query('//a[@class="swipeNumberClick"][last()]')->item(0)->C14N();

echo $nl;

How can i check if $nl finds the element in the DOM ?
Thanks in advance!

A: As XPath:query() returns an instance of DOMNodeList, you can check length attribute in order check if any node was found:
$nl = $xpath->query('//a[@class="swipeNumberClick"][last()]');
# or $nl->length > 0
if ($nl->length) {
    $nl = $nl->item(0)->C14N();
}


text:
Q: How to use EmbedObject from Discord Webhook API Well, im using the the https://gist.github.com/k3kdude/fba6f6b37594eae3d6f9475330733bdb API, but when i try to create a EmdedObject over my Mainclass, it willnot work, always a NullPointerException
So, i want to send a message to Discord over Webhook and i already tried just EmbedObject a; but it just says it cant be imported like that.
MainClass.java:

    public static DiscordWebhook dwh;
        dwh = new DiscordWebhook("https://canary.discordapp.com/api/webhooks/AAAAAA/AAAAAAA");
        dwh.setAvatarUrl("https://pbs.twimg.com/profile_images/774033927476420608/ALqUMZi1_400x400.jpg");
        dwh.setUsername("LR-BotTest");

    public static void whenDone() throws InterruptedException, IOException {
        for(Map.Entry<String, String> entry : botstatus.entrySet()) {
            String key = entry.getKey(); //RobotID
            String value = entry.getValue(); //State on/off
            System.out.println("1" + value + key);
            DiscordWebhook.EmbedObject a = null;
            a.setTitle("test");

            if(value.equalsIgnoreCase("online")) {
                dwh.addEmbed(a);
//              dwh.setContent("" + botowner.get(key) + " just went live with " + botnames.get(key) + " https://letsrobot.tv/robocaster/" + botowner.get(key) + "/robot/" + key);
                dwh.execute();
                TimeUnit.SECONDS.sleep(1);
            }
            System.out.println("2" + value + key);
        }
    }

DiscordWebhook.java:
https://gist.github.com/k3kdude/fba6f6b37594eae3d6f9475330733bdb

With code which is shown:
Exception in thread "main" java.lang.NullPointerException
    at ReadJSON.whenDone(ReadJSON.java:61)
    at ReadJSON.main(ReadJSON.java:52)


text:
Q: Error installing gems: cannot load such file -- zlib I'm trying to install bundler gem on Mac OS Yosmite
~/code/hello gem install bundler
ERROR:  Loading command: install (LoadError)
    cannot load such file -- zlib
ERROR:  While executing gem ... (NoMethodError)
    undefined method `invoke_with_build_args' for nil:NilClass

I've done the following:

*

*Install zlib through homebrew

*Upgrade Rubygems

*Reinstall RVM and Ruby 2.2.2

*Switched to Rbenv and Ruby 2.2.2

This is really doing my head in. Ruby 2.2.1 works fine but 2.2.2 causes this issue whenever I try to install a gem.
Anyone got any ideas?

A: Try rvm pkg install zlib
(from this question)
RVM pkg docs: https://rvm.io/packages

It also looks like RVM has a more up to date way of managing packages called autolibs. Check rvm autolibs show, which I hope will be default(enabled) since you just installed. If it's not, rvm autolibs enable, or you can even tell it to use Homebrew instead of its own manager with rvm autolibs homebrew.
RVM autolibs docs: https://rvm.io/rvm/autolibs

A: The following worked for me:
brew install homebrew/dupes/zlib
rvm reinstall 2.2.2 --with-zlib-dir=/usr/local/Cellar/zlib/1.2.8

Hope this helps anyone else who runs into it.


text:
Q: Every ordinal $\alpha>0$ can be expressed uniquely as $\alpha=\omega^{\beta_1}\cdot k_1+\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$
Every ordinal $\alpha>0$ can be expressed uniquely as
$$\alpha=\omega^{\beta_1}\cdot k_1+\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$$
where $\beta_1>\beta_2>\cdots>\beta_n$ and $k_1>0,k_2>0,\cdots,k_n>0$ are finite.

Does my attempt look fine or contain logical flaws/gaps? Any suggestion is greatly appreciated. Thank you for your help!

My attempt:
Existence
Assume that $\xi$ can be expressed as normal form for all $\xi<\alpha$.
Let $\beta=\max\{\xi\in\rm Ord\mid\omega^\xi\le\alpha\}$. Then there is $\delta$ and $\rho<\omega^\beta$ such that $\alpha=\omega^\beta\cdot\delta+\rho$. Since $\rho<\omega^\beta$, $\rho<\alpha$ and thus $\delta>0$. I claim that $\delta$ is finite. If not, $\delta$ is infinite and thus $\delta\ge\omega$. Then $\omega^{\beta+1}=\omega^\beta\cdot\omega\le\omega^\beta\cdot\delta\le\alpha$ and thus $\omega^{\beta+1}\le\alpha$. This contradicts the maximality of $\beta$. Thus $\delta$ is finite. Let $\beta_1=\beta$ and $k_1=\delta$. If $\rho=0$, then $\alpha=\omega^{\beta_1}\cdot k_1$. If $\rho>0$, then $\rho=\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$ for some $\beta_2>\cdots>\beta_n$ and finite $k_2,\cdots,k_n>0$ by inductive hypothesis. We have $\omega^{\beta_2}\le\rho<\omega^{\beta_1}$, then $\beta_2<\beta_1$. As a result, $\alpha=\omega^{\beta_1}\cdot k_1+\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$ as desired.
We observed that $\beta<\gamma\implies\forall k\in\omega:\omega^\beta\cdot k<\omega^\gamma$. This is because $\omega^\beta\cdot k<\omega^\beta\cdot\omega=\omega^{\beta+1}\le\omega^\gamma$. It follows that if $\alpha=\omega^{\beta_1}\cdot k_1+\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$ is in normal form and $\beta_1<\gamma$, then $\alpha<\omega^\gamma$.
Uniqueness
Assume that the normal form of $\xi$ is unique for all $\xi<\alpha$.
Let $\alpha=\omega^{\beta_1}\cdot k_1+\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n=\omega^{\gamma_1}\cdot l_1+\omega^{\gamma_2}\cdot l_2+\cdots+\omega^{\gamma_m}\cdot l_m$. The previous observation implies that $\beta_1=\gamma_1$. Let $\delta=\omega^{\beta_1}=\omega^{\gamma_1}$, $\rho=\omega^{\beta_2}\cdot k_2+\cdots+\omega^{\beta_n}\cdot k_n$, and $\sigma=\omega^{\gamma_2}\cdot l_2+\cdots+\omega^{\gamma_m}\cdot l_m$. Then $\alpha=\delta\cdot k_1+\rho=\delta\cdot l_1+\sigma$ where $\rho<\delta$ and $\sigma<\delta$. Thus $k_1=l_1$ and $\rho=\sigma$. By inductive hypothesis, the normal form of $\rho$ is unique and thus $m=n$, $\beta_2=\gamma_2,\cdots,\beta_n=\gamma_n, k_2=l_2,\cdots,k_n=l_m$. It follows that the normal form of $\alpha$ is unique.

A: "The previous observation implies that $\beta_1 = \gamma_1$." I don't see that. For the existence part, I don't see any errors.
Also, this looks similar to the proof in section 3 of the excelent article "A short introduction to Ordinal Notations", by Simmons. It's freely available online; you should check it out. (Are you doing a thesis on ordinal notations?)
I like Simmon's way of writing the proof because it feels more like an algorithm :-). However, it's basically the same as yours.


text:
Q: Vuejs with ChartJS populate from API How can I populate my chart with the data from my API
<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar } from 'vue-chartjs'
import axios from 'axios'

export default {
data() {
  return {
    dailyLabels: [] ,
    dailyData: []
  }
},
extends: Bar,
mounted() {
  // Overwriting base render method with actual data.
  this.renderChart({
    labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday ', 'Friday', 'Saturday', 'Sunday'],
    datasets: [
      {
        label: 'Daily Students',
        backgroundColor: '#f87979',
        data: [12, 20, 1, 50, 10, 40, 18]
      }
    ]
  })
},
created() {
  axios.get(`https://localhost:44379/api/DailyStudents`)
    .then(response => {
      // JSON responses are automatically parsed.
      this.dailyData = response.data.days
    })
    .catch(e => {
      this.errors.push(e)
    })
}
}
</script>

MY Api returns This:

[
  {"day":"Wednesday","totalStudents":"21"},
  {"day":"Tuesday","totalStudents":"2"},
  {"day":"Thursday","totalStudents":"20"},
  {"day":"Friday","totalStudents":"23"}
]

Days should be my Label and totalStudents my data
the chart should show of course the number of students by day, but the examples that I found are a little bit confusing.

A: You can use Array.map to extract necessary data.
<script>
import VueCharts from 'vue-chartjs'
import { Pie, Bar, mixins } from 'vue-chartjs'
import axios from 'axios'

export default {
  mixins: [mixins.reactiveData],
  data() {
    return {
      chartData: ''
    }
  },
  extends: Bar,
  mounted() {
    this.renderChart(this.chartData)
  },
  created() {
    axios.get(`https://localhost:44379/api/DailyStudents`)
      .then(response => {
        // JSON responses are automatically parsed.
        const responseData = response.data
        this.chartData = {
          labels: responseData.map(item => item.day),
          datasets: [
            label: 'Daily Students',
             backgroundColor: '#f87979',
             data: responseData.map(item => item.totalStudents)
          ]
        }
      })
      .catch(e => {
        this.errors.push(e)
      })
  }
}
</script>

Note that you need to use mixins.reactiveData to make component reactive with data change.


text:
Q: "New style getargs format but argument is not a tuple" Pillow image paste error I'm using the Pillow library to create randomized bingo sheets of Game of Thrones characters for my friends, and created a PNG background sheet to paste thumbnails of the images I found on to. However, when I go to paste my picture of random Game of Thrones character (let's say Arya) onto my background image and define the area used to paste, I get the error "new style getargs format but argument is not a tuple" and the code fails.
I was using Python 3.6.6 and I tried 3.6.5 as well, using both Pip and Conda to reinstall Pillow on each version (now have Pillow 5.1.0 and Pillow 6.0.0) I've tried writing the paste coordinates directly instead of using a variable, and changing the types of image I'm pasting onto and pasting directly from PNG to JPEG to see if that would change the way it defined the coordinates, with no luck.
I've also tried recasting the variable as a tuple although it already is, still didn't work. In the documentation it said if you left the area blank it should automatically past the top left corner to (0,0) but when I do that I get an error telling me to input the box coordinates. It also said if you use a tuple of 2 instead of 4 coordinates it should work, but that returned an error telling me to use a tuple of 4.
bingo = Image.new("RGB",(740,740), color=(10,10,10))

size = 128,128
arya = Image.open("arya_edit.jpg")              #arya 1
arya = arya.thumbnail(size)

box = (10,10,138,138)
#tried box = tuple(box)
bingo.paste(arya, box)

Arya's photo should take up the top left corner of the background image, but just returns the error every time. I don't understand where this error is coming from.

A: The issue with your code isn't with the paste line, but with how you're making your thumbnail. The Image.thumbnail method modifies an Image in place, and returns None, so when you run arya = arya.thumbnail(size), you're overwriting your reference to the newly resized image with None, which is certainly not what you intended.
That None value breaks your later code in the way you have described. You can avoid it by just calling thumbnail without assigning its return value to anything:
arya = Image.open("arya_edit.jpg")
arya.thumbnail(size)               # don't assign here, it modifies the image in place


text:
Q: Datomic v1.0.6202 throws NoSuchMethodError on datomic.api/create-database for :dev storage (io.netty.channel.SingleThreadEventLoop) Attempting to create a database in a local Datomic :dev transactor (v1.0.6202) throws NoSuchMethodError, but in-memory DB works:
(d/create-database "datomic:mem://localhost:4334/test")
=> true
(d/connect "datomic:mem://localhost:4334/test")
=> #object[datomic.peer.LocalConnection 0x3a5266c4 "datomic.peer.LocalConnection@3a5266c4"]

Now let's try against the local :dev transactor running Java 1.8:
(d/connect "datomic:dev://localhost:4334/blog")
=> Execution error at datomic.peer/get-connection$fn (peer.clj:661).
Could not find blog in catalog

;; Let's try to create it:
(d/create-database "datomic:dev://localhost:4334/blog")
Execution error (NoSuchMethodError) at io.netty.channel.SingleThreadEventLoop/<init> (SingleThreadEventLoop.java:65).
'void io.netty.util.concurrent.SingleThreadEventExecutor.<init>(io.netty.util.concurrent.EventExecutorGroup, java.util.concurrent.Executor, boolean, java.util.Queue, io.netty.util.concurrent.RejectedExecutionHandler)'

At first I assumed this was related to my recent question about Datomic transactor requiring Java 1.8 or earlier (v15 fails silently), but this error occurs for all JDKs I tried.
I am using Clojure 1.10.1 and Datomic v1.0.6202 on transactor and dependency in my app.

A: Looks like a Netty conflict from aleph or manifold. I downgraded Aleph and the issue was resolved.
I wish there was a better way to debug these types of conflicts.


text:
Q: Multiple Tomcat instances configuration I have a Windows server that currently runs 2 different Tomcat instances as Windows services. Both have their own directories and don't share any files between them. The first Tomcat instance that was installed via the setup wizard set the CATALINA_HOME and CATALINA_BASE environment variables. The second one was installed in the same manner. It ignores the global settings and runs as a self-contained instance.
Here's the problem. I need to install a product which ships with its own Tomcat. I have finished installing the product but now I need to configure this Tomcat. When I run bin\tomcat7w.exe (the GUI control window) it picks up the settings from the first Tomcat that was installed on this machine. I suspect that it looks at the global CATALINA_HOME and CATALINA_BASE and ignores the fact that its in a different folder. Running bin\tomcat7w.exe in the second Tomcat's directory works as expected, ignoring the global environment variables.
I want tomcat7w.exe in Tomcat 3's directory to control Tomcat 3, not Tomcat 1. How can I configure Tomcat 3 to ignore the global environment variables set by Tomcat 1 and behave like Tomcat 2?

A: I haven't been able to fix the problem regarding the Tomcat monitor, tomcat7w.exe. However, I was able to get Tomcat3 to run. I deleted the global environment variables, CATALINA_HOME and CATALINA_BASE and registered Tomcat3 as a Windows service by using bin\service.bat. service.bat will complain about the missing variables but they can be set for the current session in CMD.


text:
Q: How do I make sure my DNS and domain routing is done properly on Route 53? I recently created a new domain on GoDaddy to which I want to move my current website.
I decided to move the hosting to AWS and create an EC2 Instance there.
Everything was going fine until I purchased the new domain I want to move my website to and started configuring Route 53.
I ended up following a tutorial that said to move the GoDaddy records to Route53 where I had created a hosted zone, so i started doing exactly that. However, the A record pointed to "parked", the 'www' cname record pointed to @ and a '_domainconnect' cname record pointed to _domainconnect.gd.domaincontrol.com'
When creating the new records on Route 53, I changed the 'www' cname record by making it point to my domain 'example.com' so that the www.example.com points to example.com.
I changed the A record so that it points to the IPv4 address on my instance.
Finally, I did not copy the "_domainconnect' record because I thought this was something that had to do with GoDaddy specifically and probably shouldn't be copied (I also did not see it in any tutorial).
Now, there was no problem accessing the website through the www.example.com or example.com domains but after reading multiple tutorials and watching multiple videos, there are 2 things I want to make sure I am doing right:
1- Somebody mentioned the server serving www.example.com and example.com twice and them being 2 separate versions when the previous process is done... I didn't understand what they meant and if this was a problem or not. If someone could clarify this, that would be awesome.
2- Somebody also mentioned using Elastic IPs for Route53 because the instance IPv4 might change? Is that something I should be worrying about if I will be running a website on the instance?
Sorry for the long explanation, I am trying to be as descriptive as possible.
This is the Route 53 Configuration:

A: To better understand point one, if you could attach the route 53 configuration the could hep us giving a better answer.
For the second point, two recommendations.

*

*it is better if you create an Elastic IP and attach to a network interface, then attach the network interface to the instance. In this way the IP would stay forever (or as long as you want). Otherwise, as soon as you restart the instance, and this can definitively happen, you will loose the IP, therefore your DNS needs to be propagated again.

*leave everything as it is, but as a further step learn what an AWS VPC is, it will give you much benefit rather than exposing your instance directly to the internet.