问:
How to use buildOpticalFlowPyramid?
I'm using OpenCV 3.3.1. I want to do a semi-dense optical flow operation using cv::calcOpticalFlowPyrLK, but I've been getting some really noticeable slowdown whenever my ROI is pretty big (Partly due to the fact that I am letting the user decide what the winSize should be, ranging from from 10 to 100). Anyways, it seems like cv::buildOpticalFlowPyramid can mitigate the slowdown by building image pyramids? I'm sorta familiar what image pyramids are, but in context of the function, I'm especially confused about what parameters I pass in, and how it impacts my function call to cv::calcOpticalFlowPyrLK. With that in mind, I now have these set of questions:

The output is, according to the documentation, is an OutputArrayOfArrays, which I take it can be a vector of cv::Mat objects. If so, what do I pass in to cv::calcOpticalFlowPyrLK for prevImg and nextImg (assuming that I need to make image pyramids for both)?

According to the docs for cv::buildOpticalFlowPyramid, you need to pass in a winSize parameter in order to calculate required padding for pyramid levels. If so, do you pass in the same winSize value when you eventually call cv::calcOpticalFlowPyrLK?

What exactly are the arguments for pyrBorder and derivBorder doing?

Lastly, and apologies if it sounds newbish, but what is the purpose of this function? I always assumed that cv::calcOpticalFlowPyrLK internally builds the image pyramids. Is it just to speed up the optical flow operation?

I hope my questions were clear, I'm still very new to OpenCV, and computer vision, but this topic is very interesting.

Thank you for your time.

EDIT:

I used the function to see if my guess was correct, so far it has worked, but I've seen no noticeable speed up. Below is how I used it:

```<code>    // Building pyramids
    int maxLvl = 3;
    maxLvl = cv::buildOpticalFlowPyramid(imgPrev, imPyr1, cv::Size(searchSize, searchSize), maxLvl, true);
    maxLvl = cv::buildOpticalFlowPyramid(tmpImg, imPyr2, cv::Size(searchSize, searchSize), maxLvl, true);

    // LK optical flow call
    cv::calcOpticalFlowPyrLK(imPyr1, imPyr2, currentPoints, nextPts, status, err,
                             cv::Size(searchSize, searchSize), maxLvl, termCrit, 0, 0.00001);
</code>```

So now I'm wondering what's the purpose of preparing the image pyramids if calcOpticalFlowPyrLK does it internally?

答:
So the point of your question is that you are trying to improve speed of optical flow tracking by tuning your input parameters.

If you want dirty and quick answer then here it is

```<code> KTL (OpenCV's calcOpticalFlowPyrLK) define a e residual function which are sum of gradient of point inside search window .
The main purpose is to find vector of point that can minimize residual function
So if you increase search window size (winSize) then it is more difficult to find that set of points.
</code>```

If your really really want to do that then please read the official paper.
See the section 2.4

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.585&rep=rep1&type=pdf

I took it from official document

https://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html#bouguet00

Hope that help

Title: How to use buildOpticalFlowPyramid?

Body:
I'm using OpenCV 3.3.1. I want to do a semi-dense optical flow operation using cv::calcOpticalFlowPyrLK, but I've been getting some really noticeable slowdown whenever my ROI is pretty big (Partly due to the fact that I am letting the user decide what the winSize should be, ranging from from 10 to 100). Anyways, it seems like cv::buildOpticalFlowPyramid can mitigate the slowdown by building image pyramids? I'm sorta familiar what image pyramids are, but in context of the function, I'm especially confused about what parameters I pass in, and how it impacts my function call to cv::calcOpticalFlowPyrLK. With that in mind, I now have these set of questions:

The output is, according to the documentation, is an OutputArrayOfArrays, which I take it can be a vector of cv::Mat objects. If so, what do I pass in to cv::calcOpticalFlowPyrLK for prevImg and nextImg (assuming that I need to make image pyramids for both)?

According to the docs for cv::buildOpticalFlowPyramid, you need to pass in a winSize parameter in order to calculate required padding for pyramid levels. If so, do you pass in the same winSize value when you eventually call cv::calcOpticalFlowPyrLK?

What exactly are the arguments for pyrBorder and derivBorder doing?

Lastly, and apologies if it sounds newbish, but what is the purpose of this function? I always assumed that cv::calcOpticalFlowPyrLK internally builds the image pyramids. Is it just to speed up the optical flow operation?

I hope my questions were clear, I'm still very new to OpenCV, and computer vision, but this topic is very interesting.

Thank you for your time.

EDIT:

I used the function to see if my guess was correct, so far it has worked, but I've seen no noticeable speed up. Below is how I used it:

    // Building pyramids
    int maxLvl = 3;
    maxLvl = cv::buildOpticalFlowPyramid(imgPrev, imPyr1, cv::Size(searchSize, searchSize), maxLvl, true);
    maxLvl = cv::buildOpticalFlowPyramid(tmpImg, imPyr2, cv::Size(searchSize, searchSize), maxLvl, true);

    // LK optical flow call
    cv::calcOpticalFlowPyrLK(imPyr1, imPyr2, currentPoints, nextPts, status, err,
                             cv::Size(searchSize, searchSize), maxLvl, termCrit, 0, 0.00001);

So now I'm wondering what's the purpose of preparing the image pyramids if calcOpticalFlowPyrLK does it internally?

Body:
So the point of your question is that you are trying to improve speed of optical flow tracking by tuning your input parameters.

If you want dirty and quick answer then here it is

 KTL (OpenCV's calcOpticalFlowPyrLK) define a e residual function which are sum of gradient of point inside search window .
The main purpose is to find vector of point that can minimize residual function
So if you increase search window size (winSize) then it is more difficult to find that set of points.

If your really really want to do that then please read the official paper.
See the section 2.4

http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.185.585&rep=rep1&type=pdf

I took it from official document

https://docs.opencv.org/2.4/modules/video/doc/motion_analysis_and_object_tracking.html#bouguet00

Hope that help


来源: stackexchange

问:
Avoid RecursionError in turtle paint code

I'm creating a simple program that uses turtle in a tkinter canvas to allow the user to draw with the mouse. The drawing function seems to work fine however after you draw for a bit the program stops and calls a RecursionError.

```<code>from turtle import *
import tkinter as tk

box=tk.Tk()

canv=ScrolledCanvas(box)
canv.pack()

screen=TurtleScreen(canv)

p=RawTurtle(screen)

p.speed(0)

def draw(event):

    p.goto(event.x-256,185-event.y) #The numbers are here because otherwise the turtle draws off center. Might be different depending on computer.

canv.bind('<B1-Motion>', draw)

box.mainloop()
</code>```

This should in theory draw just fine but instead it is calling a RecursionError. I'm lost as to what I can do to prevent this other than maybe wrap the function in a try loop. Any help would be really appreciated.

The output in the Python Shell:

```<code>Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Users\Charlie\Desktop\demo.py", line 17, in draw
    p.speed(0)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2174, in speed
    self.pen(speed=speed)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2459, in pen
    self._update()
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2660, in _update
    self._update_data()
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2651, in _update_data
    self._pencolor, self._pensize)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 545, in _drawline
    self.cv.coords(lineitem, *cl)
  File "<string>", line 1, in coords
RecursionError: maximum recursion depth exceeded while calling a Python object
</code>```

I've spent a good deal of time looking around for an answer and as far as I can tell there isn't one anywhere easy to find. This is my first question on this site so please forgive me if something I did was wrong.

答:
I was not able to reproduce your recursion error but I have seen it before.  Usually in situations where there are new events coming in while the event handler is busy handling an event.  (Which is why it looks like recursion.)  The usual fix is to turn off the event handler inside the event handler.  Give this a try to see if it works any better for you:</p>

```<code>from turtle import RawTurtle, ScrolledCanvas, TurtleScreen
import tkinter as tk

box = tk.Tk()

canv = ScrolledCanvas(box)
canv.pack()

screen = TurtleScreen(canv)

p = RawTurtle(screen)
p.speed('fastest')

def draw(x, y):
    p.ondrag(None)
    p.setheading(p.towards(x, y))
    p.goto(x, y)
    p.ondrag(draw)

p.ondrag(draw)

box.mainloop()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a simple program that uses turtle in a tkinter canvas to allow the user to draw with the mouse. The drawing function seems to work fine however after you draw for a bit the program stops and calls a RecursionError.

from turtle import *
import tkinter as tk

box=tk.Tk()

canv=ScrolledCanvas(box)
canv.pack()

screen=TurtleScreen(canv)

p=RawTurtle(screen)

p.speed(0)

def draw(event):

    p.goto(event.x-256,185-event.y) #The numbers are here because otherwise the turtle draws off center. Might be different depending on computer.

canv.bind('<B1-Motion>', draw)

box.mainloop()

This should in theory draw just fine but instead it is calling a RecursionError. I'm lost as to what I can do to prevent this other than maybe wrap the function in a try loop. Any help would be really appreciated.

The output in the Python Shell:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python36-32\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Users\Charlie\Desktop\demo.py", line 17, in draw
    p.speed(0)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2174, in speed
    self.pen(speed=speed)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2459, in pen
    self._update()
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2660, in _update
    self._update_data()
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 2651, in _update_data
    self._pencolor, self._pensize)
  File "C:\Program Files (x86)\Python36-32\lib\turtle.py", line 545, in _drawline
    self.cv.coords(lineitem, *cl)
  File "<string>", line 1, in coords
RecursionError: maximum recursion depth exceeded while calling a Python object

I've spent a good deal of time looking around for an answer and as far as I can tell there isn't one anywhere easy to find. This is my first question on this site so please forgive me if something I did was wrong.

Body:
I was not able to reproduce your recursion error but I have seen it before.  Usually in situations where there are new events coming in while the event handler is busy handling an event.  (Which is why it looks like recursion.)  The usual fix is to turn off the event handler inside the event handler.  Give this a try to see if it works any better for you:

from turtle import RawTurtle, ScrolledCanvas, TurtleScreen
import tkinter as tk

box = tk.Tk()

canv = ScrolledCanvas(box)
canv.pack()

screen = TurtleScreen(canv)

p = RawTurtle(screen)
p.speed('fastest')

def draw(x, y):
    p.ondrag(None)
    p.setheading(p.towards(x, y))
    p.goto(x, y)
    p.ondrag(draw)

p.ondrag(draw)

box.mainloop()


问:
Foreign characters in website
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

```<code><meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</code>```

Would this not cause the page to be served up as Latin-1 in the HTTP header?

答: This has all got to do with encoding. Take a look back at the source, is there a tag at the top specifying it (charset)? My guess is it'll be UTF8 - although it could be something completely different.</p>

ContentLicense: CC BY-SA 2.5

Title: Foreign characters in website

Body:
I found a website that contains the string "donâ€™t". The obvious intent was the word "don't". I looked at the source expecting to see some character references, but didn't (it just shows the literal string "donâ€™t". A Google search yielded nothing (expect lots of other sites that have the same problem!). Can anyone explain what's happening here?

Edit: Here's the meta tag that was used:

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">

Would this not cause the page to be served up as Latin-1 in the HTTP header?


问:
How to connect Firebase in Chart.js?
I'm using Ionic and I have a CRUD that creates a list of name "Item":

item.models.ts:

```<code>export interface Item {
    key?: string;
    data: string;
    humor: string;
    mania: string;
    numero: string;
    medicamento?: string;
    dormidas?: string;
    menstrual?: boolean;
    evento?: string;
    impacto?: number;
    outras?:  string;

}
</code>```

See how the data is stored in firebase:

So, how to connect the list data created in my chart done in Chart.js?
I can create a static graph only, I would like the graphic to be dynamic and with the data stored in Firebase. On the X axis I want to put the variable "data" and on the Y axis the variable "numero".

.HTML CODE:

```<code><div class="row">
<div class="col-md-6">
  <div style="display: block;">
  <canvas baseChart width="600" height="400"
              [datasets]="lineChartData"
              [labels]="lineChartLabels"
              [options]="lineChartOptions"
              [colors]="lineChartColors"
              [legend]="lineChartLegend"
              [chartType]="lineChartType">
  </canvas>
  </div>
</div>
</code>```

.TS CODE:

```<code> import { Item } from '../../models/item/item.models';

  public lineChartData:Array<any> = [
  {data: [-34, -78, 45, 65], label: 'Humor'}
  ];

  public lineChartLabels:Array<any> = ['19/jun', '20/jun', '21/jun', '22/jun' ];

public lineChartColors:Array<any> = [
  { // grey
    backgroundColor: 'rgba(148,159,177,0.2)',
    borderColor: 'rgba(148,159,177,1)',
    pointBackgroundColor: 'rgba(148,159,177,1)',
    pointBorderColor: '#fff',
    pointHoverBackgroundColor: '#fff',
    pointHoverBorderColor: 'rgba(148,159,177,0.8)'
  }
];
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';
</code>```

Could someone please help me connect Firebase to my chart?
I have not found any material on the subject.
If possible, I would like to see a practical example.

答:
Ionic 3 is based off Angular 2/4/5.
There is a library that you can use to connect to Firebase called AngularFire2.

Here's the documentation:
https://github.com/angular/angularfire2

As far as the chart is concerned, you can get the data retrieved from the firebase. (Usually you have to loop through the array of retrieved Firebase data and clear the lineChartData[0].data element and assign the retrieved data into the element. Afterwards, two-way binding in Angular will do its magic.

Title: How to connect Firebase in Chart.js?

Body:
I'm using Ionic and I have a CRUD that creates a list of name "Item":

item.models.ts:

export interface Item {
    key?: string;
    data: string;
    humor: string;
    mania: string;
    numero: string;
    medicamento?: string;
    dormidas?: string;
    menstrual?: boolean;
    evento?: string;
    impacto?: number;
    outras?:  string;

}

See how the data is stored in firebase:

So, how to connect the list data created in my chart done in Chart.js?
I can create a static graph only, I would like the graphic to be dynamic and with the data stored in Firebase. On the X axis I want to put the variable "data" and on the Y axis the variable "numero".

.HTML CODE:

  <canvas baseChart width="600" height="400"
              [datasets]="lineChartData"
              [labels]="lineChartLabels"
              [options]="lineChartOptions"
              [colors]="lineChartColors"
              [legend]="lineChartLegend"
              [chartType]="lineChartType">
  </canvas>

.TS CODE:

 import { Item } from '../../models/item/item.models';

  public lineChartData:Array<any> = [
  {data: [-34, -78, 45, 65], label: 'Humor'}
  ];

  public lineChartLabels:Array<any> = ['19/jun', '20/jun', '21/jun', '22/jun' ];

public lineChartColors:Array<any> = [
  { // grey
    backgroundColor: 'rgba(148,159,177,0.2)',
    borderColor: 'rgba(148,159,177,1)',
    pointBackgroundColor: 'rgba(148,159,177,1)',
    pointBorderColor: '#fff',
    pointHoverBackgroundColor: '#fff',
    pointHoverBorderColor: 'rgba(148,159,177,0.8)'
  }
];
public lineChartLegend:boolean = true;
public lineChartType:string = 'line';

Could someone please help me connect Firebase to my chart?
I have not found any material on the subject.
If possible, I would like to see a practical example.


问:
Ionic 3 page.module.ts exports statement
I just started with Ionic 3. And I am following the new page lazy loading guidelines.

Assume that I have a page called ControlPage. So in most of the tutorials I looked at, it was specified that I should add

```<code>exports: [
ControlPage
]
</code>```

to the control.module.ts.

But I noticed that the pages load fine even without this part in the control.module.ts. So what is the real use of this statement? And why does my page loading work even if I don't use that statement?

答:
If you use latest CLI then you don't need that.

```<code>ionic generate page Control
</code>```

This will create control.module.ts file by default and it has lazy loading enabled. It looks like this:

```<code>import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ControlPage } from './control';

@NgModule({
  declarations: [
    ControlPage,
  ],
  imports: [
    IonicPageModule.forChild(ControlPage),
   ],
})
export class ControlPageModule { }
</code>```

Here is the official blog post about it.

Body:
I just started with Ionic 3. And I am following the new page lazy loading guidelines.

Assume that I have a page called ControlPage. So in most of the tutorials I looked at, it was specified that I should add

exports: [
ControlPage
]

to the control.module.ts.

But I noticed that the pages load fine even without this part in the control.module.ts. So what is the real use of this statement? And why does my page loading work even if I don't use that statement?

Body:
If you use latest CLI then you don't need that.

ionic generate page Control

This will create control.module.ts file by default and it has lazy loading enabled. It looks like this:

import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { ControlPage } from './control';

@NgModule({
  declarations: [
    ControlPage,
  ],
  imports: [
    IonicPageModule.forChild(ControlPage),
   ],
})
export class ControlPageModule { }

Here is the official blog post about it.


问:
Different size form WPF - Design mode vs Runtime mode
I'm sorry for the beginner's question but 'im quite newbie in creating WPF forms.
I've some problems to set and viewing correct size of forms in Visual Studio.
In design mode the size is larger than in runtime mode.
Here the XAML. Any ideas???

```<code><Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:EnginedrawWPF"
    xmlns:h="http://helix-toolkit.org/wpf" x:Class="MainWindow"
    mc:Ignorable="d"
    Title="Motore di disegno" Height="400.0" Width="970.0" ResizeMode="NoResize">
<Grid Margin="0,0,0,0">

    <h:HelixViewport3D x:Name="helixviewport3dobj"  Height="301" Margin="207,10,10.2,0" h:VerticalAlignment="Top" Foreground="Black" Background="#FFC0E2B5" >

        <h:HelixViewport3D.DefaultCamera>
            <PerspectiveCamera Position="0,-3.5,3.5" LookDirection="0,3.5,-3.5" UpDirection="0,0,1" FieldOfView="61" NearPlaneDistance="0.001"/>
        </h:HelixViewport3D.DefaultCamera>
        <h:SunLight />
        <h:GridLinesVisual3D Fill="#FFB9B9B9" Thickness="0.01" MinorDistance="0.2" MajorDistance="1"/>
    </h:HelixViewport3D>
    <Button x:Name="CBlineare" Content="Nuovo tratto lineare" HorizontalAlignment="Left" Height="30" Margin="10,10,0,0" VerticalAlignment="Top" Width="181"/>
    <Button x:Name="CBcurva90" Content="Aggiungi curva 90°" HorizontalAlignment="Left" Height="30" Margin="10,57,0,0" VerticalAlignment="Top" Width="181"/>
    <Button x:Name="CBcurva45" Content="Aggiungi curva 45°" HorizontalAlignment="Left" Height="30" Margin="10,105,0,0" VerticalAlignment="Top" Width="181"/>
</Grid>
</Window>
</code>```

答:
You may put Grid tag inside the original Grid tag, with Height and Width set manually to fit into the design size.
Then you put the SizeToContent="WidthAndHeight" to the Window tag.

Example of MainWindow.xaml (Visual Studio 2017 Community + WPF):

```<code><Window x:Class="_171207_t0936_controlLocation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_171207_t0936_controlLocation"
        mc:Ignorable="d"
        Title="MainWindow" Height="378.431" Width="607.353"
        SizeToContent="WidthAndHeight">
    <Grid>
        <!-- In order to avoid the difference in size of debug and run modes -->
        <!-- set "SizeToContent=WidthAndHeight" -->
        <!-- Then put Grid insdie the original Grid with Height and Width set manually -->
        <!-- to fit into the design size -->
        <Grid>
            <Button Content="Button" HorizontalAlignment="Left"
                    Margin="430,10,0,0" VerticalAlignment="Top" Width="75"/>
        </Grid>
    </Grid>
</Window>
</code>```

Body:
I'm sorry for the beginner's question but 'im quite newbie in creating WPF forms.
I've some problems to set and viewing correct size of forms in Visual Studio.
In design mode the size is larger than in runtime mode.
Here the XAML. Any ideas???

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:EnginedrawWPF"
    xmlns:h="http://helix-toolkit.org/wpf" x:Class="MainWindow"
    mc:Ignorable="d"
    Title="Motore di disegno" Height="400.0" Width="970.0" ResizeMode="NoResize">
<Grid Margin="0,0,0,0">

    <h:HelixViewport3D x:Name="helixviewport3dobj"  Height="301" Margin="207,10,10.2,0" h:VerticalAlignment="Top" Foreground="Black" Background="#FFC0E2B5" >

        <h:HelixViewport3D.DefaultCamera>
            <PerspectiveCamera Position="0,-3.5,3.5" LookDirection="0,3.5,-3.5" UpDirection="0,0,1" FieldOfView="61" NearPlaneDistance="0.001"/>
        </h:HelixViewport3D.DefaultCamera>
        <h:SunLight />
        <h:GridLinesVisual3D Fill="#FFB9B9B9" Thickness="0.01" MinorDistance="0.2" MajorDistance="1"/>
    </h:HelixViewport3D>
    <Button x:Name="CBlineare" Content="Nuovo tratto lineare" HorizontalAlignment="Left" Height="30" Margin="10,10,0,0" VerticalAlignment="Top" Width="181"/>
    <Button x:Name="CBcurva90" Content="Aggiungi curva 90°" HorizontalAlignment="Left" Height="30" Margin="10,57,0,0" VerticalAlignment="Top" Width="181"/>
    <Button x:Name="CBcurva45" Content="Aggiungi curva 45°" HorizontalAlignment="Left" Height="30" Margin="10,105,0,0" VerticalAlignment="Top" Width="181"/>
</Grid>
</Window>

Body:
You may put Grid tag inside the original Grid tag, with Height and Width set manually to fit into the design size.
Then you put the SizeToContent="WidthAndHeight" to the Window tag.

Example of MainWindow.xaml (Visual Studio 2017 Community + WPF):

<Window x:Class="_171207_t0936_controlLocation.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:_171207_t0936_controlLocation"
        mc:Ignorable="d"
        Title="MainWindow" Height="378.431" Width="607.353"
        SizeToContent="WidthAndHeight">
    <Grid>
        <!-- In order to avoid the difference in size of debug and run modes -->
        <!-- set "SizeToContent=WidthAndHeight" -->
        <!-- Then put Grid insdie the original Grid with Height and Width set manually -->
        <!-- to fit into the design size -->
        <Grid>
            <Button Content="Button" HorizontalAlignment="Left"
                    Margin="430,10,0,0" VerticalAlignment="Top" Width="75"/>
        </Grid>
    </Grid>
</Window>


问:
xCode - how to link dynamic framework from workspace
What is the proper way to link a dynamic framework which lives in the same workspace like the app?

I have a problem when adding the framework from the products folder to the App's "Embedded Binaries" section - because the added framework may be built for simulator and the app builds against iphoneos. I can not add both, can I?

I want to achieve that when my app builds, the framework is built too and I can work the changes immediately instead of doing some cumbersome update via Carthage or something link that.

EDIT: http://netsplit.com/xcode-two-apps-with-a-shared-private-framework-in-a-workspace This blog post describes exactly what i want to do - but this does not work since i want to develop on simulator and iphone (it would require a fat framework). Or did I miss something.

答:
Although is possible to develop main app and framework and doing integration test in the same time from many workspaces, at same point becomes a slow-ish and not scalable development process.

So I suggest you to make a sample app in the workspace of your framework and develop and test your features directly from there. Once your framework is quite stable you release it and you integrate it with your main app.


问:
Unable to use a when...thenReturn on a mocked object in Mockito Junit testing
I am mocking the object of class MockClass and using the when clause to return someClassObject when one of its methods is called ( which is internal to methodToBeTested ). Now in the last line of the code below when I make a call to methodToBeTested , I hope that a internal call to someMethod would run successfully . But there is a nullPointerException which happens in the line of the call to someMethod . Why is my mockObject still null ? I am using @RunWith(MockitoJUnitRunner.class)  as indicated in a lot of threads here .

Edit: As per @Dawood , I replaced @Mock MockClass mockObject with @InjectMocks MockClass mockObject . The output I have below is after this replacement. My idea is that someMethod is not executed in the below line.
when(mockObject.someMethod(arg1,arg2)
But it does get executed and I have an exception being thrown from within it. What am I doing incorrectly here as I want to only mock the method and define what output it gives rather than calling it

```<code>@RunWith(MockitoJUnitRunner.class)
public testClassToBeTested{

    @Mock
    MockClass mockObject;

    @Before
    public void setUp() throws Exception {

        Whitebox.setInternalState(ClassToBeTested, "argumentName",
            arg2);
    }

    @Test
    public void methodToBeTested{

        Class1 arg1 = new Class1();
        Class1.setUserId("test");

        //someMethod which is called within methodToBeTested
        when(mockObject.someMethod(arg1,arg2).thenReturn(someClassObject));

        ClassAnotherClass anotherClassObject = ClassToBeTested.methodToBeTested(arg1);

    }

}
</code>```

Console output:

```<code>java.lang.NullPointerException
at com.mycompany.utils.MockClass.someMethod(MockClass.java:36)
at com.mycompany.impl.ClassToBeTested.methodToBeTested(ClassToBeTested.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

答:
It is a bit hard to tell since your code example is not complete, not a direct copy, and you also did not paste the NPE or the line in which it happens. Chances are:

The mock is not injected

In that case you could put @Inject on the constructor of the class and manually inject the mock in the test, just to make sure.

The mock returns null

This can happen if the mock arguments do not match, or some other error in the mocking code.

In the example you do not mock correctly:

```<code>when(mockObject.someMethod(arg1,arg2).thenReturn(someClassObject));
</code>```

should be

```<code>when(mockObject.someMethod(arg1,arg2)).thenReturn(someClassObject);
</code>```

Notice the change in parentheses

Body:
I am mocking the object of class MockClass and using the when clause to return someClassObject when one of its methods is called ( which is internal to methodToBeTested ). Now in the last line of the code below when I make a call to methodToBeTested , I hope that a internal call to someMethod would run successfully . But there is a nullPointerException which happens in the line of the call to someMethod . Why is my mockObject still null ? I am using @RunWith(MockitoJUnitRunner.class)  as indicated in a lot of threads here .

Edit: As per @Dawood , I replaced @Mock MockClass mockObject with @InjectMocks MockClass mockObject . The output I have below is after this replacement. My idea is that someMethod is not executed in the below line.
when(mockObject.someMethod(arg1,arg2)
But it does get executed and I have an exception being thrown from within it. What am I doing incorrectly here as I want to only mock the method and define what output it gives rather than calling it

@RunWith(MockitoJUnitRunner.class)
public testClassToBeTested{

    @Mock
    MockClass mockObject;

    @Before
    public void setUp() throws Exception {

        Whitebox.setInternalState(ClassToBeTested, "argumentName",
            arg2);
    }

    @Test
    public void methodToBeTested{

        Class1 arg1 = new Class1();
        Class1.setUserId("test");

        //someMethod which is called within methodToBeTested
        when(mockObject.someMethod(arg1,arg2).thenReturn(someClassObject));

        ClassAnotherClass anotherClassObject = ClassToBeTested.methodToBeTested(arg1);

    }

}

Console output:

java.lang.NullPointerException
at com.mycompany.utils.MockClass.someMethod(MockClass.java:36)
at com.mycompany.impl.ClassToBeTested.methodToBeTested(ClassToBeTested.java:21)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.rules.ExpectedException$ExpectedExceptionStatement.evaluate(ExpectedException.java:239)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.JUnit45AndHigherRunnerImpl.run(JUnit45AndHigherRunnerImpl.java:37)
at org.mockito.runners.MockitoJUnitRunner.run(MockitoJUnitRunner.java:62)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Body:
It is a bit hard to tell since your code example is not complete, not a direct copy, and you also did not paste the NPE or the line in which it happens. Chances are:

The mock is not injected

In that case you could put @Inject on the constructor of the class and manually inject the mock in the test, just to make sure.

The mock returns null

This can happen if the mock arguments do not match, or some other error in the mocking code.

In the example you do not mock correctly:

when(mockObject.someMethod(arg1,arg2).thenReturn(someClassObject));

should be

when(mockObject.someMethod(arg1,arg2)).thenReturn(someClassObject);

Notice the change in parentheses


问:
How to run an .exe file downloaded with InternetOpenFile() in Winapi
I have a C app written using Winapi and an .exe file that I need to download and execute. My code so far is:

```<code>if (NULL == (hRequest = HttpOpenRequest(hHTTP, "GET", "/~alexandru.antochi/exe_1.exe", NULL, NULL, rgpszAcceptTypes, NULL, INTERNET_FLAG_NO_COOKIES || INTERNET_FLAG_NO_AUTH)))
        {
            _error("HttpOpenRequest error.");
        }

        if (HttpSendRequest(hRequest, NULL, NULL, NULL, NULL))
        {

            if (InternetReadFile(hRequest, &buffer, 65536, &bytesRead))
            {
                if (bytesRead == 65536)
                {
                    printf("Warning: .exe file too big. Ignoring");
                    continue;
                }
            }
        }
        else
        {
            _error("Could not send HTTP request.");
        }

        closeHandles(2, hRequest, hHTTP);
</code>```

I read the file, what now? If I try to write it in a local file, it will stop at the first \0 delimiter, which is after 2 letters in my case. The file can be found at http://students.info.uaic.ro/~alexandru.antochi/exe_1.exe

答:
You must save the EXE file to a local file before you can execute it.  You can't execute an EXE from memory (without writing your own EXE loader, or using a 3rd party one).

InternetReadFile() reads arbitrary amounts of data, so you need to call it in a loop until the end of the response is reached. Write each block of data that is received as-is to your local file.  Your claim that your writing "will stop at the first \0 delimiter" means that you are writing the received data as null-terminated strings instead of as raw binary data.  Binary files, especially executable files, contain plenty of 0x00 bytes in them. So this is a logic bug in your code that you need to fix.

Try something more like this instead:

```<code>HINTERNET hInternet = InternetOpen(...);
if (!hInternet)
{
    _error("InternetOpen error.");
}

HINTERNET hHTTP = InternetConnect(hInternet, "students.info.uaic.ro", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (!hHTTP)
{
    InternetCloseHandle(hInternet);
    _error("InternetConnect error.");
}

const char* rgpszAcceptTypes[] = {"application/vnd.microsoft.portable-executable", "application/octet-stream", "application/x-msdownload", NULL};
HINTERNET hRequest = HttpOpenRequest(hHTTP, "GET", "/~alexandru.antochi/exe_1.exe", NULL, NULL, rgpszAcceptTypes, NULL, INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_AUTH);
if (!hRequest)
{
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HttpOpenRequest error.");
}

if (!HttpSendRequest(hRequest, NULL, NULL, NULL, NULL))
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("Could not send HTTP request.");
}

DWORD statusCode;
DWORD size = sizeof(statusCode), index = 0;
if (!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &size, &index))
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HttpQueryInfo error.");
}

if (statusCode != 200)
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HTTP request failed.");
}

HANDLE hFile = CreateFile("C:\\path to\\exe_1.exe" , GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("Could not create local file.");
}

BYTE buffer[1024];
DWORD bytesRead, bytesWritten;

do
{
    if (!InternetReadFile(hRequest, buffer, sizeof(buffer), &bytesRead))
    {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        InternetCloseHandle(hHTTP);
        InternetCloseHandle(hInternet);
        _error("Could not read HTTP response.");
    }

    if (bytesRead == 0)
        break;

    if (!WriteFile(hFile, buffer, bytesRead, &bytesWritten))
    {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        InternetCloseHandle(hHTTP);
        InternetCloseHandle(hInternet);
        _error("Could not write to local file.");
    }
}
while (true);

CloseHandle(hFile);
InternetCloseHandle(hRequest);
InternetCloseHandle(hHTTP);
InternetCloseHandle(hInternet);

// use EXE file as needed...
</code>```

Refer to MSDN documentation for more details:

HTTP Sessions

Downloading Resources from the WWW

Body:
I have a C app written using Winapi and an .exe file that I need to download and execute. My code so far is:

if (NULL == (hRequest = HttpOpenRequest(hHTTP, "GET", "/~alexandru.antochi/exe_1.exe", NULL, NULL, rgpszAcceptTypes, NULL, INTERNET_FLAG_NO_COOKIES || INTERNET_FLAG_NO_AUTH)))
        {
            _error("HttpOpenRequest error.");
        }

        if (HttpSendRequest(hRequest, NULL, NULL, NULL, NULL))
        {

            if (InternetReadFile(hRequest, &buffer, 65536, &bytesRead))
            {
                if (bytesRead == 65536)
                {
                    printf("Warning: .exe file too big. Ignoring");
                    continue;
                }
            }
        }
        else
        {
            _error("Could not send HTTP request.");
        }

        closeHandles(2, hRequest, hHTTP);

I read the file, what now? If I try to write it in a local file, it will stop at the first \0 delimiter, which is after 2 letters in my case. The file can be found at http://students.info.uaic.ro/~alexandru.antochi/exe_1.exe

Body:
You must save the EXE file to a local file before you can execute it.  You can't execute an EXE from memory (without writing your own EXE loader, or using a 3rd party one).

InternetReadFile() reads arbitrary amounts of data, so you need to call it in a loop until the end of the response is reached. Write each block of data that is received as-is to your local file.  Your claim that your writing "will stop at the first \0 delimiter" means that you are writing the received data as null-terminated strings instead of as raw binary data.  Binary files, especially executable files, contain plenty of 0x00 bytes in them. So this is a logic bug in your code that you need to fix.

Try something more like this instead:

HINTERNET hInternet = InternetOpen(...);
if (!hInternet)
{
    _error("InternetOpen error.");
}

HINTERNET hHTTP = InternetConnect(hInternet, "students.info.uaic.ro", INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (!hHTTP)
{
    InternetCloseHandle(hInternet);
    _error("InternetConnect error.");
}

const char* rgpszAcceptTypes[] = {"application/vnd.microsoft.portable-executable", "application/octet-stream", "application/x-msdownload", NULL};
HINTERNET hRequest = HttpOpenRequest(hHTTP, "GET", "/~alexandru.antochi/exe_1.exe", NULL, NULL, rgpszAcceptTypes, NULL, INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_NO_AUTH);
if (!hRequest)
{
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HttpOpenRequest error.");
}

if (!HttpSendRequest(hRequest, NULL, NULL, NULL, NULL))
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("Could not send HTTP request.");
}

DWORD statusCode;
DWORD size = sizeof(statusCode), index = 0;
if (!HttpQueryInfo(hRequest, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &statusCode, &size, &index))
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HttpQueryInfo error.");
}

if (statusCode != 200)
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("HTTP request failed.");
}

HANDLE hFile = CreateFile("C:\\path to\\exe_1.exe" , GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, 0, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
    InternetCloseHandle(hRequest);
    InternetCloseHandle(hHTTP);
    InternetCloseHandle(hInternet);
    _error("Could not create local file.");
}

BYTE buffer[1024];
DWORD bytesRead, bytesWritten;

do
{
    if (!InternetReadFile(hRequest, buffer, sizeof(buffer), &bytesRead))
    {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        InternetCloseHandle(hHTTP);
        InternetCloseHandle(hInternet);
        _error("Could not read HTTP response.");
    }

    if (bytesRead == 0)
        break;

    if (!WriteFile(hFile, buffer, bytesRead, &bytesWritten))
    {
        CloseHandle(hFile);
        InternetCloseHandle(hRequest);
        InternetCloseHandle(hHTTP);
        InternetCloseHandle(hInternet);
        _error("Could not write to local file.");
    }
}
while (true);

CloseHandle(hFile);
InternetCloseHandle(hRequest);
InternetCloseHandle(hHTTP);
InternetCloseHandle(hInternet);

// use EXE file as needed...

Refer to MSDN documentation for more details:

HTTP Sessions

Downloading Resources from the WWW


问:
Mounting Virtual Directory, or Running Code in Memory for python 3
I'm making a program that generates code randomly in batches, and given an input, tests to see if that code generates the desired output. I'm wanting to make the batches of generated code pretty large, say 10,000 randomly generated files per batch, so I want to work within memory instead of messing with writing them to the disk. I also want the compiler to do all the work for me, where the file, once created, is imported as a module, and then generated function in that module is run, and the result is tested against the desired output.

I found that Python has tempfile.SpooledTemporaryFile(), which will allow me to create and manipulate a file-like object, but once created, I want to access it as if it were a python script. However, since the file is in RAM, and is deleted once closed, I'm struggling to find a way to do this. What I'm wanting is something like this:

```<code>import os, tempfile, importlib, desiredInAndOut, codeGenerator
generatedCodeAsAString = codeGenerator.generateCode()
cwd = os.getcwd()
successfulCode = []
batchSize = int(input(Enter desired batch size:))
runs = 0
while runs < batchSize:
    with tempfile.SpooledTemporaryFile(10240, 'w+b', None, None, '\n', '.py', 'tmp', cwd) as stf:
        stf.write(generatedCodeAsAsAString.encode())
        import tmp #import the newly generated file (that maybe has a 'shortcut' in the cwd? Somehow?)
        importlib.invalidate_caches() #make sure the compiler knows that there is a new module for the first time this runs
        importlib.reload(tmp) #if the compiler gets smart and re-uses the module from the first import/first iteration of this loop, make sure it reloads/updates it to match the new file that was just created
        out = tmp.generatedFunction(desiredInAndOut.GIVEN_INPUT)
        if out == desiredInAndOut.DESIRED_OUTPUT:
            successfulCode.append(generatedCodeAsAString+'\n'+'#BATCHFILE NO '+str(runs))
        runs += 1
print(successfulCode)
</code>```

Despite my efforts, the tmp file is in no way linked to the current working directory, so the import above won't work. I need to find a way to feed the memory address of that temporary file to the import statement where it would expect a standard '/foo/bar/tmp.py', and make sure it interprets it as a file.

Mounting a virtual drive directly on the computer is not an option because of permission difficulties. If you know of an in-python way to do something like that without admin access to the computer, I'm all ears. I'm currently exploring the functionality of the built-in function exec - not sure how it will respond outside of the shell. I'm hoping it will work, but we'll see.

Is there a correct/better way to do what I'm trying? More specifically, is there a way to point the compiler in the direction of the file existing in the memory so it can be manipulated as if it were an existing file and/or run? Or a python formatted string, it doesn't necessarily need to be a file if I can run it in string form.

答:
https://stackoverflow.com/a/2849077/6047611 (If manipulating as SpooledTemporaryFile)

AND

https://stackoverflow.com/a/3906309/6047611

Provided me with the information necessary to make this solution using the built-in exec() function:

```<code>import sys
from io import StringIO

def main():
    GIVEN_INPUT = input('Enter input as an integer:')
    code = "def main():\n\tinput = "+GIVEN_INPUT+"\n\tprint(input + 3)\nmain()"
    #this code would be randomly generated elsewhere. As is, simply adds 3 to GIVEN_INPUT

    old_stdout = sys.stdout
    redirected_output = StringIO()
    sys.stdout = redirected_output

    exec(code)#, sys._getframe(1).f_globals, sys._getframe(1).f_locals)

    sys.stdout = old_stdout

    print('function completed')
    OUTPUT = redirected_output.getvalue().strip()
    print(OUTPUT+' is the result of:\n'+ code)

main()
</code>```

In summary, exec() can't return a value that I could see, but it can print to sys.stdout, so instead of 'returning' an outcome, it prints an outcome, and I'm able to get what it prints by switching out sys.stdout for a new StringIO while the generated code runs, switching it back to normal once it's finished, and then getting the contents of that StringIO object. If it needed to be in file form, that could easily be done with tempfile.SpooledTemporaryFile, see my first link above, but I'm already generating the code as a string so I have no need to convert it into file form first to run it. I'm hoping exec() doesn't have a max characters limit, that could cause significant problems...

No import statements needed to open/run the generated code, and can be run many times without messing with a mounted virtual directory, or even file objects in general.

Body:
I'm making a program that generates code randomly in batches, and given an input, tests to see if that code generates the desired output. I'm wanting to make the batches of generated code pretty large, say 10,000 randomly generated files per batch, so I want to work within memory instead of messing with writing them to the disk. I also want the compiler to do all the work for me, where the file, once created, is imported as a module, and then generated function in that module is run, and the result is tested against the desired output.

I found that Python has tempfile.SpooledTemporaryFile(), which will allow me to create and manipulate a file-like object, but once created, I want to access it as if it were a python script. However, since the file is in RAM, and is deleted once closed, I'm struggling to find a way to do this. What I'm wanting is something like this:

import os, tempfile, importlib, desiredInAndOut, codeGenerator
generatedCodeAsAString = codeGenerator.generateCode()
cwd = os.getcwd()
successfulCode = []
batchSize = int(input(Enter desired batch size:))
runs = 0
while runs < batchSize:
    with tempfile.SpooledTemporaryFile(10240, 'w+b', None, None, '\n', '.py', 'tmp', cwd) as stf:
        stf.write(generatedCodeAsAsAString.encode())
        import tmp #import the newly generated file (that maybe has a 'shortcut' in the cwd? Somehow?)
        importlib.invalidate_caches() #make sure the compiler knows that there is a new module for the first time this runs
        importlib.reload(tmp) #if the compiler gets smart and re-uses the module from the first import/first iteration of this loop, make sure it reloads/updates it to match the new file that was just created
        out = tmp.generatedFunction(desiredInAndOut.GIVEN_INPUT)
        if out == desiredInAndOut.DESIRED_OUTPUT:
            successfulCode.append(generatedCodeAsAString+'\n'+'#BATCHFILE NO '+str(runs))
        runs += 1
print(successfulCode)

Despite my efforts, the tmp file is in no way linked to the current working directory, so the import above won't work. I need to find a way to feed the memory address of that temporary file to the import statement where it would expect a standard '/foo/bar/tmp.py', and make sure it interprets it as a file.

Mounting a virtual drive directly on the computer is not an option because of permission difficulties. If you know of an in-python way to do something like that without admin access to the computer, I'm all ears. I'm currently exploring the functionality of the built-in function exec - not sure how it will respond outside of the shell. I'm hoping it will work, but we'll see.

Is there a correct/better way to do what I'm trying? More specifically, is there a way to point the compiler in the direction of the file existing in the memory so it can be manipulated as if it were an existing file and/or run? Or a python formatted string, it doesn't necessarily need to be a file if I can run it in string form.

Body:
https://stackoverflow.com/a/2849077/6047611 (If manipulating as SpooledTemporaryFile)

AND

https://stackoverflow.com/a/3906309/6047611

Provided me with the information necessary to make this solution using the built-in exec() function:

import sys
from io import StringIO

def main():
    GIVEN_INPUT = input('Enter input as an integer:')
    code = "def main():\n\tinput = "+GIVEN_INPUT+"\n\tprint(input + 3)\nmain()"
    #this code would be randomly generated elsewhere. As is, simply adds 3 to GIVEN_INPUT

    old_stdout = sys.stdout
    redirected_output = StringIO()
    sys.stdout = redirected_output

    exec(code)#, sys._getframe(1).f_globals, sys._getframe(1).f_locals)

    sys.stdout = old_stdout

    print('function completed')
    OUTPUT = redirected_output.getvalue().strip()
    print(OUTPUT+' is the result of:\n'+ code)

main()

In summary, exec() can't return a value that I could see, but it can print to sys.stdout, so instead of 'returning' an outcome, it prints an outcome, and I'm able to get what it prints by switching out sys.stdout for a new StringIO while the generated code runs, switching it back to normal once it's finished, and then getting the contents of that StringIO object. If it needed to be in file form, that could easily be done with tempfile.SpooledTemporaryFile, see my first link above, but I'm already generating the code as a string so I have no need to convert it into file form first to run it. I'm hoping exec() doesn't have a max characters limit, that could cause significant problems...

No import statements needed to open/run the generated code, and can be run many times without messing with a mounted virtual directory, or even file objects in general.


问:
Mysql slow with multiple queries at same time
I have a large mysql table (1 million rows) that if my users hit at the same time will make lots of queries at around the same time (say 300 queries over span of 5 seconds), and it brings my site to a halt (takes like 22 seconds to execute all of the queries).

Is this normal, what can I do?

I tried with smaller table, and it works fine, but on larger table its brutal.

Any ideas?

I tried on both php and node and its not that, its my db.
Thanks

This is what EXPLAIN on the table says:
Current selection does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available.
Field   Type    Null    Key Default Extra
id      int(11) NO  PRI NULL    auto_increment
game_id int(11) NO      NULL

user_id int(11) NO      NULL

question_id varchar(10) NO

answer  text    YES     NULL

distanceAway    int(11) YES     NULL

points  int(11) YES     NULL

questionNum int(11) NO      NULL

lat float   YES     NULL

longg   float   YES     NULL

color   varchar(6)  NO      NULL

submitTime  timestamp   NO      CURRENT_TIMESTAMP

avg float   NO      NULL

答: Add a PK column and index all the columns where parameters are passing in queries. Index with unique or normal as applicable. </p>


问:
How to detect when EF Core must do some of the IQueryable operations in memory
I've been going through my application, and there are times where only part of the IQueryable is actually translated into a SQL query and the rest of the work is done in-memory.

I understand that there's no way for the EF team to account for every possible expression that a developer may come up with and magically translate that into a useable SQL query, but IIRC, EF would throw an exception if it was unable to translate ALL of the operations defined in an IQueryable to SQL.

Is there a way to have EF Core also throw an exception, or at the very least, raise an event when it's unable to fully translate an IQueryable into SQL?

答:
Is there a way to have EF Core also throw an exception, or at the very least, raise an event when it's unable to fully translate an IQueryable into SQL?

Sure. First, this is a EF Core concept called client evaluation which didn't exist in pre EF Core (EF6.x). It's covered by the Client vs. Server Evaluation documentation topic, and Disabling client evaluation section explains the default behavior and how it can be changed:

By default, EF Core will log a warning when client evaluation is performed. See Logging for more information on viewing logging output. You can change the behavior when client evaluation occurs to either throw or do nothing. This is done when setting up the options for your context - typically in DbContext.OnConfiguring, or in Startup.cs if you are using ASP.NET Core.

The later is achieved by using ConfigureWarnings method of DbContextOptionsBuilder class for RelationalEventId.QueryClientEvaluationWarning. Valid actions are Log (default), Ignore and Throw (desired):

```<code>protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // ...
    optionsBuilder.ConfigureWarnings(warnings =>
        warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}
</code>```

Body:
Is there a way to have EF Core also throw an exception, or at the very least, raise an event when it's unable to fully translate an IQueryable into SQL?

Sure. First, this is a EF Core concept called client evaluation which didn't exist in pre EF Core (EF6.x). It's covered by the Client vs. Server Evaluation documentation topic, and Disabling client evaluation section explains the default behavior and how it can be changed:

By default, EF Core will log a warning when client evaluation is performed. See Logging for more information on viewing logging output. You can change the behavior when client evaluation occurs to either throw or do nothing. This is done when setting up the options for your context - typically in DbContext.OnConfiguring, or in Startup.cs if you are using ASP.NET Core.

The later is achieved by using ConfigureWarnings method of DbContextOptionsBuilder class for RelationalEventId.QueryClientEvaluationWarning. Valid actions are Log (default), Ignore and Throw (desired):

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    // ...
    optionsBuilder.ConfigureWarnings(warnings =>
        warnings.Throw(RelationalEventId.QueryClientEvaluationWarning));
}


问:
Accessing member functions in templated container
I want to be able to << val.first() and val.second() element in
struct Data<std::pair<F, S>. F, S should be generic in the sense that they can be anything specified like struct Data<int> (specific type). I don't know how to write the template for struct Data<std::pair<F, S> in a way that allows it to only take struct Data as F or S.

```<code>#include <fstream>
#include <iostream>
#include <sstream>
#include <utility>

template <typename T>
struct Data;

template <typename T>
std::ostream& operator<<(std::ostream& os, const Data<T>& val) {
    return val(os);
}

template <typename T>
Data<std::remove_cv_t<T>> data(const T& val) { return { val }; }

template <>
struct Data<int> {
    std::ostream& operator()(std::ostream& os) const {
        os << val;
        return os;
    }
    const int& val;
};

//More struct Data for templatized types for other specific types

template <typename F, typename S>
struct Data<std::pair<F, S> > {
    std::ostream& operator()(std::ostream& os) const {
        os << data(val.first()) << data(val.second());
        return os;
    }
    std::pair<F, S> val;
};

//More struct Data templatized for other container types
</code>```

The error when tested is:

```<code> error: called object type 'int' is not a function or function pointer
                    os << data(val.first()) << data(val.second());
                               ^~~~~~~~~
</code>```

答:
first and second are two (public) member variables of std::pair, they are not member functions.

```<code>os << data(val.first()) << data(val.second());
</code>```

becomes

```<code>os << data(val.first) << data(val.second);
</code>```

Body:
I want to be able to << val.first() and val.second() element in
struct Data<std::pair<F, S>. F, S should be generic in the sense that they can be anything specified like struct Data<int> (specific type). I don't know how to write the template for struct Data<std::pair<F, S> in a way that allows it to only take struct Data as F or S.

#include <fstream>
#include <iostream>
#include <sstream>
#include <utility>

template <typename T>
struct Data;

template <typename T>
std::ostream& operator<<(std::ostream& os, const Data<T>& val) {
    return val(os);
}

template <typename T>
Data<std::remove_cv_t<T>> data(const T& val) { return { val }; }

template <>
struct Data<int> {
    std::ostream& operator()(std::ostream& os) const {
        os << val;
        return os;
    }
    const int& val;
};

//More struct Data for templatized types for other specific types

template <typename F, typename S>
struct Data<std::pair<F, S> > {
    std::ostream& operator()(std::ostream& os) const {
        os << data(val.first()) << data(val.second());
        return os;
    }
    std::pair<F, S> val;
};

//More struct Data templatized for other container types

The error when tested is:

 error: called object type 'int' is not a function or function pointer
                    os << data(val.first()) << data(val.second());
                               ^~~~~~~~~

Body:
first and second are two (public) member variables of std::pair, they are not member functions.

os << data(val.first()) << data(val.second());

becomes

os << data(val.first) << data(val.second);


问:
remove value from string
If I have a string with IDs

```<code>$myIDs = '22,34,445,67889,23';
</code>```

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

```<code>$removeID = '445';
</code>```

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

```<code>preg_replace($removeID, '', $myIDs);
</code>```

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

```<code>$myIDs = '2312,23,234234';
</code>```

and ID to remove

```<code>$removeID = '23';
</code>```

There's too many potential matches...

答:
I'm going to throw in a solution as well:

```<code>preg_replace( '/\b(,' . $rID . '|' . $rID . ',|' . $rID . ')\b/', '', $myIDs );
</code>```

i.e.

```<code>preg_replace( '/\b(,445|445,|445)\b/', '', $myIDs );
</code>```

(example)

Title: remove value from string

Body:
If I have a string with IDs

$myIDs = '22,34,445,67889,23';

and I am given a value, how do I remove it from the string, assuming I know for sure it is in the string?

$removeID = '445';

Do I user preg_replace or is there a better method? For example, if it is in the middle of the string and I remove just a value, I'll end up with two commas and then I need to replace those with a single comma?

preg_replace($removeID, '', $myIDs);

UPDATE: These are all great suggestions. However, I just thought about one potential issue. This probably need to be handled as an array instead of regex. What is my string looks like this

$myIDs = '2312,23,234234';

and ID to remove

$removeID = '23';

There's too many potential matches...

Body:
I'm going to throw in a solution as well:

preg_replace( '/\b(,' . $rID . '|' . $rID . ',|' . $rID . ')\b/', '', $myIDs );

i.e.

preg_replace( '/\b(,445|445,|445)\b/', '', $myIDs );

(example)


问:
MPI broadcast array of strings
is it possible to broadcast array of strings defined as

```<code>char **lines;
lines = malloc(512 * sizeof(char*));
</code>```

I have tried

```<code>MPI_Bcast(lines, linesCount, MPI_BYTE, 0, MPI_COMM_WORLD);
</code>```

and

```<code>MPI_Bcast(lines, linesCount, MPI_CHAR, 0, MPI_COMM_WORLD);
</code>```

where linesCount is number of strings in array.

How can it be achieved?

答:
Assuming the strings that you store in the lines array may have a varying size, you can first broadcast an int array of sizes of each string and then broadcast each string separately,

```<code>/* Create an Array with length of each line
   Broadcast it from process 0 */
int lin_siz[linesCount];
if (p_rank == 0)
    for (i=0; i < linesCount; i++)
        lin_siz[i] = strlen(lines[i])+1;
MPI_Bcast(&lin_siz, linesCount, MPI_INT, 0, MPI_COMM_WORLD);

/* Broadcast each line */
for (i=0; i < linesCount; i++)
    MPI_Bcast(&lines[i], lin_siz[i], MPI_CHAR, 0, MPI_COMM_WORLD);
</code>```

MPI_Bcast can broadcast only elements that are contiguous in memory - in this case the int array with sizes, lin_siz and each line stored in lines. This may not be a very elegant solution and better is surely possible but it works.

It was tested with the following array

```<code>char **lines;
lines = malloc(linesCount * sizeof(char*));

if (p_rank == 0){
    for (i=0; i<linesCount-2; i++)
        lines[i] = "This is a test.";
    lines[i++] = "More testing.";
    lines[i++] = "Even more..";
}
</code>```

with p_rank being a standard processor rank obtained with     MPI_Comm_rank(MPI_COMM_WORLD, &p_rank). And successfully printed at the end as

```<code>/* Print */
printf("Process rank %d:\n", p_rank);
for (i=0; i < linesCount; i++)
     printf("%s\n", lines[i]);
</code>```

I can post the entire test case if you have issues implementing my answer.

Title: MPI broadcast array of strings

Body:
is it possible to broadcast array of strings defined as

char **lines;
lines = malloc(512 * sizeof(char*));

I have tried

MPI_Bcast(lines, linesCount, MPI_BYTE, 0, MPI_COMM_WORLD);

and

MPI_Bcast(lines, linesCount, MPI_CHAR, 0, MPI_COMM_WORLD);

where linesCount is number of strings in array.

How can it be achieved?

Body:
Assuming the strings that you store in the lines array may have a varying size, you can first broadcast an int array of sizes of each string and then broadcast each string separately,

/* Create an Array with length of each line
   Broadcast it from process 0 */
int lin_siz[linesCount];
if (p_rank == 0)
    for (i=0; i < linesCount; i++)
        lin_siz[i] = strlen(lines[i])+1;
MPI_Bcast(&lin_siz, linesCount, MPI_INT, 0, MPI_COMM_WORLD);

/* Broadcast each line */
for (i=0; i < linesCount; i++)
    MPI_Bcast(&lines[i], lin_siz[i], MPI_CHAR, 0, MPI_COMM_WORLD);

MPI_Bcast can broadcast only elements that are contiguous in memory - in this case the int array with sizes, lin_siz and each line stored in lines. This may not be a very elegant solution and better is surely possible but it works.

It was tested with the following array

char **lines;
lines = malloc(linesCount * sizeof(char*));

if (p_rank == 0){
    for (i=0; i<linesCount-2; i++)
        lines[i] = "This is a test.";
    lines[i++] = "More testing.";
    lines[i++] = "Even more..";
}

with p_rank being a standard processor rank obtained with     MPI_Comm_rank(MPI_COMM_WORLD, &p_rank). And successfully printed at the end as

/* Print */
printf("Process rank %d:\n", p_rank);
for (i=0; i < linesCount; i++)
     printf("%s\n", lines[i]);

I can post the entire test case if you have issues implementing my answer.


问:
Batch resize images and output images to new folder with ImageMagick
Current image folder path:

```<code>public_html/images/thumbs
</code>```

Output image folder path:

```<code>public_html/images/new-thumbs
</code>```

I have 10 video thumbs per video in current folder, named of image thumbs:

```<code>1-1.jpg
1-2.jpg
1-3.jpg
1-4.jpg
1-5.jpg (Resize)
1-6.jpg
1-7.jpg
1-8.jpg
1-9.jpg
1-10.jpg

2-1.jpg
2-2.jpg
2-3.jpg
2-4.jpg
2-5.jpg (Resize)
2-6.jpg
2-7.jpg
2-8.jpg
2-9.jpg
2-10.jpg
</code>```

I want to resize all 5th images(*-5.jpg) to the new folder. I've tried below command but no luck:

```<code>mogrify
-path
  public_html/images/thumbs/*-5.jpg
-resize 16×12
-quality 100
  public_html/images/new-thumbs/*-5.jpg
</code>```

答:
In ImageMagick 7 versions its built into the magick ...so..

```<code>magick mogrify -resize 16x12 -quality 100 -path ../new-thumbs *.jpg
</code>```

Make sure that the folder you specify in path exists. It will not be created by ImageMagick.

Find more information here https://www.imagemagick.org/script/mogrify.php

Body:
Current image folder path:

public_html/images/thumbs

Output image folder path:

public_html/images/new-thumbs

I have 10 video thumbs per video in current folder, named of image thumbs:

1-1.jpg
1-2.jpg
1-3.jpg
1-4.jpg
1-5.jpg (Resize)
1-6.jpg
1-7.jpg
1-8.jpg
1-9.jpg
1-10.jpg

2-1.jpg
2-2.jpg
2-3.jpg
2-4.jpg
2-5.jpg (Resize)
2-6.jpg
2-7.jpg
2-8.jpg
2-9.jpg
2-10.jpg

I want to resize all 5th images(*-5.jpg) to the new folder. I've tried below command but no luck:

mogrify
-path
  public_html/images/thumbs/*-5.jpg
-resize 16×12
-quality 100
  public_html/images/new-thumbs/*-5.jpg

Body:
In ImageMagick 7 versions its built into the magick ...so..

magick mogrify -resize 16x12 -quality 100 -path ../new-thumbs *.jpg

Make sure that the folder you specify in path exists. It will not be created by ImageMagick.

Find more information here https://www.imagemagick.org/script/mogrify.php

ContentLicense: CC BY-SA 4.0


问:
EZBounce Make error
I am trying to install ezbounce on an SSH Shell. (Host has OK'ed use of the bouncer)
(I do NOT have sudo, however, my host is lenient and I can get things ran. If possible, I prefer a solution that does NOT require sudo or equivalent.)

I have finished ./configure , and am on the make step.

when I go to make the file, it errors with the following:
https://pastebin.com/YetM6nGN

I found a possible solution to the problem here:
https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=219298
The solution seems to be centered on the fact that GCC++/GNU make calls its latest version as opposed to the newer one.

They have an included patch, but I am honestly clueless how this gets applied.

Any help fixing the error via here or directly editing the makefile is greatly appreciated.

My makefile: https://www.dropbox.com/s/u75toiigd4v5wgl/Makefile?dl=0

答:
So I had some help from an external source (Thank you discord communities!)

The patch listed above is for FreeBSD ONLY! (As I was made aware)

For Non-FreeBSD Ports, the fix (if your makefile looks like mine) is to edit line 32 to the following: CXX_OPTIMIZATIONS = -std=gnu++98 -O2

There is some error looking items in console that follows, but the build is successful, so I'm gonna assume they are moot.

It honestly was a confusing little puzzle for your average user, but there ya go :)

Title: EZBounce Make error


问:
Trouble inserting into a sql table from a form
The expect result is for the data that is submitted through a HTML form, and then the form action is this code below. Proccessing the code below I was expecting it to insert the data from the form into a SQL table called customers. However the data is not being inserted and there is no errors showing on the page.

```<code><?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$uName = $_POST['uname'];
$password = sha1($_POST['upassword']);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$dob = $_POST['dob'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$postcode = $_POST['postcode'];

echo $uName;
echo $password;

include("dbconn.php");
$sql = "INSERT INTO customers (username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES ('$uName', '$password', '$fname', '$lname', '$dob', '$address1', '$address2', '$postcode')";

mysqli_query($conn, $sql);
mysqli_close($conn);

?>
</code>```

This is the form in which the data is from:

```<code><div id = "reg_form">
    <form name="register" action="register_customer.php" method="post">
        <p id = "form_text"> Username: </p> <input name="uname" type="text" placeholder="Please enter a user name">
        <p id = "form_text"> Password: </p> <input name="upassword" type="password" placeholder="Please enter a password"><br>
        <p id = "form_text"> First Name: </p> <input name="fname" type="text" placeholder="Please enter your first name"><br>
        <p id = "form_text"> Last Name: </p> <input name="lname" type="text" placeholder="Please enter your last name"><br>
        <p id = "form_text"> Date of Birth: </p> <input name="dob" type="text" placeholder="Please enter your date of birth"><br>
        <p id = "form_text"> Address 1: </p> <input name="address1" type="text" placeholder="Please enter first line of address"><br>
        <p id = "form_text"> Address 2: </p> <input name="address2" type="text" placeholder="Please enter second line of address"><br>
        <p id = "form_text"> Postcode: </p> <input name="postcode" type="text" placeholder="Please enter your postcode"><br>
        <input name="submit" type="submit">
    </form>
</div>
</code>```

This is the dbconn.php:

```<code><?php
$config = parse_ini_file('config.ini');
$conn = mysqli_connect('localhost',$config['username'],
    $config['password'],$config['dbname']);
    echo "Connected to the database";
?>
</code>```

答:
you have to use MySqli Prepared Statements for Inserting the query to make it more secure like below:

```<code>// prepare and bind Customers Query
$queryCustomers = $conn->prepare("INSERT INTO customers(username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$queryCustomers->bind_param("ssssssss",$uName,$password,$fname,$lname,$dob,$address1,$address2,$postcode);

// execute Customers Query
$queryCustomers->execute();

// Close Connections
$queryCustomers->close();
</code>```

To learn more, follow http://php.net/manual/en/mysqli.quickstart.prepared-statements.php

Body:
The expect result is for the data that is submitted through a HTML form, and then the form action is this code below. Proccessing the code below I was expecting it to insert the data from the form into a SQL table called customers. However the data is not being inserted and there is no errors showing on the page.

<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

$uName = $_POST['uname'];
$password = sha1($_POST['upassword']);
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$dob = $_POST['dob'];
$address1 = $_POST['address1'];
$address2 = $_POST['address2'];
$postcode = $_POST['postcode'];

echo $uName;
echo $password;

include("dbconn.php");
$sql = "INSERT INTO customers (username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES ('$uName', '$password', '$fname', '$lname', '$dob', '$address1', '$address2', '$postcode')";

mysqli_query($conn, $sql);
mysqli_close($conn);

?>

This is the form in which the data is from:

    <form name="register" action="register_customer.php" method="post">

 Username:
 <input name="uname" type="text" placeholder="Please enter a user name">

 Password:
 <input name="upassword" type="password" placeholder="Please enter a password">

 First Name:
 <input name="fname" type="text" placeholder="Please enter your first name">

 Last Name:
 <input name="lname" type="text" placeholder="Please enter your last name">

 Date of Birth:
 <input name="dob" type="text" placeholder="Please enter your date of birth">

 Address 1:
 <input name="address1" type="text" placeholder="Please enter first line of address">

 Address 2:
 <input name="address2" type="text" placeholder="Please enter second line of address">

 Postcode:
 <input name="postcode" type="text" placeholder="Please enter your postcode">

        <input name="submit" type="submit">
    </form>

This is the dbconn.php:

<?php
$config = parse_ini_file('config.ini');
$conn = mysqli_connect('localhost',$config['username'],
    $config['password'],$config['dbname']);
    echo "Connected to the database";
?>

Body:
you have to use MySqli Prepared Statements for Inserting the query to make it more secure like below:

// prepare and bind Customers Query
$queryCustomers = $conn->prepare("INSERT INTO customers(username, password_hash, customer_foremane, customer_surname, date_of_birth, customer_address1, customer_address2, customer_postcode) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$queryCustomers->bind_param("ssssssss",$uName,$password,$fname,$lname,$dob,$address1,$address2,$postcode);

// execute Customers Query
$queryCustomers->execute();

// Close Connections
$queryCustomers->close();

To learn more, follow http://php.net/manual/en/mysqli.quickstart.prepared-statements.php


问:
getenv() returning environment as null?
I am trying to print the executables in the current directory in c and bash with the following code:

```<code>system("EXEC_PATH=$(find . -maxdepth 1 -type f -executable)");
printf("executables are: %s\n", getenv("EXEC_PATH"));
</code>```

However, when I compile and run the c code, the result I get is:

```<code>executables are: (null)
</code>```

Any help will be appreciated!

答:
I tried Ahmed Masud's solution with popen and fgets and got a working solution:</p>

```<code>    char buff[BUFSIZ];
    char elf_arr
    FILE *fp = popen("find . -maxdepth 1 -type f -executable","r");
    while (fgets( buff, BUFSIZ, fp ) != NULL ) {
            printf("executables are: %s\n", buff);
    }
    pclose(fp);
</code>```

Title: getenv() returning environment as null?

Body:
I am trying to print the executables in the current directory in c and bash with the following code:

system("EXEC_PATH=$(find . -maxdepth 1 -type f -executable)");
printf("executables are: %s\n", getenv("EXEC_PATH"));

However, when I compile and run the c code, the result I get is:

executables are: (null)

Any help will be appreciated!

Body:
I tried Ahmed Masud's solution with popen and fgets and got a working solution:

    char buff[BUFSIZ];
    char elf_arr
    FILE *fp = popen("find . -maxdepth 1 -type f -executable","r");
    while (fgets( buff, BUFSIZ, fp ) != NULL ) {
            printf("executables are: %s\n", buff);
    }
    pclose(fp);


问:
matlab command obtain best fit of form $y(t)=a_1+a_2*t+a_3*sin(t) $
Is there a matlab command obtain best fit of form y(t)=a_1+a_2*t+a_3*sin(t) ???

Cannot find a command because of the sine function

thank you!!

答:
In this case, you could use fittype command.

Here is the code might help:

```<code>%sample data
x=[1;2;3;4;5];y=3+4*x+5*sin(x)+rand(5,1)*0.01;

%curve-fitting
p=fittype('a_1+a_2*t+a_3*sin(t)','independent','t')
f=fit(x,y,p)

%plot
plot(f,x,y);
</code>```

It will return f like this: (there could be little different because of random data, but the answer is correct [3,4,5])

f =

```<code> General model:
 f(t) = a_1+a_2*t+a_3*sin(t)
 Coefficients (with 95% confidence bounds):
   a_1 =       2.996  (2.95, 3.043)
   a_2 =       4.002  (3.987, 4.017)
   a_3 =       5.005  (4.978, 5.032)
</code>```

Body:
In this case, you could use fittype command.

Here is the code might help:

%sample data
x=[1;2;3;4;5];y=3+4*x+5*sin(x)+rand(5,1)*0.01;

%curve-fitting
p=fittype('a_1+a_2*t+a_3*sin(t)','independent','t')
f=fit(x,y,p)

%plot
plot(f,x,y);

It will return f like this: (there could be little different because of random data, but the answer is correct [3,4,5])

f =

 General model:
 f(t) = a_1+a_2*t+a_3*sin(t)
 Coefficients (with 95% confidence bounds):
   a_1 =       2.996  (2.95, 3.043)
   a_2 =       4.002  (3.987, 4.017)
   a_3 =       5.005  (4.978, 5.032)


问:
Vim whole word search - but faster
I know that to search for a whole word in vim you need to type:

```<code>/\<word\><CR>
</code>```

Now, what I would like to do is to map this behaviour to ? (as I never search backwards, and if needed I could search forward and then NN). I.e. I'd like to type:

```<code>?word<CR>
</code>```

and have the same result as above (vim searches the whole word). I've been fiddling around with vim commands and mappings for some weeks now, but I'm not sure about how to accomplish this one. Thank you for any help.

Update: (insead of ? I use \ now).

答:
You can search for words under the cursor using * and # (forwards and back). g* and g# will do the same but finding words containing what's under your cursor initially.

Obviously (!) you need to have found the first instance already for this to work, but it's very effective for successive searches.

Title: Vim whole word search - but faster

Body:
I know that to search for a whole word in vim you need to type:

/\<word\><CR>

Now, what I would like to do is to map this behaviour to ? (as I never search backwards, and if needed I could search forward and then NN). I.e. I'd like to type:

?word<CR>

and have the same result as above (vim searches the whole word). I've been fiddling around with vim commands and mappings for some weeks now, but I'm not sure about how to accomplish this one. Thank you for any help.

Update: (insead of ? I use \ now).


问:
adding two dictionaries of ints
I think I have the right idea of solving this function, but it's not getting the desired result shown in the docstring i test it. Can anyone please help me fix this?</p>

```<code>def add_dicts(d1, d2):
'''(dict, dict) -> dict
Parameters d1 and d2 are dicts where each key is an int and each value is an
int. Return dict d1 with the contents of d2 added to d1. More concisely, if
key k is in d1 and in d2, update d1[k] to be the sum of d1[k] and d2[k]. If
d2 has a key that is not in d1, add the key value pair from d2 to d1.
>>> d1 = {1:1, 2:1, 3:2}
>>> d2 = {1:3, 3:1, 4:1}
>>> d = add_dicts(d1, d2)
>>> d == {1:4, 2:1, 3:3, 4:1}
True
'''
for (key, value) in d1.items():
    if key in d1 and key in d2:
        d1[key] = d1[key] + d2[key]
        if key in d2 and key not in d1:
            d1[key] = {key: value}
return d1
</code>```

答:
Instead of iterating over d1's items, iterate over d2:

```<code>for a, b in d2.items():
   if a in d1:
      d1[a] += b
   else:
      d1[a] = b
</code>```

Title: adding two dictionaries of ints

Body:
I think I have the right idea of solving this function, but it's not getting the desired result shown in the docstring i test it. Can anyone please help me fix this?

def add_dicts(d1, d2):
'''(dict, dict) -> dict
Parameters d1 and d2 are dicts where each key is an int and each value is an
int. Return dict d1 with the contents of d2 added to d1. More concisely, if
key k is in d1 and in d2, update d1[k] to be the sum of d1[k] and d2[k]. If
d2 has a key that is not in d1, add the key value pair from d2 to d1.
>>> d1 = {1:1, 2:1, 3:2}
>>> d2 = {1:3, 3:1, 4:1}
>>> d = add_dicts(d1, d2)
>>> d == {1:4, 2:1, 3:3, 4:1}
True
'''
for (key, value) in d1.items():
    if key in d1 and key in d2:
        d1[key] = d1[key] + d2[key]
        if key in d2 and key not in d1:
            d1[key] = {key: value}
return d1

Body:
Instead of iterating over d1's items, iterate over d2:

for a, b in d2.items():
   if a in d1:
      d1[a] += b
   else:
      d1[a] = b


问:
Ionic3 framework network.onConnect().subscribe not working?
I have created a little phone app with Ionic. I am trying to implement a bit logic where the component knows when its online or offline. To do so I am using the network plugin fom Ionic and it just does not work as expected.

instead of updating the

```<code>this.connected
</code>```

value every time when I switch on / off the network, it will only do so if I switch it off / on AND do something like switching from landscape to portrait mode, or work on a different app for a while and come back to the app.

Really puzzled by that.

Here is the code:

```<code>import {Component} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '@ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "@ionic-native/network";

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: [SurveyService, Network]
})
export class HomePage {
    public surveys: Survey[] = [];
    public connected;
    public networkType;

    constructor(public navCtrl: NavController,
                private googlePlus: GooglePlus,
                private surveyService: SurveyService,
                public navParams: NavParams,
                platform: Platform,
                private network: Network) {

        this.checkForNetwork();
        this.surveyService.getAvailable().subscribe(surveys => {
            this.checkForNetwork();
            this.surveys = surveys;
        })
    }

    login() {

        this.googlePlus.login({
            'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
        }).then((res) => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });

    }

    logout() {

        this.googlePlus.logout().then(() => {
            console.log("logged out");
        });

    }

    openSurvey = (survey: Survey) => {

        this.navCtrl.push(SurveyPage, {
            survey: survey
        });

    }

    checkForNetwork = () => {
        this.networkType= this.network.type;
        this.network.onDisconnect().subscribe(() => {
            this.connected = false;
            this.network.type = null;
        });
        this.network.onConnect().subscribe(() => {
            this.connected = 'network connected!';
            setTimeout(() => {
                if (this.network.type === 'wifi') {
                    this.connected = true;
                }
            }, 3000);
        });
    }
}
</code>```

答:
OK, I worked it out:

Turns out that ionic works perfectly fine, but I tried to change the view of my application depending on whether

```<code>this.connected
</code>```

is true or false. I did not realize that I needed to tell Angular to refresh its view by using Application

applicationRef.tick();

in the right place. So basically, once the Ionic changes the value of this.connected you need to tell Angular about it, here is the corrected part of the code:

You need to inject ApplicationRef into the constructor

```<code>constructor(public navCtrl: NavController,
                ...
                private appReference: ApplicationRef) {
                ...

checkForNetwork = () => {
    this.networkType= this.network.type;
    this.network.onDisconnect().subscribe(() => {
        this.connected = false;
        this.network.type = null;
        this.appReference.tick();
    });
    this.network.onConnect().subscribe(() => {
        this.connected = 'network connected!';
        setTimeout(() => {
            if (this.network.type === 'wifi') {
                this.connected = true;
                this.appReference.tick();
            }
        }, 3000);
    });
}
</code>```

Body:
I have created a little phone app with Ionic. I am trying to implement a bit logic where the component knows when its online or offline. To do so I am using the network plugin fom Ionic and it just does not work as expected.

instead of updating the

this.connected

value every time when I switch on / off the network, it will only do so if I switch it off / on AND do something like switching from landscape to portrait mode, or work on a different app for a while and come back to the app.

Really puzzled by that.

Here is the code:

import {Component} from '@angular/core';
import {NavController, NavParams, Platform} from 'ionic-angular';
import {GooglePlus} from '@ionic-native/google-plus';
import {SurveyService} from "./survey.service";
import {Survey} from "../../Declarations/Survey";
import {SurveyPage} from "../survey/survey";
import {Network} from "@ionic-native/network";

@Component({
    selector: 'page-home',
    templateUrl: 'home.html',
    providers: [SurveyService, Network]
})
export class HomePage {
    public surveys: Survey[] = [];
    public connected;
    public networkType;

    constructor(public navCtrl: NavController,
                private googlePlus: GooglePlus,
                private surveyService: SurveyService,
                public navParams: NavParams,
                platform: Platform,
                private network: Network) {

        this.checkForNetwork();
        this.surveyService.getAvailable().subscribe(surveys => {
            this.checkForNetwork();
            this.surveys = surveys;
        })
    }

    login() {

        this.googlePlus.login({
            'webClientId': '632130231957-dmjd154jhq1eenimedri3m0de6sh7tln.apps.googleusercontent.com'
        }).then((res) => {
            console.log(res);
        }, (err) => {
            console.log(err);
        });

    }

    logout() {

        this.googlePlus.logout().then(() => {
            console.log("logged out");
        });

    }

    openSurvey = (survey: Survey) => {

        this.navCtrl.push(SurveyPage, {
            survey: survey
        });

    }

    checkForNetwork = () => {
        this.networkType= this.network.type;
        this.network.onDisconnect().subscribe(() => {
            this.connected = false;
            this.network.type = null;
        });
        this.network.onConnect().subscribe(() => {
            this.connected = 'network connected!';
            setTimeout(() => {
                if (this.network.type === 'wifi') {
                    this.connected = true;
                }
            }, 3000);
        });
    }
}

Body:
OK, I worked it out:

Turns out that ionic works perfectly fine, but I tried to change the view of my application depending on whether

this.connected

is true or false. I did not realize that I needed to tell Angular to refresh its view by using Application

applicationRef.tick();

in the right place. So basically, once the Ionic changes the value of this.connected you need to tell Angular about it, here is the corrected part of the code:

You need to inject ApplicationRef into the constructor

constructor(public navCtrl: NavController,
                ...
                private appReference: ApplicationRef) {
                ...

checkForNetwork = () => {
    this.networkType= this.network.type;
    this.network.onDisconnect().subscribe(() => {
        this.connected = false;
        this.network.type = null;
        this.appReference.tick();
    });
    this.network.onConnect().subscribe(() => {
        this.connected = 'network connected!';
        setTimeout(() => {
            if (this.network.type === 'wifi') {
                this.connected = true;
                this.appReference.tick();
            }
        }, 3000);
    });
}


问:
Can't add objects to an array after initializing the array
I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object".

I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array.

The main is:

```<code>Sorteo P=new Sorteo();
P.Predetermined();
</code>```

Class Sorteo:

```<code>// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}
</code>```

答:
I'm struggling to understand your question but is this what you were trying to do?</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace YourNameSpace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ClassA Item = new ClassA();
            Item.PredeterminedValues();

            foreach(string s in Item.StringArray)
            {
                Console.WriteLine(s);
            }
        }
    }

    public class ClassA
    {
        public int Counter {get;private set;}
        public string[] StringArray{get;private set;}

        public ClassA()
        {
            StringArray = new string[2];
        }

        public void Add(int Value)
        {
            Counter += Value;
        }

        public void PredeterminedValues()
        {
            StringArray[0] = ("SomeString1");
            StringArray[1] = ("SomeString2");
        }
    }
}
</code>```

Body:
I'm trying to initialize an array of objects with predetermined values but I get "Object reference not set to an instance of an object".

I don't understand the cause of the problem since I'm initializing properly and then I'm adding values to the array.

The main is:

Sorteo P=new Sorteo();
P.Predetermined();

Class Sorteo:

// Atribute
private ClassA[] A;
int count=0;

// Methods
public Sorteo()
{
    A=new ClassA[2];
}
public void Add(ClassA a)
{
    A[count]=a;
    count++;
}
public void PredeterminedValues()
{
    A[0].Add(new ClassB("SomeString1"));
    A[1].Add(new ClassB("SomeString2"));
}

Body:
I'm struggling to understand your question but is this what you were trying to do?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace YourNameSpace
{
    public class Program
    {
        public static void Main(string[] args)
        {
            ClassA Item = new ClassA();
            Item.PredeterminedValues();

            foreach(string s in Item.StringArray)
            {
                Console.WriteLine(s);
            }
        }
    }

    public class ClassA
    {
        public int Counter {get;private set;}
        public string[] StringArray{get;private set;}

        public ClassA()
        {
            StringArray = new string[2];
        }

        public void Add(int Value)
        {
            Counter += Value;
        }

        public void PredeterminedValues()
        {
            StringArray[0] = ("SomeString1");
            StringArray[1] = ("SomeString2");
        }
    }
}