Can a neural network classify a new input in the same coordinate of another but have different output label?

Question: In a 3D model, say we have the following input:
x---y---z---Label
0---0---0---A
1---0---0---A
1---1---0---A
0---1---1---A
1---0---1---B
1---1---1---B
Now, there's a new input that we want to add to the previous data with the (0,1,1) coordinates. If the new input is labeled "A", a NN can easily separate perfectly the data in two classes (a simple regression would do it).
However, if it is labeled "B", we will have two data that have the same coordinates but different labels. How does a NN with, say one hidden layer, deal with this kind of problem?
My guess is that the problem becomes not linearly separable (NN are good with that) however, they are at the same spot so we would not be able to separate perfectly the data between A and B. Am I correct?
Comment: Since the network has to classify that (x, y, z) point one way or another, it can never separately perfectly. See for yourself! Here's a sandbox which lets you add a point right on top of another of the opposite class. https://cs.stanford.edu/people/karpathy/convnetjs/demo/classify2d.html
Answer: The actual problem is not just separability, but conflicting information. When you have it, not only neural nets but any deterministic decision mechanism will produce wrong result for one of the samples. There is no way to deal with it. And, depending on your data or method, sometimes your training example might be classified wrongly while the test sample is being classified correctly.


Passing current_scopes from the has_scopes gem as a param

Question: I've been struggling with this problem for several days. I'm a lawyer and I'm building a Q&A type site for legal advice (yups, I'm a relative newbie to rails :-)).
I want users to be able to filter questions by category (i.e. company law, IP etc etc) and then be able to sort them on a secondary basis by most recent or popular etc.
I've tried a number of approaches and ultimately, I've been unable to find a way to pass the current category selected as another param when trying to sort by recent, popular etc.
I've just started using the has_scopes gem and I see from the documentation that there is a method called 'current_scopes'. I can't seem to work out how to pass current_scopes in the view as a param where the recent or popular scope can then be called on it. Logically, I'm assuming that current_scopes needs to be assigned to a variable in the controller, but again, can't work out how to then pass this in the view as a param.
My current code:
post.rb
    has_many :comments, dependent: :destroy
    belongs_to :user, :counter_cache => true
    belongs_to :category, :counter_cache => true

    scope :recent,      ->{ order("created_at DESC")}
    scope :popular,     -> { order("comments_count DESC")}
    scope :unanswered,  -> {where(comments_count: 0)}
    scope :category, -> category_id {where(:category_id => category_id)}

posts_controller.rb
  has_scope :category
  has_scope :recent, :type => :boolean
  has_scope :popular, :type => :boolean
  has_scope :unanswered, :type => :boolean

  def index
    @posts = @q.result.includes(:comments).order("created_at DESC") #@q comes from using Ransack gem and applying in the application controller
    @posts = apply_scopes(Post).all
    @scope = current_scopes

_sidebar.html.erb

Filter by:

<%= link_to "Show all", root_path %>

<%= link_to "Corporate", category: 1 %>

<%= link_to "Intellectual Property", category: 2 %>

<%= link_to "Employment", category: 3 %>

<%= link_to "Commercial", category: 4 %>

<%= link_to "Real Estate", category: 5 %>

<%= link_to "Venture Capital", category: 6 %>

Sort by:

 <%= link_to "Most Recent", :recent => true %>

 <%= link_to "Most Popular", :popular => true  %>

 <%= link_to "Unanswered", :unanswered => true %>

Thank you and really appreciate any assistance with this matter.
Comment: I'm not a fan of using third party libraries inside controllers: controllers behaviours are usually quite specific and you end up to spend too much time trying to understand what's wrong and adjusting functionalities to your fits (Devise, I hate you more than how much I love you). Are you already coupled to `has_scope` or you could get rid of it?
Comment: Hiya, not coupled to has_scopes at all. This was my third strategy after effort 1 (using just scopes) and effort 2 (using a separate category and filter model) failed. So basically, happy to get rid of it, if it helps solve the problem! :-)
Comment: Very good, thank's!!!
Answer: For anyone else looking for the answer to this question, the current_scopes value is only available after apply_scopes has been called. The issue is documented here.


How to move whole Drupal website on USB for localhost use using XAMPP?

Question: My cPanel subscription will come to an end soon and I want to move my site to a USB stick or CD and still be 'runnable' / executed. It is currently on a cPanel server...
I have seen these options but they all seem outdated and might not be ideal as my website is nearly 300MB in size.

Static Module
uniform server
CD deploy

I want to keep the site static and lose the editing features that come with the modules - essentially I want to freeze what I have done up to now and keep a record of it that will always work locally on a medium.
Comment: There are many ways to do this, and they depend very much on your definition of 'runnable'. Do you only want only to navigate through pages and lose editing options (that is what the proposed modules do)? Or should the content creation side of the website also remain to work (in that case CD is not an option as you need to write changes to the storage medium). And why CD/USB, why not the HDD? These details might help to narrow down the question so it qualifies for reopening.
Answer: If you are married to the idea of running your website via a USB Drive, you can always just download a lamp stack to your computer and configure it to look at usb drive as it's default home directory.
There are several options for this.

Xampp: General one size fits all lamp stack
DEV Desktop: A Drupal specific lamp stack
Mamp
Wamp

This is great for doing dev work on a duplicate copy of a site for testing in order to not screw up the production. The only problem with this is if you are trying to plug the usb to multiple computers you will have download the software each time and configure it look at the usb for it's root directory.
On the plus side using a local lamp stack you won't lose you ability to edit the site. It'll operate exactly the same way. With the exception that ftp ability will vary. Also it's good practice for doing standard Drupal Migrations.
NOTE: I would suggest if you try these options you operate from a desktop and not a USB. The USB could be for just keeping backups.
If this is something you deem acceptable I can expand on this idea.
Comment: Yes please! I am currently following this [link](http://www.howtogeek.com/howto/14998/turn-your-flash-drive-into-a-portable-web-server/) to install xampp on my USB --- My main concern is on how to move an existing site (i.e. as the site is at the moment) after I install Drupal on the USB... I have the backup and migrate module installed currently on it do I use this to help me? http://i.imgur.com/s1qbABn.png
Comment: @user2326637 So there's a few steps you need to take.

Obviously you need to get xampp to run from your USB. I Personally have never achieve this but I hear it's possible.

Next you should set up a **virtual host**. This basically means that you designate a directory to act as the root directory for a fake domain name you create. For example mydrupalsite.local can be typed into any browser on that computer and it will run your site.

Last thing you do is a standard drupal migration. Details how to this can be found here. [Migrating a site](https://www.drupal.org/node/776864)
Comment: @user2326637 The quick and dirty step by step guide to installing drupal is. 1. Export old site's database using _backup and migrate_ module and zip/compress site files. 2. Unzip site files on root of new website. 3. Complete basic configuartion drupal on new site. 4.Turn on _backup and migrate_ module and import old site database export. 5. Clear all caches
Comment: @user2326637, Just checking up. How did this work for you?
Comment: Sorry for the late reply - was called on other projects but Im back on this one now --- I have successfully made XAMMP work on the USB - I have installed a clean version of Drupal 7.43 on it... Do I just copy my site's folder from cPanel to the correct directory on the USB (with matching sql table in phpmyadmin) or is there something else (or better methods to use) I was thinking to install backup and migrate on the fresh install and upload my files via that... thanks
Comment: @user2326637 If you already have a fresh copy of Drupal 7 installed and it's working. Next I would move my /sites/default/files directory from cPanel to the appropriate folder on your usb. Then I would move all the modules, themes, and libraries from the /sites/all folder. This should make the Backup migrate module available to be enabled. Enable that module and restore your exported database file.

That should be it. Unless you have a multisite. That setup is a little above my head.
Comment: after many attempts I eventually managed to do just what you said above! Many thanks for your help! + great accepted answer!


animated NetworkX Graph in TkCanvas: background color

Question: For a demonstration of a Graph algorithm i need to draw a networkx graph to a Tkinter Canvas and be able to modify that graph (and the plot) at runtime.
I have pieced together the following code (I hope it is the minimal code leading to my problem, but I'm new to this so I'm not sure):
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import Tkinter as Tk
import networkx as nx
from tkMessageBox import showinfo

root = Tk.Tk()
root.wm_title("Animated Graph embedded in TK")
root.wm_protocol('WM_DELETE_WINDOW', root.quit())

f = plt.figure(figsize=(5,4))
a = f.add_subplot(111)
plt.axis('off')

# the networkx part
G=nx.complete_graph(5)
nx.draw_networkx(G,pos=nx.spring_layout(G),ax=a)

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def next_graph():
    if G.order():
        a.cla()
        G.remove_node(G.nodes()[-1])
        nx.draw(G, pos=nx.circular_layout(G), ax=a)
        canvas.draw()

b = Tk.Button(root, text="next",command=next_graph)
b.pack()

Tk.mainloop()

My problem now is this:
The first display of the graph is like I want it (backgroundcolor-wise), but after you first click 'Next' the backgroundcolor of the graph changes to white. I have tried changing the background color of the figure and the canvas.
I don't even know what brings that change about, I think it is simply drawing to the same canvas twice.
How can I modify the code to have the graph always have the same background color?
On an unrelated note: the root.quit() I added does not help in ending the application properly. This might be stupid on my side, but what did go wrong here?
Comment: also, Welcome to SO!.  You should also split your question about `root.quit` into a new question to keep things tidy.
Comment: I'm aware it's terrible style, I tried to remove some of the clutter code needed to describe the main problem here so that I could give a good code example for a different question. The funny thing is: the weird behavior (script not closing on closing the window with 'WM_DELETE_WINDOW') stopped once I removed the part about the graph and the canvas. So a added it here in case there are any takers ;)
Answer: I think you are very close.  If you use nx.draw_networkx() in your event loop then it works (turn off the axis there too).
Here is your example with those modifications and also with a single layout computed at the beginning that is reused in the loop:
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import matplotlib.pyplot as plt
import Tkinter as Tk
import networkx as nx
from tkMessageBox import showinfo

root = Tk.Tk()
root.wm_title("Animated Graph embedded in TK")
# Quit when the window is done
root.wm_protocol('WM_DELETE_WINDOW', root.quit)

f = plt.figure(figsize=(5,4))
a = f.add_subplot(111)
plt.axis('off')

# the networkx part
G=nx.complete_graph(5)
pos=nx.circular_layout(G)
nx.draw_networkx(G,pos=pos,ax=a)
xlim=a.get_xlim()
ylim=a.get_ylim()

# a tk.DrawingArea
canvas = FigureCanvasTkAgg(f, master=root)
canvas.show()
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)

def next_graph():
    if G.order():
        a.cla()
        G.remove_node(G.nodes()[-1])
        nx.draw_networkx(G, pos, ax=a)
        a.set_xlim(xlim)
        a.set_ylim(ylim)
        plt.axis('off')
        canvas.draw()

b = Tk.Button(root, text="next",command=next_graph)
b.pack()

Tk.mainloop()

Comment: Thanks a lot, that helped. Works like a charm now. Did I misinterpret the use of the 'draw' method or is this behavior just unexpected?
Comment: @DaniGehtdichnixan If this answer solved you problem you should accept (and maybe upvote) it.
Comment: @tcaswell: accepted it (somehow didn't take the first time around), upvoting is not yet possible with my reputation :) guess i gotta work on that.
Comment: @DaniGehtdichnixan  The draw() function sets the axis off and the figure background color to white- then calls draw_networkx().  So skipping those parts and caling draw_networkx() directly was what you needed.


Pyqgis code for generating themes for each layer group

Question: Based on
https://gis.stackexchange.com/questions/428662/how-to-add-a-layer-to-a-maptheme-in-qgis-with-pyqgis
and
https://gis.stackexchange.com/questions/364733/automatically-creating-themes-in-qgis-3-x
I wrote two Pyqgis codes for generating themes for each layer group. Both are not working.
Which one shows a possible solution and were is the mistake (2 is my favorite)?
1.
<code>root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()

for group in groups:
       group.setItemVisibilityChecked(True)
       layersToChanges = group.findLayers()
       for layer in layersToChanges:
    for child in root.children():
        if isinstance(child, QgsLayerTreeGroup):
            print("- group: " + child.name())
        elif isinstance(child, QgsLayerTreeLayer):
            print("- layer: " + child.name() + "  ID: " + child.layerId())
            # Layer you want to tick
            if (child.name() == layer):
                child.setItemVisibilityChecked(True)
                print("Check only once")
            elif child.name() in layersToChanges:
                child.setItemVisibilityChecked(False)
                print("Check the others you want to hide")
    mapThemeRecord = QgsMapThemeCollection.createThemeFromCurrentState(
        QgsProject.instance().layerTreeRoot(),
        iface.layerTreeView().layerTreeModel()
    )
    mapThemesCollection.insert(layer, mapThemeRecord)
</code>
2.EDIT:
<code>#Variables: Groups, project layer
root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()
AllLayers = root.findLayers()

#Visibilities
for layer in AllLayers:
    layer.setItemVisibilityChecked(False)
for group in groups:
    group.setItemVisibilityChecked(False)

for group in groups:
    group.setItemVisibilityChecked(True)
    groupLayers = group.findLayers()
    for groupLayer in groupLayers:
        groupLayer.setItemVisibilityChecked(True)

#Set themes for each group
    mtc = QgsProject.instance().mapThemeCollection()
    theme_name = str(group)
    theme_state = mtc.mapThemeState(theme_name)
    layer_record = QgsMapThemeCollection.MapThemeLayerRecord()
    theme_state.addLayerRecord(layer_record)
    group.setItemVisibilityChecked(False)
</code>
Answer: This made it:
<code>#Variables: Groups, project layer
root = QgsProject.instance().layerTreeRoot()
groups = root.findGroups()
AllLayers = root.findLayers()
mapThemesCollection = QgsProject.instance().mapThemeCollection()

#Visibilities
for layer in AllLayers:
    layer.setItemVisibilityChecked(False)
for group in groups:
    group.setItemVisibilityChecked(False)

for group in groups:
    group.setItemVisibilityChecked(True)
    groupLayers = group.findLayers()
    for groupLayer in groupLayers:
        groupLayer.setItemVisibilityChecked(True)
#Set themes for each group
    mapThemeRecord = QgsMapThemeCollection.createThemeFromCurrentState(
    QgsProject.instance().layerTreeRoot(),
    iface.layerTreeView().layerTreeModel())
    mapThemesCollection.insert(str(group), mapThemeRecord)
</code>
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Joins: How to Return default values for empty right side of left outer join

Question: In my Oracle DB, I have a left outer join for a parent workorder to its child workorders. I then run a calculation performing a SUM() of some of the child values. I wrap the results from the child workorders in Nvl() to ensure they'll be calculated correctly.
This works, except when there are no child workorders for the parent. In this case, the "nulls" returned during display are because there are no results in the join, and thus it appears that Nvl([fieldname],0) doesn't convert them to show 0. Thus, when I think sum the child values with the parent values, they also return null due to adding a value to a null value.
What's the best way to get around this? Is this something that can be worked around or is it a smell that something is wrong with my query fundamentally?
The Query
Sorry, I'm not able to post a setup for it at the moment. For this specific workorder (hard-coded), the "right hand" part of the join is empty because the parent has no children, and thus displays null.
SELECT *
FROM   (SELECT *
        FROM   R_PCR_ALLWOSANDTASKSSEPARATELY)WOINFO
       LEFT OUTER JOIN (SELECT WORKORDERNUMBER                AS TASKWORKORDRENUMBER
                               , PARENT                       AS TASKPARENT
                               , NVL(TOTALMATESTCOSTFORWO, 0) AS TOTALMATESTCOSTFORWO_TASK
                               , NVL(TOTALLABESTCOSTFORWO,0)         AS TOTALLABESTCOSTFORWO_TASK
                               , NVL(TOTALMATACTCOSTFORWO,0)         AS TOTALMATACTCOSTFORWO_TASK
                               , NVL(TOTALLABACTCOSTFORWO,0)         AS TOTALLABACTCOSTFORWO_TASK
                               , NVL(TOTALLABACTHOURSFORWO,0)        AS TOTALLABACTHOURSFORWO_TASK
                        FROM   R_PCR_ALLWOSANDTASKSSEPARATELY)TASKINFO
         ON ( WOINFO.WORKORDERNUMBER = TASKINFO.TASKPARENT )
WHERE  WORKORDERNUMBER = '2826059';

Answer: You need to apply NVL after the results are returned by LEFT join.
Try this:
SELECT  WOINFO.*
                , TASKWORKORDRENUMBER
                , TASKPARENT
                , NVL(TOTALMATESTCOSTFORWO_TASK,0) AS TOTALMATESTCOSTFORWO_TASK
                , NVL(TOTALLABESTCOSTFORWO_TASK,0) AS TOTALLABESTCOSTFORWO_TASK
                , NVL(TOTALMATACTCOSTFORWO_TASK,0) AS TOTALMATACTCOSTFORWO_TASK
                , NVL(TOTALLABACTCOSTFORWO_TASK,0) AS TOTALLABACTCOSTFORWO_TASK
                , NVL(TOTALLABACTHOURSFORWO_TASK,0) AS TOTALLABACTHOURSFORWO_TASK
FROM   R_PCR_ALLWOSANDTASKSSEPARATELY WOINFO
       LEFT OUTER JOIN (SELECT WORKORDERNUMBER                AS TASKWORKORDRENUMBER
                               , PARENT                       AS TASKPARENT
                               , TOTALMATESTCOSTFORWO_TASK
                               , TOTALLABESTCOSTFORWO_TASK
                               , TOTALMATACTCOSTFORWO_TASK
                               , TOTALLABACTCOSTFORWO_TASK
                               , TOTALLABACTHOURSFORWO_TASK
                        FROM   R_PCR_ALLWOSANDTASKSSEPARATELY) TASKINFO
         ON ( WOINFO.WORKORDERNUMBER = TASKINFO.TASKPARENT )
WHERE  WORKORDERNUMBER = '2826059';

Comment: Or COALESCE. And now something to make the comment big enough.
Comment: Yep! That was absolutely it. Completely obvious, too, but not so much after a long day of staring at SQL. Thanks!


Batching a bash array by an arbitrary number and store results in another array

Question: Suppose you did something simple like this in a BASH shell script:
folders=$(find "$1" -type d)

Against the root of a volume with 100,000s of thousands of folders and you want to perform some form of operation against them but in a batch fashion.
Is it possible, without enumerating with lots of code, to batch an array into an array of arrays, each consisting of 10 - or whatever - or in the last array maybe less?
Thanks,
Lee
EDIT for Cyrus
folders=('/Volume/Data/1'. '/Volumes/Data/1', '/Volumes/Data/1/A', 'Volumes/Data/1/B', '/Volumes/Data/1/C')

Batched version based on a batch site if twi (syntax could be totally incorrect and not supported, I'm a total BASH noob):
foldersBatched=(('/Volume/Data/1', '/Volumes/Data1/1'), ('/Volumes/Data/1/A', 'Volumes/Data/1/B'), ('/Volumes/Data/1/C'))

Comment: Please add sample input and your desired output for that sample input to your question.
Comment: First, you shouldn't do `folders=$(find "$1" -type d)` as this variable is unusable (in case of filenames with newlines). There's very likely a much better way to proceed. What do you want to do with these directories?
Comment: Please would you explain further @gniourf-gniourf since I'm dealing with directories not filenames.   Thanks.
Comment: Ok @Cyrus... lets base the batch size on 2 for simplicity (laziness)
Comment: When I say filename I mean filename or directory name or device name or link name, etc. Now you should know that Bash _does not_ support arrays of arrays. What are you trying to _do_ with these directories?
Answer: bash does not support multidimensional arrays.
Comment: `for i in $(find …)` is broken in case of filename with spaces or glob characters!
Comment: Well, if your only purpose it to spread bad practices and broken code, you'd better leave SO. But how about you learn from us? I actually told you _why_ your code is broken (I'm not harassing, rather I'm explaining). Now _This is common code in nearly every operating system_ well… I hope it's not, otherwise nearly every operating system is broken `:)`. [Here's a good link that explains why you shouldn't parse `ls`—and it also mentions why `for i in $(find …)` is bad](http://mywiki.wooledge.org/ParsingLs).
Comment: Thanks for the link @gniourf_gniourf.  The purpose of this is to move a  very large number of files and folders (Terabytes of data) from my local storage to the cloud via ExpanDrive (mounts a cloud service as a drive).   The problem being ExpanDrive caches the transfer on the OS drive and brought the whole system down by leaving just 1.24GB  free on that drive.  Despite having symmetric Gigabit it couldn't move the files fast enough.  So my idea is to send batches to the cloud, keep checknig/sleeping until the batch has been uploaded (i.e. cache folder is empty) and then send the next batch.
Answer: #!/bin/bash

folders=$(find $1 -type d)

#associative memory
typeset -A Tab
#max col
iMaxCol=10

iLg=0
iCol=0
for fold in ${folders}
do
 Tab[${iLg}_${iCol}]=${fold}
 iCol=$(( iCol + 1 ))
 if [ ${iCol} -eq ${iMaxCol} ] ; then
   iLg=$(( iLg + 1 ))
   iCol=0
 fi
done

#Like Tab[0][0]
echo ${Tab[0_0]}
#Like Tab[0][9]
echo ${Tab[0_9]}
#Like Tab[1][5]
echo ${Tab[1_5]}


Consumindo API Externa Java Spring Boot - JSON retornando nulo

Question: Estou iniciando meus estudos em Spring e estou tentando consumir uma API Externa, tudo parece estar "Ok", mas o retorno do JSON está nulo, alguém poderia me aujdar, pra ontem?
Art Institute of Chicago API: https://api.artic.edu/docs/#quick-start
Minha classe controller
@RestController
@RequestMapping("/controller")
public class ArtworkController {

    @Autowired
    private ArtworkService artworkService;

    @ResponseBody
    @GetMapping(value="/getArtwork/{id}")
    public ResponseEntity<ArtworkDTO> getArtwork(@PathVariable("id") int id){
        ArtworkDTO artworkDTO = artworkService.getArtwork(id);
        return new ResponseEntity<ArtworkDTO>(artworkDTO, HttpStatus.OK);
    }
}

Classe Service
@Service
public class ArtworkService {

    public ArtworkDTO getArtwork(int id){
        return new RestTemplate()
                .getForEntity("https://api.artic.edu/api/v1/artworks/"
                        +id+"?fields=id,title,artist_title", ArtworkDTO.class).getBody();
    }
}

Classe DTO
@JsonIgnoreProperties(ignoreUnknown = true)
public class ArtworkDTO implements Serializable {

    private int id;
    private String title;
    private String artist_title;

    public int getId() {
        return id;
    }
    public void setId(int id) { this.id = id; }
    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getArtist() {
        return artist_title;
    }
    public void setArtist(String artist_title) {
        this.artist_title = artist_title;
    }
}

Retorno do JSON
{
"id": 0,
"title": null,
"artist": null
}

Comment: Não escrevam **Resolvido** no título das perguntas, isso interfere com nosso sistema indexação. Para indicar que uma pergunta foi solucionada apenas [aceitem uma resposta](https://pt.meta.stackoverflow.com/q/1078/137387) como foi feito aqui.
Comment: Certo, Augusto. Obrigado pela orientação!
Answer: Os campos da api artic estão vindo dentro de um outro objeto chamado data.
{
    "data": {
        "id": 12996,
        "title": "Nathanael Dilgerus",
        "artist_title": "Gérard Edelinck"
    },
    "info": {
        "license_text": "The data in this response is licensed under a Creative Commons Zero (CC0) 1.0 designation and the Terms and Conditions of artic.edu.",
        "license_links": [
            "https://creativecommons.org/publicdomain/zero/1.0/",
            "https://www.artic.edu/terms"
        ],
        "version": "1.4"
    },
    "config": {
        "iiif_url": "https://www.artic.edu/iiif/2",
        "website_url": "http://www.artic.edu"
    }
}

O json acima foi retornado a seguinte chamada.
curl --location --request GET 'https://api.artic.edu/api/v1/artworks/12996?fields=id,title,artist_title'

Sugestão de alteração para o seu dto
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;

import java.io.Serializable;

@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
public class ArtworkDTO implements Serializable {
    private Data data;
}

@Getter
class Data {
    @JsonAlias(value = "id")
    private int id;
    @JsonAlias(value = "title")
    private String title;
    @JsonAlias(value = "artist_title")
    private String artistTitle;
}

Comment: Cara, funcionou. Eu tinha em mente que o problema poderia ser isto, mas ainda não sabia como resolver. Muito obrigado.


A diificulty in understanding a formula in Petrovic.

Question: Here is below: if we know that $\theta_{n}$ and $c_{n}$is defined as below

How is the two lines containing  $\theta_{n}$ below produced? I feel there is something wrong.
Answer: Assuming lemma $1.5.6$ to be correct.
Correction:
\begin{align}
\frac{\theta_n }{n!}  &= \frac{(e-c_n)n!}{n!}\\
&=  e-c_n \\
&= \frac{m}{n}-c_n
\end{align}
Now multiply $n!$ to both sides
$$\theta_n = n!\left(\frac{m}{n}-c_n \right)$$
Now by Lemma $1.5.6$, the LHS is between $0$ and $1$ but the RHS is an integer.
Remark:
Another possibility is in lemma $1.5.6$, he intended to define $\theta_n = (e-c_n)(n+1)!$. Notice that if $(e-c_n)(n+1)! \in (0,1)$ then we have  $(e-c_n)n! \in (0,1)$.
Comment: So $(n+1)!$ is a typo..?
Comment: Seems like it isn't it if the lemma is true?
Comment: Fine..........!
Comment: Another possibility is perhaps there is mitake in lemma $1.5.6$ or if I make a mistake (could be)


Prove $\int_0^1 | \Sigma_{k=1}^N a_k e^{2\pi i k \theta}|d \theta \geq 1$

Question: Suppose $a_1,...a_N$ are complex numbers with $|a_i|=1$ for $i=1,....N$. Prove that:
$\int_0^1 | \Sigma_{k=1}^N a_k e^{2\pi i k \theta}|d \theta \geq 1$
My attempt:
I know that $\int_0^1 e^{2 \pi i k \theta} d \theta = 1$ if $k=0$ and equals $0$ if $k \neq 0$ otherwise.
I'm trying to use the fact that if $f \in L^1 \cap L^{\infty}$ then $f \in L^2$ and $||f||_2^2 \leq ||f||_1||f||_{\infty}$
I'm stuck in tunnel vision.. Could use a new perspective!
Answer: I think you can also show this by the triangle inequality for integrals. First, I claim that
$$  | \sum_{k=1}^N a_k e^{2\pi i k \theta}|=| \sum_{k=1}^N a_k e^{2\pi i (k-1) \theta}|\cdot \vert e^{2\pi i\theta} \vert= | \sum_{k=1}^N a_k e^{2\pi i (k-1) \theta}| .$$
Thus our integral equals
$$ \int_0^1 | \sum_{k=1}^N a_k e^{2\pi i(k-1)\theta}|d \theta \geq \Big\vert \int_0^1  \sum_{k=1}^N a_k e^{2\pi i (k-1) \theta}d \theta \Big\vert =|a_1|=1. $$
I'm not completely sure about this argument, since it seems to work whenever one of the $a_i$-s have absolute value one.
Comment: Good argument, +1. I edited it to shorten it, because it's very simple. Your last line: There is no problem; all we need is that $|a_1|=1$
Comment: Okay, good to know.
Answer: Your idea is pretty good. Note that
\begin{align}
\int_0^1 \left|\sum_{k=1}^N a_k e^{2\pi i k\theta} \right|^2\textrm{d}\theta &=\int_0^1   \left(\sum_{k=1}^N a_k e^{2\pi i k\theta}\right)\left(\sum_{j=1}^N \overline{a_j} e^{-2\pi i j\theta}\right)\textrm{d}\theta\\
&= \sum_{j,k=1}^N \int_0^1 a_k \overline{a_j} e^{i(k-j)\theta}\textrm{d}\theta \\
&= \sum_{k=1}^N |a_k|^2=N
\end{align}
By your observation. Furthermore, by your inequality, we have
$$
N=\int_0^1 \left|\sum_{k=1}^N a_k e^{2\pi i k\theta} \right|^2\textrm{d}\theta \leq \left\| \sum_{k=1}^N a_k e^{2\pi i k\theta} \right\|_{\infty} \int_0^1 \left|\sum_{k=1}^N a_k e^{2\pi i k\theta} \right|\textrm{d}\theta
$$
Since $\left\| \sum_{k=1}^N a_k e^{2\pi i k\theta} \right\|_{\infty}\leq \sum_{k=1}^N |a_k|=N,$ you get your result.


bV substitution in ii V I

Question: So I have been playing around with the good'ol ii V I standard and I have found, just by playing around, that instead of going to the V, it sounds odd, but you can substitute it for a bV.
Key: D
Normal:

iim - Vmaj - Imaj | Em - Amaj - Dmaj

Substituted:

iim9 - bV7 - Imaj7 | Em9 - Ab7 - Dmaj7

Can we even use this substitution or am I just hearing things? :^)
If this does work,
Why can we substitute the V for bV?
Does this substitution work for every perfect cadence?
Comment: I have seen this chord, but as a tritone sub of I7 leading to IV.
Comment: VMaj?!  This is quite unusual for a ii V I. Normally you have a V7. Where did you find this? Also what mode do you plan on the bV7?
Comment: @gurneyalex Not very unusual. It is actually the most basic version of ii V I. Who says you need tension to complete a V-I?
Comment: Do you play any tensions on the Ab7?
Comment: @DisplayName my bad, I read Maj7.
Comment: @MattL. Yes but I made it simple as possible for explanation purposes. :)
Comment: But if you let us know the tensions that you play it might be easier for us to understand how to interpret that chord.
Answer: This is actually something that I stumbled upon a few years back and explored quite a bit, even extending it to a VI-II-V-I with bVI(minor or dominant)-II-bV-I.  I think the sound is very interesting and clearly not common, so it has some unique characteristics compared to most of what we hear.  There are, however, a few issues with treating this as a true substitution in the same sense as a tritone substitution.  I would define a true substitution as an alternate chord to be used in place of another that would serve the same function; this substitution would also be able to be used in most songs/pieces without disrupting the function or melody.
The reason a tritone substitution works so well is that it shares the same guide tones as the chord it is substituting (G7 guide tones: B, F; Db guide tones F, Cb (enharmonically equivalent to B).  Because of this, the voice leading works the same for the ever important tritone of 7 and 3.  This allows the substitution to have the same function without taking away from the important resolution.
When using bV, the guide tones are also a half-step lower, which changes the notes that cause the tension that will resolve to the following chord.  This resolution is less strong, largely because the leading tone is no longer a part of the chord but also because of the voice leading.  With traditional Jazz voicings in a II-V-I, each guide tone's line will follow a pattern of moving down by step, then held as a common chord tone, or vice versa (slightly different with the resolution to minor where both guide tones move down by step when resolving to I).  For example, a II-V-I in C would have guide tones: C-B-B; F-F-E.  When we substitute bV, the guide tone line starting on C would be: C-Bb-B (the other guide tone line still holds the pattern with F-E-E).  This disrupts the linear motion that the guide tones usually create in a II-V-I, taking away from its smoothness.  So the combination of no leading tone and the lack of linear motion in the guiding voices ends up disrupting the smooth motion that a typical II-V-I has, as well as having a less strong resolution to tonic.
Speaking to the melodic aspect, the bV brings a lot of issues in terms of a true substitution.  The tritone sub doesn't have this issue because it ends up just creating an Alt7 chord, with all of the diatonic notes from the key still being chord tones/alterations; the only diatonic note that is not accounted for in the tritone sub is the tonic, which is usually not a melodic note over a V anyway.  This means that any diatonic melody can use a tritone sub in place of the V.  With bV, you end up having some important melodic notes not being able to be properly harmonized within a diatonic melody, specifically ^7 and ^4, the two strongest tendency tones.
That's essentially my case against bV being a true substitution but I wouldn't say that I'm against its use, in fact I have written many songs including this chord and love how it sounds.  The main issue that I have faced is trying to write a nice melody that goes along with the changes.  This stems from the fact that the bV is derived from the major scale a half-step below the tonic.  This sort of tonal relationship only has two notes in common, ^7 and ^3 of the tonic key, and ^7 is not properly harmonized by the bV chord.  You can alter the bV and get ^2, ^5 and ^6 as common tones, which helps, but I still find that the melodies I was able to come up with did not sound very nice to me, presumably because of the dissonant nature of the harmony combined with the weakened resolution.
I also found that I liked the resolution to minor better than major, which I attribute to the voice leading being more smooth.  This also made the bVI-II relationship that I referenced at the beginning of this answer seem more at home, as the standard in minor is to use a bVI, though in my case I used a dominant or minor chord instead of the expected maj7.
I've also seen bV in some Jazz songs as part of a sequence (though I can't remember which): II-V-bII-bV-I.  It's arguable as to the functionality of the bV being a substitution for V here and instead thinking of it just as a sequence.  I also believe that Debussy's Prelude to Afternoon of a Faun uses a bV as a substitution but I would argue this is not a true substitution, as it is specific to that piece, not a concept that can be applied in all settings.
I always like to remind people that theory is not a set of rules; it is an explanation.  As such, you can do whatever you want, wherever you want, as long as it sounds good.  If it sounds good to others and you gain some sort of audience, your approach here could end up creating new theoretical concepts.  I clearly referred to things using words like 'properly', which may sounds like it subverts what I'm just now saying, but ultimately theory becomes rules when applied to specific genres and idioms.  So my use of 'properly' and such is basically just referring to how things are handled in a traditional approach to Jazz.  So be creative and write these songs but you just need to be aware of how using any sort of substitution in a more traditional setting can cause some issues with functionality and harmonic consistency that may subvert the idiom you are performing/writing within.
Comment: This answer is so on-point! I understood everything you said. It's nice to know there is someone on here who understands. Thank you so much!
Comment: Glad to provide some insight.  I realize now that I didn't really speak to minor tonality much in this answer but the same thought process can be applied there and have the same sort of results.  I tend to be long winded, so I think it's best that I didn't go into minor with the same depth.
Answer: Em9 A7 AbV7 makes some sense: A7 in this context is a tritone substitution of the Eb7 going to AbM7, which is swapped with Ab7 upon landing.
Then Ab7 is the tritone substitution of D7. Swapping D7 with DM7 is going to sound weird (definitely weirder that the other way round) and not a very satisfactory resolution but it is conceivable.
In any case this is not in my list of "usual substitutions" but I reckon it can work.
Comment: It's not Coltrane changes. You'd have E- A7 |  D  | D | -> E- F7 | Bb Db7 | F# A7 | D
Answer: maybe if you try to see chords notes you can find some analogy.
Usually V substitution is to its tritone, so in your case is EB: Eb-G-Bb-Db(-F-Ab). Now Ab: Ab-C-Eb-G-(Bb-Db). Then it can be Eb7-11 > Ab7-9-11, in this case Ab7-9-11 shares 5 notes with Eb7-11, but in different position.
Conceptually, I think that any chord could be superimposed to another when adding 9-11-13, it depends on how it sounds and... mainly on who is playing it!
Music is full of transgress rules, which really build its theory and history.
Hope this helps.

bV substitution in ii V I


How to notify a UWP app that its secondary tile has been removed (unpinned) by the user?

Question: In Windows 10, an app can pin secondary tiles to the start menu.
How is the app notified when the user removes (unpins) such a tile?
Answer: You can query the API to see if the tile exists when you need to present information:
<code>// Check if the secondary tile is pinned
bool isPinned = SecondaryTile.Exists(tileId);
</code>
That's all, there is no notification: https://learn.microsoft.com/en-us/windows/uwp/design/shell/tiles-and-notifications/secondary-tiles-pinning
Comment: So there is no callback that the user has removed the tile? So if the tile is no longer there, and it should be, I can assume that it has been removed...  huh.

Thanks


jQuery doesn't work on page loaded by ajax

Question: My jQuery code:
var menu = 0;
var link = "";
var column = 2;

jQuery( document ).ready( function($) {
$('body').css('height', $(window).height());
$('body').css('width', 32 + (230*column));

$(".button").click(function(event) {
    event.preventDefault();
    link = $(this).find('a').attr("href");

    $("#menu").css({'left':event.pageX});
    $("#menu").css({'top':event.pageY});
    $("#menu").find('#gotosite').attr("href", link);
    $("#menu").slideDown();
    menu = 1;
});

$("#zamknij_menu").click(function(event) {
    event.preventDefault();
    $("#menu").slideUp();
    menu = 0;
});

$("#zbadaj_element").click(function(event) {
    event.preventDefault();
    $("#menu").slideUp();
    menu = 0;
    $("body").append("
");
    $("#" + column).html('
Loading... Please Wait
');
    $("#" + column).load("robotone.php?url=" + link);

    column++;
    $("body").append("
");
    $('body').css('width', 32 + (230*column));
});

$("#openhelp").click(function(event) {
    $("#legend").slideToggle('slow', function() {
    // Animation complete.
  });
});
});

This script append div with class column to body and load into it php file. This script work properly with html document, but doesn't work for new columns which were added by this script. Can you help me?
Answer: Sice those are added dynamically do Event Delegation.
Example:
$(document).on("eventname",'.selector', function(event,ele){
 //Your code goes here
});

http://api.jquery.com/on/
Answer: When you add new HTML elements to the DOM after you've bound your events, those new elements won't be bound.  The jQuery .on function is designed to address this.  It works in a slightly different way.
Events in the DOM "bubble up" to their parent elements (unless explicitly told not to in code, which you don't appear to be doing).  So, when you "click" an element, you also "click" its parent element, that element's parent, and so on, all the way up to the body element and, ultimately, the document.  Thus, you can also bind to those parent elements to respond to a click.
The .on function does just that, and includes a filter to only respond to events raised to that parent element which are from a specific selector.  So, instead of binding to the child element itself, you can bind to a common parent.  body or document are often used for this purpose.  Something like this:
$(document).on('click', '.button', function () {
    // your event handling code
});

This binds to the click event of document, but only responds to that event if the originator of the event was of class button.  The end result is the same as if you bound to the click event of the elements of class button, but with two distinct differences under the hood:

You only create one event on the DOM, instead of one for every element of class button.  If you have many elements, this results in improved performance.
Any elements of class button added to the DOM after this event is bound are still affected.  As long as they're a child of the common parent (in this case they are, everything is a child of document), then their event will still "bubble up" to that parent.  This is often referred to as "deferred events."  Essentially, you can add all the elements you want and they'll still be responded to.
Answer: You need to add 'on' in every event say for ex.,
$(".button").on('click',function(event) {
    // code
});

Follow this way
Comment: This won't catch new added elements of the `.button` class because it still binds directly to them instead of to a common parent.
Answer: $(selector).click(...) appends the clickHandler only to the domElements that are already exisiting, you should use $(selector).on('click', function(){...}); to append the handler also to elements that will be inserted later on...


Probability of find finding girl from arts or science stream

Question: There are $40\%$ science students and the remaining are $60\%$ are arts students. It is known that $5\%$ of science students are girls and $10\%$ of the arts students are girls. One student selected at random is a girl. What is probability that she is an arts student?
A girl is randomly selected and there are total $15\%$ girls out of which $10\%$ of girls are from the arts stream, so the probability that she is an arts student$=\frac{10}{15}=\frac{2}{3}$, but it's wrong. Please help.
Comment: That's a very poor title up there!
Answer: Let $G$ represent the event "a girl is selected" and let $A$ be the event "an arts student is selected". Then, obviously, $\neg G$ is the event "A boy is selected" and $\neg A$ is the event "a science student is selected".
What you need to calculate is the probability
$$P(A|G)$$
Using Bayes's formula, you know that $$P(G|A) = =\frac{P(G|A)\cdot P(A)}{P(G)}$$
Now, what are the missing numbers? Well, $P(G|A)$ is the probability of selecting a girl if you know you selected an arts student, meaning that's $0.1$ ($10\%$). $P(A)$ is the probability of selecting an arts student, that's $0.6$, i.e. $60\%$.
The probability that a random student is a girl is trickier, but you can use total probability:
$$P(G) = P(G|A)\cdot P(A) + P(G|\neg A)\cdot P(\neg A)$$
There are no unknown numbers in this expression, so $P(G)$ is easy to calculate.
Answer: $2\%$ of students are female science students (because $5\%$ of $40\%$, or $1/20$ of $40\%$, is $2\%$) and $6\%$ of students are female arts students (because $10\%$ of $60\%$, or $1/10$ of $60\%$, is $6\%$). Thus, six of every eight female students are arts students, so $75\%$.


Which modules are required for the dynamic webform on webform.com?

Question: I'd like to allow users to create webforms like the one on webform.com.

Which modules are required? Is Arrange Fields one of them?
Comment: This kind of questions is [off-topic](http://drupal.stackexchange.com/help/on-topic). (See "Implementing a functionality, or a layout, seen in a site for which only a screenshot, or the site URL is provided.")
Answer: The website is using the Form Builder module.

This project allows users to build entire Form API structures through a graphical, AJAX-like interface. It has the ability to read and export FAPI arrays, and users are permitted to change any properties exposed by modules that expose forms to the Form Builder.
Comment: + the webform module right?
Answer: you could go through http://www.commercialprogression.com/post/drupal-webforms-dynamic-select-boxes-tutorial for creating webform dynamically.
Link tells you how to create dynamic drupal select boxes. It is done mainly in three steps which are to

Build your form with Webform Module.
Create a custom module to access your database.
Dynamically create and change select boxes on your form.


add code automatically for any article/post

Question: I built a Drupal website with a custom theme, but in the last stand I need to add a specific code after any post/article published on the site. For example:
article 1
code
article 2
the same code...
The pinpoint is that I don't know how to take a reference of a single post/article to include it in a buckle to add this code.
Comment: How do you insert "article 1" ? Do you use a node display ? In this case you should modify the node template in your theme.
Comment: I need insert the article 1 trough the add content menu (admin menu). But when it show in the "content" region need add a specific code in any article.

I don't understand how y can reference all articles in the code (a hook?) of the region for implement the specific code.
Answer: The easiest way is to create a block and add your code to it if it's html or javascript code. Then for Show block on specific pages select only on the listed pages and add articles/* This will affect all the pages that have articles in their url.
If it's php, you will need to create a custom page tpl file.
go to drupal/sites/all/themes/mythemename/templates and add page--articles.tpl.php This will affect all the pages that have articles in their url.


Why would predicted values be normally-distributed when the actual values are uniform?

Question: I'm building a supervised learning model where the target variable is a uniformly-distributed continuous value ranging from 0-1 (originally a rank value from 1-38000, then scaled down to 0-1). The 20 predictor variables are a mix of continuous and categorical variables, with no more than 6 levels for the latter. But when I apply various modeling techniques to the data (including regression, random forest, MARS, neural nets) using R, the predicted values for every model are shaped like a bell curve.
What could cause the fitted values (bell shape) to be so consistently different from the actual ones (uniform shape)? And is there any way to force these models to produce a more uniformly-shaped prediction?
Comment: In what sense are the predicted values normally distributed? In general, for a specific point in the covariate space (ie, a specific set of predictor values) the predicted value is a single point--it has no conditional distribution. If your covariates are normally distributed, the *marginal* distribution of the predicted values might be normal, but that's a different issue.
Answer: First, to address the issue of bell-shaped predictive values.  This will be a heuristic explanation, to say the least.  Let's take a linear regression as our "example" case.  If you think of the predictor variables as being drawn from some 20+ - dimensional probability distribution (more on the "+" later), a prediction from a linear regression can be thought of as a weighted average of 20+ random variables... the distribution of which, under a wide range of conditions, will tend towards Normality as the number of random variables goes up.  Hence the bell-shaped curve.
The "+" is present because, from a numerical standpoint, a categorical variable with 6 levels is equivalent to 6 binary variables (which, obviously, are not independent.)  Note I'm not claiming that these 6 binary variables contribute to the asymptotic Normal distribution to the same degree as a continuous variable would.
Insofar as other methodologies all have a "weighted average" flavor to them, something similar will occur, though mediated by the actual calculations involved.  Here's an example using random forests; I have 10 predictors, independently distributed $U(0,1)$, and the target variable $y$ is the normalized rank of the sum of the square roots of the 10 predictors (so $y$ is in (0,1]).
<code>U <- as.data.frame(matrix(runif(10000),1000))
y <- rowSums(sqrt(U))
U$y <- rank(y)/length(y)

foo <- randomForest(y~V1+V2+V3+V4+V5+V6+V7+V8+V9+V10, mtry=4, data=U)
hist(predict(foo))
</code>

As you can see, the bell-shaped histogram of the predicted values occurs in other contexts than yours.
Second, converting to a more uniformly-shaped prediction.  One way would be to rank the predicted values from 1-38000, then scale down to 0-1, just as with the original rank-valued target variable.
Here's what happens when we continue the above example in this vein:
<code>> u.predict <- rank(predict(foo))/length(predict(foo))
> mean((u.predict-U$y)^2)
[1] 0.007450796

> mean((predict(foo)-U$y)^2)
[1] 0.01875836
</code>
The mean squared error of the ranked predictions has decreased by a factor of roughly 2.5 relative to the "raw" predictions.  My guess as to why this works, which I admit surprised me, is that the original variable is a normalized rank, not a true interval-valued variable (i.e., 0.002 is not 2 times 0.001, really,) and the ranked predictions are in a way correcting for the fact that the estimation procedures are all assuming that they are.


Office 365 In-Place Hold preventing me from deleting user

Question: I am using AD Connect to synchronize my on-premises Active Directory to our Office 365 tenant. I tried disabling a user from on-premises and then synchronizing to O365. However, it seems to have broken everything because nothing is synchronizing any longer and the user still exists in O365.
When I open the user properties in O365 admin, I see the following error:

Exchange: An unknown error has occurred. Refer to correlation ID:
  769ccf2f-bd09-4651-801e-983aaeaace7f;

If I try to run Get-MsolUser I get the following error:

Exchange can't disable the mailbox "ZZZZ.PROD.OUTLOOK.COM/Microsoft
  Exchange Hosted Organizations/domain.onmicrosoft.com/UserName" because
  it is on In-Place Hold.

I can't find any In-Place Hold policy active and I can't seem to be able to delete this user. I even tried running Remove-MailUser and got the error:

The operation couldn't be performed because object 'email@example.com'
  couldn't be found on 'YYYY.ZZZZ.PROD.OUTLOOK.COM'.
Answer: Try to sync the objector manually and check if you will receive any error:
Azure AD Connect sync: Scheduler
https://docs.microsoft.com/en-us/azure/active-directory/connect/active-directory-aadconnectsync-feature-scheduler
And try to reactive this account and disable it again.


Gauss elimination over $\mathbb{Z}_2$

Question: I should solve this system of equations over $\mathbb{Z}_2$:
$3x_1 + x_2 + 2x_3 + x_4 = 2$
$-x_1 + x_2 + x_3 - x_4 = 1$
$-5x_1 + x_2 + 3x_3 + 3x_4 = 1$
So I tried to set up the matrix, which would be
$\begin{pmatrix} 1 & 1 & 0 & 1 | 0\\
                 1 & 1 & 1 & 1 | 1\\
                 1 & 1 & 1 & 1 | 1 \\
   \end{pmatrix}$
so line 2 and 3 are equal, then
$\begin{pmatrix} 1 & 1 & 0 & 1 | 0\\
                 1 & 1 & 1 & 1 | 1\\
                 0 & 0 & 0 & 0 | 0 \\
   \end{pmatrix}$
then subtracted the first from the second line
$\begin{pmatrix} 1 & 1 & 0 & 1 | 0\\
                 0 & 0 & 1 & 0 | 1\\
                 0 & 0 & 0 & 0 | 0 \\
   \end{pmatrix}$
So I would be having I. $x_3 = 1$ and II. $x_1 + x_2 + x_4 = 0$, but there are many cases which would fulfill II.
Are my calculations correct up to here and how could I write the solutions for II. nicely?
Answer: Your work looks good. To express the multiple solutions for $x_1$, $x_2$, and $x_4$, you can allow $x_2$ and $x_4$ to be arbitrary, and then we have $$x_1=x_2+x_4$$ In this way, we end up with four solutions, corresponding to different choices for the two free variables.
Comment: thank you so much :)

Gauss elimination over $\mathbb{Z}_2$


Show that for any odd natural $n$, and a natural $k$ such that $1 \leq k \leq n − 1$ $k^n + (n − k)^n \equiv 0 \pmod n$

Question: I was given this question and I am completely confused how to go about it. Show that for any odd natural n, and a natural k such that $1  \leq k \leq n − 1$
$$k^n + (n − k)^n \equiv 0 \pmod n$$
I tried to search the textbook and online for a similar problem but could not find one.
Comment: Did you copy the problem correctly?  clearly $(n-k)n\equiv 0$ mod($n$) so you could delete that whole term.  You are then left with $k^n$ on the left and if $(k,n)=1$ that term will never be $0$ mod($n$).
Comment: $2^3+(3-2)*3 = 11$ which is not $0$ mod ($3$).
Comment: @lulu yes sorry i edited it
Answer: One thing you can use $(a+b)^n=a^n+\dbinom{n}{1}a^{n-1}b+\cdots+\dbinom{n}{n-1}ab^{n-1}+b^n$ will have symmetric structure since $n$ is odd and the terms where I put explicitly binomial notations are zero. That is
$$
(a+b)^n=x+y \pmod n
$$
where $a^n=x \pmod n$ and $y=b^n \pmod n$. Now take $a=n-k$ and $b=k$. By the way the claim is true for $k=0$ and $k=n$.
Answer: Note that $(n-k)^n\equiv (-k)^n\equiv -k^n \pmod{n}$.
If congruences are not yet familiar, imagine expanding $(n-k)^n$ using the binomial theorem. We will get a bunch of terms divisible by $n$, followed by $(-k)^n$, which is $-k^n$ since $n$ is odd.
Answer: $$
\eqalign{
& k^n+(n-k)^n = \cr
= {} & k^n+(-)^n(k-n)^n \\
= {} & k^n-(k-n)^n \qquad \text{because $n$ is odd} \\
= {} & (k-k+n)(k^{n-1}+k^{n-2}n+\cdots +kn^{n-2}+n^{n-1}) \\
= {} & n(k^{n-1}+k^{n-2}n+\cdots +kn^{n-2}+n^{n-1})
}
$$


Inferring distribution over concurrent events given arrival and duration distributions

Question: Suppose you're working on infrastructure for web service and you're tasked with determining the probability distribution of concurrent requests to your services.
In example, suppose the first request arrives at 6:05:00 am with a duration of two seconds (until 6:05:02), the second arrives at 6:05:01 am with a duration of one second (6:05:02) and the third arrives at 6:05:03 with a duration of three seconds (6:05:06.) Of these three requests, only two were concurrent (the first two.)
Suppose you have two distributions, first, when requests arrive over time and second, the length of requests. (Perhaps arrivals are uniformly distributed throughout the day and durations are distributed as lognormal.)
In a real world, if total concurrent requests exceed some threshold, one of the following would result: 1/ request dropped (0 duration), 2/ requests added to a queue (increased duration if queue time is counted), new infrastructure spin-up (increased duration to only the requests arriving duration spin-up time.)
However, to simplify the problem, suppose that computational resources are limitless and none of the above three scenarios would be realized.
How would you go about deriving the probability distribution over concurrent requests given the distributions presented (request arrivals and request durations.)
Comment: Empirical estimation is not an option? You could simply draw random points in time, compute the number of concurrent connections and then make a histogram over the number of concurrent connections.
Comment: What is the copula between p(arrival) and p(duration)? It is not clear what the joint probability distribution p(arrival, duration would be)
Answer: The probability that the next call becomes concurrent is $$P[A<D]$$ where $A$ is the time between call arrivals and $D$ is the duration of calls.
Similarly, the cdf  for the lengths of concurrent calls is $$F(x)=\frac{P[x<D-A\ |\ A<D]}{P[A<D]}$$
For the example in the post, these probabilities might not have closed-form expressions.
A similar example with a closed-form expression is where $A$ is distributed exponentially with rate $\lambda$ and $D$ is distributed as $\max(0,N(\mu,\sigma))$. Then
$$P[A<D]=1-P[\lambda \sigma^2<D]\exp(-\lambda\mu + \lambda^2\sigma^2/2).$$
Comment: For the CDF, if x=3, the CDF should give us the proportion of all requests that are less than or equal to 3 seconds.
Comment: P[Ax]. If we determined that P[C>5]=0.05 then we're 95% sure that there are 5 or fewer concurrent requests.
Comment: However I'm not sure if this is tractable from the inputs I've described.
Comment: The question asked for the probability distribution of concurrent requests, which is given by the CDF $F$ in the question. The proportion of all requests less than or equal to 3 seconds is $F_D(3)$, given the CDF $F_D$ for $D$.
Comment: The second comment (https://stats.stackexchange.com/questions/627721/inferring-distribution-over-concurrent-events-given-arrival-and-duration-distrib/628387?noredirect=1#comment1172327_628387) seems to have a typo.
Comment: The third and fourth comments (https://stats.stackexchange.com/questions/627721/inferring-distribution-over-concurrent-events-given-arrival-and-duration-distrib/628387?noredirect=1#comment1172328_628387) and (https://stats.stackexchange.com/questions/627721/inferring-distribution-over-concurrent-events-given-arrival-and-duration-distrib/628387?noredirect=1#comment1172329_628387) ask about the fraction of time when there are $C$ concurrent requests, which was not clearly asked about in the post, and is a different enough question that it belongs in a separate post.
Comment: The context was about concurrent requests for servers. How many concurrent requests you expect is instrumental to provisioning resources cost-effectively.


Upload an image file takes too long on AWS S3 c++ SDK

Question: Using AWS S3 C++ SDK for uploading .jpg images to a certain IAM user introduce huge time delays that in any case are caused due to network traffic and latency issues. I am using free-tier S3 version and MSVC 2017 64bit for my application (on Windows 10 PC). Here is a sample code:
<code>Aws::SDKOptions options;
Aws::InitAPI(options);

Aws::Client::ClientConfiguration config;
config.region = Aws::Region::US_EAST_2;

Aws::S3::S3Client s3_client(Aws::Auth::AWSCredentials(KEY,ACCESS_KEY), config);

const Aws::String bucket_name = BUCKET;
const Aws::String object_name = "image.jpg";

Aws::S3::Model::PutObjectRequest put_object_request;

put_object_request.SetBucket(bucket_name);
put_object_request.SetKey(object_name);

std::shared_ptr<Aws::IOStream> input_data =
        Aws::MakeShared<Aws::FStream>("PutObjectInputStream",
                                      "../image.jpg",
                                      std::ios_base::in | std::ios::binary);

put_object_request.SetBody(input_data);
put_object_request.SetContentType("image/jpeg");

input_data->seekg(0LL, input_data->end);
put_object_request.SetContentLength(static_cast<long>(input_data->tellg()));

auto put_object_outcome = s3_client.PutObject(put_object_request);
</code>
When I upload images bigger than 100KB the total

PutObject(put_object_request);

time of execution exceeds 2min for a 520KB image.
I have tried the same example using Python boto3 and the total upload time for the same image is around 25s.
Have anyone faced the same issue?
Comment: The multipart Upload object API is [available](https://docs.aws.amazon.com/AmazonS3/latest/dev/sdksupportformpu.html) only for Java, PHP, .NET. The functions tho seems to be available on C++ API but there is no example of such use.
Comment: I think there is some SDK method to break the image and upload all parts simultaneously
Comment: There is UploadPartAsync (I think it refers to objects greater of 5MB). Nevertheless the total time for one such small file and also the time difference between Python and C++ implementation makes no sense for me.
Comment: I dont think comparing across languages is a good idea.
Comment: Try to write a program to calculate 1000 primes. The time taken by a python and a CPP program will probably be quite different. Some languages are just slower than others. It is a simple fact.
Comment: I agree, but the reason I indicate that is that I am using the same SDK.
Answer: After a better look to AWS github repo I figure out the issue.
The problem was that WinHttpSyncHttpClient was making timouts and reset upload activity internally thus not exiting the upload thread and finally aborting the transaction. By adding a custom timeout value the problem solved.
I used multipart Upload to re-implement the example as it seems more robust and manageable. Although I thought that it is unavailable for C++ SDK, its not the case as the TransferManager does the same job for C++ (not by using S3 headers as Java, .NET and PHP does).
Thanks KaibaLopez and SCalwas from AWS github repo who help me solve the issues (issue1, issue2). I am pasting an example code is case anyone face the same issue:
<code>#include "pch.h"
#include <iostream>
#include <fstream>
#include <filesystem>

#include <aws/core/Aws.h>
#include <aws/core/auth/AWSCredentials.h>
#include <aws/s3/S3Client.h>
#include <aws/s3/model/Bucket.h>
#include <aws/transfer/TransferManager.h>
#include <aws/transfer/TransferHandle.h>

static const char* KEY = "KEY";
static const char* BUCKET = "BUCKET_NAME";
static const char* ACCESS_KEY = "AKEY";
static const char* OBJ_NAME = "img.jpg";
static const char* const ALLOCATION_TAG = "S3_SINGLE_OBJ_TEST";

int main()
{
    Aws::SDKOptions options;
    Aws::InitAPI(options);
    {
        Aws::Client::ClientConfiguration config;
        config.region = Aws::Region::US_EAST_2;
        config.requestTimeoutMs = 20000;

        auto s3_client = std::make_shared<Aws::S3::S3Client>(Aws::Auth::AWSCredentials(KEY, ACCESS_KEY), config);

        const Aws::String bucket_name = BUCKET;
        const Aws::String object_name = OBJ_NAME;
        const Aws::String key_name = OBJ_NAME;

        auto s3_client_executor = Aws::MakeShared<Aws::Utils::Threading::DefaultExecutor>(ALLOCATION_TAG);
        Aws::Transfer::TransferManagerConfiguration trConfig(s3_client_executor.get());
        trConfig.s3Client = s3_client;

        trConfig.uploadProgressCallback =
            [](const Aws::Transfer::TransferManager*, const std::shared_ptr<const Aws::Transfer::TransferHandle>&transferHandle)
        { std::cout << "Upload Progress: " << transferHandle->GetBytesTransferred() <<
            " of " << transferHandle->GetBytesTotalSize() << " bytes" << std::endl;};

        std::cout << "File start upload" << std::endl;

        auto tranfer_manager = Aws::Transfer::TransferManager::Create(trConfig);
        auto transferHandle = tranfer_manager->UploadFile(object_name.c_str(),
            bucket_name.c_str(), key_name.c_str(), "multipart/form-data", Aws::Map<Aws::String, Aws::String>());

        transferHandle->WaitUntilFinished();

        if(transferHandle->GetStatus() == Aws::Transfer::TransferStatus::COMPLETED)
            std::cout << "File up" << std::endl;
        else
            std::cout << "Error uploading: " << transferHandle->GetLastError() << std::endl;
    }
    Aws::ShutdownAPI(options);
    return 0;
}
</code>


trigger a script when mailbox recieves mail?

Question: I want to process a particular mailbox when it receives mail, I know I could have cron check every n minutes for any mail, but wondering if there's a way to "listen" for mail rather than continually polling.
Answer: Try a .forward file
You can pipe the message into any program or script you want, but also check if procmail can do what you want.
Answer: If you're using postfix I'd suggest aliasing the mailbox you're interested in to a process that will do the work for you.  Then there's no polling.  The message comes in and goes directly to being processed.
Answer: Depending on your mail server, it may be possible to actually have any incoming message be delivered to a process.  Either in a .forward or by setting up something more advanced.  In exim you can setup a transport to run a command, for certain addresses.
Answer: As Jason and Zoredache have already mentioned, you might be able to do this in the MTA itself.  Another possibility is to have inotify watch the mailbox file or maildir.
Answer: if you dont have a mail-server on your own (root-access) - you could use a web service for that: http://cloudmailin.net (200mails/month for free) - works like charme and helped me out.


Proving $\sqrt{1+\sqrt{2+\cdots+\sqrt{n}}} < 3$ for $n\geq 1$ by induction

Question: How can I prove by induction that $\sqrt{1+\sqrt{2+\cdots+\sqrt{n}}} < 3$ for $n\geq 1$? My guess is that there must be another form to express the sum of nested square roots, but I don't know how to find it.
Comment: For Ramanujan this is an axiom. (Its a joke)
Comment: Related: http://math.stackexchange.com/questions/437209/how-can-i-show-that-sqrt1-sqrt2-sqrt3-sqrt-ldots-exists. – Your inequality is proved in the top-voted answer http://math.stackexchange.com/a/437228/42969.
Comment: Searching for "sqrt 1 + sqrt 2 + sqrt 3" shows more similar/related questions.
Answer: We can actually prove a more general version of what you hope to prove (set $a=0$ for your problem, specifically):
Claim: For every $n\in\mathbb{Z^+}$ and every non-negative real number $a$
$$
\sqrt{a+1+\sqrt{a+2+\cdots+\sqrt{a+n}}}< a+3.
$$
Proof. For $n\geq 1$, let $S(n)$ denote the statement that for any non-negative real $a$,
$$
S(n) : \sqrt{a+1+\sqrt{a+2+\cdots+\sqrt{a+n}}}< a+3.
$$
Base step: $S(1)$ says that $\sqrt{a+1}<a+3$, and this is verifiable since
$$
a+1<(a+3)^2\Leftrightarrow 0<a^2+5a+8,
$$
which is true for $a\geq 0$.
Inductive step: Fix some $k\geq 0$, and suppose that $S(k)$ is true for any non-negative $a$ where
$$
S(k) : \sqrt{a+1+\sqrt{a+2+\cdots+\sqrt{a+k}}}< a+3.
$$
To be shown is that $S(k+1)$ follows for any non-negative $b$ where
$$
S(k+1) : \underbrace{\sqrt{b+1+\sqrt{b+2+\cdots+\sqrt{b+k+\sqrt{b+k+1}}}}}_{\text{LHS}}<\underbrace{b+3}_{\text{RHS}}.
$$
Using $a=b+1$,
\begin{align}
\text{LHS} &= \sqrt{b+1+\sqrt{b+2+\cdots+\sqrt{b+k+\sqrt{b+k+1}}}}\\[1em]
&= \sqrt{b+1+\sqrt{a+1+\cdots+\sqrt{a+k-1+\sqrt{a+k}}}}\\[1em]
&< \sqrt{b+1+a+3}\tag{by $S(k)$}\\[0.5em]
&= \sqrt{2b+5}\\[0.5em]
&< b+3\\[0.5em]
&= \text{RHS},
\end{align}
where the last inequality follows since
$$
2b+5<(b+3)^2=b^2+6b+9
$$
and $b^2\geq 0$. This proves $S(k+1)$, completing the inductive step.
By mathematical induction, the statement $S(n)$ is true for all $n\geq 1$. $\blacksquare$

Your particular problem holds for $S(n)$ where $a=0$.
Answer: $$(1) \quad x=k+\sqrt x$$
$$x=\sqrt {k+\sqrt x}$$
continuing the recursion...
$$x=\sqrt {k+\sqrt {k+\sqrt {k+...}}}$$
Thus (1) is the equivalent expression.
Solve for x with $k=1$
$$x=\phi$$
Thus, x equals the golden ratio. Multiply the expression by c...
$$c \cdot x=c \cdot \sqrt {k+\sqrt {k+\sqrt {k+...}}}$$
$$c \cdot x=\sqrt {c^2 \cdot k+\sqrt {c^4 \cdot k+\sqrt {c^8 \cdot k+...}}}$$
Choose c to equal $2^{1/4}$ (This is where you use induction to prove this works)
Prove $$2^{2^n/4} \ge n$$
For $n=1 \ $, $ \ \sqrt 2 \gt 1$ so we have a base case
Inductive step, assume the above holds for $n=k$
Let, $n=k+1$
$$2^{2^k/4} \ge k$$
$$2 \cdot 2^{2^k/4} \ge 2 \cdot k$$
$$ 2^{2 \cdot 2^{k}/4} \ge 2 \cdot k$$
$$2^{2^{k+1}/4} \ge k+1$$
assuming k is greater than 1, thus the above holds for all n.
$$2^{1/4} \cdot \phi=\sqrt {\sqrt 2+\sqrt {2+\sqrt { 4+\sqrt {16+...}}}}$$
Thus the inequality for the radical is given by
$$\phi \le S \le 2^{1/4} \cdot \phi$$
$$1.618... \le S \le 1.924...$$
I personally guess the radical to be approximately equal to $1.771$...
Comment: But this doesn't use induction as requested by the OP.
Comment: How is this even relevant? You're not considering the same sequence as in the question. The sequences $\sqrt{k+\sqrt{k+\cdots}}$ and $\sqrt{1+\sqrt{2+\cdots}}$ are not the same.
Comment: He gets there in the end.  (although $c^6$ should be $c^8$).
Comment: @PatrickDaSilva you need to read the proof closer, I multiply after that...
Comment: This is clever, but you still need to show (a) that the interior terms are all greater than the corresponding integers (not hard, but needs proof all the same) and (b) that $a\lt a', b\lt b', c\lt c', \ldots\implies\sqrt{a+\sqrt{b+\sqrt{c+\ldots}}}\lt\sqrt{a'+\sqrt{b'+\sqrt{c'+...}}}$ - also not hard, and 'intuitively obvious', but it does need proof!
Comment: @Zach466920 : At the moment where I wrote my comment, your approach did not seem clear at all ; now it is. I hadn't voted, for the record.
Comment: @PatrickDaSilva Duly noted. And good to know the answer is clearer now.
Answer: You can also try going at it from the other direction: by squaring both sides, the given inequality can be written as $1+\sqrt{2+\sqrt{3+\ldots}}\lt 3^2$.  Subtract $1$ and square: $2+\sqrt{3+\ldots}\lt (3^2-1)^2$.  Subtract 2 and square: $3+\sqrt{\ldots}\lt\left((3^2-1)^2-2\right)^2$.  So define $a_0=3$, $a_i=a_{i-1}^2-i$.  Can you show by induction that $a_n^2\gt n+1$ for all $n$?
Comment: Would the downvoters care to explain themselves?
Comment: +1 there is no explanation, just a gut reaction for (generally) illogical reasons.
Comment: @Zach466920 I'm used to the occasional drive-by downvote, but seeing two on an answer so benign and seemingly straightforward makes me wonder if I missed something.
Comment: @Zach466920 Although I see that your answer has 4(!) downvotes, so maybe something is going on here...
Comment: 4! I didn't even know that! I thought it was 2. Hmmm...well on the bright side 4 people liked my answer. I think I'll state that my answer is only a partial in the future. In this case I did to little to late.
Answer: HINT
Take $U_n=\sqrt{1+\sqrt{2+ ... + \sqrt{n}}}, n\in \mathbb N.$
Then show that $\forall n \in \mathbb{N}, U_{n+1}^2 < 1+\sqrt{2} U_n$
After that, consider $Q(x)=x^2-\sqrt{2}x-1$ find the solutions then consider $Q(U_n)$ if it works you will find that
$$
\lim_{n \to \infty} U_n \le \frac{\sqrt{2}+\sqrt{6}}{2} <3
$$


href tag image not appearing on addclass

Question: I am struggling with a strange issue for last couple of days. I have href tag like below

And I am trying to apply another css class on click of this tag,in which i am trying to change the background image of the tag. The class is getting applied but the image is not displaying. Can anybody have an idea of this issue?
My javascript looks like below
 function shoptions(obj) {
        var a = $('#'+obj+'');
        if (a.hasClass('up')) {
            a.removeClass('up').addClass('down');
        }
        else {
            a.removeClass('down').addClass('up');
        }
        return false;
    }

And my css looks like below
a.up:link
{
background: #fff url(../egami/arrows_up.gif) scroll no-repeat left center !important;
padding: 2px 0 2px 16px !important;
}
a.down:link
{
background: #fff url(../egami/arrows_down.gif) scroll no-repeat left center !important;
padding: 2px 0 2px 16px !important;
}

Comment: Hello can you please create jsfiddle?
Answer: Are you sure ":link" is the selector you want to use? My understanding is that this selector only applies to link which the user has not visited. You may want to try removing this and just having "a.up" and "a.down".
Answer: Since you are using jQuery, you can make everything more jQuery-style:
$('#opt').click(function(e) {
    e.preventDefault();
    $(this).toggleClass('down up');
});

And get rid of inline handlers in HTML:

Demo: http://jsfiddle.net/3NYdF/
Comment: I have implemented same thing in my page. But it is working on first click, from second click the image is not changing. Any idea?
Comment: I have got it working after applying display: inline-block; in the CSS file. Any inputs on why we require this?
Comment: You need `inline-block` because your `a` tags collapses without content. When it's block or inline block you can set them a height. and it will become visible.
Answer: Why are using both onClick and href? Use only href:

or only  onClick:

Answer: the problem is you use a.up:link & a.down:link
use only  a.up  & a.down
a:link - a normal, unvisited link
a:visited - a link the user has visited
a:hover - a link when the user mouses over it
a:active - a link the moment it is clicked

Reference


2 runners on base, lead runner misses a base and both runs score, correct ruling?

Question: Runner on first and second, ball is hit to outfield, both the runner on first and second score on the outfield hit. The runner who was on second, misses touching third base, and scores, followed by the runner who was on first...
appealed and the umpire called the runner out who missed 3rd base....
is this the correct call?
Comment: Can you edit your question to add which ruleset you are using?
Comment: How many outs are there?
Comment: @PhilipKendall - Baserunning rules are universal.  The pitcher would step on mound and then off and throw to third base to appeal.  Or in some cases would just hold the ball and tell umpire she wants to appeal.  The runner is called out for sure for missing the bag.  What the author needs to tell us is where the other runners went and how many outs there were because that is where it can get interesting.
Answer: Tricky situation. Under baseball rules 7.08 (h) any runner is out when they pass another runner. However the runner never actually passes the other runner. So rule 7.10 (b) applies. In this case the first runner would be called out if a defensive player holding the ball were to tag the runner (who missed the bag) or third base.
Comment: Have you noticed this question is tagged "softball", not "baseball"?
Comment: @PhilipKendall Fortunately many of the same rules in baseball, especially those regarding baserunning and putouts are carried over into the game of softball. You are welcome to reference the rulebook of whatever governing body your softball league follows, but i would almost certainly guarantee that as far as baserunning goes the rules will be carried over from baseball. For example: see [International Softball Federation Playing Rules Committee](http://www.baseball-softball.de/wp-content/uploads/Softball-Rules-2014-2017-English.pdf) Rule 8 Sec 9. It's almost word for word the same as MLB
Answer: If there are 2 outs when the appeal takes place, no runs score. If less than 2 outs, the trail runner would score.  Hope that helps.
Comment: Could you provide a reference to the rule book or other authority supporting this please?


Convert to correct BigDecimal representation

Question: I have a string being returned as a data feed which I need to convert to the correct BigDecimal format - the string is of the format
1.6945E3
and needs to translate to 1694.50 but instead translates only to 1694.5 leading to loss of information. The following is the code I am using.
I am just passing the string and doing a new on a instance of BigDecimal.
Any ideas on how to get the correct data representation.
Thanks
'
Comment: 1694.5 it's equal to 1694.50; just a different formatter
Comment: "leading to loss of information" => what loss of information? Why do you expected 1694.50 and not 1694.500? etc.
Answer: it depends, try this
    BigDecimal bd = new BigDecimal("1694.50");
    System.out.println(bd);

output
1694.50

but this
    BigDecimal bd = new BigDecimal(1694.50);
    System.out.println(bd);

produces
1694.5

and this
    BigDecimal bd = new BigDecimal("1694.50");
    System.out.printf("%.3f", bd);

prints
1694.500


Firing RTK dispatch after condition is true?

Question: I have a RTK query that takes a few seconds to fetch the data.  When isSuccess is true I am then trying to fire a dispatch.
const router = useRouter();
const num = router.query.id;
const { data, error, isLoading, isSuccess } = useModByIdQuery(num);
const dispatch = useDispatch();

  {
    isSuccess && dispatch(addCurrentMod(data));
  }

The problem with this is it fires multiple times (4 to be exact).  I tried putting it in a useEffect but as the data takes a few seconds to fetch the dispatch errors out (as it's undefined).
I am not really sure the best way to approach fixing this?
Thanks.
Answer: RTK will keep firing request once component is loaded,
it will also keep firing even if input params is not available,
this can be controlled by skip params for conditional fetching
const Pokemon = ({ name, address }) => {
  const { data, error, status } = useGetPokemonByNameQuery(name, {
    skip : (!name || !address),
  });

  return (

      {name} - {status}

  );
};

If name OR address not available then it will skip api call
Answer: First of all, given information is not enough to understand what you are trying to do. still I can see your response depends of isSuccess true and if you will console isSuccess you will found multiple true false values, so try get last value only (check for place which are effecting isSuccess API call)
Comment: Apologies.  I am trying to fetch the data through the RTK query and then when I have the data, dispatch it to the redux store.  The problem is the data takes some time to come in so it cannot be done on mount, hence trying to do it the way I am above but as you are aware, isSuccess is firing multiple times.  I will try and narrow down why that is.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


GCC __builtin_expect checking pointer nullability of temporary during constexpr context results in strange run time behavior

Question: I'm using __builtin_expect to perform a null pointer check in a constexpr function like so:
constexpr int Add(const int * x, const int * y)
{
    assert(__builtin_expect(!!(x && y), 1));
    return *x + *y;
}

I also have a wrapper method for const refs to allow for passing temporaries:
constexpr int Add(const int & x, const int & y)
{
    return Add(&x, &y);
}

I then create a global constant using temporaries:
static constexpr int result = Add(1, 2);

Printing this value results in 0:

int main() {
    std::cout << result; // 0
}

What exactly is going on here?
Removal of __builtin_expect fails to compile with GCC complaining about pointer comparisons to temporaries inside constexpr context maybe related.
Godbolt
Comment: I don't see anything wrong with the code. Of course `__builtin_expect(x,y)` is a compiler extension, but I think it is supposed to work like this. If you replace it with `x == y`, then I don't see any issue with the program. It should compile and produce `3`. So I'll say it is a bug in the compiler.
Comment: I take it all back, [clang compiles this correctly](https://wandbox.org/permlink/eszSE0YHDSj7isMi).
Answer: This is a compiler bug, specifically https://gcc.gnu.org/bugzilla/show_bug.cgi?id=85944.
The issue is not related to __builtin_expect. It is about the null pointer check itself in the constant expression context. It should be fine. During the evaluation as constant expression it is known to the compiler that the pointers are referring to temporary objects whose lifetime spans that of the constant expression evaluation and therefore not null. All conditions for Add(1, 2) to be a core constant expression are satisfied.
But GCC does not seem to handle this information correctly for temporaries at namespace scope. If result is made a block scope variable (either with or without static), then everything works as expected.
For a simple workaround, you can of course use by-value parameters in the second overload instead or alternatively you can store the arguments in constexpr variables first and then pass on to Add. Wrapping the initializer in a lambda to introduce a block scope will probably also be work fine:
static constexpr int result = []{ return Add(1, 2); }();


Tansformar uma resposta JSON em uma lista e exibir os dados na tela com IONIC

Question: Boa tarde pessoal, sempre que tenho alguma duvida corro aqui na esperança de vocês me ajudarem e sempre consigo respostas positivas, desde já meu muito obrigado.
Bom, estou com um probleminha aqui (não tenho muita afinidade com typescript). Eu estou recebendo um objeto em Json como resposta e preciso colocar esses itens neste array e passar pra um componente na tela.
O retorno Json
[
    {
        "distancia": "0.0000000000",
        "resultado": "9551, FRANCISCO CAVALCANTE LACERDA-LACERDOPOLIS, G019688"
    },
    {
        "distancia": "0.0000000000",
        "resultado": "9552, FRANCISCO CAVALCANTE LACERDA-LACERDOPOLIS, G019689"
    },
    {
        "distancia": "0.0000000000",
        "resultado": "9553, FRANCISCO CAVALCANTE LACERDA-LACERDOPOLIS, Z118507"
    },
    {
        "distancia": "0.0000000000",
        "resultado": "9554, ROSA DOS VENTOS-LACERDOPOLIS, Z013630"
    },
    {
        "distancia": "0.0900949795",
        "resultado": "9557, ALTEMAR DUTRA-HELIOPOLIS, G019695"
    },
    {
        "distancia": "0.0900949795",
        "resultado": "9558, ALTEMAR DUTRA-HELIOPOLIS, G019693"
    },
    {
        "distancia": "0.0900949795",
        "resultado": "9550, FRANCISCO CAVALCANTE LACERDA-LACERDOPOLIS, G019687"
    },
    {
        "distancia": "0.0900949795",
        "resultado": "9556, ROSA DOS VENTOS-LACERDOPOLIS, G019573"
    },
    {
        "distancia": "0.0900949795",
        "resultado": "9555, ROSA DOS VENTOS-LACERDOPOLIS, G019694"
    },
    {
        "distancia": "0.1274138708",
        "resultado": "9559, ALTEMAR DUTRA-HELIOPOLIS, G019572"
    }
]

Onde preciso exibir os dados json
<ion-list>
  <ion-item>
    <ion-label>Postes</ion-label>
    <ion-select [(ngModel)]="postes">
      <ion-option *ngFor="let lista_postes of lista_postes; let i = index;" value={{lista_postes}}>{{ i + lista_postes}}</ion-option>
    </ion-select>
  </ion-item>
</ion-list>

Método que submet a informação ao servidor e recebe como retorno um Json, que teria que popular esta lista.
submitCadastroNotification() {
  var _link = 'http://www.baseterritorial.com.br/desktop/projetos/baselumina/baselumina.app.php?baselumina_mobile=';
  var _data = JSON.stringify({
    acao: "localizar",
    uuid: this.uuid,
    barramento: this.barramento,
    latitude: this.latitude,
    longitude: this.longitude,
  });
  console.log(_data);
  //iniciando conexão HTTP para cadastro do usuário via JSON
  this.http.post(_link + _data)
    .subscribe(_data => {
      this.data.response = _data._body;
      this.lista_postes.push(this.data.response);

      console.log(this.lista_postes);

      //console.log(this.data.response);
    }, error => {
      console.log("Ocorreu algum erro!");
    });
}

Answer: Parece que seu problema está nesta linha:
<ion-option *ngFor="let lista_postes of lista_postes; let i = index;" value={{lista_postes}}>{{ i + lista_postes}}</ion-option>
O *ngFor funciona como um foreach em outras linguagens, neste caso o let lista_postes define uma variável chamada lista_postes para cada lista_postes, algo de estranho?
Pois é, o nome da variável do for, (let lista_postes) deveria ter um nome diferente, assim podendo acessar cada um das chaves do objeto no array, por exemplo:
<ion-option *ngFor="let poste of lista_postes; let i = index;" value={{poste.distancia}}>{{ i +' '+ post.resultado}}</ion-option>
Mais informações: https://angular.io/api/common/NgForOf


how to make choice between spring framework and EJB3

Question:
Possible Duplicate:
JEE6 vs. Spring 3 stack

Let I'm going to develop a mission critical application which will be massively transaction based. I will do it with Java. Now I have to choose the technology. My application must be scalable, good performing, code must be maintainable and I want to get long term ROI. First thing, I'm going to choose framework. As a framework, spring comes at first in my mind. But I know there are more like EJB3 or anything. Now my question, what should I choice, EJB3 with JPA or spring framework with Hibernate. I know every technology have tradeoffs.  Can anyone help me to make good choice? And one thing to make clear, I'm still learner.And I want to know advantage and disadvantage of EJB and spring framework too. Thanks
Answer:
And I want to know advantage and disadvantage of EJB and spring
  framework too

Both are light and POJO based, and you could get a good picture from similar threads. You might find that many of the pain-points that existed with EJB 2.x are no longer there.
'EJB' might simplify things for you

If your application would need distributed transactions started by remote clients
If your application is message-driven

Now my question, what should I choice, EJB3 with JPA or spring
  framework with Hibernate.

Also look at adding CDI to the stack ( i.e EJB3.x + JPA + CDI ) and then compare with (Spring + Hibernate)