text:
Q: How to manage exception of ViewData in SelecList? controller : `
public IActionResult SendReport()
    {
        List<SelectListItem> listAdmin = new List<SelectListItem>();

        listAdmin.Add(
        new SelectListItem
        {
            Text = "admin",
            Value = "0"
        });

        ViewBag.listAdmin = listAdmin;
        ViewData["listAdmin"] = listAdmin;

        return View();
    }`

View :@Html.DropDownList("listAdmin",ViewData["listAdmin"] as IEnumerable<SelectListItem> ,"Selecte")
but Exception is "There is no ViewData item of type 'IEnumerable' that has the key 'listAdmin'".where is m mistake?

A: First,if  I use your code,I cannot reproduce the error.
And then if the data in controller is null, I will have the same error with yours:
Error message:
There is no ViewData item of type 'IEnumerable' that has the key 'listAdmin'.
public IActionResult SendReport()
        {
            List<SelectListItem> listAdmin = new List<SelectListItem>();

            listAdmin.Add(
            new SelectListItem
            {
                Text = "admin",
                Value = "0"
            });
            ViewBag.listAdmin = null;
            return View();
        }

Next,if  I change the view like this,I will also have the same error with yours:
Error message:
There is no ViewData item of type 'IEnumerable' that has the key 'listAdmin111'.
<div>
    @Html.DropDownList("listAdmin111", ViewData["listAdmin"] as IEnumerable<SelectListItem>, "Selecte")

</div>

So I think you can make sure the ViewBag and ViewData is null or not by debugging the code and right click 'ViewBag' and choose the 'QuickWatch' to see the ViewBage information.And then you can make sure if the spelling in View is the same in Controller.


text:
Q: Modifying LastWriteTime directory in Powershell I would like to change a folder lastWriteTime without modify a lastWriteTime of files which are in this directory.
I have been trying this:
$a = Get-Date "02/09/2013 4:59 PM"
$d = "C:\Users\user\Documents\CV"
$d.LastWriteTime = $a

but it's didn't working because d has not a LastWriteTime property.
There is any way to change this property? I have to modified lastTimeWrite property only "CV" directory - files in "CV" shouldn't be touched.

A: One way is to cast it to [system.io.directoryinfo]
$a = Get-Date "02/09/2013 4:59 PM"
$d = [system.io.directoryinfo]"C:\Users\user\Documents\CV"
$d.LastWriteTime = $a

or using get-item cmdlet
$a = Get-Date "02/09/2013 4:59 PM"
$d = get-item C:\Users\user\Documents\CV
$d.LastWriteTime = $a

A: Function Touch-File
#Touches a file or folder if the file does not exist it creates a new empty    file
    {
    $file = $args[0]
    $date = $args[1]

    if($file -eq $null) {
        throw "No filename supplied"
    }

    if($date -eq $null) {
        throw "No date supplied"
    }

    if(Test-Path $file)
    {
    #Optionally select the date stamp you want to update

         (Get-Item $file).LastWriteTime = $date
         (Get-Item $file).CreationTime = $date
         (Get-Item $file).LastAccessTime =$date
     }
     else
    {
         echo $null > $file
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Determine tablelayoutpanel item dropped into I am trying to determine which cell (row/column) of my TableLayoutPanel the user drops an object into. Currently I have only been able to find how to determine coordinates of where the item is dropped which is:
Dim location As Point = TableLayoutPanel1.PointToClient(New Point(e.X, e.Y))

However I can not figure out how to locate which cell that is in. I did find the command GetCellPosition and attempted that with the coordinates; however that did not work either.
TableLayoutPanel1.GetCellPosition(location)

A: You can try this function:
Private Function GetCellFromPoint(p As Point) As Point
  Dim result As New Point(-1, -1)
  Dim colWidths As Integer() = tlp.GetColumnWidths()
  Dim rowHeights As Integer() = tlp.GetRowHeights()
  Dim top As Integer = 0
  For y As Integer = 0 To rowHeights.Length - 1
    Dim left As Integer = 0
    For x As Integer = 0 To colWidths.Length - 1
      If New Rectangle(left, top, colWidths(x), rowHeights(y)).Contains(p) Then
        result = New Point(x, y)
      End If
      left += colWidths(x)
    Next
    top += rowHeights(y)
  Next
  Return result
End Function

It just loops through the rows and columns to see if the passed in point is inside the existing cell.  Note though, that GetColumnWidths and GetRowHeights do not appear in the intellisense dropdown.
Usage:
Private Sub tlp_MouseMove(sender As Object, e As MouseEventArgs) _
                          Handles tlp.MouseMove
  Me.Text = GetCellFromPoint(e.Location).ToString
End Sub

BTW, GetCellPosition is expecting a control to be passed as a parameter, not a Point structure.
You can also use TableLayoutPanelCellPosition in place of Point in this function, since that is what GetCellPosition is returning in its function.

A: I have used this function (thanks a million) but I have found an issue. To define correctly the cell where the object is droped, we need to take into account the location of the TableLayoutPanel in the screen. I have solved this making the declaration of p (build with e.X and e.Y in the DragDrop event) and r (a reference of the location of the TableLayoutPanel in the screen).
Then you have to assing p = p - r and send that P to the function GetCellFromPoint(p).
Private Sub TableLayoutPanel1_DragDrop(sender As Object, e As DragEventArgs) Handles TableLayoutPanel1.DragDrop
Dim p As New Point(e.X, e.Y)
Dim r As Point
r = TableLayoutPanel1.PointToScreen(New Point(0, 0))
p.X = p.X - r.X
p.Y = p.Y - r.Y
MessageBox.Show(GetCellFromPoint(p).ToString)
End Sub


text:
Q: jQuery Mobile and Textpattern - Comment form I'm working with the textpattern commenting system using the jQuery Mobile framework.
At the moment when loading the individual article page "http://www.elisabettaclaudio.com/maestro-conte" the form in the popup won't let me post the preview.
Instead the form works when getting to the article page, let's say from this URL "http://www.elisabettaclaudio.com/oh-my-blog" and then go the "http://www.elisabettaclaudio.com/maestro-conte" and I'm able to post the preview.
Any ideas? Thanks!


text:
Q: Lebesgue integral limit Suppose $f:\mathbb{R}^+ \to \mathbb{R}$ is Lebesgue integrable on every finite interval and
$$I(x;\alpha) = \int_\alpha^{\alpha+x} f(t) dt$$
 If $\lim_{\alpha \to \infty}I(x; \alpha) = F(x)$ exists for every $x$, then show $F(x) = Cx$ for some real number $C$.
My attempt is to first consider a continuous function with a finite limit at infinity.  Then by mean value theorem there exists a point $\xi_\alpha > \alpha$ where
$$\lim_{\alpha \to \infty}\int_\alpha^{\alpha+x} f(t) dt = \lim_{\alpha \to \infty}f(\xi_\alpha)x = [\lim_{t\to \infty}f(t)]x $$
I do not see how to prove the result without these strong assumptions.

A: Note that
$$\int_\alpha^{\alpha + x_1 +x_2} f(t) \, dt = \int_\alpha^{\alpha + x_1} f(t) \, dt + \int_{\alpha+x_1}^{(\alpha + x_1)+ x_2} f(t) \, dt$$
Since $\alpha + x_1 \to \infty$ iff $\alpha \to \infty$ it follows that $F$ is additive:
$F(x_1+x_2) = F(x_1) + F(x_2)$.
With any sequence $\alpha_n \to \infty$, we have $F(x) = \lim_{n \to \infty}I(x;\alpha_n)$ and $F(x)$ is a pointwise limit of a sequence of continuous functions. Using Baire's theorem, it can be shown that $F$ is continuous on an everywhere dense set.
However, we only need continuity at one point to conclude that $F$, as an  additive function, is everywhere continuous with $F(x) = F(1)\cdot x$.
Addendum
To elaborate, it is easy to prove that an additive function has the property $F(rx) = rF(x)$ for any rational number $r$.  Hence, for any real number $\xi$, taking a sequence of rationals $r_n \to \xi$, we have if $F$ is continuous,
$$\xi F(x) = \lim_{n \to \infty}r_nF(x) = \lim_{n \to \infty}F(r_n x) = F(\xi x)$$
Also, if $F$ is additive and continuous at one point, say $c$, then it is continuous everywhere since
$$F(x + \delta) - F(x) = F(\delta) = F(c + \delta) - F(c)$$
That $F$ must be continuous at one point is a somewhat deeper result requiring a lengthy argument. For example, see here.


text:
Q: Kaplan-Meier with known censor distribution I would like to know if you can do better than Kaplan-Meier when you know the censor distribution. I searched google but I could not find anything.
This problem seems to be quite natural/useful when you are doing hypothesis testing and your Null includes information about the censor distribution.
Thanks


text:
Q: Angular (4): Multiple HTTP requests with Observables: one after another succeeds I am kind of new to Angular 4 and Observables and everything related to it.
I am trying to execute two http requests one after another (only when the first one succeeds).
I'm using this code:
public getCompany(id: string): any {
    let company = null;

    this.authService.isValidUser().subscribe(response => {
      const token = this.tokenStorageService.getTokenFromStorage();
      const requestUrl = environment.gatewayUrl + environment.companyService + environment.getCompanyEndPoint + id;
      const headers = new Headers();
      headers.set('Authorization', 'Bearer ' + token);
      const options = new RequestOptions({headers: headers});

      return this.http.get(requestUrl, options).catch(this.errorService.handleError);

    }, (error: AppError) => {
       // ........ //
    });
  }

This is the isValidUser() method code:
  public isValidUser(): any {
    const token = this.tokeStorageService.getTokenFromStorage();
    if (!token) {
      console.log('cannot find token');
      return false;
    }

    const requestUrl = environment.gatewayUrl + environment.authorizationService + environment.userServiceEndPoint;
    const headers = new Headers();
    headers.set('Authorization', 'Bearer ' + token);
    const options = new RequestOptions({headers: headers});

    return this.http.get(requestUrl, options).catch(this.errorService.handleError);
  }

The idea here is to only return return this.http.get(requestUrl, options).catch(this.errorService.handleError); after the authService.isValidUser() code worked.
I don't think this is a proper way of performing such requests, since my second request is already completed before the first one does.
Maybe I am missing some way on how to do it properly?
Thank you.

A: Where is code where you try to chain these two functions?
You can achieve what you want using switchMap operator. Here is docs for it.
I think you need something like this:
isValidUser()
  .filter(isValidUser => isValidUser) // <-- perhaps you need this filter since you want to make getCompany call only if user is valid
  .switchMap(() => getCompany())
  .subscribe(...do something...);

Don't forget to add import 'rxjs/add/operator/switchMap';. You can also use mergeMap or flatMap (mergeMap is synonim for flatMap), but it is not preferred.
As @BeetleJuice mentioned in comments: Why switchMap is better? For example, you use mergeMap or flatMap and something caused another call of that code. Even if two first requests was not finished new ones will be sended. It is even possible that second bundle of requests will be finished faster than first one. After that first bundle finishes and you have wrong data in your state. To solve this RxJS provides perfect operator switchMap. If you used this operator in situation above then first observable (first request bundle) will be cancelled. Only last observable (from last call) will stay alive. You need switchMap only if you have possibility to run that code several times in a short period of time. If you know that this code will run only once mergeMap/flatMap will do same for you.
Also, check out this post.
Update 3/28/2020: With new versions of rxjs, you can no longer call the switchMap operator on the returned Observable. Instead, you need to call pipe on the observable and pass in what should happen afterwards. For example:
isValidUser()
  .pipe(
    switchMap(() => getCompany())
  )
  .subscribe(...do something...)

Multiple operators can be passed into the pipe function as well. More info can be found on the rxjs site on the operators page


text:
Q: To be able to: physical ability or polite form? Is it possible to use to be able to for polite inquiry:

Will you be able to walk the dog this afternoon?

Or it's not how it can be used?

A: Yes, that is a polite form of asking for a favor. It leaves the door open for the person you are asking to refuse politely.

Will you be able to walk the dog this afternoon?
No, I'll be visiting my sister on the other side of town.

(an actual, physical reason)

No, I'm sorry I won't.

(an unstated reason that you won't try to dig deeper into)
"be able to" can be used for either of the senses you ask in the question title.
Able (MW, adjective, definitions 1 & 2)

having enough power, resources, or skill to do something "Are you able to swim?"
having the freedom or opportunity to do something "I'll come when I'm able."


text:
Q: Create a central bibtex file in ShareLaTeX I want to build a central BibTeX file. This file contains all my references of several papers. I put the file in a project that I call Central in the uncategorized folder.
How can I use this BibTeX file in other projects placed in other folders?
I found a solution that requires installing MiKTeX on my laptop here. I want to do the same thing with ShareLaTeX. Can anyone help me?

A: ShareLaTeX does not have the ability to link files between projects--yet. However, the online LaTeX editor Overleaf does have this ability. Since the two editors are in the process of merging together, there's a possibility that this feature might be made available in ShareLaTeX in the future.
If you're really looking to stick with ShareLaTeX, one option you might consider is using the reference managing software Mendeley. Mendeley allows you to save references and create bibliographies that can then be directly imported into ShareLaTeX and synced as you add entries. This can be done by clicking the Menu button on the left, finding the Sync submenu, and clicking Mendeley. Unfortunately, this is currently a premium feature that requires a paid subscription.
If you're willing to use the Overleaf editor, the ability to link files between projects is available for free. You can do this as follows:

*

*Create the central file

*Open the project you'd like to link the central file into

*Click the Project button on the upper left

*Hover over the appropriate folder button and click the downward-facing arrow next to it

*Click File from other project

*Navigate the menu to find the central file, and select it

Using this method, not only can you link central BibTeX files into all your projects, but you can also create central command .tex files with all your favorite user-defined shortcuts and link them into your documents. Changing the central file will change each of the linked files. Lastly, Overleaf allows you to import Mendeley bibliographies for free if you wanted to try that direction.

A: Mostly an update to Inquistive's answer
Sharelatex has merged with Overleaf.
The ability to link files between projects is still available for free
The Mendeley import feature is only available to premium users


text:
Q: Proving that product of difference ideal (left-right ideal) is subset of their intersection as follows. Let $R$ be an arbitrary ring, $I$ and $J$ be the right and left ideals, respectively.
Prove that $IJ \subseteq I \cap J$.
My attempt:
Let $x \in IJ$. That is, $x = i_1j_1+i_2j_2+\dots + i_nj_n$, for all $i_k \in I, j_k \in J, 1\leq k \leq n, n \in \mathbb{N}$.
Now, if $i_k \in I, \sum_{k=1}^{n} i_kj_k \in I$ and if $j_k \in J, \sum_{k=1}^{n} i_kj_k \in J$. Hence, $x = I \cap J \Leftrightarrow IJ \subseteq I \cap J$.
As above, may I assume that if $i_k \in I, j_k \in R$ and if $j_k \in J, i_k \in R$ ?
Please correct me if I got mistake way in proving. Thanks in advanced.


text:
Q: How to solve a single dot product inequality? We have an inequality of real numbers:
$$ a_1x_1 + a_2x_2 + \dots + a_nx_n \ge 0. $$
Is there a way to express the most precise bounds $\{l_i$, $u_i\}$, in function of the $\{x_j\}$, such that $\forall i, a_i \in [l_i,u_i]$ ?

A: To expand on Erick Wongs answer in the comments, imagine that $n = 2$ or $3$ so that you can draw a picture. Let's say $n = 3$ for now. $x := (x_1, x_2, x_3)$ is a point in 3-dimensional space. The set of all vectors $(b_1, b_2, b_3)$ such that $b_1x_1 + b_2x_2 + b_3 x_3 = 0$ is an infinite plane through the origin: it is the plane of vectors that are orthogonal to the line passing through $0$ and $(x_1, x_2, x_3)$. Let's call this plane $P$. Now the set of points $(a_1, a_2, a_3)$ you describe make up HALF OF ALL SPACE, namely all points that are on the same side of $P$ as point $x$ is. Now look only at the first coordinates that are possible for points in this half space. For almost all choices of $x$ (that is: of $P$) they can be any number. Only in the special case that $x$ is of the form $(x_1, 0, 0)$ we have that the half space consists of all points $(a_1, a_2, a_3)$ where $a_1 \geq 0$ with no further conditions on $a_2$ and $a_3$ (or, if $x_1 < 0$, where $a_1 \leq 0$ with no conditions on $a_2, a_3$).
So the answer is one of two cases:
A. $(-\infty, \infty)$ for all coordinates
B. $(-\infty, \infty)$ for all but one coordinates and for one special coordinate either $(-\infty, 0]$ or $[0, \infty)$.


text:
Q: How do I get all of the results from a hasMany() relationship in Laravel? For example, I have a Product, and I have a BaseProduct.
In the model for the Product, I've specified the following:
//In class Product
public function BaseProduct()
{
    return $this->belongsTo("BaseProduct", "BaseProductId");
}

In the BaseProduct, I've specified the following relationship:
//In class BaseProduct
public function Products()
{
    return $this->hasMany("Product", "ProductId");
}

If I were to select a product, like so:
$Product::first()

I could get the BaseProduct by doing the following:
$Product::first()->BaseProduct()->get();

Instead of getting the array of the result from that, how would I get the Model of the BaseProduct, so I can get all of the children of BaseProduct, meaning all Products that have a foreign key relating to this BaseProduct.
I've tried BaseProduct()->all(); instead, but it isn't a valid method.

Edit:
I've created the following chain of function calls - but it's awful.
return BaseProduct::find(Product::first()->BaseProduct()->getResults()['BaseProductId'])->Products()->getResults();

Final edit:
I had made a mistake in my BaseProduct model. In the Products() function, I had specified return $this->hasMany("Product", "ProductId"); where ProductId should have been BaseProductId.
After I fixed that, I could successfully use:
Product::first()->BaseProduct->products;

As Sheikh Heera had explained.

A: To get the children of the BaseProduct you may try this:
$bp = BaseProduct::with('Products')->get();

Now, you have a collection of BaseProduct so, you may use something like this:
$bp->first()->products

Or get the second item from collection
$bp->get(1)->products

Also, you may run a loop like this (most probably in the view after pass it):
// From the controller
$bp = BaseProduct::with('Products')->get();
return View::make('view_name')->with('baseProduct', $bp);

In the View
@foreach($baseProduct->products as $product)
    {{ $product->field_name }}
@endforeach

Update: Yes, you may try this
$product = Product::first();
$baseProduct = $product->BaseProduct;

// Dump all children/products of this BaseProduct
dd($baseProduct->products->toArray());

You may chain like:
Product::first()->BaseProduct->products;

Update: Your table structure should look something like:
Table:baseproduct:
id(pk) | some_field | another_field

Table:products:
id(pk) | baseproduct_id(fk) | another_field

According to this table structure, relationship should be
// BaseProduct
public function Products()
{
    return $this->hasMany("Product");
}

// Product
public function Products()
{
    // second parameter/baseproduct_id is optional unless
    // you have used something else than baseproduct_id
    return $this->belongsTo("BaseProduct", "baseproduct_id");
}

A: $product = Product::find('id');
$baseProduct = $product->baseProduct()->getModel();
$baseProduct->products()->getModels();


text:
Q: No. of real roots of $2^x = 1+x^3$ No. of real roots of $2^x = 1+x^3$
$\bf{My\; Try::}$ Let $f(x)=2^x-x^3-1\;,$ Then $f'(x)=2^x\cdot \ln(2)-3x^2$
and $f''(x)=2^{x}\cdot (\ln 2)^2-6x$ and $f'''(x)=2^x\cdot (\ln2)^3-6$ and $f''''(x)=2^x\cdot (\ln 2)^4>0\; \forall\;  x\in \mathbb{R}$
So $f''''(x) = 0$ has no real roots. So using $\bf{LMVT}$, The equation $f'''(x)=0$ has at most one real
roots. So $f''(x) = 0$ has $2$  at most real roots. So $f'(x) = 0$ has $3$ at most  real roots. So $f(x)=0$
has at most at most $4$ real roots.
Here $x=0$ and $x=1$ are two integer roots
But How can i find that $f(x)=0$ has exactly $4$ real roots
Help me, Thanks

A: You showed there are at most 4 real roots. You can show there are at least 4 real roots by using the continuity of $f(x)$ and showing four intervals where it changes sign. Show and use these facts:
$$f(-1)>0$$
$$f \left(-\frac 12 \right)<0$$
$$f \left(\frac 12 \right)>0$$
$$f(2)<0$$
$$f(10)>0$$

A: Well, let me add something :
$f'''(x)$ is continuous and monotonous in $\mathbb{R}$, and we have :  $$\forall x \in \mathbb{R}, f''''(x)>0$$ and $$\lim_{x\to-\infty} f(x)=-6, \lim_{x\to\infty} f(x)=\infty$$  using LMVT the equation $f'''(x)=0$ has only one solution in $\mathbb{R}$, using the same method until we get $f(x)=0$ has exactly $4$ solutions $\forall x \in \mathbb{R}$.


text:
Q: How can I change a button's color back? I am using python tkinter to make my gui and I want the user to be able to use a key on their keyboard to similate a button press. With this, I need to make it look like they hit the button by changing its color. I have this so far:
def clickedButton(event, number, button):
    global outputCalc

    outputCalc.config(text = number)
    button.configure(bg = "red")

numbers1Button = Button(root, text="1", padx=90, pady=90, bg='#FFFFFF', activebackground='#D9D9D9')
numbers1Button.bind('<Button-1>', lambda event: clickedButton(event, 1, numbers1Button))
root.bind('<Key-1>', lambda event: clickedButton(event, 1, numbers1Button))

When I make it sleep and then change the background color back to white it doesn't do anything. I have also tried some other methods, but none of them have been successful. However, when I use this code, It successfully changes the button's color to red. Is there any way I can make this work? Also, if there is an easier way of doing it I would like to know. Thank you!

A: Note that tkinter mainloop can only update widgets when it takes back the control, i.e. after clickedButton() returns.  So if you change the button to red, sleep and change it back to white inside the function, then you will only see the button in white after the function.
You can use .after() instead of sleep() to change the button to white after some delay:
def clickedButton(event, number, button):
    ...
    button.configure(bg="red")
    button.after(100, lambda: button.configure(bg="white"))

However I would suggest to bind <KeyRelease-1> to same function and determine the color based on the bind event type:
def clickedButton(event, number, button):
    ...
    color = "red" if event.type == EventType.KeyPress else "white"
    button.configure(bg = color)

...
root.bind('<Key-1>', lambda event: clickedButton(event, 1, numbers1Button))
root.bind('<KeyRelease-1>', lambda event: clickedButton(event, 1, numbers1Button))


text:
Q: Persist Object using Hibernate and Guice I want to persist an object in my database, I'm using @Trasactional and @Inject from Guice to persist the data .... the hibernate configuration is declared in a file persistence.xml in ressources/meta-inf folder ....
import ca.model.jpa.user;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;

import javax.persistence.EntityManager;
import javax.ws.rs.*;

@Path("/test")
public class TestService {

    @Inject
    private EntityManager entityManager;

    @GET
    @Transactional
    public String persistUser() {

        // User
        User user = new User();
        user.setPseudoname("Anonymous");
        user.setAge(20);

        entityManager.persist(user);

        return null;
    }

when I debug my code, the entityManager is always null ... In my understanding, the injection aim to initiate the entityManager. But it doesn't do so !
How can I correct My code ? thank you

Here the content of my file persistence.xml :
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">

    <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>

        <properties>

            <!--PostgreSQL-->
            <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/postgres"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
            <property name="hibernate.connection.username" value="postgres"/>
            <property name="hibernate.connection.password" value="postgres"/>
            <property name="hibernate.archive.autodetection" value="class"/>
            <property name="hibernate.id.new_generator_mappings" value="true"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
            <property name="hibernate.ejb.metamodel.generation" value="disabled"/>
            <property name="hibernate.ejb.naming_strategy" value="org.hibernate.cfg.DefaultComponentSafeNamingStrategy"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>

    </persistence-unit>

</persistence>

A: Your EntityManager is not injected.
Did you implement a persistence module?
public class ExampleHibernateModule extends PrivateModule {

    @Override
    public void configure() {

        install(new JpaPersistModule("example-persistence-unit").properties(jpaProperties()));

        bind(ExampleAO.class).to(ExampleImpl.class);

        expose(ExampleDAO.class);

        Key<PersistFilter> key = Key.get(PersistFilter.class, ExamplePersistenceUnit.class);
        bind(key).to(PersistFilter.class);
        expose(key);
    }

    Properties jpaProperties() {

        Properties appProperties = PropertiesUtils.getApplicationProperties();
        Properties properties = new Properties();

        properties.put("hibernate.connection.driver_class", "org.postgresql.Driver");
        properties.put("hibernate.connection.url", appProperties.get("hibernate.connection.url"));
        properties.put("hibernate.connection.username", appProperties.get("hibernate.connection.username"));
        properties.put("hibernate.connection.password", appProperties.get("hibernate.connection.password"));
        properties.put("hibernate.connection.pool_size", "1");
        properties.put("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
        properties.put("hibernate.hbm2ddl.auto", appProperties.get("hibernate.hbm2ddl.auto"));
        properties.put("hibernate.show_sql", appProperties.get("hibernate.show_sql"));
        properties.put("hibernate.format_sql", appProperties.get("hibernate.format_sql"));
        properties.put("hibernate.cache.use.query_cache", "true");
        properties.put("hibernate.cache.use_second_level_cache", "true");

        return properties;
    }
}

Another implementation example:
Hibernate with JPA Annotations and Guice

A: Could you please share your persistence.xml? Because inside this file you can among other things declare the transaction type of your entity manager. Be sure you have listed that correctly.
And here's also a nice link: http://piotrnowicki.com/2012/11/types-of-entitymanagers-application-managed-entitymanager/


text:
Q: Three-way pivot table or complex relationship in Laravel I have two tables, shipments and customers. In the real world, a customer can be related to a shipment in three ways: as the biller, the destination and/or the origin.
So my question here is, do I have a pivot table with three columns, one for the shipment_id, one for the customer_id, and one for the relationship_type id? Or do I have separate tables? I'm not sure how best to approach this as it's the first of it's kind that I've run up against.

A: I faced this couple weeks ago and I came up with a solution.

Assuming that one customer can have different relations to different
  shipments.

First of all you need a new model for customer roles obviously that model it will be Relation model.
First approach: You could solve this by using more than one pivot table which works but its not a good database design. I solved it first like this but realized its not optimal choice when it comes to db.
Second approach: You could solve this by defining pivot table as a model, but I havent tried that way even though I know it works and its a solution.
Better approach: use one pivot table for three models. In that case you have to define pivot table when you define a relationship example :
Customer model:
public function relations()
{
    return $this->belongsToMany(Relation::class, 'customer_relation_shippment');
}

Relation model:
public function customers()
{
    return $this->belongsToMany(Relation::class, 'customer_relation_shippment');
}

and the other model as well.
now lets say you want to add a relation to a customer.
Lets grab first customer and first shipment and say we want to add a relation as a biller:
$customer = Customer::first();

$shipment = Shipment::first();

$relation = Relation::where('name','biller')->get();

$customer->relations()->attach($shipment->id, ['relationship_type'=>$relation->id]);

By using only one pivot table of course its a bit more complex to perform operations towards those models like CRUD, but when it comes to database design/optimazation of course it is the right choice! Note that I came to this conclusion after dealing with a similar real world issue and it turned way more faster db interaction then using more than one pivot.

A: Here is how I would design your project.
I don't think you even need a pivot table or many-to-many relationship.
Note:  For clarity and avoiding confusion with the User, I will use Account to refer to what you call a Customer. At the end you used customer account in your comments.
You have a shipment that relates to three different entities. However, those entities are represented by the same data model in your database: the Account model.
A basic one-to-many relationship will suffice.
An account can have many shipments. And the shipment belongs to one account.
Now, how to add the "Type" of the relationship? We don't need a pivot table, we just add another one-to-many relationship.

*

*An Account as biller may have many shipments, and the shipment belongs to one biller.

*An Account as origin may have many shipments, and the shipment belongs to one origin.

*An Account as destination may have many shipments, and the shipment belongs to one origin.
To explain, here is an example code:
We have three models: User, Account, and Shipment
Let's start with the schema:
    Schema::create('accounts', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->timestamps();
    });

    Schema::create('shipments', function (Blueprint $table) {
        $table->increments('id');
        $table->string('from');
        $table->string('to');

        $table->unsignedInteger('biller_id');
        $table->unsignedInteger('origin_id');
        $table->unsignedInteger('destination_id');

        $table->foreign('biller_id')
            ->references('id')->on('accounts');

        $table->foreign('origin_id')
            ->references('id')->on('accounts');

        $table->foreign('destination_id')
            ->references('id')->on('accounts');

        $table->timestamps();
    });

We have three columns referencing the id on the accounts table.
For the models and the relationships:
Account Model:
class Account extends Model
{
    public function billerShipments()
    {
        return $this->hasMany(Shipment::class, 'biller_id');
    }

    public function originShipments()
    {
        return $this->hasMany(Shipment::class, 'origin_id');
    }

    public function destinationShipments()
    {
        return $this->hasMany(Shipment::class, 'destination_id');
    }

    public function users()
    {
        return $this->belongsToMany(User::class);
    }

}

Shipment Model:
class Shipment extends Model
{
    public function billerAccount()
    {
        return $this->belongsTo(Account::class, 'biller_id');
    }

    public function originAccount()
    {
        return $this->belongsTo(Account::class, 'origin_id');
    }

    public function destinationAccount()
    {
        return $this->belongsTo(Account::class, 'destination_id');
    }

}

Example to create a shipment
    $billerAccount = \App\Account::create(['name' => 'account b']);
    $originAccount = \App\Account::create(['name' => 'account a']);
    $destinationAccount = \App\Account::create(['name' => 'account c']);

    $newShipment = \App\Shipment::create([
        'from'           => 'city 1',
        'to'             => 'city 2',
        'biller_id'      => $billerAccount->id,
        'origin_id'      => $originAccount->id,
        'destination_id' => $destinationAccount->id,
    ]);

    echo $billerAccount->billerShipments()->count(); // 1
    echo $originAccount->originShipments()->count(); // 1
    echo $destinationAccount->destinationShipments()->count(); // 1

    echo $newShipment->billerAccount->name === $billerAccount->name; // 1
    echo $newShipment->originAccount->name === $originAccount->name; // 1
    echo $newShipment->destinationAccount->name === $destinationAccount->name; // 1

For the account-user relationships, it can be many-to-many or one-to-many depending on your requirements.


text:
Q: Array of unique numbers I'm trying to write a function that returns an array of unique numbers. The array must be sorted. The function works fine when there are more than just one element, but it doesn't work for when there is just one element in the array. The function should return the only element found in that array, but instead, it is returning an empty array.
Why is this happening?
Array must be sorted for numUnique and removeDuplicates
    public static int numUnique (double[] list){
    int uniques = 1;
    int i = 1;
    if(list.length == 0) return 0;
    while(i<list.length){
        if(list[i] != list[i - 1])
            uniques++;
        i++;
    }
    return uniques;
}

    public static double[] removeDuplicates(double[] list){
    double[] arrayOfUniques = new double[numUnique(list)];
    if(list.length == 0) return arrayOfUniques;

    int uniques = 1;
    int i = 1;
    arrayOfUniques[0] = list[0];
    while(i < list.length){
        if(list[i] != list[i - 1])
            arrayOfUniques[uniques++] = list[i];
        i++;
    }
    return arrayOfUniques;
}

Array:
double[] a = {11,11,21,31,41,41,51,61,61,61,71,71,81,91,91,100,100};
Output:
Unique numbers: 9
Array of uniques:
[11.0, 21.0, 31.0, 41.0, 51.0, 61.0, 71.0, 81.0, 91.0]
But it doesn't work when the array just has one element:
 double[] a = {11};

Output:
Unique numbers: 0
Array of uniques:[]

A: Try this.. Convert your array to list & convert list to set
Set not have duplicate values.. simple
List<String> myList= Arrays.asList(a);//convert array to List
Set<Double> uniqueSet = new HashSet<Double>(myList);//you get unique values

If you want to Set to Array try this https://stackoverflow.com/a/5982478/3879847

A: public List<Double> removeDuplicates (List<Double> list){
        // add elements to al, including duplicates
        Set<Double> hs = new HashSet<Double>();
        hs.addAll(list);
        list.clear();
        list.addAll(hs);
        return list;
    }

A: Actually, it doesn't work for arrrays having only one unique element either (e.g. it returns empty array for new double[]{11.0,11.0, 11.0}). I would recommed a simpler approach using Java 8's stream:
public static double[] removeDuplicates(double[] list){
    LinkedHashSet<Double> uniqueElements = Arrays.stream(list)
    .boxed()
    .collect(Collectors.toCollection(LinkedHashSet::new));
    return uniqueElements.stream().mapToDouble(d -> d).toArray();
}

A: With Java 8 we get Stream, so how to use it in this case :
public static void main (String[] args) {
    double[] a = {11,11,21,31,41,41,51,61,61,61,71,71,81,91,91,100,100};
    //Way 1 just to print the unique element
    DoubleStream.of(removeDuplicate(a)).forEach(System.out::println);
    //Way 2 to save the update the array with only the unique element
    a = removeDuplicate(a);
}

private static double[] removeDuplicate(double[] a) {
    return DoubleStream.of(a).distinct().sorted().toArray();
}

In the main, we're just calling the method, and then read the result and print the values
In the removeDuplicate method : we create  Stream of the values, then we keep only the different elements, then we sort them, and them we come back to an array (to follow your wishes)
If you're not sure to HAVE to use array, better use List every time ;)


text:
Q: Deploy 2 dependent cloudformation stack parts in 2 regions I want to deploy 2 cloudformation stack parts in 2 different regions(us-east-1, eu-west-1).
One part creates vpc and x resources - I want deploy to us-east-1.
Second part creates y resources with dependencies to x.Outputs - I want deploy to eu-west-1.
I can't simply run the stack in eu-west-1 region( it will create only the first part)
Any way to do that?

A: When you deploy your stacks programmatically, using CLI for example and bash, you can do the following (cli example):

*

*use [deploy] command to deploy your stack in the first region. CLI has --region parameter to specify the region for the operation.

*using basic loop you can wait for the stack to be created. describe-stacks provides status of the stack creation.

*once the status is CREATE_COMPLETE you call describe-stacks  one more time to get it outputs.

*you take the outputs from the stack, and deploy the second stack in the region you want. deploy command has --parameter-overrides which you can specify the input parameters for the second stack. These inputs will be from the outputs you got from the first stack.
You can do similar things using SDK, e.g. boto3 in python.


text:
Q: Behavior of intellisense in solution of multiple projects? There is no way (at least for me) to find out information for this very specific question.
I need to know, If Solution in Visual Studio has multiple projects, how does intellisense works in that case:

*

*does it scan all projects, and spends valuable computer resources for all projects, OR

*does intellisense work only for the project I'm currently working on in solution?

If the answer is case 1. (and hopefully you have some reference to backup this claim) then I wan't to know if there is anything I can to to limit inellisense activity to work only on a project I currently have opened.
I don't know but I think this approach could help speed up intellisense, and maybe also help reduce the amount of background tasks related to regualar intellisense scans.
thsese projects are not really small, and I have over 20 of them in one solution, (not much I can do about that btw.), and I'm getting tired of seeing slow performance due to these frequent parsings.

A:
1.does it scan all projects, and spends valuable computer resources for all projects, OR
2.does intellisense work only for the project I'm currently working on in solution?

The answer, of course, is case 1. Intellisense works by default on the entire solution, not on a single project. It just subdivides individual files, such as c++, c#, js, XML, and so on. You can got it from Tools-->Options-->Text Editor-->(c#/c++/javascript/....)-->general/IntelliSense. You can then enable or disable Intellisense based on a single file type.

does intellisense work only for the project I'm currently working on
in solution?

I think the answer is negative. I looked for a lot of documents on Intellisense and didn't find any examples of Intellisense being used for a project. This feature of Intellisense is not proposed by Microsoft. If you want this feature,  you could suggest a feature to the Support Team to get their attention.
In addition, maybe it's not Intellisense that affects VS performance. You can refer to this document to improve VS performance.
Hope this could help you.


text:
Q: Writing values to excel csv in python I have the below code where I'm trying to write values to an excel file, but my output adds one letter in every single column, instead of the whole word, like so

I want the whole word to be in one column. I'm currently passing in an array that has the words [u'Date / Time', u'City', u'State', u'Shape', u'Duration', u'Summary'] into my writer. How can I make it so that I get the whole word in one column?
import requests
import csv
from bs4 import BeautifulSoup

r = requests.get('http://www.nuforc.org/webreports/ndxlAK.html')
soup = BeautifulSoup(r.text, 'html.parser')
csv.register_dialect('excel')

f = open('ufo.csv', 'wb')
writer = csv.writer(f)

headers = soup.find_all('th')
header_text = []
header_count = 1
for header in headers:
    if header_count == len(headers):
        print "value being written: " + str(header_text)
        writer.writerows(header_text)
    else:
        header_text.append(header.text)
        header_count += 1

f.close()

A: You're extracting the text of a single column via:

for header in headers

For each single column, you're writing it out like a row of columns via:

writer.writerows(header_text)

The writerows method expects a list of columns to write, so it iterates over it.  You've passed it a single string, so it iterates over that and writes one character per column.
So either:
writer.writerows([header_text])  # turn this single column into a list
# or
writer.writerow(header_text)  # just write out as a single item

should work.


text:
Q: habilitar y deshabilitar boton submit con react-form-hook en React Estoy utilizando react-hook-form para mi formulario que consta de dos input, uno para escribir el titulo y el otro para la descripcion del producto.
cuando se hace el submit del formulario, la data de los input se guarda en una variable de estado llamada Entradas y se limpia el formulario. La idea es que mi formulario inicie con el boton submit inhabilitado y que solo se habilite cuando el formulario es valido.
De la forma que lo hice inicia inhabilitado pero nunca se habilita.

import React, { Fragment, useState } from "react";
import { useForm } from "react-hook-form";
import { yupResolver } from "@hookform/resolvers/yup";
import * as yup from "yup";

const schema = yup.object().shape({
  title: yup.string().required('campo obligatorio'),
  description: yup.string().required('campo obligatorio!'),
  // description: yup.number().positive().integer().required(),
});

const EjemploUno = () => {

  const{formState} = useForm();

  const {register,handleSubmit,formState: { errors },} = useForm({
    resolver: yupResolver(schema),
  });

  const [Entradas, setEntradas] = useState([]);

  const onSubmit = (data, event) => {
      //event.preventDefault();
      console.log(data);
      setEntradas([
          ...Entradas, data
      ])

      // Limpia el formulario
      event.target.reset();
    }

  return (
    <Fragment>
      <form onSubmit={handleSubmit(onSubmit)}>
        <input
            name="title"
            type="text"
            {...register("title")}
            placeholder="titulo"
            className="form-control"
        />
        {errors.title?.message}

        <input
            name="description"
            type="text"
            {...register("description")}
            placeholder="description"
            className="form-control"
        />
        {errors.description?.message}

        <button
          type="submit"
          disabled={!formState.isDirty || !formState.isValid}>
            Enviar
        </button>

      </form>

      {
        Entradas.map((item, index) =>

{item.title} - {item.description}

        )
      }

    </Fragment>
  );
};

export default EjemploUno;


text:
Q: How to read all data from SAP GUI window with VBA I'm trying to automate T-Code-VA03.
I enter the PO number in PO number text box and press F8.

This prompts a window which contains multiple rows of labels.

My requirement is, I want to select the one with latest date. I tried to record the script for it and below the code.
session.findById("wnd[0]/usr/txtRV45S-BSTNK").text = "123456789"
session.findById("wnd[0]/usr/txtRV45S-BSTNK").setFocus
session.findById("wnd[0]/usr/txtRV45S-BSTNK").caretPosition = 8
session.findById("wnd[0]").sendVKey 8
session.findById("wnd[1]/usr/lbl[49,6]").setFocus
session.findById("wnd[1]/usr/lbl[49,6]").caretPosition = 0

I can see there are labels with indexes. How can I iterate through whole window and take the focus to row with latest date?

A: With VB script you could try the following:
. . .
session.findById("wnd[0]").sendVKey 8
for i = 6 to 99
 on error resume next
 session.findById("wnd[1]/usr/lbl[49," & cstr(i) & "]").setFocus
 if err.number <> 0 then Exit for
 on error goto 0
 session.findById("wnd[1]/usr/lbl[49," & cstr(i) & "]").caretPosition = 0
next

Regards,
ScriptMan

A: If you really need to do something like iterating through window and taking the focus to row with latest date, do not do it with VBA, because you may get into lots of problems.
Having said the one above, try with sendkeys https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-sendkeys-method-excel and send TAB. Then make a code searching for "Item" in your form. After this, send tab 8 times to go to the PO Date. Write the date on a list. Send TAB again 11 times to the next date. Write it on a list. And so, until there are no more dates.
Anyhow, as I mentioned, this is not a great solution. The best way is simply to ask the DB Admin for read-only access to the DB or a customized view. With it, you can make a robust solution, which reads the latest date.


text:
Q: How to write a list of combinations to a file in python import itertools
stuff = [1,2,3]
for i in range(0, len(stuff)+1):
    for subset in itertools.combinations(stuff, L):
        print(subset)

Is there a way to write this to a file instead of printing it on the screen?

A: Something like this should work:
import itertools
stuff = [1,2,3]
with open("a_file.txt", "w") as the_file:
    for i in range(0, len(stuff)+1):
        for subset in itertools.combinations(stuff, L):
            print(subset)
            the_file.write(str(subset))

A: You need to open a file and write your data , in it . but note that the write function only accept string so you need to convert your list to string with str function .
import itertools
stuff = [1,2,3]

with open('out.txt','w') as f :
   for i in range(0, len(stuff)+1):
      for subset in itertools.combinations(stuff, L):
        f.write(str(subset))

A: In python 3, you can print directly to a file, to do that you need a file object
out = open(filename)

and the keyword argument file= in your print
print(subset, file=out)

BTW, this is possible, albeit with different syntax, also in python 2
print >>out, subset


text:
Q: RecyclerView and CardView implement onClick I have a bunch of values that get pulled from mysql database and then are displayed in cardview using RecyclerView. This works great.
I want to now implement onClick on each item that is pulled, can anyone please point me in the right direction? I'm looking at being able to click on a card and have another view open with the "image", "name" and "publisher" values that are pulled from mysql using json, problem is I don't know how to pass these values onto a new activity, especially the values being pulled from mysql.
Movies.java
public class Movies extends AppCompatActivity implements RecyclerView.OnScrollChangeListener {

//Creating a List of superheroes
private List<SuperHero> listSuperHeroes;

//Creating Views
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private RecyclerView.Adapter adapter;

//Volley Request Queue
private RequestQueue requestQueue;

//The request counter to send ?page=1, ?page=2  requests
private int requestCount = 1;

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

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    //Initializing Views
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);
    layoutManager = new GridLayoutManager(this,2);
    recyclerView.setLayoutManager(layoutManager);

    recyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST));
    recyclerView.setItemAnimator(new DefaultItemAnimator());

    //Initializing our superheroes list
    listSuperHeroes = new ArrayList<>();
    requestQueue = Volley.newRequestQueue(this);

    //Calling method to get data to fetch data
    getData();

    //Adding an scroll change listener to recyclerview
    recyclerView.setOnScrollChangeListener(this);

    //initializing our adapter
    adapter = new CardAdapter(listSuperHeroes, this);

    //Adding adapter to recyclerview
    recyclerView.setAdapter(adapter);
}

//Add back button to go back
@Override
public void onBackPressed() {
    super.onBackPressed();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
}

public boolean onSupportNavigateUp(){
    finish();
    overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    return true;
}

//Request to get json from server we are passing an integer here
//This integer will used to specify the page number for the request ?page = requestcount
//This method would return a JsonArrayRequest that will be added to the request queue
private JsonArrayRequest getDataFromServer(int requestCount) {
    //Initializing ProgressBar
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    //Displaying Progressbar
    progressBar.setVisibility(View.VISIBLE);
    setProgressBarIndeterminateVisibility(true);

    //JsonArrayRequest of volley
    JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(ConfigMovies.DATA_URL + String.valueOf(requestCount),
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    //Calling method parseData to parse the json response
                    parseData(response);
                    //Hiding the progressbar
                    progressBar.setVisibility(View.GONE);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    progressBar.setVisibility(View.GONE);
                    //If an error occurs that means end of the list has reached
                    Toast.makeText(Movies.this, "No More Items Available", Toast.LENGTH_SHORT).show();
                }
            });

    //Returning the request
    return jsonArrayRequest;
}

//This method will get data from the web api
private void getData() {
    //Adding the method to the queue by calling the method getDataFromServer
    requestQueue.add(getDataFromServer(requestCount));
    //Incrementing the request counter
    requestCount++;
}

//This method will parse json data
private void parseData(JSONArray array) {
    for (int i = 0; i < array.length(); i++) {
        //Creating the superhero object
        SuperHero superHero = new SuperHero();
        JSONObject json = null;
        try {
            //Getting json
            json = array.getJSONObject(i);

            //Adding data to the superhero object
            superHero.setImageUrl(json.getString(ConfigMovies.TAG_IMAGE_URL));
            superHero.setName(json.getString(ConfigMovies.TAG_NAME));
            superHero.setPublisher(json.getString(ConfigMovies.TAG_PUBLISHER));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //Adding the superhero object to the list
        listSuperHeroes.add(superHero);
    }

    //Notifying the adapter that data has been added or changed
    adapter.notifyDataSetChanged();
}

//This method would check that the recyclerview scroll has reached the bottom or not
private boolean isLastItemDisplaying(RecyclerView recyclerView) {
    if (recyclerView.getAdapter().getItemCount() != 0) {
        int lastVisibleItemPosition = ((GridLayoutManager) recyclerView.getLayoutManager()).findLastCompletelyVisibleItemPosition();
        if (lastVisibleItemPosition != RecyclerView.NO_POSITION && lastVisibleItemPosition == recyclerView.getAdapter().getItemCount() - 1)
            return true;
    }
    return false;
}

//Overriden method to detect scrolling
@Override
public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
    //Ifscrolled at last then
    if (isLastItemDisplaying(recyclerView)) {
        //Calling the method getdata again
        getData();
    }
}
}

CardAdapter.java
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {

//Imageloader to load image
private ImageLoader imageLoader;
private Context context;

//List to store all superheroes
List<SuperHero> superHeroes;

//Constructor of this class
public CardAdapter(List<SuperHero> superHeroes, Context context){
    super();
    //Getting all superheroes
    this.superHeroes = superHeroes;
    this.context = context;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.superheroes_list, parent, false);
    ViewHolder viewHolder = new ViewHolder(v);
    return viewHolder;
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {

    //Getting the particular item from the list
    SuperHero superHero =  superHeroes.get(position);

    //Loading image from url
    imageLoader = CustomVolleyRequest.getInstance(context).getImageLoader();
    imageLoader.get(superHero.getImageUrl(), ImageLoader.getImageListener(holder.imageView, R.drawable.ic_blank, android.R.drawable.ic_dialog_alert));

    //Showing data on the views
    holder.imageView.setImageUrl(superHero.getImageUrl(), imageLoader);
    holder.textViewName.setText(superHero.getName());
    holder.textViewPublisher.setText(superHero.getPublisher());

}

@Override
public int getItemCount() {
    return superHeroes.size();
}

class ViewHolder extends RecyclerView.ViewHolder{
    //Views
    public NetworkImageView imageView;
    public TextView textViewName;
    public TextView textViewPublisher;

    //Initializing Views
    public ViewHolder(View itemView) {
        super(itemView);
        imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
        textViewName = (TextView) itemView.findViewById(R.id.textViewName);
        textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
    }
}
}

Movies.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_centerInParent="true" />
<ProgressBar
    android:id="@+id/progressBar1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true" />
</LinearLayout>

superheroes_list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:nestedScrollingEnabled="false"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="3dp">
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="@dimen/activity_horizontal_margin">
        <com.android.volley.toolbox.NetworkImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/imageViewHero"
            android:layout_gravity="center_horizontal" />
        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <TableRow>
                <TextView
                    android:text="Name"
                    android:paddingRight="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/textViewName"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
            </TableRow>
            <TableRow>
                <TextView
                    android:text="Publisher"
                    android:paddingRight="10dp"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"/>
                <TextView
                    android:id="@+id/textViewPublisher"
                    android:textStyle="bold"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
            </TableRow>
        </TableLayout>
    </LinearLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>

A: *

*Let the ViewHolder class implement View.OnClickListener, then move it into CardAdapter class.

*Call setOnClickListener(this) just after calling super inside ViewHolder constructor like that:
public ViewHolder(View itemView) {
    super(itemView);
    itemView.setOnClickListener(this);
    imageView = (NetworkImageView) itemView.findViewById(R.id.imageViewHero);
    textViewName = (TextView) itemView.findViewById(R.id.textViewName);
    textViewPublisher = (TextView) itemView.findViewById(R.id.textViewPublisher);
}

@Override
public void onClick(View view) {
    // here you can get your item by calling getAdapterPosition();
    SuperHero superHero =  superHeroes.get(getAdapterPosition());
}


text:
Q: Auto update svn using post-commit hook I am hosting a SVN repository and I want to set up a hook that launches after commit, so post-commit.
I see a lot of scripts using C but I am not sure how and if that works on Debian.
I have a Debian 32 bit server. So where would I need to set the script because I have a hooks folder with some scripts in it already (generated automatically). The current present post-commit script is this:
hooks/post-commit.tmpl
#!/bin/sh

# POST-COMMIT HOOK
#
# The post-commit hook is invoked after a commit.  Subversion runs
# this hook by invoking a program (script, executable, binary, etc.)
# named 'post-commit' (for which this file is a template) with the
# following ordered arguments:
#
#   [1] REPOS-PATH   (the path to this repository)
#   [2] REV          (the number of the revision just committed)
#
# The default working directory for the invocation is undefined, so
# the program should set one explicitly if it cares.
#
# Because the commit has already completed and cannot be undone,
# the exit code of the hook program is ignored.  The hook program
# can use the 'svnlook' utility to help it examine the
# newly-committed tree.
#
# On a Unix system, the normal procedure is to have 'post-commit'
# invoke other programs to do the real work, though it may do the
# work itself too.
#
# Note that 'post-commit' must be executable by the user(s) who will
# invoke it (typically the user httpd runs as), and that user must
# have filesystem-level permission to access the repository.
#
# On a Windows system, you should name the hook program
# 'post-commit.bat' or 'post-commit.exe',
# but the basic idea is the same.
#
# The hook program typically does not inherit the environment of
# its parent process.  For example, a common problem is for the
# PATH environment variable to not be set to its usual value, so
# that subprograms fail to launch unless invoked via absolute path.
# If you're having unexpected problems with a hook program, the
# culprit may be unusual (or missing) environment variables.
#
# Here is an example hook script, for a Unix /bin/sh interpreter.
# For more examples and pre-written hooks, see those in
# /usr/share/subversion/hook-scripts, and in the repository at
# http://svn.apache.org/repos/asf/subversion/trunk/tools/hook-scripts/ and
# http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/

REPOS="$1"
REV="$2"

"$REPOS"/hooks/mailer.py commit "$REPOS" $REV "$REPOS"/mailer.conf

A: If you need functionality of current script then add your script code at the end of current script. If you don't need functionality of current script then just remove current script altogether and add your own script.
EDIT: Is this script that is listed in the question the actual script that you want to be executed on post commit hook? If yes then rename it to post-commit.sh and copy it to hooks folder of your repository. Disregard post-commit.tmpl, because that is just an example, a template script.


text:
Q: Split string into array of equal length strings I have a string that I need split into smaller strings with an equal length of 6. I tried using:
'abcdefghijklmnopqrstuvwxyz'.split(/(.{6})/)

But it returns an array with empty strings like so:
["", "abcdef", "", "ghijkl", "", "mnopqr", "", "stuvwx", ""]

A: Use match in conjunction with a global flag, instead of split. {1,6} is needed, to also include the last part of the matched string. Patterns are greedy by default, which means that as much is matched as possible. So, .{1,6} will only match less than 6 characters at the end of a string.
'abcdefghijklmnopqrstuvwxyz'.match(/.{1,6}/g);

Result:
["abcdef", "ghijkl", "mnopqr", "stuvwx", "yz"];

Note that the returned object is a true array. To verify:
console.log('.'.match(/./g) instanceof Array);  //true


text:
Q: Lazy instantiation before or inside of a loop I'm trying to implement lazy instantiation within my code to speed up my app. My question is, when dealing with a for loop, should I create an object right before the loop begins, or within the loop, basically should I do this:
NSPredicate *pred= [NSPredicate predicateWithFormat:@"self LIKE %@", filter];
for(NSString* str in myArray){
//do stuff
}

or this:
for(NSString* str in myArray){
//do stuff
NSPredicate *pred= [NSPredicate predicateWithFormat:@"self LIKE %@", filter];
//do stuff that needs this variable
}

My thoughts were to do the first one, but a friend says the 2nd one, although isn't the 2nd one creating the object everytime you go through the loop so it's more costly?

A: Neither one of these is truly lazy:

*

*The first one creates the predicate even when the loop does not need to execute at all

*The second one is optimal only when the loop executes once; otherwise, throw-away instances of NSPredicate get created.

If you wish to stay truly lazy, you could add a condition around the first code example to check that myArray is not empty. You could also use a conditional expression, like this:
NSPredicate *pred= myArray.count ? [NSPredicate predicateWithFormat:@"self LIKE %@", filter] : nil;

This is not particularly readable, though, so I would recommend staying with your first approach, which is optimal when the loop is entered at least once.

A: Well, lazy instantiation would look something like this I think...
NSPredicate *pred = nil;

for (NSString *string in myArray) {
    // do stuff...

    // if predicate is required
    if (!pred) {
        pred = [NSPredicate predicateWithFormat:@"self LIKE %@", filter];
    }
    // use pred
}

But out of the three options. I'd use your first method.

A: I don't see much of a choice, with the first way being both clean and simple.  The equivalent alternative is actually:
NSPredicate *pred = nil;
for (NSString* str in myArray){
    if (!pred)
        pred = [NSPredicate predicateWithFormat:@"self LIKE %@", filter];
    //do stuff
}

Which is clearly more complicated than it needs to be.
I would also argue that this isn't really lazy initialization, which really relates to initialization of instance variables at some point after object creation.


text:
Q: Fields duplicated during de-serialization I have a class which looks like this :
public class Item {
private ItemHeader header;
private ItemBody body;
}

public class ItemHeader {
private int id;
private String name;
}
public class ItemBody {
private List<String> values;
private List<String> details;

}
The fields of ItemHeader and ItemBody are accessible via setters and getters from the Item class as well as from their corresponding classes. All said setters and getters EXCEPT get/setItemBody +get/setItemHeader are annotated with @JsonIgnore.
When Item instance is returned by a GET REST method, the Response looks as following :
    {
  "body": {
    "details":[]
    "values":[]
  },
  "header": {
    "id": 145,
    "name": "name_of_item",
   },
    "details":[],
    "values":[],
    "id": 145,
    "name": "name_of_item"
}

Internals of itemHeader and itemBody are spilled twice into the deserialized Json , once (correctly) inside the corresponding fields and the second time just outside them.
I do not have much control over Jackson definitions behind the scenes and can basically only control my class hierarchy with annotations and such.
Please advise - how to remove the duplication, the "spilled over" values...

A: I've ended up removing the double layer of getters/setters which solved the issue, and in the process discovered that indeed, the serialization path and the de- path used different libraries . So https://stackoverflow.com/users/2513573/adamskywalker had the right idea


text:
Q: The "android" prefix of the "android: versionCode" attribute associated with an "manifest" element type is not linked So, I'm trying to deploy my app into my device, but I'm getting this error:
The "android" prefix of the "android: versionCode" attribute associated with an "manifest" element type is not linked
Here's my AndroidManifest
<?xml version='1.0' encoding='utf-8'?>
<manifest android:versionCode="1" android:versionName="0.0.1" package="io.ionic.starter" xmlns:tools="http://schemas.android.com/tools">
    <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
    <uses-permission android:name="android.permission.INTERNET" />
    <application android:hardwareAccelerated="true" android:icon="@mipmap/icon" android:label="@string/app_name" android:supportsRtl="true">
        <activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale" android:label="@string/activity_name" android:launchMode="singleTop" android:name="MainActivity" android:theme="@android:style/Theme.DeviceDefault.NoActionBar" android:windowSoftInputMode="adjustResize">
            <intent-filter android:label="@string/launcher_name">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:exported="false" android:name="de.appplant.cordova.plugin.localnotification.TriggerReceiver" />
        <receiver android:exported="false" android:name="de.appplant.cordova.plugin.localnotification.ClearReceiver" />
        <activity android:exported="false" android:launchMode="singleInstance" android:name="de.appplant.cordova.plugin.localnotification.ClickReceiver" android:theme="@android:style/Theme.Translucent" />
        <provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="de.appplant.cordova.plugin.notification.util.AssetProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/localnotification_provider_paths" tools:replace="android:value" />
        </provider>
        <provider android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true" android:name="de.appplant.cordova.plugin.notification.util.AssetProvider">
            <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/localnotification_provider_paths" />
        </provider>
    </application>
    <uses-sdk android:minSdkVersion="19" android:targetSdkVersion="27" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
</manifest>

Am I doing something wrong?


text:
Q: vba pivot table in new sheet of same workbook With the help of below coding, I am able to create Pivot table. I am facing problem when I change the table destination to another sheet.
If I use below coding, it is working fine.
Set PT = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, Tabledestination:=Range("A1"))
If I use below coding, it is showing error as invalid procedure.
Set PT = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, Tabledestination:=ThisWorkbook.Sheets("Sheet4").Range("A1"))
Complete code.
Dim PT As PivotTable
Dim PTCache As PivotCache

Worksheets("Sheet3").Select
Set PT = ActiveSheet.PivotTables.Add(PivotCache:=PTCache, Tabledestination:=ThisWorkbook.Sheets("Sheet4").Range("A1"))
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Cells(1, 1).CurrentRegion)
With PT
.PivotFields("phase").Orientation = xlColumnField
.PivotFields("month").Orientation = xlColumnField
.PivotFields("vertical").Orientation = xlRowField
.PivotFields("pp").Orientation = xlDataField
.DisplayFieldCaptions = False
End With

A: Use Row number and Column number referencing syntax.
This works for me:
Dim PT As PivotTable
Dim PTCache As PivotCache
Worksheets("Sheet3").Select
Set PTCache = ActiveWorkbook.PivotCaches.Create(xlDatabase, Cells(1, 1).CurrentRegion)
Set PT = PTCache.CreatePivotTable("Sheet4!R1C1", "PivotPP")
With PT
.PivotFields("phase").Orientation = xlColumnField
.PivotFields("month").Orientation = xlColumnField
.PivotFields("vertical").Orientation = xlRowField
.PivotFields("pp").Orientation = xlDataField
.DisplayFieldCaptions = False
End With

A: Try with
Tabledestination:=ThisWorkbook.Sheets("Sheet4").Name & "!R1C1"


text:
Q: Does TextField fireDoneEvent() to call stopEditing() in order to close the virtual keyyboard? I can close the virtualkeyboard from a button by calling textField.stopEditing. However, I would have expecting setting a DoneListener to close the virtualkeyboard as well when "Search" or "Go" is pressed.
The DoneListener does fire and the code is executed, but the virtualkeyboard remains open. I've tried adding a stopEditing to the DoneListerer, even placing stopEditing callSerially.

A: I just tried this on my Android OPO device and it worked as expected. The second field did nothing but the first folded the keyboard like a champ:
Form hi = new Form("TextTest", BoxLayout.y());
TextField other = new TextField("");
TextField ttt = new TextField("");
hi.add(ttt).add(other);
ttt.setDoneListener(e -> {
    hi.add(ttt.getText());
    hi.getContentPane().animateLayout(200);
});
hi.show();


text:
Q: using newaxis in Python A = np.array([[ 1, 2, 3],
             [ 4, 5, 6],
             [ 7, 8, 9],
             [10,11,12]])
B = A[:, np.newaxis]
print(B)
print(B.shape)

the output is
[[[ 1  2  3]]

 [[ 4  5  6]]

 [[ 7  8  9]]

 [[10 11 12]]]

(4L, 1L, 3L)

I have two questions:

*

*Why are there extra brackets outside brackets, for example, [[ 1  2  3]], so why it is not [ 1  2  3]?

*what does 1L mean? It looks like to me that B is a 4X3 matrix, so why is it not (4L, 3L)?

A: Refer to numpy reference document (http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html),
Each newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension. The added dimension is the position of the newaxis object in the selection tuple.

*

*Here, each bracket represent one dimension, extra bracket is caused by newaxis.

*1L means the dimension increased by newaxis.

A: The "extra" bracket and the 1L are  there for the same reason: your use of np.newaxis inserted a new dimension of extent 1 into the array shape—in other words, you transformed a two-dimensional 4x3 array into a three-dimensional 4x1x3 array.
Each of the 4 "rows" of Bcontains a two-dimensional 1x3 array, such as
[[4,5,6]]

whereas each corresponding row of A was just a one-dimensional array of length 3:
[4,5,6]

Hence the extra brackets.


text:
Q: Accuracy increase but loss also increases I am using this model.While using this model validation accuracy is  increasing but at a same time validation loss is also increasing.What happening here?
from keras.layers import Dense
from keras.models import Sequential
from keras.optimizers import adam

model_alpha1 = Sequential()
model_alpha1.add(Dense(64, input_dim=96, activation='relu'))
model_alpha1.add(Dense(2, activation='softmax'))

opt_alpha1 = adam(lr=0.001)
model_alpha1.compile(loss='sparse_categorical_crossentropy', optimizer=opt_alpha1, metrics=
['accuracy'])

history = model_alpha1.fit(x_train, y_train, validation_data=(x_test, y_test), epochs=200, verbose=1)

If need any more details i will provide just comment for the detail.Thank you

A: It seems that your model is overfitting. In other words, your model is fitting too much for the training data and that is why it is not performing as well for the validation data anymore.
Typical way to prevent overfitting is to use regularization techniques. For example:

*

*Dropout layers https://keras.io/api/layers/regularization_layers/dropout/

*Early stopping https://keras.io/api/callbacks/early_stopping/

*Noise https://keras.io/api/layers/regularization_layers/gaussian_noise/
Try to train less deep NN for your problem or try dropout layers (or both obviously depending how these would affect). From your figure, we can see that the overfitting starts after ~25 epochs.
Overfitting may be caused, for example, by using too complex model for data set, which is not large enough. Or you just train the model too long! (here early stopping will fix the issue)
Here some regularization examples with TF: https://tensorflow.rstudio.com/tutorials/beginners/basic-ml/tutorial_overfit_underfit/

A: When training a classification model, it is not possible to optimize for accuracy directly since it is not a differentiable function. Therefore, we use cross-entropy as our loss function, which is highly correlated with accuracy. When inspecting our metrics it is important to remember that these are still two different metrics.
In terms of CE loss, your model is exhibiting textbook overfitting. However, in terms of accuracy, which is what you are actually interested in, it simply "finished training". This is why we track not only the loss but also the actual metrics we are interested in in the bottom line - so that we make our decisions based on them.


text:
Q: При скролле сильно тормозит таблица или какие другим способом можно сделать круглую ImageView? Доброе время суток всем, у меня уже был похожий вопрос, но тут другое, в общем тормозит таблица при скролле, вот код:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    MyCell *cell = [[self tableView] dequeueReusableCellWithIdentifier:@"Cell"];

    Mapping *mapping = [[self arrayData] objectAtIndex:[indexPath row]];

    [[cell myTextLabel] setText:[mapping name]];
    [[cell myDetailTextLabel] setText:[mapping last_name]];
    [[cell myImageView] setImage:[UIImage imageNamed:[mapping imageData]]];

//Делаю круглую myImageView
    [self.myImageView.layer setCornerRadius:self.myImageView.frame.size.width / 2];
    [self.myImageView setClipsToBounds:YES];

    return cell;
}

Было замеченно, что тормоза из-за этих строк, которые делают myImageView круглой, но почему так, каим другим способом можно сделать круглую myImageView?
Вот код, как я делаю круглую..
[self.myImageView.layer setCornerRadius:self.myImageView.frame.size.width / 2];
[self.myImageView setClipsToBounds:YES];

Что не так в этих строках?
A: попробуй в фоне менять радиус
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Код, который должен выполнится в фоне

    dispatch_async(dispatch_get_main_queue(), ^{
        // Код, который выполнится в главном потоке
    });
});

A: Лучшее решение это использовать фон с закруглениями. Используйте 9-patсh или стандартный resizableImageWithCapInsets


text:
Q: EventMachine unbind reason I am building a program with EventMachine and sometimes clients on weak internet will trigger unbind in our program. I was wondering how can I determine why the unbind function is being triggered and if there is anything I can do to help these weak clients.

A: Unbind will be called when connection is terminated for some reason, usually you need to reconnect to server.
class MyConnection < EM::Connection
  def initialize(host, port)
    @host, @port = host, port
    @retry = 0
  end

  def self.connect(host, port, timeout)
    EM.connect(host, port, self, host, port)
  end

  def connection_completed
    @retry = 0
  end

  def unbind
    if @retry < 3
      EM.add_timer(1){ @retry +=1 && reconnect(@host, @port) }
    else
      fail "Can't reconnect"
    end
  end
end

A: appears you can also define unbind with a "reason" parameter:
def unbind(reason=nil)
end

refs:
https://groups.google.com/forum/#!topic/eventmachine/9HFuXS15HYg
https://github.com/eventmachine/eventmachine/issues/362


text:
Q: How do i access the text of the selected radio button in JavaFX? I am creating a project for my new understanding of JavaFX GUI. I am just having trouble getting the file to write "Small Cake", "Medium Cake", or "Large Cake" depending on which radio button has been selected. I know most of my logic is working and it has come down to the
writer.write(cakeSize.getSelectedToggle().selectedProperty().getValue().toString());
No matter the documentation I look at or what . selector I choose I can only seem to access the Boolean stating if is it 'true' for selected or not and if not that then it returns the name value as 'selected'
It does not need to use setText(value) I can get rid of those setters if needed I was just trying to find where I went wrong. Without those it just returns in an object the "Small" "Medium" or "Large" based on selection. Those being written on their own to the file I am fine with as well.
Thanks!

import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.*;

public class BakeryApplication extends Application {
    @Override
    public void start(Stage stage) {
        //Create a pane
        //the pane is the layout container that contains other JavaFX components
        GridPane gridPane = new GridPane();
        //Create a label and pass it through the pane layout
        Label orderTitle = new Label("Place your Cake Order Below");
        Label nameTitle = new Label("First and Last Name");
        Label numberTitle = new Label("Please enter your phone number:");
        //Create a text field area
        TextField name = new TextField();
        TextField number = new TextField();

        Label cakeSizeTtl = new Label("Please select your Cake Size:");
        RadioButton cakeSm = new RadioButton("Small");
        cakeSm.setText("Small Cake");
        RadioButton cakeMd = new RadioButton("Medium");
        cakeMd.setText("Medium Cake");
        RadioButton cakeLg = new RadioButton("Large");
        cakeLg.setText("Large Cake");

        ToggleGroup cakeSize = new ToggleGroup();
        cakeSm.setToggleGroup(cakeSize);
        cakeMd.setToggleGroup(cakeSize);
        cakeLg.setToggleGroup(cakeSize);

        Label cakeTypeTtl = new Label("Please select your Cake Type:");
        //Combo Box
        ComboBox<String> cakeSelection = new ComboBox<>();
        cakeSelection.getItems().addAll("Apple","Carrot", "Cheesecake","Chocolate", "Coffee", "Opera", "Tiramisu");
        cakeSelection.setValue("Cake Type");

        //create a save and quit button
        Button saveBtn = new Button("Save");
        Button quitBtn = new Button("Quit");

        //Events for buttons
        saveBtn.setOnAction(e -> {

                    try {
                        BufferedWriter writer = new BufferedWriter( new FileWriter("Order.txt"));
                        writer.write(number.getText());
                        writer.newLine();
                        writer.write(name.getText());
                        writer.newLine();
                        //add cakeType selection
//                        writer.write(cakeSize.getSelectedToggle().selectedProperty().toString());
                        writer.write(cakeSize.getSelectedToggle().selectedProperty().getValue().toString());
                        writer.newLine();
                        writer.write(cakeSelection.getValue());
                        //add cakeSize selection
                        writer.close();
                    } catch (IOException err) {
                        err.printStackTrace();
                    }
                });

        //handles click event on quit button to exit program
        quitBtn.setOnAction(e ->{
            Platform.exit();
        });
        //add an HBox to hold the buttons and arrange them horizontally
        HBox buttonBox = new HBox(10, saveBtn, quitBtn);
        gridPane.setHgap(10);
        gridPane.setVgap(10);
        //node, column, row
        gridPane.setConstraints(orderTitle,2,0);
        gridPane.setConstraints(nameTitle,2,1);
        gridPane.setConstraints(name, 2, 2);
        gridPane.setConstraints(numberTitle,2,3);
        gridPane.setConstraints(number, 2, 4);
        gridPane.setConstraints(cakeSizeTtl, 3, 5);
        gridPane.setConstraints(cakeSm, 3, 6);
        gridPane.setConstraints(cakeMd, 3, 7);
        gridPane.setConstraints(cakeLg, 3, 8);
        gridPane.setConstraints(cakeTypeTtl, 2, 5);
        gridPane.setConstraints(cakeSelection, 2, 6);
        gridPane.setConstraints(buttonBox, 3, 11);
        gridPane.setPadding(new Insets(20));
        //use getChildren and add method to  place the label node in the pane layout
       gridPane.getChildren().addAll(buttonBox, orderTitle, name, number, nameTitle, numberTitle, cakeSm, cakeMd, cakeLg, cakeSizeTtl, cakeSelection, cakeTypeTtl);
        //Use BorderPane to aid in layout
        //controls are typically inserted into a different
        //type  of layout and then added into the BorderPane accordingly
        //like how our buttons and title are in a GridPane right now
        BorderPane mainPain = new BorderPane();
        mainPain.setCenter(gridPane);
        //add the pane to the scene
        Scene scene = new Scene(mainPain, 500, 500);
        stage.setTitle("Assignment2 Order Your Cake!");
        //Placing the Scene in the stage
        stage.setScene(scene);
        //Displays the Stage
        stage.show();
    }

    public static void main(String[] args) {
        //launches the Stage
        launch();
    }

}

A: You can ask the ToggleGroup for the currently selected Toggle using the getSelectedToggle() or selectedToggleProperty() method, as you are already doing.
However Toggle is an interface that doesn't define a text property. The Toggle interface has many implementations, one of which is RadioButton.
Now, since you know that your ToggleGroup only contains RadioButton toggles you can safely cast it and ask for its text.
Briefly:
RadioButton selectedToggle = (RadioButton) cakeSize.getSelectedToggle();
if (selectedToggle != null) // it can be null if nothing is selected
   String selectedText = selectedToggle.getText();


text:
Q: Конструктор класса cStringIO.StringIO Читаю чужой код. Увидел, что в одном месте в конструктор класса cStringIO.StringIO попадает строка. Не могу разобраться на что она влияет и зачем нужна в конструкторе...

A: Разбираться в данном случае нет нужды - надо всего лишь открыть документацию. Цитата:

Another difference from the StringIO module is that calling StringIO()
  with a string parameter creates a read-only object. Unlike an object
  created without a string parameter, it does not have write methods.
  These objects are not generally visible. They turn up in tracebacks as
  StringI and StringO.

Еще одно отличие от модуля StringIO - вызов конструктора со строковым параметром. В этом случае будет создан объект только для чтения и у него не будет никаких методов для записи. Такие объекты обычно невидимы. Они представлены как StringI и StringO.
Ради интереса еще можно полистать исходники cStringIO. Конкретно в этой строке можно подсмотреть конструктор - объект создается с заранее предустановленным свойством STATE_REALIZED. Затем при попытке записи проверяется наличие другого свойства и кода для состояния REALIZED просто нету - потому что аккумулятор, в котором хранятся данные должен быть уничтожен. Эти состояния объясняются так: In accumulating state, the internal buffer contains nothing and the contents are given by the embedded _PyAccu structure. In realized state, the internal buffer is meaningful and the _PyAccu is destroyed. Мне, однако, неведомо зачем инициализировать объект с уже заданной строкой таким образом.


text:
Q: How to add a scrollbar to accordion in PrimeNG? I have an issue when expanding panels within my accordion in my Angular App. Basically if I expand a panel this is expanding and going over the footer of my application so I was thinking on adding a scrollbar to the accordion so it doesn't go over the footer anymore but I'm not sure where to start. Does anyone know how to add a scrollBar to accordion ? My guess is that I will need to put the accordion in a container and then add a scrollbar ?
Here's my code and would like to add a scrollbar.
PLUNKER
<p-accordion [activeIndex]="index">
  <p-accordionTab header="Header 1">
   Content 1
</p-accordionTab>
<p-accordionTab *ngIf="true" header="Header 2">
   Content 2
</p-accordionTab>
<p-accordionTab header="Header 3">
  Content 3
</p-accordionTab>

Here are two images on what happens with my footer when a panel gets expanded:
1) BEFORE Expanding Panel

2) AFTER Expanding Panel

A: Just add these CSS properties to the p-accordion element :
height: 275px;
display: block;
overflow: scroll;

Plunker


text:
Q: Как в modx revo отсортировать чанки в шаблоне? Вот к примеру есть у нас шаблон с выводом чанков:
[[$banner]]
[[$service]]
[[$news]]

и т.д.
Как мне с помощью дополнительных полей отсортировать его? (чтобы можно было редактировать позицию чанка). Буду очень признателен за помощь!

A: Например воспользоваться компонентом MIGX.
Создать tv например с именем chunks и типом ввода migx
Вкладки формы примерно так:
[{"caption":"Секции", "fields": [
    {"field":"chunk","caption":"Чанк"}
  ]
}]

Разметка колонок:
[{
  "header": "Чанк", "sortable": "true", "dataIndex": "chunk"
}]

В итоге, можно будет добавлять через это поле нужные чанки и сортировать их "перетаскиванием" в нужном порядке.
В шаблоне соответственно выводить с помощью getImageList:
[[getImageList? &tvname=`chunks` &tpl=`@CODE:[[+chunk]]`]]


text: Q: How can i sort the recycleview's item by keyevent? RT. I have a recycler view and the view holder has the item of "move imageview" , if the item's "move imageview" has the focus and you can click KeyEvent.KEYCODE_DPAD_UP or KeyEvent.KEYCODE_DPAD_DOWN to sort the item with its front or near one.I have made it for the finger to move .But for the KeyEvent the focus is not correct, i need the focus retain after the move action. Maybe i dont make myself understanded. Who can help me ? Thank you!


text:
Q: Gradle 2.1 is required Migrate to Gradle wrapper and sync project I am trying to build u202 android project by Jake Wharton. My android studio is failing to build the project. The error being shown is as below:
Gradle 2.1 is required
Migrate to Gradle wrapper and sync project

The line where error is shown points to apply plugin: 'com.android.application' in the build.gradle file.
I have tried the following solutions but to no avail.

*

*Run gradlew from the highest project directory. However when I run this from command line, I get a message that the build was successful but when I try to sync the project in android studio I get the above mentioned error.

*Run gradle through command line. Since the gradle version I had in my path was of version 2.2.1, I got the error that plugin "com.android.application" cannot be found - I assume this is because I have this version of gradle-plugin in the project which needs to be updated to support newer version of gradle: 'com.android.tools.build:gradle:0.13.3'

Finally I could build the project by downloading gradle 2.1 manually and pointing the project to use local gradle instead of wrapper. I wanted to know if there is anything wrong in the way I tried to use gradle wrapper.

A: Go to Settings -> Gradle and click Use default gradle wrapper (recommended). Press Apply.
After that go to project-dir/gradle/wrapper/gradle-wrapper.properties and change distributionUrl like so:
distributionUrl=https\://services.gradle.org/distributions/gradle-2.1-all.zip

Try to Build -> Make Project.
You also may need to make sure that all components (Android Studio, Gradle itself and Android Gradle plugin) can be used together. Check out this page, here we can see that Gradle 2.1 can be used on Android Studio 0.9.0 - 0.9.3 and Gradle plugin has to be of version 0.14.0 - 0.14.4.


text:
Q: Lagging when mouse position updated? I've been using pygame to create a pretty basic game just to experiment with, and I recently have encountered some lag. Whenever I add this code:
if exitcode==0:
            pygame.font.init()
            font = pygame.font.Font(None, 24)
            text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0))
            textRect = text.get_rect()
            textRect.centerx = screen.get_rect().centerx
            textRect.centery = screen.get_rect().centery+24
            screen.blit(gameover, (0,0))
            screen.blit(text, textRect)
        else:
            pygame.font.init()
            font = pygame.font.Font(None, 24)
            text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0))
            textRect = text.get_rect()
            textRect.centerx = screen.get_rect().centerx
            textRect.centery = screen.get_rect().centery+24
            screen.blit(youwin, (0,0))
            screen.blit(text, textRect)

It lags. I thought it might be because of my while loops, but that wasn't it. Can anyone tell me the source of my lag? I can post other codes from my game if you need. Thank you!

A: Don't call pygame.font.init() or create a new Font object in your mainloop, since this costs lot of time.
If you already call pygame.init(), you don't need pygame.font.init() at all.
For your Font object: just create it once outside your mainloop.
Also, if you do a lot of font rendering (calling font.render), you should cache the resulting surfaces, since font rendering is also a quite expensive operation in pygame.


text:
Q: TSQL: Different execution due to parallelism One of my query is performing slow for small records but for large records its working as expected.
Foe example:
Query #1
SELECT *
FROM vwServwerHealthReport
WHERE startDate >= '20/02/2018'
  AND startDate <= '06/03/2018'

-- fetching more than 6000 records in 0:02 seconds
Query #2
SELECT *
FROM vwServwerHealthReport
WHERE startDate >= '02/03/2018'
  AND startDate <= '06/03/2018'

-- fetching approx 800 records in 02:05 seconds
I have checked execution plans as well and found that the execution plans of both the queries is different and the slow running query is using parallelism operator a lot but the fast query is not using any parallelism operation.
Initially I was assuming this to be a parameter sniffing problem and implemented "Recompile, Optimize for" hints but have not got the improvement.
Please let me know why parallelism is being used by slow running query even for small records and how can i resolve this issue.


text:
Q: Ruby loop via lambda, how to break? It is possible to create dead loop using lambdas in ruby:
a = 0
lambda = ->{ a += 1; puts "#{a}"; sleep 1}
loop &lambda
p a

Now I'm seeking for a way how to break this kind of loop generated by a lambda transferred into block. Both apparent approaches I used to try dose not finish a loop they just exit out of the lambda, but loop still works:
break dose not stop a loop:
a = 0
lambda = ->{ a += 1; puts "#{a} break"; sleep 1; break; p "This line will not appears"}
loop &lambda
p a

return dose not stop a loop too:
a = 0
lambda = ->{ a += 1; puts "#{a} return"; sleep 1; return; p "This line will not appears"}
loop &lambda
p a

If I use proc instead of lambda I able to return out of a loop, but also I exit out of the program:
a = 0
prc_ = Proc.new{a += 1; puts "#{a} proc return"; sleep 1; return; p "This line will not appears"}
loop &prc_
p a

The same situations when I use break inside proc, I just throw away from the program with LocalJumpError exception.
a = 0
prc_ = Proc.new{a += 1; puts "#{a} proc break"; sleep 1; break; p "This line will not appears"}
loop &prc_
p a

A: You can raise StopIteration exception from the lambda:
a = 0
lambda = ->{ a += 1; puts "#{a}"; sleep 1; raise StopIteration if a>10}
loop &lambda
p a

Docs says:

loop() public
  Repeatedly executes the block.
  If no block is given, an enumerator is returned instead.
  (...)StopIteration raised in the block breaks the loop.


text:
Q: How to compare a NSNumber in an if How to:
if (myNSNumber == 1)
{
 ...
}

This doesn't seem to build
The object:

A: NSInteger is normally a plain int type so your code should work fine.
if myNSNumber a NSNumber object (as variable name suggests) then you should extract its int value:
if ([myNSNumber intValue] == 1)
{
 ...
}

A: If myNSNUmber is NSNumber, your code should read,
if ([myNSNumber intValue] == 1) {
    ...
}

If it is NSInteger, you can directly compare it with an integer literal. Because NSInteger is a primitive data type.
if (myNSNumber == 1) {
    ...
}

Note: Make sure you don't have * in your declaration. Your NSInteger declarations should read,
NSInteger myNSNUmber; // RIGHT
NSInteger *myNSNUmber; // WRONG, NSInteger is not a struct, but it is a primitive data type.

The following is based on @BoltClock's answer, which he recently posted here

However if you do need to use a pointer to an NSInteger (that is, NSInteger *) for some reason, then you need to dereference the pointer to get the value:
if (*myNSNUmber == 11) {
}


text:
Q: How do I access my Player Camera Manager (replicated (listen server and client)) in UE4 Blueprints When I try to access the location of my Player Camera Manager on the server it returns 0, 0, 0.
I think that I tried every option on setting the Player Camera Manager respectively the Player Controller in all the replicated options. To be clear: At first, I used my common sense but after a week of failure I tried every combination with no success.
As an example: Here is how I tried to access the Location and the forward Vector for a Line Trace

I also tried to set the Camera Manager as a variable (I tried both server and client) and then access it on the server.
Does anyone have any ideas on how to fix that?
Any help is much appreciated.

A: APlayerCameraManager is not an actor that replicates, so I'd expect that blueprints to only work on the client. You'll have to replicate the values you need back to the server.
If you're making a first person game APawn replicates a variable named RemoteViewPitch that may be enough depending on what you're doing.

A: You can do it just make an interface function with input the information that you need from the manager then go to character and assign that to it then go to the manager blueprint and get the information and use controlled pawn to get ur player ref and call interface function