text:
Q: Using differentials to approximate the change in f(x,y) I have been
"Use differentials to approximate the change in $f(x, y)$  as $(x, y)$ changes
from $(−2, 3)$ to $(−2.02, 3.01)$."
$$f(x,y)=x^2-3x^3y^2+4x-2y^3+6$$
I have obtained:
$$\partial_xf(x,y)=2x-9x^2y^2+4,\qquad \partial_y f(x,y)=-6x^3-6y^2$$
Where do I go from here?

A: HINT: from the definition of Fréchet derivative we have that
$$f(x+h)=f(x)+\partial f(x)h+o(|h|),\quad \text{as }h\to 0$$
for $x\in\Bbb R^n$.

A: The total differential is the sum of the partials.  So, $df = \partial_x f + \partial_y f$.  Since $\partial_x f$ literally means the amount of changes in $f$ due to changes in $x$, then stick in the values for $x$, $y$, and $dx$ (i.e., the amount of change in $x$ from your starting point to your next point) into the formula for $\partial_x f$.  Then, do the same thing for $\partial_y f$.  Then add then together.


text:
Q: GCC Compiler, Plugins and structures I have scenario like this:
int open_ext2 () {}
int close_ext2 () {}
int read_ext2 () {}
int write_ext2 () {}

const struct fs_callbacks FS = {
    open_file: open_ext2,
    close_file: close_ext2,
    read_bytes: read_ext2,
    write_bytes: write_ext2
};

void main(){
    FS.close_file();
}

When I look at the gimple representation (compiled with -fdump-tree-all)
I see something like this:
D.1796 = close_ext2;
D.1796 ();

What I do not get is where happens the assignment open_file: open_ext2
My questions

*

*How GCC is doing this?

*In what pass does it happen ?

*Is there a way to figure out the mapping label -> member function?

A: Found the answer
The gcc option -fdump-tree-original-raw dumps the info
With GCC plugin:

*

*Use the pass PLUGIN_FINISH_DECL

*Have a look in GCC source for the function debug_variable in file: gcc/tree-dfa.c

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you shut down threads after running test in the sbt shell I am using sbt 0.13.9 with scalatest. The project contains a bunch of daemon threads. Simplified example:
object Storage {
  private lazy val scheduler = Executors.newSingleThreadScheduledExecutor(
    new com.twitter.concurrent.NamedPoolThreadFactoryNamedPoolThreadFactory("thread-name", true)
  )

  scheduler.scheduleAtFixedRate(new Runnable {
    override def run(): Unit = {
      println("Running ...")
      // do something
    }
  }, 0, 1, TimeUnit.MINUTES)

  // other code
}

Some tests use Storage. When running test in the SBT shell, I can see that the Runnable is still running after all tests have finished.
[info] All tests passed.
[success] Total time: 32 s, completed Dec 1, 2015 10:39:57 AM
> 2015-12-01 10:40:51,806 INFO  Storage$$anon$1 - Running ...
2015-12-01 10:41:51,810 INFO  Storage$$anon$1 - Running ...

How can I make sure that they are stopped?

A: Looks like daemon threadFactory is used for creating Runnable tasks, but scheduler itself is executed on normal/non daemon thread pool.
As an option.
After scheduling  your task , you should take ScheduleFuture and handle it. For example cancel after some executions.
val fff = scheduler.scheduleAtFixedRate(new Runnable {
    override def run(): Unit = {
      println("Running ...")
      // do something
    }
  }, 0, 10, TimeUnit.SECONDS)

  fff.cancel(true)


text:
Q: Why there is no option to re throw the exception with custom message? To customize the error message, we need to do the following

*

*Catch the exception

*wrap the exception to another Exception

*Re throw the exception

Instead why there is no way to just change the Exception error message and re throw it?
I know it is a basic question, but curious to know your opinions.
Take an example:
    try
    {
        // Any operation which might throw NumberFormatException.
        int result = 1 / 0;

    } catch (NumberFormatException e)
    {
        // Observe that if I just throw by 'e' then I will get message as '/ by zero'
        throw e;

        // OR I wrap the exception (optional) and throw new exception with custom message.
        throw new NumberFormatException("<Custom Message> instead of '/ by zero'");

        // Instead, wouldn't it be easy if I could just overwrite the exception message of NumberFormatException?

        // below code isn't valid, but wondering why Java doesn't let me do this?
        e.setMessage("<Custom Message> instead of '/ by zero'");
        throw e;
    }

A:  catch (NumberFormatException e){
    e.setMessage("<Custom Message> instead of '/ by zero'");
    throw e;

 }

This is a bad way of handling exception if Java let you to do so. Now you loss the original message and loss the stack trace of the exception. That's why no point of let you to set the message,and no point to catch and throw same exception, Just throw it and handle it in upper level.
If you want to do something you are trying to do, you can do it in following way
catch(NumberFormatException e){
    throw new MyException("your message matched with the method" ,e);
}

In this case you can see, both original message and stackTrace is preserve while you are adding your message.

A: It is possible to write some real buggy code if you could change the message of the exception. An Exception is part of the contract of a method. It reflects what happened at some point deep in the code.
It is there to communicate about something that went wrong deeper in the code. It is not your business to change this message. Either you throw the message up to some other method that can deal/understand how to go about this Exception, or you catch the exception and throw your own Exception if you so wish.
Basically the message is an intrinsic part of the Exception (immutable if you wish).
And it is also not too hard to write something like
catch(Exception e){
    throw new Exception("custom message" ,e);
}

Which is one line shorter than :
catch(Exception e){
    e.setMessage('my custom message');
    throw e;
}

Ask yourself, if your job was a messanger on a horse who has to send a letter from person A to person B, and you read the letter and realised that some additional information needed to be updated. Would you rewrite the letter and put it back in the envelope, or would you write a post-it note and stick it on the envelope?

A: There's no setMessage() meghod, you could throw a different instances of NFE but with the original exception as its cause:
catch (NumberFormatException e) {
    throw new NumberFormatException("<Custom Message> instead of '/ by zero'", e);
}

It's important to preserve the context of the exception so the stacktrace is as useful as possible to the caller.


text:
Q: Python 2.7 - Converting a single character string to an integer I'm trying to make a program which reads from two text file line by line and stores the line which you have specified in Name_Input earlier (in variable line and line 2), it then strips off anything which is not a number from the string.
for line in Roster_Inputed:

        if Name_Input in line:
            line = re.sub('[^0-20]', '', line)

            if line == "1":
                print(Name_Input + " " + "should have " + line + " " + "ally.")
                print " "
            else:
                print(Name_Input + " " + "should have " + line + " " + "allies.")
                print " "

    for line2 in Roster_Should_Have:
        if Name_Input in line2:
            line2 = re.sub('[^0-20]', '', line2)

            if line2 == "1":
                print(Name_Input + " " + "actually has " + line2 + " " + "ally.")
                print " "
            else:
                print(Name_Input + " " + "actually has " + line2 + " " + "allies.")
                print " "

The code reads from two files which contain names and number after a space, it then goes on to compare them to determine what it outputs to the user:
     if line == line2:
        print "All good"
    elif line != line2:
        print "Check " + Name_Input + "'s " + "spies"
        print " "

What I need it to do is check if the value of "line" is greater than "line2" however I cannot do so because they are strings which contain numbers. Is there a way to temporarily convert them to integers?

A: You can use chr() and ord() functions:
>>> chr(97)
'a'
>>> ord('a')
97

Hope it helps.

A: What about calling int?
>>> int('345')
345

A: Since I have now gotten confirmation that the characters will always be integers and the integers are what you want to compare, I can now say use int():
>>> int('4')
4

In your case, if int(line) > int(line2): should do what you want.  Since files usually have new-line characters at the end of each line, you should probably consider using int(line.strip()) and int(line2.strip()).


text:
Q: How do I use ListView with an accordion panel from the ajax toolkit? This one is kind of hard to explain. But basically, I'm trying to nest accordions using a ListView with a datasource. The problem is, that it won't allow listview into the accordion template. here's the layout:
>>Section (accordion pane)
   >>List of Documents to be reviewed
      >>List of Reviewing parties

The section is an accordion pane inside an accordion control. Inside of this is another accordion control which is built from a list of document currently in review. In other words, each document is another pane. The content of each of of the document panes is just an unordered list of reviewers (names).
So I need to be able to basically build the layout based on lists inside the object. I thought I would be able to do something like this:
<ajaxToolkit:Accordion runat="server" ID="accordionMain" HeaderCssClass="panelHeader" ContentCssClass="panelContent" CssClass="accordionPanel" FadeTransitions="True">
        <Panes>
            <ajaxToolkit:AccordionPane runat="server" ID="pane3" HeaderCssClass="panelHeader">

                    <asp:Image ID="Image3" runat="server" ImageUrl="../icon_expand.gif"/>
                    Awaiting Reviewers
                    <asp:Label runat="server" ID="lblAwaitingReviewers" Text="(4)"></asp:Label>

                <Content>
                    <ajaxToolkit:Accordion runat="server">
                        <Panes>
                            <asp:ListView runat="server">
                                <ItemTemplate>
                                    <ajaxToolkit:AccordionPane runat="server">

                                            <asp:Label runat="server" ID="lblReviewItem"/>

                                        <Content>
                                            <asp:ListView runat="server" ID="lvReviewers" ItemPlaceholderID="phReviewers">
                                                <LayoutTemplate>

                                                        <asp:PlaceHolder runat="server" ID="phReviewers"/>

                                                </LayoutTemplate>
                                                <ItemTemplate>

                                                        <asp:LinkButton runat="server" ID="lnkMocReviewItem">
                                                            <asp:HiddenField runat="server" ID="hfMocReviewItemId"/>
                                                            <asp:Label runat="server" ID="lblReviewItemAssignee"/>
                                                        </asp:LinkButton>

                                                </ItemTemplate>
                                            </asp:ListView>
                                        </Content>
                                    </ajaxToolkit:AccordionPane>
                                </ItemTemplate>
                            </asp:ListView>
                        </Panes>
                    </ajaxToolkit:Accordion>
                </Content>
            </ajaxToolkit:AccordionPane>
        </Panes>
    </ajaxToolkit:Accordion>

But the accordion isn't playing nice with the list view. I tried to use the listview to act as a template to add panes as required, but the accordion control won't allow anything but panes inside of the pane section.
Is there a way around this?
Here is a photo of the effect that I'm going for:

A: Turns out that the accordion control has a DataSource complete with a content template. If you bind it to something, then it will create panes for each item. I then placed a listview in the content template and all was good.


text:
Q: Suspense boundary error of renderToString with GatsbyJS and React 18 on production build I am trying to code splitting and lazy loading in my website but I am getting an error about Suspense boundary.
Error:
Uncaught Error: The server did not finish this Suspense boundary: The server used "renderToString" which does not support Suspense. If you intended for this Suspense boundary to render the fallback content on the server consider throwing an Error somewhere within the Suspense boundary. If you intended to have the server wait for the suspended component please switch to "renderToPipeableStream" which supports Suspense on the server.

Info:
I am using GatsbyJS 4.24.1 and React 18.2.0.
I get the error with the production build or in development mode with DEV_SSR: true.
I read a lot but I got the idea GatsbyJS fully support Lazy loading and Suspense, so I do not know if I am doing something wrong or it is just a bug of Gatsby (maybe a regression?). I already post an issue on Gatsby (https://github.com/gatsbyjs/gatsby/issues/36678), but still no answer.
Example:
Looking around I do not think I am doing something wrong. It is just
const Hero = lazy(() => import('../components/home/Hero'));

function Home() {
  return (
    <Layout>
      <Suspense fallback={null}>
        <Hero />
      </Suspense>
    </Layout>
  );
}

Minimal reproduction:
I also created a codesanbox: https://codesandbox.io/s/determined-violet-cs7bxh.
You can also find another live example here: https://gatsbysuspensereproduction.gtsb.io/, and the code here: https://github.com/PaulieScanlon/gatsby-suspense-reproduction
Ideal solution:
Looking for a fix (so I am doing something wrong) or a bug confirm (so I can move on and try to migrate migrate to nextjs to overcome the issue, or still with GatsbbyJS but downgrade to React 17 and @loadable/components).


text:
Q: Highlight a tableViewCell I want to highlight some cells in my tableView. By highlighting I mean setting the background color of the cell to the blue color used for example when copying a text. I used tried this code to check if it works
public func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.setHighlighted(true, animated: false)
    }

I also tried this
cell.setSelected(true, animated: false)

In both cases the cells become grey and not blue. Is there a solution for that?

A:
Change the selectionStyle property of yourcell. If you want to change it to UITableViewCellSelectionStyleBlue, it will be blue. for alternate method , you can get the another SO answer

for e.g
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
cell.selectionStyle = .blue
}

UITableViewCell has three default selection styles:-
typedef NS_ENUM(NSInteger, UITableViewCellSelectionStyle) {
UITableViewCellSelectionStyleNone,
UITableViewCellSelectionStyleBlue,
UITableViewCellSelectionStyleGray,
UITableViewCellSelectionStyleDefault NS_ENUM_AVAILABLE_IOS(7_0)
};

or you can directly set the Selection color in your cell class like

A: Try like this
 public func tableView(_ tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.selectionStyle = .blue
    }


text:
Q: Redirect to custom url after login I user Spring security + Angular in my application.
And in the spring-security.xml following form login is specified
<security:form-login
               always-use-default-target="true"
               login-page="/login"
               default-target-url="/login"
               login-processing-url="/perform_login"
               authentication-failure-url="/login?error"
               username-parameter="username"
               password-parameter="password"
               />

And this will redirect the user to login page which is working fine as expected.
But now I want to enhance it to remember the url before login and after successful login redirect to that page
Expected scenario

*

*Application is logged out

*user type the url : http://WEB-SITE/ReportModule/#/report

*user is redirected to login page

*Once the user logged in successfully it is redirected to http://WEB-SITE/ReportModule/#/report
Tried solutions
Tried to save the url in to the session and after login redirect the user.
problem in this solution is when the  http://WEB-SITE/ReportModule/#/report entered to the browser application is redirected to http://WEB-SITE/login/#/report so the part of the url (ReportModule/#/report) is missing to store.
Are there any way to achieve this
Answer:
Found the solution  by using AuthenticationSuccessHandler and useReferer
<bean id="AuthenticationSuccessHandler"
          class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <property name="useReferer" value="true"/>
    </bean>
<security:form-login
                always-use-default-target="true"
                login-page="/login"
                default-target-url="/login"
                login-processing-url="/perform_login"
                authentication-failure-url="/login?error"
                username-parameter="username"
                password-parameter="password"
                authentication-success-handler-ref="AuthenticationSuccessHandler"
                />

A: Hello I am not sure about your frontend solution for protecting the urls.I assume you are uing guards for redirecting the  user.
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    if (localStorage.getItem('currentUser')) {
        // logged in so return true
        return true;
    }

    // not logged in so redirect to login page with the return url and return false
    this.router.navigate(['login'], { queryParams: { returnUrl: state.url }});
    return false;
}

}
this.router.navigate(['login'], { queryParams: { returnUrl: state.url }}); This is what you are looking for.


text:
Q: How to have one RadioButtons group display in EditorTemplates in ASP.Net MVC(3) I have a list of items from which I want the user to be able to input some value  select one
But the radio-buttons generated by the EditorTemplate are named like "Item[x].SelectedItemId" so they are totally independent from each other and I can't get the value...
Let's go show some code.
The model:
public class FormModel
{
    public List<ItemModel> Items { get; set; }
    public int SelectedItemId { get; set; }
}

public class ItemModel
{
    public int ItemId { get; set; }
    public string ItemName { get; set; }
    public string SomeString { get; set; }
}

The view:
@model FormModel
@using (Html.BeginForm())
{
    @Html.EditorFor(m => m.Items)
}

The editor template:
@model ItemModel
@Html.RadioButton("SelectedItemId", Model.ItemId)
@Model.ItemName

@Html.TextBoxFor(m => m.SomeString)

UPDATE
This is what I want:

This is what I get:

As a result, FormModel.SelectedItemId never gets the value of any radio-button.
What am I doing wrong?

A: It appears as though you are aware that setting the names for radio buttons to be the same is necessary to make them work. However, when you do that in an editor template by using the line of code @Html.RadioButton("SelectedItemId", Model.ItemId), MVC 3 will take into consideration that you are in an editor template for Items and prepend items[n].
This would create a name of something like name="Items[0].SelectedIndex". This would be fine if it weren't for the fact that the next radio button would be `name="Items[1].SelectedIndex".
One way to solve this is to not use an editor template and use a foreach loop instead. Here is some code that I was able to get functional. I confirmed that model-binding worked for the SelectedIndex.
    @model FormModel

    @{
        ViewBag.Title = "Index";
    }

    @using (Html.BeginForm())
    {
        foreach (var item in Model.Items)
        {
            @Html.RadioButtonFor(x => x.SelectedItemId, item.ItemId)
            @item.ItemName

            @Html.TextBoxFor(m => item.ItemName)

        }

        <input type="submit" value = "submit" />
    }

A: I had same problem, and we solved it with this piece of code.
@Html.RadioButton("", Model.Id, Model.Selected, new { Name = "deliveryMethod" })

You need to put Name property explicitly, so it will be used instead name that you get after EditorFor executes.


text:
Q: How can I solve the folowing Diophantine equation with two unknowns?
Find one integer solution to the following Diophantine equation:
  \begin{equation*}
\\\forall \,x,y \in \mathbb{Z}\\
6xy + x - y = 274
\end{equation*}

The resultat ist $x = 9$, $y = 5$ (Obtained with wolframalpha )
I need to know a method that allows me to reach such a result. How can I calculate the value of these two variables in a Diophantine equation?
For example: 6xy + x - y = 458

A: Hint $\ $ This type of diophantine equation is solvable by a generalization of completing the square. Namely, completing a square generalizes to completing a product, using the AC-method, viz.
$$\begin{eqnarray} &&axy + bx + cy\, =\, d,\ \ a\ne 0\\
\overset{\times\,a}\iff\, &&\!\! (ax+c)(ay+b)\, =\, ad+bc\end{eqnarray}\qquad\qquad$$
So the problem reduces to checking which factors of $\,ad+bc\,$ have above form, a finite process.

A: $\dfrac{274+y}{6y+1}=x$
As $x$is an integer, if integer $d$ divides both $274+y,6y+1;d$  must divide $6(274+y)-(6y+1)=1643$
For integer $x,6y+1$ must divide $1643=31\cdot53$ whose divisors are $\pm1\pm31,\pm53$

A: This is @Bill Dubuque's answer in more detail.
I don't know what you mean by $\mathbb Z_0$.
$$ \forall x,y \in \mathbb Z_0, \quad 6xy + x - y = 274 $$
\begin{align}
   6xy + x - y        &= 274 \\
   36xy + 6x - 6y     &= 1644 \\
   36xy + 6x - 6y - 1 &= 1643 \\
   6x(6y+1) -1(6y+1)  &= 1643 \\
   (6x-1)(6y+1)       &= 1643
\end{align}
\begin{array}{|cc|cc|}
\hline
   6x-1 & 6y+1 & x &y \\
\hline
   1    & 1643   & \ast & \ast\\
   31   &   53   & \ast & \ast\\
   53   &   31   &    9 &    5\\
   1643 &    1   &  274 &   0\\
\hline
\end{array}


text:
Q: Why am I getting segfault? I'm a beginner to C++, and am working on a class that grades a student's answer ("11 3 1133 22322314231432211231 34 2") by comparing it to an answer sheet ("112341423114322314231442314231223422"). I must compare each value of the student's answer and if they match, add 2 points; if they don't, subtract 1. Now, if the answer is empty, I don't do anything to the student's grade.
Right now, the code is as follows:
//
#ifndef GRADER_H
#define GRADER_H

using namespace std;

#include <iostream>

class Grader {
  protected:
    int punt;
    string answers, id, stans;
  public:
    Grader(){
      answers = "112341423114322314231442314231223422";
      int i;

      char ans_arr[answers.length()];

      for (i = 1; answers.length(); i++){
        ans_arr[i] = answers[i];
      }
    }

    Grader(string ans) {
      answers = ans;
    }

    void Grade (string ans, string id, string stans) {
      int punt = 0;
      for (int i = 0; ans.length(); i++) {
        if (stans[i] == ans[i]){
          punt = punt + 2;
        } else if ((stans[i] != ans[i]) && (stans[i] != ' ')) {
          punt = punt - 1;
        }
      }

      cout << punt;
    }
};

#endif

//Main

#include <iostream>
#include "grader.h"
using namespace std;

int main() {

  string ans = "112341423114322314231442314231223422";

  Grader a(ans);

  string student_id = "12345";
  string student_ans = "11 3 1133 22322314231432211231 34 2";

  int punt = 0;

  a.Grade(ans,student_id,student_ans);

  return 0;
}

With this, I get a segfault. I understand I'm dealing with memory I shouldn't deal with, but I have no idea how to make this work.

A: Your for-loop conditions are not actually conditions.
From w3schools:
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

Your conditions are, for example, ans.length(), when they should be i < ans.length().
Since ans.length() will always have the same (positive) value, it will be interpreted as the loop needing to continue and i will continue to be incremented.  Then something like ans[i] is actually attempting to look at memory after the end of the array, resulting in a segfault when that out-of-bounds memory is not allocated to your application.

A: ans.length is 36 and stans.length is 35. The following code reads from the outside of stans.
for (int i = 0; ans.length(); i++) {
        if (stans[i] == ans[i]){

Here is the memory access error:
  Memory access error: reading from the outside of a memory block; abort execution.
  # Reading 1 bytes from 0x9df62c0 will read undefined values.
  #
  # The memory-block-to-be-read (start:0x9df6290, size:48 bytes) is allocated at
  #    unknown_location (report this ::244)
  #
  #  0x9df6290           0x9df62bf
  #  +--------------------------+
  #  | memory-block-to-be-read  |......
  #  +--------------------------+
  #                              ^~~~~~~~~~
  #        the read starts at 0x9df62c0 that is right after the memory block end.
  #
  # Stack trace (most recent call first) of the read.
  # [0]  file:/prog.cc::28, 13
  # [1]  file:/prog.cc::50, 3
  # [2]  [libc-start-main]

You can use this link to debug segfaults of your code in the future. Just click "Start" to build and run your code in the Terminal.


text:
Q: Crystal Reports XI R2 Compatible with SQL Server 2008? I'm currently running Crystal Reports XI R2 on SQL 2000. I need to migrate to SQL Server 2008 asap, but am no longer on Crystal Support.
Can anyone tell me if CR XI R2 Server is compatible with SQL Server 2008? I Googled it but came up empty.

A: I'm sure you have found out by now, but it is. You have to upgrade to Service pack 6 of XI and you may also have to install the sql client for 2008. It installs a new ODBC driver for Sql Client 10.

A: Yes it does support sql server 2008.
http://www.sdn.sap.com/irj/boc/go/portal/prtroot/docs/library/uuid/00225757-ab5c-2c10-c1a8-fb9f9f0f4ac2?QuickLink=index&overridelayout=true
The sap documentation when moving a sap backend to sql server 2008 has a great document which I have linked you to.


text:
Q: Bluetooth application has stopped I imported a project Bluetooth_Chat in Android Studio. Since days I am struggling to make it work. The Emulator starts, but the app stops. I am afraid that I made a mistake while creating  a device. I get this at the end E/Internal: device 'emulator-5554' not found. I googled a mistake but sincerely I got confused because there are many different answers and I don't know which one reffers to my problem.
These are codes impelemented in build.gradle. Can somebody say to me exactly which parameters(including RAM, target, resolution ) should have my virtual device? Thank you
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.1"
defaultConfig {
    minSdkVersion 11
    targetSdkVersion 23
}

A: The emulator also gave me some problems with bluetooth, i suggest to tre on a physical device..
Also post the code that gives you problems if this didn't work

A: The android emulator does not support Bluetooth, WiFi, NFC, SD card insert/eject, Device-attached headphones, or USB. To test Bluetooth you will have to use a physical device.
Here is the documentation for the emulator as of 4/12/2016.


text:
Q: Using aggregated data from a database with data from another Let's say I have two databases, in the first (DB1) there is individual data on how much people trust in the government ($X_{j,r}$), and on the second (DB2) there is individual data on how much people donate $Y_{i,r}$  (I use $j$ instead of $i$ to make clear the individuals observed in both databases are not the same).
So my theory (in this example) is that in regions with lower trust in government, people donate more. So I want to run:

REG: $Y_{i, r} = \beta X_{r} + \gamma_{r} Z_{r} + \gamma_{i} Z_{i}$

So I calculate the mean of $X_{j,r}$ in DB1, and use it as variable in DB2 to run the OLS above.
My questions are:

*

*Do I need to correct the standard errors of REG to account for the fact that $X_{r}$  is imperfectly estimated?

*Should I weight REG for the standard errors of the mean of $X_{j,r}$ (give more weight to $r$ for which $X_{r}$ is better estimated)?


text:
Q: Postgresql 9.2 ??? symbols I've installed pg 9.2 on Ubuntu 12.04
$ psql
psql: ?????:  ???? "varan" ?? ??????????

How to configure it to output correct symbols?

A: Most likely you are using some non-English locale.
Check what is your LANG andLC_* environment variables are set to (locale command can show you that).
If you want to just use English for your terminal, you can set English locale for current session using
export LANG=en_US.UTF-8

If you want to make this permanent, one of the simple ways to override locale is to add this line your ~/.bashrc.
If you want to use non-English locale and not touch .bashrc, you may need to fix your terminal or ssh client. For putty, typical good setting is to use UTF-8 encoding.


text:
Q: LIKE in Elasticsearch for large texts I'm trying to simulate the LIKE operation from SQL in Elastic.
Base Records:
1. The quick brown fox jumps over the lazy dog
2. The thequick brown fox jumps over the lazy dog
3. The quick and brown fox jumps over the lazy dog
4. The quick brownnow fox jumps over the lazy dog

Search SQL: LIKE '%quick brown%'
Results: 1, 2 and 3
And very simply I'm trying to do this in Elasticsearch 6.
So far I'm able to apply a Regex or Wildcard to a Keyword field and make this work.
However, one of my properties has a lot of text and can't be indexed as a Keyword - It exceeds max number of bytes.
Any pointers would be welcome! :)

A: I can think of mapping the field as "Text" which will enable a inverted indexes on the analyzed terms. This will support full-text search on this field. Since they are not considered as a keyword, there is no impact on the memory used.
More info: https://www.elastic.co/guide/en/elasticsearch/reference/current/text.html

A: Apparently the best way to achieve this is by using Span Queries.
SpanNear and multiple wildcard queries.
I'll chuck in an example if it helps anyone.


text:
Q: NPM package post install target root directory I have an NPM package that has a post install script such as
 "postinstall": "node install.js"

I'm trying to target the directory from which the npm install mypackage was run originally. Right now I'm resorting to using in install.js some relative path such as
 path.normalize(__dirname+'./../../../www');

My structure goes as follow
 node_modules/@namespace/mypackage
 www

But it's kind of ugly and cannot guarantee that this wouldn't break in future revisions of Node/NPM. Is there a constant that targets the path from which the npm install mypackage was run?
Long story short, I'm moving files into www.


text:
Q: Call JavaScript function in AbstractJavaScriptExtension class I would like to call javascript function in vaadin. Its a AbstractJavaScriptExtension.
this.callFunction("removeNode"); does not fire the javascript function. Is this a bug or am I doing something wrong?
@Override
public void remove() {
    super.remove();
    fireRemoveNode();
    this.callFunction("removeNode");
}

JavaScript code:
window.vaadin_components_graph_Node = function() {
        var self = this;
        var state = this.getState();

...
        this.removeNode = function() {
            console.log("CALL FUNCTION", "remove node")
            $(node).remove();
        }
};

A: You can't call JavaScript functions after the AbstractJavaScriptExtension is removed. Try placing this JavaScript call to another method and don't call remove();

A: While user1411778 answer is correct, you can also call JavaScript function using:
JavaScript.getCurrent().execute("removeNode()");

It should work always.


text:
Q: Relation Between Opportunity Products and Opportunity Line Items I read about Opportunity Object and OpportunityLineItems and sub object in Opportunity named Opportunity Product Object.Is OpportunityLineItems and Opportunity Products are same thing or different??
if different what is the difference.Please clarify.

A: Yes they are the same : Salesforce official doc

Name: The opportunity line item name (known as "Opportunity Product" in the
  user interface).


text:
Q: How to modify TikZ patterns The Task: Draw a ground for a tank.
My solution: Using TikZ patterns library (see page 171 of the TikZ & PGF manual).
MWE:
\documentclass{scrartcl}
\usepackage{stanli}% loads TikZ, see: https://ctan.org/pkg/stanli

\usetikzlibrary{patterns}

\begin{document}

  \begin{tikzpicture}

    % ground
    \draw
      [very thick] (0, 0) -- (5, 0);
    % for comparison
    \support{3}{0, 0};% stanli
    \filldraw         % tikz
      [pattern = north east lines] (1, 0) rectangle (5, -.4);
    % tank
    \draw
      (5, 0)     .. controls (5, 1) and (5.1, 1.1)
                 .. (5.5, 1.1)
      (5.5, 1.4) .. controls (5.1, 1.4) and (5, 1.5)
                 .. (5, 2.5) -- (5, 5)
      (5, 4) -- (0, 4)
      (0, 5) -- (0, 0);
    % atmospheric pressure
    \node at (6, 5) {$p_0$};
    % density
    \node at (1, 3) {$\varrho$};
    % inflow
    \draw
      [->] (-.5, 5.5) .. controls (-.25, 5.5) and (.25, 5.5)
                      .. node[sloped, above] {Zufluss}
           (.5, 4.25);
    % hydrostatic head
    \draw
      (4, 4) -- (4.15, 4.3) -- (3.85, 4.3) -- cycle
      (3.85, 3.9) -- (4.15, 3.9)
      (3.90, 3.8) -- (4.10, 3.8)
      (3.95, 3.7) -- (4.05, 3.7);
    % velocity
    % v_1
    \draw
      [->] (2.5,4) node[above] {1} -- node[sloped, above, at end] {$v_1$} (2.5, 3);
    %v_2
    \draw
      [->] (5.5, 1.25) node[above = 5pt] {2} -- node[above, at end] {$v_2$} (6.5, 1.25);
    % flow line
    \draw
      [dashed] (2.5, 2.9) .. controls (3, 2) and (5, 1.25)
                          .. (5.4, 1.25);
    % coordinate system
    \support{3}{7.5, 1.25};
    \draw
      [->,dashed] (7, 1.25) -- node[sloped, above, at end] {$z$} (7, 2.5);
    % height
    \dimensioning{2}{8, 1.25}{8, 4}{8}[$h$];

  \end{tikzpicture}

\end{document}

The result:

Right is the ground drawn by Tikz. That isn't nice (my opinion). Can I somehow modify the north east lines pattern, so that the ground for the tank looks like a ground drawn by the stanli package (for example \support{3}{coordinates}). The ground comes with the stanli package, if observe strictly, isn't a ground, but I like it and would use it here, but it has fixed length.
An completely different solution, which gives the same result for the ground like done by the stanli package (even with different length) is welcome too. Any suggestions?
P. S. Any other optimizations or criticism are welcome too!
Thank you for your help and effort in advance!

A: All I did was to copy the flexible hatch pattern from this answer and to adjust two parameters.
\documentclass{scrartcl}
\usepackage{stanli}% loads TikZ, see: https://ctan.org/pkg/stanli

\usetikzlibrary{patterns}
% from https://tex.stackexchange.com/a/29367/121799
\tikzset{
    hatch distance/.store in=\hatchdistance,
    hatch distance=10pt,
    hatch thickness/.store in=\hatchthickness,
    hatch thickness=2pt
}

\makeatletter
\pgfdeclarepatternformonly[\hatchdistance,\hatchthickness]{flexible hatch}
{\pgfqpoint{0pt}{0pt}}
{\pgfqpoint{\hatchdistance}{\hatchdistance}}
{\pgfpoint{\hatchdistance-1pt}{\hatchdistance-1pt}}%
{
    \pgfsetcolor{\tikz@pattern@color}
    \pgfsetlinewidth{\hatchthickness}
    \pgfpathmoveto{\pgfqpoint{0pt}{0pt}}
    \pgfpathlineto{\pgfqpoint{\hatchdistance}{\hatchdistance}}
    \pgfusepath{stroke}
}
\makeatother

\begin{document}

  \begin{tikzpicture}

    % ground
    \draw
      [very thick] (0, 0) -- (5, 0);
    % for comparison
    \support{3}{0, 0};% stanli
    \filldraw         % tikz
      [pattern=flexible hatch,
        hatch distance=5pt,
        hatch thickness=0.3pt] (1, 0) rectangle (5, -.4);
    % tank
    \draw
      (5, 0)     .. controls (5, 1) and (5.1, 1.1)
                 .. (5.5, 1.1)
      (5.5, 1.4) .. controls (5.1, 1.4) and (5, 1.5)
                 .. (5, 2.5) -- (5, 5)
      (5, 4) -- (0, 4)
      (0, 5) -- (0, 0);
    % atmospheric pressure
    \node at (6, 5) {$p_0$};
    % density
    \node at (1, 3) {$\varrho$};
    % inflow
    \draw
      [->] (-.5, 5.5) .. controls (-.25, 5.5) and (.25, 5.5)
                      .. node[sloped, above] {Zufluss}
           (.5, 4.25);
    % hydrostatic head
    \draw
      (4, 4) -- (4.15, 4.3) -- (3.85, 4.3) -- cycle
      (3.85, 3.9) -- (4.15, 3.9)
      (3.90, 3.8) -- (4.10, 3.8)
      (3.95, 3.7) -- (4.05, 3.7);
    % velocity
    % v_1
    \draw
      [->] (2.5,4) node[above] {1} -- node[sloped, above, at end] {$v_1$} (2.5, 3);
    %v_2
    \draw
      [->] (5.5, 1.25) node[above = 5pt] {2} -- node[above, at end] {$v_2$} (6.5, 1.25);
    % flow line
    \draw
      [dashed] (2.5, 2.9) .. controls (3, 2) and (5, 1.25)
                          .. (5.4, 1.25);
    % coordinate system
    \support{3}{7.5, 1.25};
    \draw
      [->,dashed] (7, 1.25) -- node[sloped, above, at end] {$z$} (7, 2.5);
    % height
    \dimensioning{2}{8, 1.25}{8, 4}{8}[$h$];

  \end{tikzpicture}

\end{document}

To an ordinary marmot's eye they are almost indistinguishable. Notice that at lower zoom the pattern does indeed look a bit weird on preview and even on acroread, but as @dexteritas points out, these are viewer issues that go away once one zooms in.


text:
Q: django cron_tab is not sending email why? I am trying to play around django cron_tab, I also know there's one called django cron but cron_tab is recommended by lots people instead.
I have it installed (I believe it is installed properly as when I run commands there are no errors)
But it is not working though. (Does it have to do with running it locally that's why it's not working?)
I have followed all the steps here to install cron_tab
https://pypi.python.org/pypi/django-crontab
I did install it via pip, I put the it into INSTALLED_APPS
also added in my settings
CRONJOBS = [
('1 * * * *', 'main.extras.cron_job.my_scheduled_job')
]

I have a folder named main under it is extras directory and under extras directory I have a file named cron_job.py
cron_job.py
def my_scheduled_job():
    from django.core.mail import send_mail
    print('######################################')  // this is added because I want to see if terminal / console would print this out as I would know at least the function did at least run but never seen this got printed

    send_mail(
        'cron job test',
        'Here is the message.',
        'from@hello.com',  // using real email locally
        ['to@hello.com'],  // using real email locally
        fail_silently=False,
    )

I believe the setting for my cron is run the following function every minute
I am currently using pycharm and running the whole application using python manage.py runserver which is running properly.
then I ran this command as the documentation mentions.
python manage.py crontab add

then I would get this message
adding cronjob: (1d3207c6e306b905406569c4fab310a3) -> ('1 * * * *', 'main.extras.cron_job.my_scheduled_job')

if I run this command
python manage.py crontab show

I would get this message
Currently active jobs in crontab:
1d3207c6e306b905406569c4fab310a3 -> ('1 * * * *', 'main.extras.cron_job.my_scheduled_job')

Can someone please give me a hand of where I have done wrong?
Thanks in advance
EDIT:
I also tried this too, which didn't work though
CRONJOBS = [
    ('*/1 * * * *', 'main.extras.cron_job.my_scheduled_job')
]

A: I think it is wrong:
CRONJOBS = [
('1 * * * *', 'main.extras.cron_job.my_scheduled_job')
]

I'm not a cron expert, but I think it will run like 00:01, 01:01, 02:01 (every hour)... (https://en.wikipedia.org/wiki/Cron#Overview)
For testing purposes, try to use:
CRONJOBS = [
('* * * * *', 'main.extras.cron_job.my_scheduled_job')
]

It will execute your script every minute, or:
CRONJOBS = [
('*/5 * * * *', 'main.extras.cron_job.my_scheduled_job')
]

to run it each 5 minutes (look the "/": */1 - every 1 minute, */2 - every 2 minutes ...)


text:
Q: Heroku using production configuration instead of staging configuration I'm running two apps on Heroku, one being myapp-production and the other one being myapp-staging.
For some reason however, the staging app uses the production environment configuration rather than the staging configuration, which I have defined in staging.rb.
The way I set up the staging app was by running
heroku create --stack cedar --remote staging

and afterwards
heroku config:add RACK_ENV=staging --app myapp-staging

Yet myapp-staging is still using the production configuration. Any ideas why and how to address that?

A: It's important to add RAILS_ENV=staging too
heroku config:add RAILS_ENV=staging --app myapp-staging

A: Did you restart your dynos (heroku restart) after making this change to your configuration?


text:
Q: conditional count in a list of strings in SQL Oracle I have list of several items
column1 column2                 desired col3  desired col4
items1  car                     car           1
items2  car,car                 car           2
items3  car,toy,car             toy           1
items4  car,toy,toy             toy           2
items5  car,toy,cards           toy           1
items6  toy,cards,cards         toy           1
items7  toy,cards,toy           toy           2
items8  car,cards,toy,cards     cards         2
items9  car,cards,cards         cards         2
itrmd10 toy,cards,car           toy           1

the rule is, if there is a car item then in col3 should come car and count of cars in col4
If there is no car item or another item is present in the list then it should always display the first one that differs form car item + the count of this item.
for example
items3 there is another item as car in the list, in this case toy is the first one, so toy with count 1 will be displayed
items6 there is no car so toy as the first one is displayed
items8 there are another items as car present so the first one is cards this time and will be displayed with count of 2
items10 car needn't be the first item in the list but the rule is the same,another item in the list as car then count the first one = toy with count of 1
thanks

A:
the rule is, if there is a car item then in col3 should come car and count of cars in col4 If there is no car item or another item is present in the list then it should always display the first one that differs form car item + the count of this item.

You can use:
SELECT t.*,
       REGEXP_COUNT(
         ',' || REPLACE( column2, ',', ',,' ) || ',',
         ',' || column3 || ','
       ) AS column4
FROM   (
  SELECT column1,
         column2,
         CASE
         WHEN ',' || column2 || ',' LIKE '%,car,%'
         THEN 'car'
         ELSE REGEXP_SUBSTR( column2, '[^,]+' )
         END AS column3
  FROM   table_name
) t

Which, for your sample data:
CREATE TABLE table_name ( column1, column2 ) AS
SELECT 'items1',  'car'                 FROM DUAL UNION ALL
SELECT 'items2',  'car,car'             FROM DUAL UNION ALL
SELECT 'items3',  'car,toy,car'         FROM DUAL UNION ALL
SELECT 'items4',  'car,toy,toy'         FROM DUAL UNION ALL
SELECT 'items5',  'car,toy,cards'       FROM DUAL UNION ALL
SELECT 'items6',  'toy,cards,cards'     FROM DUAL UNION ALL
SELECT 'items7',  'toy,cards,toy'       FROM DUAL UNION ALL
SELECT 'items8',  'car,cards,toy,cards' FROM DUAL UNION ALL
SELECT 'items9',  'car,cards,cards'     FROM DUAL UNION ALL
SELECT 'items10', 'toy,cards,car'       FROM DUAL;

Outputs:

COLUMN1 | COLUMN2             | COLUMN3 | COLUMN4
:------ | :------------------ | :------ | ------:
items1  | car                 | car     |       1
items2  | car,car             | car     |       2
items3  | car,toy,car         | car     |       2
items4  | car,toy,toy         | car     |       1
items5  | car,toy,cards       | car     |       1
items6  | toy,cards,cards     | toy     |       1
items7  | toy,cards,toy       | toy     |       2
items8  | car,cards,toy,cards | car     |       1
items9  | car,cards,cards     | car     |       1
items10 | toy,cards,car       | car     |       1

db<>fiddle here

If you want the first non-car item or else car if only car items then:
SELECT column1,
       column2,
       column3,
       REGEXP_COUNT( double_delimited, ',' || column3 || ',' ) AS column4
FROM   (
  SELECT t.*,
         CASE
         WHEN REPLACE( double_delimited, ',car,' ) IS NOT NULL
         THEN REGEXP_SUBSTR( REPLACE( double_delimited, ',car,' ), '[^,]+' )
         ELSE 'car'
         END AS column3
  FROM   (
    SELECT column1,
           column2,
           ',' || REPLACE( column2, ',', ',,' ) || ',' AS double_delimited
    FROM   table_name
  ) t
) t

Which outputs:

COLUMN1 | COLUMN2              | COLUMN3 | COLUMN4
:------ | :------------------- | :------ | ------:
items1  | car                  | car     |       1
items2  | car,car              | car     |       2
items3  | car,toy,car          | toy     |       1
items4  | car,toy,toy          | toy     |       2
items5  | car,toy,cards        | toy     |       1
items6  | toy,cards,cards      | toy     |       1
items7  | toy,cards,toy        | toy     |       2
items8  | car,cards,toy,cards  | cards   |       2
items9  | car,cards,cards      | cards   |       2
items10 | toy,cards,car        | toy     |       1

db<>fiddle here


text:
Q: How to implement `breakpoints` in Flutter to check the response line by line? How to implement breakpoints in Flutter to check the response line by line?
I tried it with inlinebreakpoint which is not working

A: I think you are very new with VS Code IDE, You can add breakpoint and manage them from here,

A: In VS Code and Android Studio you should click next to line numbers to put breakpoints. then run app in debug mode


text:
Q: SQL use a two column index or two single indexes ( x = ? and y > ?) This question might seem very similar to previous posted ones but slightly different.
When your queries always contains both columns I know it is a good practice to create an index for both column but for this scenario the queries will be like checking for a column and then finding all records greater than a given value from the second column, e.g.
SELECT * FROM Data WHERE User_Id = 'Johndoe' AND Last_Query > 1001

So should I still use a single index for both Columns (User_id, Last_Query in the above example) or should I make different indices for each columns?

A: Multicolumn indexes are designed to handle exactly this case.  When the first column in an index has a value that is known (User_Id = 'Johndoe' in your example), all the rows with that value are ordered by the second column in the index (Last_Query in your example).  This allows for efficient seeking to where the range on the second column starts.
In general, this works when any prefix of the index columns have "=" filters on them followed by a range filter (> or <) on the next index column. i.e, an index on (col1, ..., colN+1) and a WHERE filter such as:
WHERE col1=a AND col2=b ... AND colN=c AND colN+1 > d


text:
Q: Partitioner implements StepExecutionListener but beforeStep is not called I have this job but when running it the beforeStep method in the partitioner is never called. What am I doing wrong?
@Configuration
public class SomeJob {

@Bean(name = "some-job")
public Job job() {
    return jobBuilderFactory.get(getName())
            .incrementer(new RunIdIncrementer())
            .start(stepOne())
            .next(stepTwo())
            .build();
}

private Step stepOne() {
    TaskletStep stepOne = stepBuilderFactory
            .get("step-one")
            .<...>chunk(CHUNK_SIZE)
            .reader(someReader())
            .writer(someWriter())
            .build();

    return stepBuilderFactory
            .get("partitionedStepOne")
            .partitioner(stepOne)
            .partitioner("partition", partitioner())
            .taskExecutor(someExecutor())
            .gridSize(SIZE)
            .build();
}

@Bean
@Scope(value = "step", proxyMode = ScopedProxyMode.TARGET_CLASS)
Partitioner partitioner() {
    return new OffsetBasedPartitioner(NAME, storedArticleMasterDataRepository);
}
} // end of job class
....

public class OffsetBasedPartitioner implements Partitioner, StepExecutionListener {

@Override
public void beforeStep(StepExecution stepExecution) {
  ...
}
...
}

I would avoid xml configuration files if possible.

A: Thanks to @LucaBassoRicci for his suggestion, I added the partitioner as listener in the step definition:
return stepBuilderFactory
        .get("partitionedStepOne")
        .partitioner(stepOne)
        .partitioner("partition", partitioner())
        .listener(partitioner())
        .taskExecutor(someExecutor())
        .gridSize(SIZE)
        .build();

and left all the rest as above, now it works :)


text:
Q: jQueryUI Drag-n-Drop: clone not dropping I'm playing with a little drag & drop ui, and I'm a bit stumped on the DROP.
You can see the Fiddle here.
IMMEDIATE GOAL:
I just need to find out how to get the .draggable span into either of the .droppable divs.
Presuming I'm on the right path with append(), how do I access the content of the clone?
ULTIMATE GOALS:
Ultimately, I'll need to add a way do delete items from the drop-zone divs and limit the .textfield input/div to accepting only a single drop (the .textarea input/div can accept an unlimited number of "payloads").
CODE:
/* html */

            Company
            Contact

                **BD

            Contacts
            Edit
                Delete

                0024

            Contacts
            Edit
                Delete

                Acme Anvil Corp

            Contacts
            Edit
                Delete

.
/* js */
// DRAG
$('span[draggable]').draggable({
    revert: true,
    helper: "clone"
});

// DROP
$('.droppable').droppable({
    tolerance: 'pointer',
    drop: function(event, ui) {
        //console.log(this);
        $(this).append($(ui.helper));
    }
});

Any and all help and suggestions are welcome

A: Alright  ...  got to the bottom of it.
The clone just doesn't seem to operate the way one would expect.
You end up having to use a custom function to package up your own clone into an object, and then pull it back out of your object in the drop.
You can see the working example here on jsFiddle.
Here's what ended up working:
// Drag
$('span[draggable]').draggable({
    revert: true,
    helper: function() {
        var container = $('
');
        var dragged = $(this);
        container.append(dragged.clone());
        return container;
    }
});

// Drop
$('.droppable').droppable({
    tolerance: 'pointer',
    drop: function(event, ui) {
        $(this).append($(ui.helper.children()));
    }
});


text:
Q: Link loads in new page, not iframe OK, I've not used iframes for a long time but this problem is so basic I must be missing something really obvious.
I have a page (Page A) containing a link (to Page B in the same domain/folder as the parent) that I want to open in an iframe in Page A.
pageA.html:
<!doctype html>

<meta charset="utf-8">
<title>Page A</title>

Load ...

pageB.html:
<!doctype html>

<meta charset="utf-8">
<title>Page B</title>

This is a test. Should load in iframe.

When the link is clicked pageB opens in a new page (as if the target id isn't present), not in the iframe in pageA.
What am I doing wrong?
=========================================================
OK, sorted that but now I need to do this using php generated JavaScript.  Here is a very minimal example:
pageA.php (parent page):
<!doctype html>

<meta charset="utf-8">
<title>Page A</title>

<?php
$srcPage = "/pageB.html";
echo "

";?>

[Click me to load] ...

pageB.html (page to load - same as before):
<!doctype html>

<meta charset="utf-8">
<title>Page B</title>

This is a test. Should load in iframe.

The script executes (alert is displayed) but the page doesn't load.
Thanks
Nigel

A: You should add the attribute name="tgt" to your iframe.
open link in iframe
For your second question, you mixed jquery with plain javascript.
This is how you change the src of an iframe using plain javascript:
document.getElementById('iframeid').src = '$srcPage'


text:
Q: CakePHP How to get data from csv file after upload I created a form with input type file, button submit to access to a function in controller, the problem is I can't get data from that file.
in controller when I call :

function displayAll() {

 $adherents = $_FILES['file']['tmp_name'];
 prd($adherents);
}

I found this error

Undefined index: file [APP\controllers\adherents.php, line 36]

and this is the view:

Upload filer

<fieldset class="pano bleu">

<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll'));?>

 <?php
  echo $this->Form->input('file', array('type' => 'file'));
  echo $bouton->block(array(
            'cancel'=>array('action'=>'index'),
            'submit'=>array('id'=>'addAdherentFile')
    ));
  echo $this->Form->end();?>
</fieldset>

A: Add 'type' => 'file' to  your form options like this:
<?php echo $this->Form->create('adherentsSuph', array('action'=>'displayAll', 'type' => 'file')); ?>
Check if is a valid request and a valid file, then use file() to read the entire file into an array and loop it.
if (!empty($this->data)) {
    if (is_file($this->data['file']['tmp_name'])) {
        $file = file($this->data['file']['tmp_name']);
        foreach ($file as $key => $row) {
            var_dump($row); die;
        }
    }
}

See also:

*

*file()

*is_file()

*Form > Options > Type

*Field naming convention

Debug $this->data to check if you need to change $this->data['file'] to $this->data['adherentsSuph']['file']

A: Your question is of poor quality since you are giving incomplete code. I will try to help you anyway.
Please check the following things:

*

*Are you using the CakePHP FormHelper?

*If so make sure you initialize the Form with 'type' => 'file' (see here).

*Finally check, what you get in $this->request->data in your Controller.


text:
Q: How to grab the oldest unread message from `mail` in a script? In a script I am trying to finish writing now, I need to get the oldest unread message from the current user's mailbox (specifically, I need the subject line for this project).
After extracting the oldest message, I also need to forward it to a different user for archive purposes.
How can I extract just that information in bash or Python?
Would it be better to use procmail to extract the subject line into a file and then forward the message, requiring only file processing by the script? If so, how could I do that instead?

A: In conventional mbox systems, the first message in /var/mail/you is -- by definition -- unread and the oldest available.
formail -zxSubject: -1 -s </var/mail/you

To extract the message to a file (so you can conveniently forward just that message) and then extract the Subject: header, try something like
tmp=$(maketemp -t findoldestunread.XXXXXXXX) || exit 127
trap 'rm -f $tmp' EXIT   # remove temp file when done
trap 'exit 1' 1 2 3 5 15 # remove also in case of error / interruption
formail -1 -s </var/mail/you >"$tmp"
formail -zxSubject: <"$tmp"
sendmail -oi uncannyvictim@example.com <"$tmp"

In Maildir, the situation is somewhat more complex.  New messages are temporarily stored in tmp and then moved to cur.  The file name indicates flags; in so many words, look for a file name containing a comma near the end where S is not among the characters after the comma.
find path/to/Maildir/cur -maxdepth 1 -type f \
    -regex '.*,[^S,]*$' -printf '%C@ %p\n' |
sort | sed '1s/^[^ ]* //;q' | xargs formail -zxSubject:

The printf format specifier prints the timestamp first for easy sorting. We sort, grab the first line, trim the timestamp, and feed it to formail for extracting the Subject: header. (This will obviously break if you have funky file names with newlines in them or something; there are ways around that, but I'm lazy and practical here.)
Refactoring to just print the file name should be trivial in this case -- just remove the pipe to xargs and capture the output into a variable.
Some Maildir implementations will also have an index of some sort which might make this task a lot easier and faster than traversing the entire mailbox in the file system, but again, without more knowledge about which implementation you are using, this is just a speculative note at this point.
If your mailbox is not in either of these two formats, (you are weird and) you will need to update your question with more details.
Your reference to mail implies that you are probably using a traditional Berkeley mbox system, but there are many versions, some of which are somewhat esoteric.

A: The mail command can be used non-interactively to print out the list of emails in the inbox:
mail -H | head -1
>U     1  jenny@mybox.example.com Tue Apr 29 14 08:13 18/774    "Subject of mail"

A: There are at least three mail delivery formats.  It would help to know which one you are using.
formail will read a mail file and can output headers from particular message via skip and total options.  This assumes the messages have been deliver into a known file.  If you want to archive all the messages this would be a suitable tool.
procmail is more suitable to archiving the messages as they arrive. It can easily be configured to send a copy to another address while delivering.   There are standard methods to avoid mail locks, and skip certain types of messages.


text:
Q: Is there a way to abort a SlickGrid asynchronous render? I have a search page whose results are rendered in a SlickGrid. It is an ajax search that executes onkeyup, so it's possible for a search to be performed, the Slick.Grid instance's render to be called, and have another result come back before the first asynchronous render completes. I'd like to cancel the initial render as soon as the second ajax request comes back so that there aren't two render calls taking place at the same time.
EDIT WITH EXAMPLE:
Here's what I'm doing, with alerts in place to track the execution order.
function setupGrid() {
    slickDataView = new Slick.Data.DataView();
    slickGrid = new Slick.Grid(slickGridDiv, slickDataView.rows, slickGridColumns, slickGridOptions);
    slickDataView.onRowsChanged.subscribe(function(rows) {
      slickGrid.removeRows(rows);
      slickGrid.updateRowCount();
      slickGrid.render();
    });
    slickDataView.onRowCountChanged.subscribe(function(args) {
      slickGrid.updateRowCount();
      slickGrid.render();
    });
}

function performSearch() {
    jQuery.get('searchPage.php', {MODEL_ID: userInputField.val()},
      function(results) {
        slickDataView.beginUpdate();
        alert(1);
        slickDataView.setItems(results);
        alert(2);
        slickDataView.endUpdate();
      }
    );
}

setupGrid();
userInputField.keyup(function() { performSearch(); });

I get the following alerts in this sequence when I type two numbers into the userInputField text field in quick succession:
1
1
2

A: There must be something else going on on your page.
The example you listed is impossible - JavaScript execution is never interrupted by an event getting fired.  The event just gets queued up and picked up by the event loop after the current code is done executing.  What you would see in your example, is 1212.
You will want to throttle the AJAX calls and also to cancel the callbacks from the previous calls since your AJAX responses may come back out of order and the older search results can override the newer ones.


text:
Q: how can I make that label go down a line between every string I have this array of string
I want it inside the label so that every string has line
"method": [
    "Bring a large frying pan of salted water to the boil over medium-high heat. Add the asparagus and cook for 2-3 minutes or until bright green and tender crisp. Use tongs to transfer the asparagus to a plate. Cover to keep warm.",
    "Add the vinegar to the water in pan. Reduce heat to medium-low. Crack 1 egg into a small bowl. Use a spoon to stir the water to make a whirlpool. Carefully pour the egg into the centre of the whirlpool. Cook for 4 minutes for a soft yolk or until cooked to your liking. Use a slotted spoon to transfer to a plate. Cover with foil to keep warm. Repeat with remaining eggs.",
    "Divide the asparagus among serving plates. Top with an egg. Season with salt and pepper. Top with parmesan to serve."
]

I want it inside the label so that every string has line

A: You can try something like this:
let arrayStr = [ "Bring a large frying pan of salted water to the boil over medium-high heat. Add the asparagus and cook for 2-3 minutes or until bright green and tender crisp. Use tongs to transfer the asparagus to a plate. Cover to keep warm.", "Add the vinegar to the water in pan. Reduce heat to medium-low. Crack 1 egg into a small bowl. Use a spoon to stir the water to make a whirlpool. Carefully pour the egg into the centre of the whirlpool. Cook for 4 minutes for a soft yolk or until cooked to your liking. Use a slotted spoon to transfer to a plate. Cover with foil to keep warm. Repeat with remaining eggs.", "Divide the asparagus among serving plates. Top with an egg. Season with salt and pepper. Top with parmesan to serve." ]

SwiftUI
Text(arrayStr.joined(separator: "\n\n"))

Storyboard
label.text = arrayStr.joined(separator: "\n\n")


text:
Q: Load Message and settimeout I want to add loading message for export file button if it takes time to load for example first message "please wait"
after 10 seconds settimeout to "loading..." after 20secound "sorry, please wait"
const [loading, setLoading] = useState(false);

function greet1() {
  return "please wait.."
}
function greet2() {
  return "loading"
}
function greet3() {
 return "sorry, please wait..."
}

const list= () => {
setLoading(true)
    if (loading) {
      setTimeout(() => {
        greet1
      }, 0);
      setTimeout(() => {
        greet2
      }, 2000);
      setTimeout(() => {
        greet3
      }, 3000);
    }
}

A: I am not sure how is your code in React but in simple JS it works. Just tweak it for your need.
Updated: added ability to write inside message div.

var message = document.getElementById("message");
function greet1() {
 message.innerHTML = "please wait..";
}
function greet2() {
   message.innerHTML= "loading";
}
function greet3() {
  message.innerHTML= "sorry, please wait...";
}
var loading = true;
    if (loading) {
      setTimeout(() => {
        greet1();
      }, 0);
      setTimeout(() => {
        greet2();
      }, 2000);
      setTimeout(() => {
        greet3();
      }, 3000);
    }

A: you can write:
if (loading) {
 let time = 0;
 setTimeout(() => {
  switch(time) {
   case 2:
    alert("please wait...");
    break;
   case 5:
    alert("loading...");
    break;
   case 10:
    alert("sorry, please wait...");
    break;
  }
  time++;
 }, 1000);
}

A: In your specific case, you might do the following:

*

*You need to correct your syntax. Functions are invoked by using () following the namespace.
E.g. greet1()

*Create a counter-based state (since it seems like your messages vary based on the "duration"). This allows us to determine the "time" that has passed.

const [downloadStatus, setDownloadStatus] = useState(0);

*Add a onClick listener to trigger the download.

const messageDownloadPairs = {
  1: ["Message1", 0],
  2: ["Message2", 10 * 1000]
  3: ["Message3", 20 * 1000]
}
const getDownloadMessageTimePair = (status) =>
  messages[Math.min(status, Object.values(messages).length)]

with the following jsx under return
<button onClick={invokeDownload}>{getDownloadMessage(downloadStatus)[0]}</button>

where invokeDownload follows the signature
const invokeDownload = () => {
  // Your download code here.
  setDownloadStatus(1) // Notifying the component that the download has started.
}

*Create a function checkDownloadStatus to check if the download has completed. You can find some examples here

*Use the hook useEffect to handle timeouts, and state updates.

useEffect(() => {
  const downloadComplete = checkDownloadStatus()

  if (!downloadComplete) {
    const newDownloadStatus = downloadStatus + 1
    setTimeOut(
      () => setDownloadStatus(newDownloadStatus),
      getDownloadMessageTimePair(downloadStatus)[1]
    )
  }
}, [downloadStatus])

With this, you have a "progress-supported" button to track your csv download. I'll update this when I get more information on the specifics of your project.


text:
Q: Embedded iFrame Showing Up Blank I am trying to embed this link using an iFrame: https:\bobcat-den-delivery.herokuapp.com
The iFrame is clearly there, but definitely blank.
This is my frame code:
<iframe src="https://bobcat-den-delivery.herokuapp.com/" style="border:2px #2980b9 none;" scrolling="yes" frameborder="1" marginheight="1px" marginwidth="1px" height="300px" width="700px"></iframe>

This seems really simple and I am having trouble figuring out exactly what is going wrong.

A: I tried it with a normal iframe and it didn't work. The website could be blocking iframe's through .htaccess. If it's your website then look at the .htaccess.
Blocking in  .htaccess
Header set X-Frame-Options DENY

But, you can enable iframes come from the same origin.
Header always append X-Frame-Options SAMEORIGIN

A: The problem was the iFrame permissions of the site to be embedded. Adding this code to the application.rb file solved the issue:
config.action_dispatch.default_headers = {
'X-Frame-Options' => 'ALLOWALL'

}
Source: Ruby on rails 4 app does not work in iframe


text:
Q: Java Applet - Drawing Polygons - Reading RGB I am trying to write a Java Applet that has the ability to draw polygons on a canvas. So far so good.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class DrawingLines2 extends Applet implements ItemListener  {
    DrawCanvas canvas;

    public void init() {
        // Create components and lay out the applet
        canvas = new DrawCanvas();
    ...
    }
}
class DrawCanvas extends Canvas implements ActionListener, MouseListener{
...
}

However, I would then like the program to be able to get the current visible canvas and loop through each pixel, collecting its color.
However, it does not appear that there is a method within the Canvas class that lets me get the color of a pixel in the canvas at a specified point (x,y).
Is there another way of achieving this?

A: One approach might be to use Robot#getPixelColor, but you will need to convert the pixel position from the component space to the screen space. This might be rather slow and you could also have issues creating the Robot instance due to the tight security restrictions that applets operate under.
Another option might be to create a BufferedImage the same size as the DrawCanvas and using its Graphics context, call print on the DrawCanvas
Something like...
class DrawCanvas extends Canvas implements ActionListener, MouseListener{
    //...

    public Color getRGBAt(int x, int y) {
        BufferedImage img = new BufferedImage(getWidth(), getHeight(), BufferedImage.TYPE_TYPE_INT_ARGB);
        Graphics2D g2d = img.createGraphics();
        paint(g2d);
        g2d.dispose();
        return new Color(img.getRGB(x, y), true);
    }

Now, personally, I'd strongly discourage you from using AWT based components and encourage you to use the Swing API instead, as AWT is rather antiquated and not many developers are using it actively, making it difficult to find support for problems you might have.  I'd also encourage you not to use applets if you can avoid it, while you are learning; they have a bunch of their own issues which just complicate the whole process, without much gain.

A: Create a BufferedImage, do your drawings on that BufferedImage then copy the content of BufferedImage to the Canvas using drawImage().
Use getData() or getRGB() from BufferedImage to get the pixel color.


text:
Q: Useless result of Integrate Considering a Fourier sine series, I calculate
int = Integrate[Log[1 + Sin[x]]*Sin[i*x], {x, 0, Pi}, Assumptions -> i ∈ PositiveIntegers]

1/4 (-((2 E^(-(1/2) I i π))/i^2) + (2 E^((I i π)/2))/i^2 +  E^(-I i π)/i^2 - E^(I i π)/i^2 + ( 4 (E^((I i π)/2) - Cos[(i π)/2]) HurwitzLerchPhi[-1, 1,  1 - i])/i - ( 2 I (1 - E^(-I i π)) HurwitzLerchPhi[-I, 1, 1 - i])/i - ( 2 I LerchPhi[-I, 1, 1 + i])/i + ( 2 I E^(I i π) LerchPhi[-I, 1, 1 + i])/i - ( E^(-(1/2) I i π) (-1 + E^(I i π)) PolyGamma[0, 1 + i/2])/ i + (E^(-(1/2) I i π) (-1 + E^(I i π)) PolyGamma[0, ( 1 + i)/2])/i + ( 4 HypergeometricPFQ[{1, 1, 3/2}, {2 - i/2, 2 + i/2}, 1] Sin[( i π)/2]^2)/(-4 i + i^3) - ( 2 HypergeometricPFQ[{1/2, 1, 1}, {3/2 - i/2, 3/2 + i/2}, 1] Sin[ i π])/(-1 + i^2))

Unfortunately, the result is useless in view of
Table[int, {i, 1, 5}]

{Indeterminate, Indeterminate, Indeterminate, Indeterminate,  Indeterminate}

and
Limit[int, i -> 3]

which returns the input.
It should be noticed that
Table[Integrate[Log[1 + Sin[x]]*Sin[i*x], {x, 0, Pi}], {i, 1, 5}]

results in {-2 + π, 0, 1/9 (10 - 3 π), 0, -(46/75) + π/5}.
Is there a workaround for the general case?

A: Often Mathematica Integrate shows problems with integer assumptions.
As a workaround try
intEven[i_] := Integrate[Log[1 + Sin[x]]*Sin[(2 i )*x], {x, 0, Pi}]
Table[{2 i, intEven[i]}, {i, 1, 5}]
(*{{2, 0}, {4, 0}, {6, 0}, {8, 0}, {10, 0}}*)

intOdd[i_] := Integrate[Log[1 + Sin[x]]*Sin[(2 i-1 )*x], {x, 0, Pi}]
Table[{2 i - 1, intOdd[i]}, {i, 1, 5}]
(*{{1, -2 + \[Pi]}, {3,1/9 (10 - 3 \[Pi])}, {5, -(46/75) + \[Pi]/5}, {7,334/735 - \[Pi]/7}, {9, -(982/2835) + \[Pi]/9}}*)

A: You can get a general formula for integrals, if you TrigExpand the integer multiples of Sin[j x] and integrate each summand alone.
Make use of the fact, that summands can be developed with a Binomial formula.
(tab = Table[(Sin[(j)*x] // TrigExpand), {j, 1, 11}]) // TableForm

(ta = Table[
Sum[(-1)^( (k - 1)/2) Binomial[n, k]*Cos[x]^(n - k) Sin[x]^k, {k,
  1, n, 2}], {n, 1, 11}]) // TableForm

ta == tab yields True
int[n_, k_] =
  Integrate[
   Log[1 + Sin[x]]*((-1)^( (k - 1)/2) Binomial[n, k]*Cos[x]^(n - k)
   Sin[x]^k), {x, 0, Pi},
     Assumptions ->
 n \[Element] Integers && n > 0 && k \[Element] Integers && k > 0 &&
 1 <= k <= n]

(*     -(I I^-k ((-1)^k + (-1)^n) Binomial[n, k] Gamma[
 1/2 (1 - k + n)] (4 Gamma[2 + k/2] Gamma[2 + n/2] Gamma[(3 + n)/
    2] HypergeometricPFQ[{1, 3/2, 2 + k/2}, {5/2, 5/2 + n/2},
    1] + 3 Gamma[(5 + n)/
    2] (4 Gamma[1 + k/2] Gamma[2 + n/2] - (2 + n) Gamma[(1 + k)/
       2] Gamma[(3 + n)/
       2] (PolyGamma[0, 1 + n/2] -
        PolyGamma[0, 1/2 (1 - k + n)]))))/(24 Gamma[
 2 + n/2] Gamma[(3 + n)/2] Gamma[(5 + n)/2])     *)

ta2 = Table[Sum[int[n, k], {k, 1, n, 2}], {n, 1, 11}] //
  FullSimplify // Expand

(*     {-2 + \[Pi], 0, 10/9 - \[Pi]/3, 0, -(46/75) + \[Pi]/5, 0,
334/735 - \[Pi]/7, 0, -(982/2835) + \[Pi]/9, 0,
10942/38115 - \[Pi]/11}     *)

ta1 = Table[
  Integrate[Log[1 + Sin[x]]*Sin[(i)*x], {x, 0, Pi}], {i, 1, 11}] //
  Expand

ta1 == ta2 yields True

A: The coefficients on Pi looks like Sin[i π/2]/i, and FindSequenceFunction can suggest the rational part:
a[i_] := a[i] = Integrate[Log[1 + Sin[x]]*Sin[i*x], {x, 0, Pi}];

seq = Table[a[i] - Sin[i π/2] π/i, {i, 1, 28, 2}] // Expand // FindSequenceFunction;
FullSimplify[seq[(i + 1)/2], i ∈ PositiveIntegers]
(* (I^(1 + i) i π + 2 (-1)^i (-1 + i LerchPhi[-1, 1, 1 + i/2]))/i^2 *)

Which simplifies to
Table[a[i] - (((-1 + (-1)^i) (-1 + i LerchPhi[-1, 1, 1 + i/2]))/i^2), {i, 18}] // Expand
(* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} *)


text:
Q: npm rebuild --verbose sharp выдаёт ошибку Попытался установить IconGenie для Quasar Framework, при запуске icongenie generate выдаёт следующую ошибку:
PS E:\TestQuasar\test> icongenie generate

E:\nvm\v15.5.1\node_modules\@quasar\icongenie\node_modules\sharp\lib\constructor.js:34
  throw new Error(error);
  ^

Error:
Something went wrong installing the "sharp" module

Cannot find module '../build/Release/sharp.node'
Require stack:
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\node_modules\sharp\lib\constructor.js
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\node_modules\sharp\lib\index.js
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\lib\utils\get-files-options.js
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\lib\cmd\generate.js
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\bin\icongenie-generate
- E:\nvm\v15.5.1\node_modules\@quasar\icongenie\bin\icongenie

- Run "npm rebuild --verbose sharp" and look for errors
- Consult the installation documentation at https://sharp.pixelplumbing.com/install
- Search for this error at https://github.com/lovell/sharp/issues

    at Object.<anonymous> (E:\nvm\v15.5.1\node_modules\@quasar\icongenie\node_modules\sharp\lib\constructor.js:34:9)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)
    at Module.load (node:internal/modules/cjs/loader:973:32)
    at Function.Module._load (node:internal/modules/cjs/loader:813:14)
    at Module.require (node:internal/modules/cjs/loader:997:19)
    at require (node:internal/modules/cjs/helpers:92:18)
    at Object.<anonymous> (E:\nvm\v15.5.1\node_modules\@quasar\icongenie\node_modules\sharp\lib\index.js:3:15)
    at Module._compile (node:internal/modules/cjs/loader:1108:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1137:10)

Запускаю npm rebuild --verbose sharp и получаю такую кучу ошибок:
npm ERR! code 1
npm ERR! path E:\TestQuasar\test\node_modules\sharp
npm ERR! command failed
npm ERR! command C:\WINDOWS\system32\cmd.exe /d /s /c (node install/libvips && node install/dll-copy && prebuild-install) || (node-gyp rebuild && node install/dll-copy)
npm ERR! info sharp Using existing vendored libvips v8.8.1
npm ERR! info sharp Creating E:\TestQuasar\test\node_modules\sharp\build\Release
npm ERR! info sharp Copying DLLs from E:\TestQuasar\test\node_modules\sharp\vendor\lib to E:\TestQuasar\test\node_modules\sharp\build\Release
npm ERR! prebuild-install info begin Prebuild-install version 5.3.6
npm ERR! prebuild-install info install installing standalone, skipping download.
npm ERR! gyp info it worked if it ends with ok
npm ERR! gyp verb cli [
npm ERR! gyp verb cli   'E:\\nodejs\\node.exe',
npm ERR! gyp verb cli   'E:\\nvm\\v15.5.1\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js',
npm ERR! gyp verb cli   'rebuild'
npm ERR! gyp verb cli ]
npm ERR! gyp info using node-gyp@7.1.2
npm ERR! gyp info using node@15.5.1 | win32 | x64
npm ERR! gyp verb command rebuild []
npm ERR! gyp verb command clean []
npm ERR! gyp verb clean removing "build" directory
npm ERR! gyp verb command configure []
npm ERR! gyp verb find Python checking Python explicitly set from command line or npm configuration
npm ERR! gyp verb find Python - "--python=" or "npm config get python" is "C:\python27\python.exe"
npm ERR! gyp verb find Python - executing "C:\python27\python.exe" to get executable path
npm ERR! gyp verb find Python - executable path is "C:\python27\python.exe"
npm ERR! gyp verb find Python - executing "C:\python27\python.exe" to get version
npm ERR! gyp verb find Python - version is "2.7.0"
npm ERR! gyp info find Python using Python version 2.7.0 found at "C:\python27\python.exe"
npm ERR! gyp verb get node dir no --target version specified, falling back to host node version: 15.5.1
npm ERR! gyp verb command install [ '15.5.1' ]
npm ERR! gyp verb install input version string "15.5.1"
npm ERR! gyp verb install installing version: 15.5.1
npm ERR! gyp verb install --ensure was passed, so won't reinstall if already installed
npm ERR! gyp verb install version is already installed, need to check "installVersion"
npm ERR! gyp verb got "installVersion" 9
npm ERR! gyp verb needs "installVersion" 9
npm ERR! gyp verb install version is good
npm ERR! gyp verb get node dir target node version installed: 15.5.1
npm ERR! gyp verb build dir attempting to create "build" dir: E:\TestQuasar\test\node_modules\sharp\build
npm ERR! gyp verb build dir "build" dir needed to be created? E:\TestQuasar\test\node_modules\sharp\build
npm ERR! gyp verb find VS msvs_version not set from command line or npm config
npm ERR! gyp verb find VS VCINSTALLDIR not set, not running in VS Command Prompt
npm ERR! gyp verb find VS checking VS2017 (15.9.28307.1342) found at:
npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools"
npm ERR! gyp verb find VS - found "Visual Studio C++ core features"
npm ERR! gyp verb find VS - found VC++ toolset: v141
npm ERR! gyp verb find VS - missing any Windows SDK
npm ERR! gyp verb find VS checking VS2017 (15.8.28010.2003) found at:
npm ERR! gyp verb find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional"
npm ERR! gyp verb find VS - found "Visual Studio C++ core features"
npm ERR! gyp verb find VS - found VC++ toolset: v141
npm ERR! gyp verb find VS - found Windows SDK: 10.0.17134.0
npm ERR! gyp info find VS using VS2017 (15.8.28010.2003) found at:
npm ERR! gyp info find VS "C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional"
npm ERR! gyp info find VS run with --verbose for detailed information
npm ERR! gyp verb build/config.gypi creating config file
npm ERR! gyp verb build/config.gypi writing out config file: E:\TestQuasar\test\node_modules\sharp\build\config.gypi
npm ERR! gyp verb config.gypi checking for gypi file: E:\TestQuasar\test\node_modules\sharp\config.gypi
npm ERR! gyp verb common.gypi checking for gypi file: E:\TestQuasar\test\node_modules\sharp\common.gypi
npm ERR! gyp verb gyp gyp format was not specified; forcing "msvs"
npm ERR! gyp info spawn C:\python27\python.exe
npm ERR! gyp info spawn args [
npm ERR! gyp info spawn args   'E:\\nvm\\v15.5.1\\node_modules\\npm\\node_modules\\node-gyp\\gyp\\gyp_main.py',
npm ERR! gyp info spawn args   'binding.gyp',
npm ERR! gyp info spawn args   '-f',
npm ERR! gyp info spawn args   'msvs',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'E:\\TestQuasar\\test\\node_modules\\sharp\\build\\config.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'E:\\nvm\\v15.5.1\\node_modules\\npm\\node_modules\\node-gyp\\addon.gypi',
npm ERR! gyp info spawn args   '-I',
npm ERR! gyp info spawn args   'C:\\Users\\Илья\\AppData\\Local\\node-gyp\\Cache\\15.5.1\\include\\node\\common.gypi',
npm ERR! gyp info spawn args   '-Dlibrary=shared_library',
npm ERR! gyp info spawn args   '-Dvisibility=default',
npm ERR! gyp info spawn args   '-Dnode_root_dir=C:\\Users\\Илья\\AppData\\Local\\node-gyp\\Cache\\15.5.1',
npm ERR! gyp info spawn args   '-Dnode_gyp_dir=E:\\nvm\\v15.5.1\\node_modules\\npm\\node_modules\\node-gyp',
npm ERR! gyp info spawn args   '-Dnode_lib_file=C:\\\\Users\\\\Илья\\\\AppData\\\\Local\\\\node-gyp\\\\Cache\\\\15.5.1\\\\<(target_arch)\\\\node.lib',
npm ERR! gyp info spawn args   '-Dmodule_root_dir=E:\\TestQuasar\\test\\node_modules\\sharp',
npm ERR! gyp info spawn args   '-Dnode_engine=v8',
npm ERR! gyp info spawn args   '--depth=.',
npm ERR! gyp info spawn args   '--no-parallel',
npm ERR! gyp info spawn args   '--generator-output',
npm ERR! gyp info spawn args   'E:\\TestQuasar\\test\\node_modules\\sharp\\build',
npm ERR! gyp info spawn args   '-Goutput_dir=.'
npm ERR! gyp info spawn args ]
npm ERR! Traceback (most recent call last):
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\gyp_main.py", line 51, in <module>
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 670, in script_main
npm ERR!     return main(sys.argv[1:])
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 662, in main
npm ERR!     return gyp_main(args)
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\__init__.py", line 647, in gyp_main
npm ERR!     generator.GenerateOutput(flat_list, targets, data, params)
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\generator\msvs.py", line 2140, in GenerateOutput
npm ERR!     _GenerateProject(project, options, msvs_version, generator_flags, spec)
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\generator\msvs.py", line 1027, in _GenerateProject
npm ERR!     return _GenerateMSBuildProject(project, options, version, generator_flags, spec)
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\generator\msvs.py", line 3825, in _GenerateMSBuildProject
npm ERR!     easy_xml.WriteXmlIfChanged(content, project.path, pretty=True, win32=True)
npm ERR!   File "E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\gyp\pylib\gyp\easy_xml.py", line 124, in WriteXmlIfChanged
npm ERR!     xml_string = xml_string.encode(encoding)
npm ERR! UnicodeDecodeError: 'ascii' codec can't decode byte 0xc8 in position 2393: ordinal not in range(128)
npm ERR! gyp ERR! configure error
npm ERR! gyp ERR! stack Error: `gyp` failed with exit code: 1
npm ERR! gyp ERR! stack     at ChildProcess.onCpExit (E:\nvm\v15.5.1\node_modules\npm\node_modules\node-gyp\lib\configure.js:351:16)
npm ERR! gyp ERR! stack     at ChildProcess.emit (node:events:376:20)
npm ERR! gyp ERR! stack     at Process.ChildProcess._handle.onexit (node:internal/child_process:284:12)
npm ERR! gyp ERR! System Windows_NT 10.0.18363
npm ERR! gyp ERR! command "E:\\nodejs\\node.exe" "E:\\nvm\\v15.5.1\\node_modules\\npm\\node_modules\\node-gyp\\bin\\node-gyp.js" "rebuild"
npm ERR! gyp ERR! cwd E:\TestQuasar\test\node_modules\sharp
npm ERR! gyp ERR! node -v v15.5.1
npm ERR! gyp ERR! node-gyp -v v7.1.2
npm ERR! gyp ERR! not ok
npm verb exit 1
npm timing npm Completed in 8211ms

Что мне надо установить, чтобы всё заработало? Помогите, пожалуйста :(

A: Проблема заключалась в том, что у меня имя пользователя содержит латинские символы, сменил категорию node-gyp и всё запустилось успешно.
npm config set --global devdir D:\node-gyp


text:
Q: error when trying class with linked list c++ I am trying out simple class and linked list implementation.
Please help me out with this code as i am receiving
"list iterator not dereferencable"
when running the code.
Thanks
#include<iostream>
#include<list>
#include<string>

using namespace std;

class Car
{
public:
    void getType(string x)
    {
        type = x;
    }

    string showType()
    {
        return type;
    }

private:
    string type;
};

void main()
{
    string p;
    list<Car> c;
    list<Car>::iterator curr = c.begin();

    cout << "Please key in anything you want: ";
    getline(cin, p);
    curr->getType(p);

    cout << "The phrase you have typed is: " << curr->showType() << endl;

}

A: Write the following way
cout << "Please key in anything you want: ";
getline(cin, p);

c.push_back( Car() );

list<Car>::iterator curr = c.begin();

curr->getType(p);

And it is much better to rename the member function getType to setType.:)
Take into account that the function main without parameters shall be declared like
int main()
^^^

A: You didn't insert anything into your list. So the iterator is not valid, it's pointing to c.end() and dereferencing it is undefined behaviour.
Instead add a Car to your list before you get the begin iterator.
#include<iostream>
#include<list>
#include<string>

using namespace std;

class Car
{
public:
    void setType(const string& x)
    {
        type = x;
    }

    string showType()
    {
        return type;
    }

private:
    string type;
};

int main()
{
    string p;
    list<Car> c;

    c.push_back(Car{});
    auto curr = c.begin();

    cout << "Please key in anything you want: ";
    getline(cin, p);
    curr->setType(p);

    cout << "The phrase you have typed is: " << curr->showType() << endl;
}


text:
Q: Java Spring NullPointerException when accessing Service I'm trying to develop a small web application using Spring. The problem is that I'm getting NullPointerException when trying to access service object in my controller. How to fix that?
Severe:   java.lang.NullPointerException
    at controller.LoginController.executeLogin(LoginController.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:175)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:446)
    at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:434)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:876)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:863)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:707)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)

LoginController.java
package controller;

import ...

@Controller
public class LoginController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView executeLogin(HttpServletRequest request, HttpServletResponse response, @ModelAttribute("user") User user) {
        ModelAndView model = null;
        try {
            boolean isValidUser = userService.isValidUser(user);
            if (isValidUser) {
                System.out.println("User Login Successful");
                request.setAttribute("loggedInUser", user.getLogin());
                model = new ModelAndView("index");
            } else {
                model = new ModelAndView("login");
                model.addObject("user", user);
                request.setAttribute("message", "Invalid credentials!!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return model;
    }
}

UserService.java
package service;

import ...

@Service
public class UserService {

    public boolean isValidUser(User user) {
        if(user.getLogin().equals("admin"))
            return true;
        else
            return false;
    }
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

</web-app>

dispatcher-servlet.xml
<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

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

    <bean class="controller.LoginController"/>

</beans>

A: Include <context:component-scan base-package="service, controller" /> in your
dispatcher-servlet.xml and remove <bean class="controller.LoginController"/>
Your UserService is not getting scanned and hence it is not getting injected into your LoginController.
By turning on the component-scan, all the classes in the base-package will be scanned for the annotations(@Service and @Controller in your case) and registered as beans.


text:
Q: Image zoom to fit Bootstrap Grid I have a Bootstrap Grid and images inside. My images aren't the same size, so I get an ugly grid.
I want all the images to look the same size. I want them to be zoomed and to hide the override part of the image.
I'm trying with this code, but no success:

I know its not clean to put the style right there, but just for tests.

A: I think this is what you're looking for.
JS:
function squareThumbs() {
  var thumbs = document.getElementsByTagName("img");

  for (i = 0; i < thumbs.length; i++) {
    if (thumbs[i].parentNode.className.indexOf("thumbnail") != -1){
      thumbs[i].style.height = thumbs[i].clientWidth + "px";
      console.log(thumbs[i].clientWidth);
      console.log(thumbs[i].clientHeight);
    }
    console.log(thumbs[i].parentNode.className);
  }
}
squareThumbs();
window.onresize = squareThumbs;

HTML:

Live Demo: http://www.bootply.com/bg1A4I9IJ0