问:
What does "abstract over" mean?
Often in the Scala literature, I encounter the phrase "abstract over", but I don't understand the intent.  For example, Martin Odersky writes

You can pass methods (or "functions") as parameters, or you can abstract over them. You can specify types as parameters, or you can abstract over them.

As another example, in the "Deprecating the Observer Pattern" paper,

A consequence from our event streams being first-class values is that we can abstract over them.

I have read that first order generics "abstract over types", while monads "abstract over type constructors".  And we also see phrases like this in the Cake Pattern paper.  To quote one of many such examples:

Abstract type members provide flexible way to abstract over concrete types of components.

Even relevant stack overflow questions use this terminology.  "can't existentially abstract over parameterized type..."

So... what does "abstract over" actually mean?

答:
In algebra, as in everyday concept formation, abstractions are formed by grouping things by some essential characteristics and omitting their specific other characteristics. The abstraction is unified under a single symbol or word denoting the similarities. We say that we abstract over the differences, but this really means we're integrating by the similarities.

For example, consider a program that takes the sum of the numbers 1, 2, and 3:

```<code>val sumOfOneTwoThree = 1 + 2 + 3
</code>```

This program is not very interesting, since it's not very abstract. We can abstract over the numbers we're summing, by integrating all lists of numbers under a single symbol ns:

```<code>def sumOf(ns: List[Int]) = ns.foldLeft(0)(_ + _)
</code>```

And we don't particularly care that it's a List either. List is a specific type constructor (takes a type and returns a type), but we can abstract over the type constructor by specifying which essential characteristic we want (that it can be folded):

```<code>trait Foldable[F[_]] {
  def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B
}

def sumOf[F[_]](ns: F[Int])(implicit ff: Foldable[F]) =
  ff.foldl(ns, 0, (x: Int, y: Int) => x + y)
</code>```

And we can have implicit Foldable instances for List and any other thing we can fold.

```<code>implicit val listFoldable = new Foldable[List] {
  def foldl[A, B](as: List[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f)
}

implicit val setFoldable = new Foldable[Set] {
  def foldl[A, B](as: Set[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f)
}

val sumOfOneTwoThree = sumOf(List(1,2,3))
</code>```

What's more, we can abstract over both the operation and the type of the operands:

```<code>trait Monoid[M] {
  def zero: M
  def add(m1: M, m2: M): M
}

trait Foldable[F[_]] {
  def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B
  def foldMap[A, B](as: F[A], f: A => B)(implicit m: Monoid[B]): B =
    foldl(as, m.zero, (b: B, a: A) => m.add(b, f(a)))
}

def mapReduce[F[_], A, B](as: F[A], f: A => B)
                         (implicit ff: Foldable[F], m: Monoid[B]) =
  ff.foldMap(as, f)
</code>```

Now we have something quite general. The method mapReduce will fold any F[A] given that we can prove that F is foldable and that A is a monoid or can be mapped into one. For example:

```<code>case class Sum(value: Int)
case class Product(value: Int)

implicit val sumMonoid = new Monoid[Sum] {
  def zero = Sum(0)
  def add(a: Sum, b: Sum) = Sum(a.value + b.value)
}

implicit val productMonoid = new Monoid[Product] {
  def zero = Product(1)
  def add(a: Product, b: Product) = Product(a.value * b.value)
}

val sumOf123 = mapReduce(List(1,2,3), Sum)
val productOf456 = mapReduce(Set(4,5,6), Product)
</code>```

We have abstracted over monoids and foldables.

Title: What does "abstract over" mean?

Body:
In algebra, as in everyday concept formation, abstractions are formed by grouping things by some essential characteristics and omitting their specific other characteristics. The abstraction is unified under a single symbol or word denoting the similarities. We say that we abstract over the differences, but this really means we're integrating by the similarities.

For example, consider a program that takes the sum of the numbers 1, 2, and 3:

val sumOfOneTwoThree = 1 + 2 + 3

This program is not very interesting, since it's not very abstract. We can abstract over the numbers we're summing, by integrating all lists of numbers under a single symbol ns:

def sumOf(ns: List[Int]) = ns.foldLeft(0)(_ + _)

And we don't particularly care that it's a List either. List is a specific type constructor (takes a type and returns a type), but we can abstract over the type constructor by specifying which essential characteristic we want (that it can be folded):

trait Foldable[F[_]] {
  def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B
}

def sumOf[F[_]](ns: F[Int])(implicit ff: Foldable[F]) =
  ff.foldl(ns, 0, (x: Int, y: Int) => x + y)

And we can have implicit Foldable instances for List and any other thing we can fold.

implicit val listFoldable = new Foldable[List] {
  def foldl[A, B](as: List[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f)
}

implicit val setFoldable = new Foldable[Set] {
  def foldl[A, B](as: Set[A], z: B, f: (B, A) => B) = as.foldLeft(z)(f)
}

val sumOfOneTwoThree = sumOf(List(1,2,3))

What's more, we can abstract over both the operation and the type of the operands:

trait Monoid[M] {
  def zero: M
  def add(m1: M, m2: M): M
}

trait Foldable[F[_]] {
  def foldl[A, B](as: F[A], z: B, f: (B, A) => B): B
  def foldMap[A, B](as: F[A], f: A => B)(implicit m: Monoid[B]): B =
    foldl(as, m.zero, (b: B, a: A) => m.add(b, f(a)))
}

def mapReduce[F[_], A, B](as: F[A], f: A => B)
                         (implicit ff: Foldable[F], m: Monoid[B]) =
  ff.foldMap(as, f)

Now we have something quite general. The method mapReduce will fold any F[A] given that we can prove that F is foldable and that A is a monoid or can be mapped into one. For example:

case class Sum(value: Int)
case class Product(value: Int)

implicit val sumMonoid = new Monoid[Sum] {
  def zero = Sum(0)
  def add(a: Sum, b: Sum) = Sum(a.value + b.value)
}

implicit val productMonoid = new Monoid[Product] {
  def zero = Product(1)
  def add(a: Product, b: Product) = Product(a.value * b.value)
}

val sumOf123 = mapReduce(List(1,2,3), Sum)
val productOf456 = mapReduce(Set(4,5,6), Product)

We have abstracted over monoids and foldables.

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Display count in ADF pie chart
When we create a pie chart in ADF (12.2.1.0.0), we get the pies that represent percentages.

e.g if we have a chart by job Id and salary, it shows the percentage of salaries for that job, but
1) How can we display the count of values(number of salaries) in that pie?
2) how can we display the value (total of salaries) in that pie.?

Thanks

答:
Create a view object that uses queries to get the data you want and then base your chart on that VO.

Something like
Select count(Salary), DepartmentId
From Employees
Group by DepartmentId

ContentLicense: CC BY-SA 3.0

Title: Display count in ADF pie chart


问:
Powershell Running URls from .txt
I am trying to make a PowerShell script to take urls from a text file and open them in Internet Explorer, or just the default browser on the computer.

I have Outlook client, that has a macro on it that will download all emails with a URL in it to a text file, these URLs are links to download files. The PowerShell Script will go into that text file and open all the URLS in the default browser, then the shell will proceed to automatically download the files.

The PowerShell will be launched from Powershell and be set on a task

How would I start this?

I am not sure how to.

EDIT

file containing the URls

```<code>http://www.google.com
http://www.youtube.com
</code>```

Example code

```<code>None, I do not know where to start
</code>```

答:
If you have a file named 'urls.txt' this PowerShell script will open each one in a new tab.  I am using Chrome in this example.

The 'urls.txt' file should have the format below...notice each url is on a separate line...

```<code>yahoo.com
bing.com
google.com
www.cnn.com
</code>```

This is the actual PowerShell script you type into the PowerShell window.  Keep in mind you will need to navigate to the directory where your 'urls.txt' file exists.  You can do that by using the 'cd' (change directory) command.  for example, if your file exists on the Desktop and your profile is under 'admin1' you could write: cd C:\Users\admin1\Desktop

```<code>$urls = Get-Content urls.txt
Start-Process -FilePath "chrome.exe" -ArgumentList $urls
</code>```

I realize this question was asked sometime ago but I was also wondering how to do the same.  This should get you what you want.

Title: Powershell Running URls from .txt

Body:
I am trying to make a PowerShell script to take urls from a text file and open them in Internet Explorer, or just the default browser on the computer.

I have Outlook client, that has a macro on it that will download all emails with a URL in it to a text file, these URLs are links to download files. The PowerShell Script will go into that text file and open all the URLS in the default browser, then the shell will proceed to automatically download the files.

The PowerShell will be launched from Powershell and be set on a task

How would I start this?

I am not sure how to.

EDIT

file containing the URls

http://www.google.com
http://www.youtube.com

Example code

None, I do not know where to start

Body:
If you have a file named 'urls.txt' this PowerShell script will open each one in a new tab.  I am using Chrome in this example.

The 'urls.txt' file should have the format below...notice each url is on a separate line...

yahoo.com
bing.com
google.com
www.cnn.com

This is the actual PowerShell script you type into the PowerShell window.  Keep in mind you will need to navigate to the directory where your 'urls.txt' file exists.  You can do that by using the 'cd' (change directory) command.  for example, if your file exists on the Desktop and your profile is under 'admin1' you could write: cd C:\Users\admin1\Desktop

$urls = Get-Content urls.txt
Start-Process -FilePath "chrome.exe" -ArgumentList $urls

I realize this question was asked sometime ago but I was also wondering how to do the same.  This should get you what you want.


问:
How to enable alignment exceptions for my process on x64?
I'm curious to see if my 64-bit application suffers from alignment faults.

From Windows Data Alignment on IPF, x86, and x64 archive:

In Windows, an application program that generates an alignment fault will raise an exception, EXCEPTION_DATATYPE_MISALIGNMENT.

On the x64 architecture, the alignment exceptions are disabled by default, and the fix-ups are done by the hardware. The application can enable alignment exceptions by setting a couple of register bits, in which case the exceptions will be raised unless the user has the operating system mask the exceptions with SEM_NOALIGNMENTFAULTEXCEPT. (For details, see the AMD Architecture Programmer's Manual Volume 2: System Programming.)

[Ed. emphasis mine]

On the x86 architecture, the operating system does not make the alignment fault visible to the application. On these two platforms, you will also suffer performance degradation on the alignment fault, but it will be significantly less severe than on the Itanium, because the hardware will make the multiple accesses of memory to retrieve the unaligned data.

On the Itanium, by default, the operating system (OS) will make this exception visible to the application, and a termination handler might be useful in these cases. If you do not set up a handler, then your program will hang or crash. In Listing 3, we provide an example that shows how to catch the EXCEPTION_DATATYPE_MISALIGNMENT exception.

Ignoring the direction to consult the AMD Architecture Programmer's Manual, i will instead consult the Intel 64 and IA-32 Architectures Software Developer’s Manual

5.10.5 Checking Alignment

When the CPL is 3, alignment of memory references can be checked by setting the
AM flag in the CR0 register and the AC flag in the EFLAGS register. Unaligned memory
references generate alignment exceptions (#AC). The processor does not generate
alignment exceptions when operating at privilege level 0, 1, or 2. See Table 6-7 for a
description of the alignment requirements when alignment checking is enabled.

Excellent. I'm not sure what that means, but excellent.

Then there's also:

2.5 CONTROL REGISTERS

Control registers (CR0, CR1, CR2, CR3, and CR4; see Figure 2-6) determine operating
mode of the processor and the characteristics of the currently executing task.
These registers are 32 bits in all 32-bit modes and compatibility mode.

In 64-bit mode, control registers are expanded to 64 bits. The MOV CRn instructions
are used to manipulate the register bits. Operand-size prefixes for these instructions
are ignored.

The control registers are summarized below, and each architecturally defined control
field in these control registers are described individually. In Figure 2-6, the width of
the register in 64-bit mode is indicated in parenthesis (except for CR0).

CR0 — Contains system control flags that control operating mode and states of
the processor

AM

Alignment Mask (bit 18 of CR0) — Enables automatic alignment checking
when set; disables alignment checking when clear. Alignment checking is
performed only when the AM flag is set, the AC flag in the EFLAGS register is
set, CPL is 3, and the processor is operating in either protected or virtual-
8086 mode.

I tried

The language i am actually using is Delphi, but pretend it's language agnostic pseudocode:

```<code>void UnmaskAlignmentExceptions()
{
   asm
      mov rax, cr0; //copy CR0 flags into RAX
      or  rax, 0x20000; //set bit 18 (AM)
      mov cr0, rax; //copy flags back
}
</code>```

The first instruction

```<code>mov rax, cr0;
</code>```

fails with a Privileged Instruction exception.

How to enable alignment exceptions for my process on x64?

PUSHF

I discovered that the x86 has the instruction:

PUSHF, POPF: Push/pop first 16-bits of EFLAGS on/off the stack

PUSHFD, POPFD: Push/pop all 32-bits of EFLAGS on/off the stack

That then led me to the x64 version:

PUSHFQ, POPFQ: Push/pop the RFLAGS quad on/off the stack

(In 64-bit world the EFLAGS are renamed RFLAGS).

So i wrote:

```<code>void EnableAlignmentExceptions;
{
    asm
       PUSHFQ;                //Push RFLAGS quadword onto the stack
       POP       RAX;         //Pop them flags into RAX
       OR        RAX, $20000; //set bit 18 (AC=Alignment Check) of the flags
       PUSH      RAX;         //Push the modified flags back onto the stack
       POPFQ;                 //Pop the stack back into RFLAGS;
}
</code>```

And it didn't crash or trigger a protection exception. I have no idea if it does what i want it to.

Bonus Reading

How to catch data-alignment faults on x86 (aka SIGBUS on Sparc) (unrelated question; x86 not x64, Ubunutu not Windows, gcc vs not)

答:
This works in 64-bit Intel CPU. May fail in some AMD

```<code>pushfq
bts qword ptr [rsp], 12h ; set AC bit of rflags
popfq
</code>```

It will not work right away in 32-bit CPUs, these will require first a kernel driver to change the AM bit of CR0 and then

```<code>pushfd
bts dword ptr [esp], 12h
popfd
</code>```

Body:
I'm curious to see if my 64-bit application suffers from alignment faults.

From Windows Data Alignment on IPF, x86, and x64 archive:

In Windows, an application program that generates an alignment fault will raise an exception, EXCEPTION_DATATYPE_MISALIGNMENT.

On the x64 architecture, the alignment exceptions are disabled by default, and the fix-ups are done by the hardware. The application can enable alignment exceptions by setting a couple of register bits, in which case the exceptions will be raised unless the user has the operating system mask the exceptions with SEM_NOALIGNMENTFAULTEXCEPT. (For details, see the AMD Architecture Programmer's Manual Volume 2: System Programming.)

[Ed. emphasis mine]

On the x86 architecture, the operating system does not make the alignment fault visible to the application. On these two platforms, you will also suffer performance degradation on the alignment fault, but it will be significantly less severe than on the Itanium, because the hardware will make the multiple accesses of memory to retrieve the unaligned data.

On the Itanium, by default, the operating system (OS) will make this exception visible to the application, and a termination handler might be useful in these cases. If you do not set up a handler, then your program will hang or crash. In Listing 3, we provide an example that shows how to catch the EXCEPTION_DATATYPE_MISALIGNMENT exception.

Ignoring the direction to consult the AMD Architecture Programmer's Manual, i will instead consult the Intel 64 and IA-32 Architectures Software Developer’s Manual

5.10.5 Checking Alignment

When the CPL is 3, alignment of memory references can be checked by setting the
AM flag in the CR0 register and the AC flag in the EFLAGS register. Unaligned memory
references generate alignment exceptions (#AC). The processor does not generate
alignment exceptions when operating at privilege level 0, 1, or 2. See Table 6-7 for a
description of the alignment requirements when alignment checking is enabled.

Excellent. I'm not sure what that means, but excellent.

Then there's also:

2.5 CONTROL REGISTERS

Control registers (CR0, CR1, CR2, CR3, and CR4; see Figure 2-6) determine operating
mode of the processor and the characteristics of the currently executing task.
These registers are 32 bits in all 32-bit modes and compatibility mode.

In 64-bit mode, control registers are expanded to 64 bits. The MOV CRn instructions
are used to manipulate the register bits. Operand-size prefixes for these instructions
are ignored.

The control registers are summarized below, and each architecturally defined control
field in these control registers are described individually. In Figure 2-6, the width of
the register in 64-bit mode is indicated in parenthesis (except for CR0).

CR0 — Contains system control flags that control operating mode and states of
the processor

AM

Alignment Mask (bit 18 of CR0) — Enables automatic alignment checking
when set; disables alignment checking when clear. Alignment checking is
performed only when the AM flag is set, the AC flag in the EFLAGS register is
set, CPL is 3, and the processor is operating in either protected or virtual-
8086 mode.

I tried

The language i am actually using is Delphi, but pretend it's language agnostic pseudocode:

void UnmaskAlignmentExceptions()
{
   asm
      mov rax, cr0; //copy CR0 flags into RAX
      or  rax, 0x20000; //set bit 18 (AM)
      mov cr0, rax; //copy flags back
}

The first instruction

mov rax, cr0;

fails with a Privileged Instruction exception.

How to enable alignment exceptions for my process on x64?

PUSHF

I discovered that the x86 has the instruction:

PUSHF, POPF: Push/pop first 16-bits of EFLAGS on/off the stack

PUSHFD, POPFD: Push/pop all 32-bits of EFLAGS on/off the stack

That then led me to the x64 version:

PUSHFQ, POPFQ: Push/pop the RFLAGS quad on/off the stack

(In 64-bit world the EFLAGS are renamed RFLAGS).

So i wrote:

void EnableAlignmentExceptions;
{
    asm
       PUSHFQ;                //Push RFLAGS quadword onto the stack
       POP       RAX;         //Pop them flags into RAX
       OR        RAX, $20000; //set bit 18 (AC=Alignment Check) of the flags
       PUSH      RAX;         //Push the modified flags back onto the stack
       POPFQ;                 //Pop the stack back into RFLAGS;
}

And it didn't crash or trigger a protection exception. I have no idea if it does what i want it to.

Bonus Reading

How to catch data-alignment faults on x86 (aka SIGBUS on Sparc) (unrelated question; x86 not x64, Ubunutu not Windows, gcc vs not)

Body:
This works in 64-bit Intel CPU. May fail in some AMD

pushfq
bts qword ptr [rsp], 12h ; set AC bit of rflags
popfq

It will not work right away in 32-bit CPUs, these will require first a kernel driver to change the AM bit of CR0 and then

pushfd
bts dword ptr [esp], 12h
popfd


问:
Mysql SQL_CALC_FOUND_ROWS and pagination
So I have a table that has a little over 5 million rows. When I use SQL_CALC_FOUND_ROWS the query just hangs forever. When I take it out the query executes within a second withe LIMIT ,25. My question is for pagination reasons is there an alternative to getting the number of total rows?</p>

答:
SQL_CALC_FOUND_ROWS forces MySQL to scan for ALL matching rows, even if they'd never get fetched. Internally it amounts to the same query being executed without the LIMIT clause.

If the filtering you're doing via WHERE isn't too crazy, you could calculate and cache various types of filters to save the full-scan load imposed by calc_found_rows. Basically run a "select count(*) from ... where ...." for most possible where clauses.

Otherwise, you could go Google-style and just spit out some page numbers that occasionally have no relation whatsoever with reality (You know, you see "Goooooooooooogle", get to page 3, and suddenly run out of results).

ContentLicense: CC BY-SA 2.5


问:
Web API 2, CORS, NTLM & OWIN / Katana with Angular 2
Massive amount of issues getting this to work.

Thought I'd put up the common issues and the solutions having wasted a day on this and being led down many false paths by other answers.

Setup :

Web Api 2 Server

Server configured for NTLM (Negotiate)

Angular website hosted on a different machine or Port

Website connects to API to do, well, stuff.

Issues :

Basic setup and first time you run it you get no access-control-allow-origin header is present

Setting Cors on the server and you still get the issue

You eventually realise that Angular isn't setting WithCredentials on its calls and fix this, now GET works but PUT, POST & DELETE fail with something about pre-flights.

答:
And the solutions :

Firstly your server needs to be enabled for cors and this must be the first line in your app config :

WebApp.Start(_configuration.Url, app =>
{
   app.UseCors(CorsOptions.AllowAll);

Enable Authentication, BUT not for the pre-flight OPTIONS calls :

var listener = (HttpListener)app.Properties["System.Net.HttpListener"];
listener.AuthenticationSchemeSelectorDelegate = request =>
   request.HttpMethod == "OPTIONS"
        ? AuthenticationSchemes.Anonymous
        : AuthenticationSchemes.Negotiate;

Set your Angular code to send calls in with WithCredentials.  There's many different ways to do this, but we used an authentication interceptor :
intercept(request: HttpRequest<any>, next: HttpHandler):
Observable<HttpEvent<any>> {
const authReq = request.clone({ withCredentials: true });
return next.handle(authReq)

If you want to do anything fancy for your Auth you can create your own middleware by extending OwinMiddleware and overriding the Invoke method. This can then be registerd in the pipeline with app.Use<MyMiddleware>(paramsToConstructor) in your override method you can access the Identity of the user with :

var identity = new ClaimsIdentity(context.Authentication.User.Identity.AuthenticationType);


问:
MySQL Daemon failed to start. ib_logfile is of different size
Help me, please.

Server : AWS ec2

problem :

```<code>#sudo service mysqld start

MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]
</code>```

vi /var/log/mysqld.log :

```<code>151015 05:46:26 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
151015  5:46:26 [Note] /usr/libexec/mysql55/mysqld (mysqld 5.5.45) starting as process 14873 ...
151015  5:46:26 [Warning] option 'innodb-buffer-pool-size': signed value 1048576 adjusted to 5242880
151015  5:46:26 [Note] Plugin 'FEDERATED' is d151015 05:46:26 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
151015 05:46:42 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
151015  5:46:42 [Note] /usr/libexec/mysql55/mysqld (mysqld 5.5.45) starting as process 15133 ...
151015  5:46:42 [Note] Plugin 'FEDERATED' is disabled.
151015  5:46:42 InnoDB: The InnoDB memory heap is disabled
151015  5:46:42 InnoDB: Mutexes and rw_locks use GCC atomic builtins
151015  5:46:42 InnoDB: Compressed tables use zlib 1.2.8
151015  5:46:42 InnoDB: Using Linux native AIO
151015  5:46:42 InnoDB: Initializing buffer pool, size = 128.0M
151015  5:46:42 InnoDB: Completed initialization of buffer pool
InnoDB: Error: log file ./ib_logfile0 is of different size 0 0 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
151015  5:46:42 [ERROR] Plugin 'InnoDB' init function returned error.
151015  5:46:42 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
151015  5:46:42 [ERROR] Unknown/unsupported storage engine: InnoDB
151015  5:46:42 [ERROR] Aborting

151015  5:46:42 [Note] /usr/libexec/mysql55/mysqld: Shutdown complete

151015 05:46:42 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
</code>```

Thank you!

答:
Most of the time this occurs because your disk space was full. To check space run..

```<code>df
</code>```

Try checking a log file somewhere.  Or run the following to find big files...

```<code>sudo find / -xdev -type f -size +100M
</code>```

Once you clear up your disk space try restarting mysql...

```<code>sudo service mysqld restart
</code>```

If it still errors, then try moving the iblog files and then restarting mysql...

```<code>sudo mv /var/lib/mysql/ib_logfile* ~/
sudo service mysqld restart
</code>```

That should be it in 90% of the cases for this problem. I would avoid messing with your my.cnf file too much.  At worst COPY IT and temporarily put in a very basic version to get more debug...

```<code>sudo vi /my/etc.cnf

[mysqld_safe]
log_error=/var/log/mysql_error.log

[mysqld]
log_error=/var/log/mysqld_error.log
</code>```

Body:
Help me, please.

Server : AWS ec2

problem :

#sudo service mysqld start

MySQL Daemon failed to start.
Starting mysqld:                                           [FAILED]

vi /var/log/mysqld.log :

151015 05:46:26 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
151015  5:46:26 [Note] /usr/libexec/mysql55/mysqld (mysqld 5.5.45) starting as process 14873 ...
151015  5:46:26 [Warning] option 'innodb-buffer-pool-size': signed value 1048576 adjusted to 5242880
151015  5:46:26 [Note] Plugin 'FEDERATED' is d151015 05:46:26 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended
151015 05:46:42 mysqld_safe Starting mysqld daemon with databases from /var/lib/mysql
151015  5:46:42 [Note] /usr/libexec/mysql55/mysqld (mysqld 5.5.45) starting as process 15133 ...
151015  5:46:42 [Note] Plugin 'FEDERATED' is disabled.
151015  5:46:42 InnoDB: The InnoDB memory heap is disabled
151015  5:46:42 InnoDB: Mutexes and rw_locks use GCC atomic builtins
151015  5:46:42 InnoDB: Compressed tables use zlib 1.2.8
151015  5:46:42 InnoDB: Using Linux native AIO
151015  5:46:42 InnoDB: Initializing buffer pool, size = 128.0M
151015  5:46:42 InnoDB: Completed initialization of buffer pool
InnoDB: Error: log file ./ib_logfile0 is of different size 0 0 bytes
InnoDB: than specified in the .cnf file 0 5242880 bytes!
151015  5:46:42 [ERROR] Plugin 'InnoDB' init function returned error.
151015  5:46:42 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
151015  5:46:42 [ERROR] Unknown/unsupported storage engine: InnoDB
151015  5:46:42 [ERROR] Aborting

151015  5:46:42 [Note] /usr/libexec/mysql55/mysqld: Shutdown complete

151015 05:46:42 mysqld_safe mysqld from pid file /var/run/mysqld/mysqld.pid ended

Thank you!

Body:
Most of the time this occurs because your disk space was full. To check space run..

df

Try checking a log file somewhere.  Or run the following to find big files...

sudo find / -xdev -type f -size +100M

Once you clear up your disk space try restarting mysql...

sudo service mysqld restart

If it still errors, then try moving the iblog files and then restarting mysql...

sudo mv /var/lib/mysql/ib_logfile* ~/
sudo service mysqld restart

That should be it in 90% of the cases for this problem. I would avoid messing with your my.cnf file too much.  At worst COPY IT and temporarily put in a very basic version to get more debug...

sudo vi /my/etc.cnf

[mysqld_safe]
log_error=/var/log/mysql_error.log

[mysqld]
log_error=/var/log/mysqld_error.log


问:
Elements not being appended to array in loop
I am writing a Bash Shell script, which reads a bunch of lines from a file, and tries to append each line to an array, thus:

```<code># counter variable
i=0

cat doc.txt | while read -r line; do
    myArr[i]="$line"
    ((i=i+1))
done
</code>```

The file doc.txt contains one word in every line. When I print the array (through echo ${myArr[@]} or for x in ${myArr[@]};do echo $x; done), my array seems to be empty. What am I doing wrong? Thanks!

Edit: I also tried doing this in Ksh, with the same results. An answer in either Bash or Ksh is acceptable, since I seem to be having the same issue in both.

答:
You are running the while loop in a subshell, so any changes you make to the array disappear once that shell exits. Use input redirection instead:

```<code>while IFS= read -r line; do
    myArr+=("$line")
done < doc.txt
</code>```

If you using bash 4.0 or later, you can use a single command

```<code>readArray -t myArr < doc.txt
</code>```

Body:
I am writing a Bash Shell script, which reads a bunch of lines from a file, and tries to append each line to an array, thus:

# counter variable
i=0

cat doc.txt | while read -r line; do
    myArr[i]="$line"
    ((i=i+1))
done

The file doc.txt contains one word in every line. When I print the array (through echo ${myArr[@]} or for x in ${myArr[@]};do echo $x; done), my array seems to be empty. What am I doing wrong? Thanks!

Edit: I also tried doing this in Ksh, with the same results. An answer in either Bash or Ksh is acceptable, since I seem to be having the same issue in both.

Body:
You are running the while loop in a subshell, so any changes you make to the array disappear once that shell exits. Use input redirection instead:

while IFS= read -r line; do
    myArr+=("$line")
done < doc.txt

If you using bash 4.0 or later, you can use a single command

readArray -t myArr < doc.txt


问:
Error while running 'python setup.py build_ext --inplace'
I'm following the 'ways to contribute' page in scikit-learn.

As per recommended, I've forked and cloned scikit-learn. After that I ran the
commands: first I ran 'python setup.py build_ext --inplace',
which gave me an error:

cc1: some warnings being treated as errors
error: Command "x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fno-strict-aliasing -Wdate-time -D_FORTIFY_SOURCE=2 -g -fstack-protector-strong -Wformat -Werror=format-security -fPIC -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/lib/python2.7/dist-packages/numpy/core/include -I/usr/include/python2.7 -I/usr/include/python2.7 -c sklearn/neighbors/quad_tree.c -o build/temp.linux-x86_64-2.7/sklearn/neighbors/quad_tree.o" failed with exit status 1

So, first I thought that maybe this was some python issue. So I googled for
'python failed with exit status 1' and I found that the solution was python-dev not installed. But I already had that. So this solution was out of the picture.

Then again I ran 'pip install --editable .', which gave me this error:

Command "/usr/bin/python -c "import setuptools, tokenize;file='/home/sumedh/Downloads/Programming/OpenSourceContributions/scikit-learn/setup.py';f=getattr(tokenize, 'open', open)(file);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, file, 'exec'))" develop --no-deps" failed with error code 1 in /home/sumedh/Downloads/Programming/OpenSourceContributions/scikit-learn/

From the error, it looks like some issue in setup.py, but i'm not sure.
I tried this as well, but no solution.
Can you guys please help. thanks. :)

答:
For those who had this issue, the issue is resolved by installing the latest Cython.

I mean, for me, it was not updated to the latest version. I'm using Ubuntu 16.04 LTS Xenial, which shows 0.23.4-0ubuntu5 as the latest.

One needs to install Cython from the official website. I mean install the very latest, not the one Ubuntu provides.(I first thought ubuntu updates our packages to the latest ones out there.) Installing it to the latest 0.27.3 solved the issue.


问:
Copy json data from Azure cosmos db to Azure sql using Azure Data Factory
I am using Azure Data Factory V1. We want to copy the json data stored as documents from Azure cosmos to a azure sql table, using a copy activity.

I figured out copying the data by specifying the columns in sql table to match the property names from json. However our goal is to copy the entire json data as a single field. We are doing this for the purpose of being agnostic to the schema within the json data.

I have tried specifying a single nvarchar(max) column to store the json data, and the query on the copy activity to be "select c as "FullData" from c". But the copy activity simply generates a NULL.

I think this is because "FullData" is of type json on the document end and it is string on the sql end. I also tried to convert the json object to string within the cosmos db query. But I couldnt find any API to do so.

I know we could write a custom activity to accomplish what I want to do, but is this possible to do with ADF out of the box functionality?

答:
To use ADF to copy the JSON document as single field into Azure SQL Database, you need to make sure the result set by the specified Cosmos DB query is actually a single "column" containing the entire object as string.

I don't think Cosmos DB has built-in query syntax for this, but you can create a UDF (user defined function) in Cosmos DB to convert object to string e.g. with JSON.stringify(), then call that UDF in the select query in ADF copy source.


问:
How to convert String[] that contains numbers to int[] in Java?
What I got it's this instruction that gives me back a String[] object:

```<code>string.trim().split(" ");
</code>```

The content using Arrays.asList(string.trim().split(" ")) it's something like:

[4, 3, 2, 5, -10, 23, 30, 40, -3, 30]

So its content is made up by numbers. What I want it's to convert the String[] object to an int[] one. How can I do that without parsing every single string to a int?

答:
You can kind of do it without loops but you only get a List<Integer> not an int[].

```<code>private static class IntegerAdapter extends AbstractList<Integer> implements List<Integer> {
    private final List<String> theList;

    public IntegerAdapter(List<String> strings) {
        this.theList = strings;
    }

    public IntegerAdapter(String[] strings) {
        this(Arrays.asList(strings));
    }

    @Override
    public Integer get(int index) {
        return Integer.parseInt(theList.get(index));
    }

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

public void test(String[] args) {
    String test = "4 3 2 5 -10 23 30 40 -3 30";
    String[] split = test.split(" ");
    IntegerAdapter adapter = new IntegerAdapter(split);
    // Look ma! No loops :)
    System.out.println(adapter.get(4));
}
</code>```

Body:
What I got it's this instruction that gives me back a String[] object:

string.trim().split(" ");

The content using Arrays.asList(string.trim().split(" ")) it's something like:

[4, 3, 2, 5, -10, 23, 30, 40, -3, 30]

So its content is made up by numbers. What I want it's to convert the String[] object to an int[] one. How can I do that without parsing every single string to a int?

Body:
You can kind of do it without loops but you only get a List<Integer> not an int[].

private static class IntegerAdapter extends AbstractList<Integer> implements List<Integer> {
    private final List<String> theList;

    public IntegerAdapter(List<String> strings) {
        this.theList = strings;
    }

    public IntegerAdapter(String[] strings) {
        this(Arrays.asList(strings));
    }

    @Override
    public Integer get(int index) {
        return Integer.parseInt(theList.get(index));
    }

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

public void test(String[] args) {
    String test = "4 3 2 5 -10 23 30 40 -3 30";
    String[] split = test.split(" ");
    IntegerAdapter adapter = new IntegerAdapter(split);
    // Look ma! No loops :)
    System.out.println(adapter.get(4));
}


问:
Duplicate removal not working on table with many NULLs
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

```<code>describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)
</code>```

I have data that looks like this..

```<code>"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"
</code>```

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

```<code>DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);
</code>```

答:
Try:

```<code>CREATE TABLE t3_new AS
         (
                  SELECT   provnum,
                           trgt_mo,
                           mcare,
                           bed2prsn_asst,
                           trnsfr2prsn_asst,
                           tlt2prsn_asst,
                           hygn2prsn_asst,
                           bath2psrn_asst,
                           ampmcare2prsn_asst,
                           any2prsn_asst,
                           n,
                           pct,
                           trgt_qtr,
                           Min(recno),
                           enddate
                  FROM     t3_test
                  GROUP BY provnum,
                           trgt_mo,
                           mcare,
                           bed2prsn_asst,
                           trnsfr2prsn_asst,
                           tlt2prsn_asst,
                           hygn2prsn_asst,
                           bath2psrn_asst,
                           ampmcare2prsn_asst,
                           any2prsn_asst,
                           n,
                           pct,
                           trgt_qtr,
                           enddate

         )
</code>```

When you use min(recno), you don't actually select just one row. you select the minimum of all recno and use the same value for all the rows. To remove less rows, you can use distinct or group by as I have used. I would say that you can remove the rec no from the temp table and use a new auto increment column in the table that you create again to avoid gaps in the ids.

This is to be used in with the method suggested by Gordon Linoff.

Body:
Perhaps I've been staring at the screen too long but I have the following [legacy] table I'm messing with:

describe t3_test;
+--------------------+------------------+------+-----+---------+----------------+
| Field              | Type             | Null | Key | Default | Extra          |
+--------------------+------------------+------+-----+---------+----------------+
| provnum            | varchar(24)      | YES  | MUL | NULL    |                |
| trgt_mo            | datetime         | YES  |     | NULL    |                |
| mcare              | varchar(2)       | YES  |     | NULL    |                |
| bed2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| trnsfr2prsn_asst   | varchar(2)       | YES  |     | NULL    |                |
| tlt2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| hygn2prsn_asst     | varchar(2)       | YES  |     | NULL    |                |
| bath2psrn_asst     | varchar(2)       | YES  |     | NULL    |                |
| ampmcare2prsn_asst | varchar(2)       | YES  |     | NULL    |                |
| any2prsn_asst      | varchar(2)       | YES  |     | NULL    |                |
| n                  | float            | YES  |     | NULL    |                |
| pct                | float            | YES  |     | NULL    |                |
| trgt_qtr           | varchar(12)      | YES  |     | NULL    |                |
| recno              | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| enddate            | date             | YES  |     | NULL    |                |
+--------------------+------------------+------+-----+---------+----------------+
15 rows in set (0.00 sec)

I have data that looks like this..

"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","5767343","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"1",NULL,NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075309","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075308","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,"0",NULL,NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","5767342","2008-12-31"
"555223","2008-10-01 00:00:00","N",NULL,"1",NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075327","2008-12-31"
"555223","2008-10-01 00:00:00","N","1",NULL,NULL,NULL,NULL,NULL,NULL,"36","83.7209","2008Q4","4075323","2008-12-31"
"555223","2008-10-01 00:00:00","Y","1",NULL,NULL,NULL,NULL,NULL,NULL,"4","9.30233","2008Q4","4075325","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"0",NULL,NULL,NULL,NULL,NULL,"3","6.97674","2008Q4","4075310","2008-12-31"
"555223","2008-10-01 00:00:00",NULL,NULL,"1",NULL,NULL,NULL,NULL,NULL,"40","93.0233","2008Q4","4075311","2008-12-31"

The first two lines of the table clearly appear to be dupes (minus the A.I. index "recno"). I've tried a half dozen dupe-removal routines and they are not automatically removed.

At this point I am not sure what exactly is wrong?  Is it possible there's an invisible character somewhere?  Is it possible a letter is in a different character encoding?  When I dump the data to CSV as is listed, it doesn't look any different.

Do you have a delete routine that would work on this file structure that would remove anything that is a dupe (minus the recno field)?  I have been staring at this for two days and for some reason, it escapes me.  (btw, I am aware of the column name anomaly for bathd2psrn_asst - that's not it)

This (original) table has over 13 million records in it.  And is over 3GB in size so I'm looking for the most efficient way to kill dupes.. Any ideas?

Here's an example of one of the dupe-killing techniques I used that did not work:

DELETE a FROM t3_test as a, t3_test as b WHERE
(a.provnum=b.provnum)
AND (a.trgt_mo=b.trgt_mo OR a.trgt_mo IS NULL AND b.trgt_mo IS NULL)
AND (a.mcare=b.mcare OR a.mcare IS NULL AND b.mcare IS NULL)
AND (a.bed2prsn_asst=b.bed2prsn_asst OR a.bed2prsn_asst IS NULL AND b.bed2prsn_asst IS NULL)
AND (a.trnsfr2prsn_asst=b.trnsfr2prsn_asst OR a.trnsfr2prsn_asst IS NULL AND b.trnsfr2prsn_asst IS NULL)
AND (a.tlt2prsn_asst=b.tlt2prsn_asst OR a.tlt2prsn_asst IS NULL AND b.tlt2prsn_asst IS NULL)
AND (a.hygn2prsn_asst=b.hygn2prsn_asst OR a.hygn2prsn_asst IS NULL AND b.hygn2prsn_asst IS NULL)
AND (a.bath2psrn_asst=b.bath2psrn_asst OR a.bath2psrn_asst IS NULL AND b.bath2psrn_asst IS NULL)
AND (a.ampmcare2prsn_asst=b.ampmcare2prsn_asst OR a.ampmcare2prsn_asst IS NULL AND b.ampmcare2prsn_asst IS NULL)
AND (a.any2prsn_asst=b.any2prsn_asst OR a.any2prsn_asst IS NULL AND b.any2prsn_asst IS NULL)
AND (a.n=b.n OR a.n IS NULL AND b.n IS NULL)
AND (a.pct=b.pct OR a.pct IS NULL AND b.pct IS NULL)
AND (a.trgt_qtr=b.trgt_qtr OR a.trgt_qtr IS NULL AND b.trgt_qtr IS NULL)
AND (a.enddate=b.enddate OR a.enddate IS NULL AND b.enddate IS NULL)
AND (a.recno>b.recno);

Body:
Try:

CREATE TABLE t3_new AS
         (
                  SELECT   provnum,
                           trgt_mo,
                           mcare,
                           bed2prsn_asst,
                           trnsfr2prsn_asst,
                           tlt2prsn_asst,
                           hygn2prsn_asst,
                           bath2psrn_asst,
                           ampmcare2prsn_asst,
                           any2prsn_asst,
                           n,
                           pct,
                           trgt_qtr,
                           Min(recno),
                           enddate
                  FROM     t3_test
                  GROUP BY provnum,
                           trgt_mo,
                           mcare,
                           bed2prsn_asst,
                           trnsfr2prsn_asst,
                           tlt2prsn_asst,
                           hygn2prsn_asst,
                           bath2psrn_asst,
                           ampmcare2prsn_asst,
                           any2prsn_asst,
                           n,
                           pct,
                           trgt_qtr,
                           enddate

         )

When you use min(recno), you don't actually select just one row. you select the minimum of all recno and use the same value for all the rows. To remove less rows, you can use distinct or group by as I have used. I would say that you can remove the rec no from the temp table and use a new auto increment column in the table that you create again to avoid gaps in the ids.

This is to be used in with the method suggested by Gordon Linoff.


问:
Add a bookmark that is only javascript, not a URL
I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...

I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code.  It would merely construct a URL based on the current date and then do a window.location = on that URL.

I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript.  I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.

OwnerDisplayName: Matt Dawdy

LastEditorDisplayName: Nickolay

OwnerDisplayName: imranamajeed


问:
Find function and line number where variable gets modified
Let's say that at the beginning of a random function variable $variables['content'] is 1,000 characters long.

This random function is very long, with many nested functions within.

At the end of the function $variables['content'] is only 20 characters long.

How do you find which of nested functions modified this variable?

答:
I think this is a problem code tracing can help with.

In my case I had this variable that was being modified across many functions, and I didn't know where.

The problem is that at some point in the program the variable (a string) was around 40,000 characters, then at the end of the program something had cut it to 20 characters.

To find this information I stepped through the code with the Zend debugger. I found the information I wanted (what functions modified the variable), but it took me a while.

Apparently XDebug does tell you what line numbers, in what functions the variables are modified:

Example, tracing documentation, project home, tutorial article.


问:
Trouble with regex / preg_match / str_replace with complicated string
I am having trouble with a complicated regex.  I have tried this every way I can think of, and I can always only get "almost" there --

I have a block of 5 messages:

```<code>---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

--- Agent 1: Friday 06/09/2017 | 9:02 AM ---

Message 2

--- Agent 1: Friday 04/14/2017 | 10:35 AM ---

Message 3

--- Agent 1: Monday 02/13/2017 | 12:07 AM ---

This

is

message

3

 --- Agent 1: Monday 12/19/2016 | 1:31 PM ---

 Message 4

 --- Agent 1: Monday 10/24/2016 | 10:48 AM ---

 Message 5
</code>```

One problem is that some of them have a space before the first ---.  Another is multi-line messages.

What I am trying to do is peel out all the individual messages.  Basically everything between the first occurrence of --- and every other occurrence thereafter.  I would like my result to look like:

```<code>---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1
</code>```

I have tried variations of ---.*? (---) (matching every other ---) But then I have no way of parsing out the message itself.  I have also tried to manually do this:

```<code>(?<=\: )(.*?)(?= \|)|(\---)(\r\n|\r|\n)(\r\n|\r|\n)(.*?)(\r\n|\r|\n)(\r\n|\r|\n)(\---)
</code>```

Which works until you have a multi-line message. (message 3)

I have also tried multiple steps -- trimming the first or last --- using str_replace but this is foiled by the ones that have a preceding space!

It's always the second --- after the time, the multi-line message, or the preceding space before --- that trips me up.  Does anyone have a more elegant solution than the monstrosity I am creating?

答:
Code

See regex in use here

```<code>-{3}.*[\s\S]*?(?=\s*(?:-{3}|$))
</code>```

Explanation

-{3} Match a hyphen exactly 3 times

.* Match any character any number of times (greedy)

[\s\S]*? Match any character any number of times, but as few as possible (lazy)

(?=\s*(?:-{3}|$)) Positive lookahead ensuring what follows matches

\s* Match any number of whitespace characters

(?:-{3}|$) Match either of the following

-{3} Match a hyphen exactly 3 times

$ Assert position at the end of the line

Body:
I am having trouble with a complicated regex.  I have tried this every way I can think of, and I can always only get "almost" there --

I have a block of 5 messages:

---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

--- Agent 1: Friday 06/09/2017 | 9:02 AM ---

Message 2

--- Agent 1: Friday 04/14/2017 | 10:35 AM ---

Message 3

--- Agent 1: Monday 02/13/2017 | 12:07 AM ---

This

is

message

3

 --- Agent 1: Monday 12/19/2016 | 1:31 PM ---

 Message 4

 --- Agent 1: Monday 10/24/2016 | 10:48 AM ---

 Message 5

One problem is that some of them have a space before the first ---.  Another is multi-line messages.

What I am trying to do is peel out all the individual messages.  Basically everything between the first occurrence of --- and every other occurrence thereafter.  I would like my result to look like:

---Agent 1: Wednesday 08/16/2017 | 11:43 AM ---

Message 1

I have tried variations of ---.*? (---) (matching every other ---) But then I have no way of parsing out the message itself.  I have also tried to manually do this:

(?<=\: )(.*?)(?= \|)|(\---)(\r\n|\r|\n)(\r\n|\r|\n)(.*?)(\r\n|\r|\n)(\r\n|\r|\n)(\---)

Which works until you have a multi-line message. (message 3)

I have also tried multiple steps -- trimming the first or last --- using str_replace but this is foiled by the ones that have a preceding space!

It's always the second --- after the time, the multi-line message, or the preceding space before --- that trips me up.  Does anyone have a more elegant solution than the monstrosity I am creating?

Body:
Code

See regex in use here

-{3}.*[\s\S]*?(?=\s*(?:-{3}|$))

Explanation

-{3} Match a hyphen exactly 3 times

.* Match any character any number of times (greedy)

[\s\S]*? Match any character any number of times, but as few as possible (lazy)

(?=\s*(?:-{3}|$)) Positive lookahead ensuring what follows matches

\s* Match any number of whitespace characters

(?:-{3}|$) Match either of the following

-{3} Match a hyphen exactly 3 times

$ Assert position at the end of the line


问:
IsEnabledChanged in class derived from ButtonBase
I have a control which inherits from the WPF class ButtonBase (System.Windows.Controls.Primitives.ButtonBase).

I would like to define a function which will be called when the IsEnabled property in the base class is changed.

I am probably being really stupid, but I can't find an easy way to do it. (There is no function OnIsEnabledChanged function which can be overridden.)

答:
IsEnabled  is Dependency Property.
So you have to override metadata, Like here:

```<code>public class MyButton : Button
{
    static MyButton()
    {
        MyButton.IsEnabledProperty.OverrideMetadata(typeof(MyButton),
            new FrameworkPropertyMetadata(string.Empty,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault |
                FrameworkPropertyMetadataOptions.Journal,
                FunctionToCallOnPropertyChange, //property changed callback
                null, // coerce value callback
                true, // is animation prohibited
                UpdateSourceTrigger.LostFocus));
    }

    private static void FunctionToCallOnPropertyChange(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        throw new NotImplementedException();
    }
}
</code>```

MSDN Reference

Body:
IsEnabled  is Dependency Property.
So you have to override metadata, Like here:

public class MyButton : Button
{
    static MyButton()
    {
        MyButton.IsEnabledProperty.OverrideMetadata(typeof(MyButton),
            new FrameworkPropertyMetadata(string.Empty,
                FrameworkPropertyMetadataOptions.BindsTwoWayByDefault |
                FrameworkPropertyMetadataOptions.Journal,
                FunctionToCallOnPropertyChange, //property changed callback
                null, // coerce value callback
                true, // is animation prohibited
                UpdateSourceTrigger.LostFocus));
    }

    private static void FunctionToCallOnPropertyChange(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        throw new NotImplementedException();
    }
}

MSDN Reference


问:
Cannot close workbook after running sub with userform
I have a macro that opens a userform to capture a start and end date. After clicking OK on the userform, a file dialog box opens to select an Excel Workbook to open.

Immediately after I run the below sub, I can't close the workbook that is opened by using the 'X' in the top-right corner. I also can't save the workbook by clicking the save icon.

However, if I click on another workbook or switch to a different sheet in the workbook that was opened, and then click back to the one opened by the sub everything works as it's supposed to.

Also, I replace the userform with two input boxes, to capture each of the two dates, I am able to close the workbook that is opened with no issue.

Maybe there's something funny with the userform code?

This is all that is in the userform.

```<code> Private Sub Ok_button_Click()
 call module1.forecast
 unload userform1
 end Sub
</code>```

And this is the main sub.

```<code> Sub forecast()
 dim start_SFY as long
 dim end_SFY as long
 dim filesToOpen as object
 dim wb as workbook

 Application.ScreenUpdating= False

 start_SFY = userform1.textbox1.value
 end_SFY = userform1.textbox2.value

 set filesToOpen = application.fileDialog(msoFileDialogOpen)
 filesToOpen.show
 set wb = application.workbooks.open(filesToOpen.selecteditems(1),false)

 Application.ScreenUpdating= True
 End Sub
</code>```

Here's the sub showing userform1

```<code> Sub run_userform()
 userform1.show
 End Sub
</code>```

Also, here is the Excel version:

Excel 2013 64-bit (15.04753.1003) Part of Microsoft Office 365 ProPlus

Can someone maybe try to replicate the issue that I'm having? I'm wondering if this is an issue related to my employer's version of Excel or something?

This sort of thing has never happened to me before.

Also, I can close the program with VBA. It's just when trying to click the 'X' that it won't close.

Update:

<s>I was able to get the code, with no changes, to work fine at home on Excel 2016. I'm going to get a coworker to test on their system today.</s>

When I was home, I didn't put a button to call the sub on a worksheet. I called it from the VBA editor. After some testing this morning, it seems that the button is the issue. If I call the sub from the VBA editor, I can close the opened workbook. However, if I use a command button (form control, not ActiveX as I get an error saying, "Cannot draw object" whenever I try to add any kind of ActiveX object to a worksheet) the opened workbook will not close.

I think I have found the problem

This issue seems to be with the 'form control command button'. ActiveX was disabled in the Trust Center. When I enabled it and created a command button, I was able to close the opened workbook. I then tried the command form button again, and could not close the opened workbook. I was also successfully able to close the opened workbook when I ran the sub from the sub listbox in the developer tab, and when I place the sub in the Excel Ribbon and ran it from there.

Any idea as to why the control form command button would cause this issue?

答:
The root of the problem is the change to using multiple excel interfaces in 2013.  Microsoft addresses the issue in the Solutions for SDI Issues section of this page.

A workbook cannot be closed by clicking the red "X" Close button when
  that workbook is programmatically opened via a modal user form. To
  work around this issue, it is suggested that you add the following
  code to the user form Layout event procedure and then open the user
  form as modeless

```<code>Private Sub UserForm_Layout()
    Static fSetModal As Boolean
    If fSetModal = False Then
        fSetModal = True
        Me.Hide
        Me.Show 1
    End If
End Sub
</code>```

Another option is to open the workbook window, activate any other
  window, and then reactivate the workbook window. You should now be
  able to close the workbook using the Close button.

So these are the two options they present and one I came up with.

Option 1) You can switch your dialog to modeless using their code, or by setting the ShowModel property to false in your userform.

Option 2) As you discovered, manually switching between workbooks after opening via modal userform resyncs everything.  Not a good solution for the users of my code, and I don't recommend relying on it.

Option 3) It's worth mentioning, if you don't open the file via the userform then there's no issue.  So if last thing the userform needs to do is open the file, you can easily save the file path in a string, unload the troublesome userform and move the workbooks.open call after closing.  Here's an example of what I mean

```<code>Public EDIT_FILE_DIRECTORY As String

Public Sub Main()

    fileOpenerForm.Show

    If EDIT_FILE_DIRECTORY <> "" Then
        Call Workbooks.Open(EDIT_FILE_DIRECTORY)
    End If

End Sub
</code>```

And in the userform something along these lines, where the filename is created based on userform parameters and a listbox selection:

```<code>Private Sub OpenSelectedWorkbooks_Button_Click()

    Dim workbookName As String

    workbookName = selectionList.Item(Me.FileSelection_ListBox.ListIndex + 1)

    EDIT_FILE_DIRECTORY = ROOT_DIR & GetSelectedSubfolder & "\" & workbookName

    Unload Me

End Sub
</code>```

Body:
I have a macro that opens a userform to capture a start and end date. After clicking OK on the userform, a file dialog box opens to select an Excel Workbook to open.

Immediately after I run the below sub, I can't close the workbook that is opened by using the 'X' in the top-right corner. I also can't save the workbook by clicking the save icon.

However, if I click on another workbook or switch to a different sheet in the workbook that was opened, and then click back to the one opened by the sub everything works as it's supposed to.

Also, I replace the userform with two input boxes, to capture each of the two dates, I am able to close the workbook that is opened with no issue.

Maybe there's something funny with the userform code?

This is all that is in the userform.

 Private Sub Ok_button_Click()
 call module1.forecast
 unload userform1
 end Sub

And this is the main sub.

 Sub forecast()
 dim start_SFY as long
 dim end_SFY as long
 dim filesToOpen as object
 dim wb as workbook

 Application.ScreenUpdating= False

 start_SFY = userform1.textbox1.value
 end_SFY = userform1.textbox2.value

 set filesToOpen = application.fileDialog(msoFileDialogOpen)
 filesToOpen.show
 set wb = application.workbooks.open(filesToOpen.selecteditems(1),false)

 Application.ScreenUpdating= True
 End Sub

Here's the sub showing userform1

 Sub run_userform()
 userform1.show
 End Sub

Also, here is the Excel version:

Excel 2013 64-bit (15.04753.1003) Part of Microsoft Office 365 ProPlus

Can someone maybe try to replicate the issue that I'm having? I'm wondering if this is an issue related to my employer's version of Excel or something?

This sort of thing has never happened to me before.

Also, I can close the program with VBA. It's just when trying to click the 'X' that it won't close.

Update:

<s>I was able to get the code, with no changes, to work fine at home on Excel 2016. I'm going to get a coworker to test on their system today.</s>

When I was home, I didn't put a button to call the sub on a worksheet. I called it from the VBA editor. After some testing this morning, it seems that the button is the issue. If I call the sub from the VBA editor, I can close the opened workbook. However, if I use a command button (form control, not ActiveX as I get an error saying, "Cannot draw object" whenever I try to add any kind of ActiveX object to a worksheet) the opened workbook will not close.

I think I have found the problem

This issue seems to be with the 'form control command button'. ActiveX was disabled in the Trust Center. When I enabled it and created a command button, I was able to close the opened workbook. I then tried the command form button again, and could not close the opened workbook. I was also successfully able to close the opened workbook when I ran the sub from the sub listbox in the developer tab, and when I place the sub in the Excel Ribbon and ran it from there.

Any idea as to why the control form command button would cause this issue?

Body:
The root of the problem is the change to using multiple excel interfaces in 2013.  Microsoft addresses the issue in the Solutions for SDI Issues section of this page.

A workbook cannot be closed by clicking the red "X" Close button when
  that workbook is programmatically opened via a modal user form. To
  work around this issue, it is suggested that you add the following
  code to the user form Layout event procedure and then open the user
  form as modeless

Private Sub UserForm_Layout()
    Static fSetModal As Boolean
    If fSetModal = False Then
        fSetModal = True
        Me.Hide
        Me.Show 1
    End If
End Sub

Another option is to open the workbook window, activate any other
  window, and then reactivate the workbook window. You should now be
  able to close the workbook using the Close button.

So these are the two options they present and one I came up with.

Option 1) You can switch your dialog to modeless using their code, or by setting the ShowModel property to false in your userform.

Option 2) As you discovered, manually switching between workbooks after opening via modal userform resyncs everything.  Not a good solution for the users of my code, and I don't recommend relying on it.

Option 3) It's worth mentioning, if you don't open the file via the userform then there's no issue.  So if last thing the userform needs to do is open the file, you can easily save the file path in a string, unload the troublesome userform and move the workbooks.open call after closing.  Here's an example of what I mean

Public EDIT_FILE_DIRECTORY As String

Public Sub Main()

    fileOpenerForm.Show

    If EDIT_FILE_DIRECTORY <> "" Then
        Call Workbooks.Open(EDIT_FILE_DIRECTORY)
    End If

End Sub

And in the userform something along these lines, where the filename is created based on userform parameters and a listbox selection:

Private Sub OpenSelectedWorkbooks_Button_Click()

    Dim workbookName As String

    workbookName = selectionList.Item(Me.FileSelection_ListBox.ListIndex + 1)

    EDIT_FILE_DIRECTORY = ROOT_DIR & GetSelectedSubfolder & "\" & workbookName

    Unload Me

End Sub


问:
no remote repository specified from new rails apps
I am trying to add new rails apps to an existing example repository. I've done this before. I'm using a current Debian on Google Cloud Platform Compute Engine Instance, using Rails 5.1.4 and git 2.11.0.

In short, I can add a new rails app, but if I try to add/commit/push from inside that application's directories, I get errors. If I add/commit/push from above the top level directory for the application, everything works.

Recreating this is simple. I use:

```<code>rails new foo
</code>```

to create a new rails app. I then add the app, commit, and push:

```<code>git add .
git commit -m "testing"
git push
</code>```

Which results in the following output (abbreviated):

[master 95cb836] testing

76 files changed, 1197 insertions(+)

create mode 100644 railapps/foo/.gitignore

create mode 100644 railapps/foo/Gemfile

...

At this point I have no problems. However, when I go into that app and try to do a pull or push, I get the following errors:

```<code>git pull
</code>```

fatal: No remote repository specified.  Please, specify either a URL or a

remote name from which new revisions should be fetched.

```<code>git push
</code>```

Either specify the URL from the command-line or configure a remote repository
  using

git remote add

and then push using the remote name

```<code>git push <name>
</code>```

OK, simple enough, just specify the remote, right?

```<code>git remote add origin git@github.com:pathto/myrepo.git

git push --set-upstream origin master
</code>```

Which results in:

error: src refspec master does not match any.

error: failed to push some refs to 'git@github.com:pathto/myrepo.git'

答:
So I'm not sure when this was added, but by default rails (at least as of version 5.1.4) now initializes a new project as an empty git repo (using git init). A call to

```<code>rails new --help
</code>```

shows

-G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file

but this is misleading; it actually does not call git init at all with this option, thus solving the problem. So if I call

```<code>rails new whatever -G
</code>```

the problem doesn't happen.

Body:
I am trying to add new rails apps to an existing example repository. I've done this before. I'm using a current Debian on Google Cloud Platform Compute Engine Instance, using Rails 5.1.4 and git 2.11.0.

In short, I can add a new rails app, but if I try to add/commit/push from inside that application's directories, I get errors. If I add/commit/push from above the top level directory for the application, everything works.

Recreating this is simple. I use:

rails new foo

to create a new rails app. I then add the app, commit, and push:

git add .
git commit -m "testing"
git push

Which results in the following output (abbreviated):

[master 95cb836] testing

76 files changed, 1197 insertions(+)

create mode 100644 railapps/foo/.gitignore

create mode 100644 railapps/foo/Gemfile

...

At this point I have no problems. However, when I go into that app and try to do a pull or push, I get the following errors:

git pull

fatal: No remote repository specified.  Please, specify either a URL or a

remote name from which new revisions should be fetched.

git push

Either specify the URL from the command-line or configure a remote repository
  using

git remote add

and then push using the remote name

git push <name>

OK, simple enough, just specify the remote, right?

git remote add origin git@github.com:pathto/myrepo.git

git push --set-upstream origin master

Which results in:

error: src refspec master does not match any.

error: failed to push some refs to 'git@github.com:pathto/myrepo.git'

Body:
So I'm not sure when this was added, but by default rails (at least as of version 5.1.4) now initializes a new project as an empty git repo (using git init). A call to

rails new --help

shows

-G, [--skip-git], [--no-skip-git]                      # Skip .gitignore file

but this is misleading; it actually does not call git init at all with this option, thus solving the problem. So if I call

rails new whatever -G

the problem doesn't happen.


问:
How to show replicate number when using sapply in R?
Consider the function below:

```<code> f = function(i) i^2
</code>```

Now we find the output of f for an input vector of length 1000 (or equivalently to run f for 1000 replications) by:

```<code>output = c()
for (i in 1:1000) output[i] = f(i)
</code>```

In the case of running time-consuming functions, we might like to know which replication we are. So we can use:

```<code>output = c()
for (i in 1:1000) {output[i] = f(i); cat("Replicate=", i, "\n")}
</code>```

This gives the replicate number at the end of each replication. Now what if we use sapply instead of for:

```<code> output = sapply(1:1000, function(i) f(i))
</code>```

How can we see which replicate we are while using sapply?  Note that I tried adding cat("Replicate=", i, "\n") in the definition of f. This shows the replicate number, but only at the end of the entire run and not at the end of each replicate.

答:
you say you have tried it, but this code works just great for me:

```<code>result <-  sapply(1:1000, function(x) {
  print(x)  # cat works too
  return(x^2)
})
</code>```

You may have forgotten the curly brackets! :-)

Body:
Consider the function below:

 f = function(i) i^2

Now we find the output of f for an input vector of length 1000 (or equivalently to run f for 1000 replications) by:

output = c()
for (i in 1:1000) output[i] = f(i)

In the case of running time-consuming functions, we might like to know which replication we are. So we can use:

output = c()
for (i in 1:1000) {output[i] = f(i); cat("Replicate=", i, "\n")}

This gives the replicate number at the end of each replication. Now what if we use sapply instead of for:

 output = sapply(1:1000, function(i) f(i))

How can we see which replicate we are while using sapply?  Note that I tried adding cat("Replicate=", i, "\n") in the definition of f. This shows the replicate number, but only at the end of the entire run and not at the end of each replicate.

Body:
you say you have tried it, but this code works just great for me:

result <-  sapply(1:1000, function(x) {
  print(x)  # cat works too
  return(x^2)
})

You may have forgotten the curly brackets! :-)


问:
PlayerPaddle won't stop spinning
I'm trying to rotate my paddle once at a keypress, but at the moment, my turnLeft() won't stop spinning my paddle, while my turnRight() won't even start.

Here is where I call this in my GameScene.

```<code>class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.player_paddle = classes.PlayerPaddle(screen_size)
        self.my_font = pygame.font.SysFont("Arial", 50)

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.player_paddle.direction = -1
                elif event.key == pygame.K_DOWN:
                    self.player_paddle.direction = 1
                elif event.key == pygame.K_LEFT:
                    self.player_paddle.turnLeft()
                elif event.key == pygame.K_RIGHT:
                    self.player_paddle.turnRight()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP and self.player_paddle.direction == -1:
                    self.player_paddle.direction = 0
                elif event.key == pygame.K_DOWN and self.player_paddle.direction == 1:
                    self.player_paddle.direction = 0

    def Update(self):
        self.player_paddle.update()
</code>```

And Here is my image class, which PlayerPaddle inherits from.

```<code>class Image(pygame.sprite.Sprite):

    def __init__(self, screen_size, color=(255,0,0)):
        super().__init__()
        self.screen_size = screen_size

        self.angle = 0
        #self.dir = 0

        self.original_image = pygame.image.load('naruto.png').convert()
        self.colorkey = self.original_image.get_at((0,0))

        self.original_image = pygame.transform.scale(self.original_image, (20, 100))
        self.rect = self.original_image.get_rect()

        self.update()

    def turnLeft(self):

        self.angle = (self.angle - 45) % 360

    def turnRight(self):
        print("entered")
        self.angle = (self.angle + 30) % 360

    def update(self):

        self.image = pygame.transform.rotate(self.original_image, self.angle).convert()
        self.image.set_colorkey(self.colorkey)

        #self.rect = self.image.get_rect(center = screen_rect.center)
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)

        self.olist = self.mask.outline()

        if self.olist:
            pygame.draw.lines(self.image, (0, 0, 0), 3, self.olist)

    def draw(self, screen):
        screen.blit(self.original_image, self.rect)
</code>```

Along with my PlayerPaddle class:

```<code>class PlayerPaddle(Image):

    def __init__(self, screen_size, color = (255,0,0)):

        self.centerx = 10
        self.centery = screen_size[1] // 2

        self.height = 100
        self.width = 20

        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, color = (255, 0, 0))

    def update(self):

        super().update()
        self.centery += self.direction*self.speed

        self.rect.center = (self.centerx, self.centery)

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1
</code>```

I tested my rotation code in another file and it worked perfectly (one key press is one rotation) so I am currently befuddled as to why this is happening right now.

EDIT: SceneBase class

```<code>class SceneBase:
    number_of_players = None
    is_game_over = False
    third_player_mode = None

    def __init__(self):
        self.next = self

    def ProcessInput(self, events, pressed_keys):
        pass

    def Update(self):
        pass

    def Render(self, screen):
        pass

    def SwitchToScene(self, next_scene):
        self.next = next_scene

    def Terminate(self):
        self.SwitchToScene(None)
</code>```

答:
I believe this has to do with your self.dir variable.  I would expect a turning function to simply apply a turn for every iteration its called, not update the turn value itself after wards.  Lets think about this.  You have three functions that will turn the character.   Two only called when you press left or right, and one that is called everysingle iteration, character.update().

So if you press left or right, assuming your turn functions apply a rotate properly (they don't) you'll just get a continuous rotation:

```<code> def update(self):

    self.angle = (self.angle + self.dir) % 360
    self.image = pygame.transform.rotate(self.original_image, self.angle).convert()
</code>```

Now the issue is that when you first call either turn operation you won't rotate at all.  In each function you set your angle (which is actually your real rotation angle, its what gets passed into the pygame transform function) to 0, and then update it with (self.angle + self.dir) % 360 and since self.dir also starts at zero, you again are left with zero...

So at the start, the very first instance of your turn event, you won't actually turn anything.   Then you do something odd...

```<code>    self.dir -= 45
    if self.dir < 0:
        self.dir = 315
</code>```

So, you start out with self.dir = 315 on the next event for turn left, (0 + 315) % 360 = 315 so you just rotated your entire image 315 degrees. Oh and now you will also be rotating your image by 315 degrees constantly in your update function as well, since it is always called, and you update self.angle with + self.dir every time, which stays 315 until you press the event key again.

So don't update that in the update function if you don't want that to happen constantly.

Finally, if you then go ahead and press the right button, you won't actually turn right, well, ever because your angles are always positive.  pygame requires negative angles for opposite rotations.

So how do you fix this?

don't update the rotation in the update() function to stop constant rotation

offset the current angle by a constant value ( like 10 or 30 degrees) in the direction you want. Don't use self.dir, change the sign on your angle, and figure out the positive or negative angle to rotate to for the pygame.transform.rotate.

Eg, if you want to rotate it counter clock wise, simply use the normal positive angle value, add the value of the angle you want to use, add 360 if its negative, and do % 360 like before

If you want to rotate clock wise, subtract your constant value from your self.angle then subtract 360 if its positive, and % -360

Title: PlayerPaddle won't stop spinning

Body:
I'm trying to rotate my paddle once at a keypress, but at the moment, my turnLeft() won't stop spinning my paddle, while my turnRight() won't even start.

Here is where I call this in my GameScene.

class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.player_paddle = classes.PlayerPaddle(screen_size)
        self.my_font = pygame.font.SysFont("Arial", 50)

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.player_paddle.direction = -1
                elif event.key == pygame.K_DOWN:
                    self.player_paddle.direction = 1
                elif event.key == pygame.K_LEFT:
                    self.player_paddle.turnLeft()
                elif event.key == pygame.K_RIGHT:
                    self.player_paddle.turnRight()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP and self.player_paddle.direction == -1:
                    self.player_paddle.direction = 0
                elif event.key == pygame.K_DOWN and self.player_paddle.direction == 1:
                    self.player_paddle.direction = 0

    def Update(self):
        self.player_paddle.update()

And Here is my image class, which PlayerPaddle inherits from.

class Image(pygame.sprite.Sprite):

    def __init__(self, screen_size, color=(255,0,0)):
        super().__init__()
        self.screen_size = screen_size

        self.angle = 0
        #self.dir = 0

        self.original_image = pygame.image.load('naruto.png').convert()
        self.colorkey = self.original_image.get_at((0,0))

        self.original_image = pygame.transform.scale(self.original_image, (20, 100))
        self.rect = self.original_image.get_rect()

        self.update()

    def turnLeft(self):

        self.angle = (self.angle - 45) % 360

    def turnRight(self):
        print("entered")
        self.angle = (self.angle + 30) % 360

    def update(self):

        self.image = pygame.transform.rotate(self.original_image, self.angle).convert()
        self.image.set_colorkey(self.colorkey)

        #self.rect = self.image.get_rect(center = screen_rect.center)
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)

        self.olist = self.mask.outline()

        if self.olist:
            pygame.draw.lines(self.image, (0, 0, 0), 3, self.olist)

    def draw(self, screen):
        screen.blit(self.original_image, self.rect)

Along with my PlayerPaddle class:

class PlayerPaddle(Image):

    def __init__(self, screen_size, color = (255,0,0)):

        self.centerx = 10
        self.centery = screen_size[1] // 2

        self.height = 100
        self.width = 20

        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, color = (255, 0, 0))

    def update(self):

        super().update()
        self.centery += self.direction*self.speed

        self.rect.center = (self.centerx, self.centery)

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1

I tested my rotation code in another file and it worked perfectly (one key press is one rotation) so I am currently befuddled as to why this is happening right now.

EDIT: SceneBase class

class SceneBase:
    number_of_players = None
    is_game_over = False
    third_player_mode = None

    def __init__(self):
        self.next = self

    def ProcessInput(self, events, pressed_keys):
        pass

    def Update(self):
        pass

    def Render(self, screen):
        pass

    def SwitchToScene(self, next_scene):
        self.next = next_scene

    def Terminate(self):
        self.SwitchToScene(None)

Body:
I believe this has to do with your self.dir variable.  I would expect a turning function to simply apply a turn for every iteration its called, not update the turn value itself after wards.  Lets think about this.  You have three functions that will turn the character.   Two only called when you press left or right, and one that is called everysingle iteration, character.update().

So if you press left or right, assuming your turn functions apply a rotate properly (they don't) you'll just get a continuous rotation:

 def update(self):

    self.angle = (self.angle + self.dir) % 360
    self.image = pygame.transform.rotate(self.original_image, self.angle).convert()

Now the issue is that when you first call either turn operation you won't rotate at all.  In each function you set your angle (which is actually your real rotation angle, its what gets passed into the pygame transform function) to 0, and then update it with (self.angle + self.dir) % 360 and since self.dir also starts at zero, you again are left with zero...

So at the start, the very first instance of your turn event, you won't actually turn anything.   Then you do something odd...

    self.dir -= 45
    if self.dir < 0:
        self.dir = 315

So, you start out with self.dir = 315 on the next event for turn left, (0 + 315) % 360 = 315 so you just rotated your entire image 315 degrees. Oh and now you will also be rotating your image by 315 degrees constantly in your update function as well, since it is always called, and you update self.angle with + self.dir every time, which stays 315 until you press the event key again.

So don't update that in the update function if you don't want that to happen constantly.

Finally, if you then go ahead and press the right button, you won't actually turn right, well, ever because your angles are always positive.  pygame requires negative angles for opposite rotations.

So how do you fix this?

don't update the rotation in the update() function to stop constant rotation

offset the current angle by a constant value ( like 10 or 30 degrees) in the direction you want. Don't use self.dir, change the sign on your angle, and figure out the positive or negative angle to rotate to for the pygame.transform.rotate.

Eg, if you want to rotate it counter clock wise, simply use the normal positive angle value, add the value of the angle you want to use, add 360 if its negative, and do % 360 like before

If you want to rotate clock wise, subtract your constant value from your self.angle then subtract 360 if its positive, and % -360


问:
Solving an Equation System in SciPy
i am trying to fit an exponential curve through three given Points. But i get only very wrong results of fsolve or actual 0. I need this for my Bachelor Thesis so if anyone knows a better solution for the problem, it would be very kind to tell me this solution.

```<code>from numpy import *
from scipy.optimize import *

def myFunction(variables):
    x1 = 1
    y1 = 100
    x2 = 5
    y2 = 50
    x3 = 10
    y3 = 1
    (a,k,b) = variables

    y1 = a*exp(-x1*k)+b
    y2 = a*exp(-x2*k)+b
    y3 = a*exp(-x3*k)+b
    #0 = a*k**2 * exp(-x1+k)
    return ([a, k, b])

z = fsolve(myFunction,(1,0.1,5))
print(z)
</code>```

this is my problem, i need to fit an e function through this 3 given points, and in addition the second derivation of the forumla should be 0

edit: 06.12.17
in some way i have now an improvement with a polynom, but does not really fit like it should.
The second Maximum should not be there.. :D

```<code>from numpy import *
from scipy.optimize import *
import matplotlib.pyplot as plt

def myFunction(z):
    a = z[0]
    b = z[1]
    c = z[2]
    d = z[3]
    e = z[4]
    f = z[5]
    g = z[6]

    x = [0, 10 ,15 ,20 ,50 ,100]
    y = [10 ,90 ,100 ,90 ,50 ,10]
    s = [0, 10, 1, 0, 0, 0]

    F = empty((8))
    F[0] = a*x[0]**6 + b*x[0]**5 + c*x[0]**4 + d*x[0]**3 + e*x[0]**2 + f*x[0]**1 + g - y[0]
    F[1] = a*x[1]**6 + b*x[1]**5 + c*x[1]**4 + d*x[1]**3 + e*x[1]**2 + f*x[1]**1 + g - y[1]
    F[2] = a*x[2]**6 + b*x[2]**5 + c*x[2]**4 + d*x[2]**3 + e*x[2]**2 + f*x[2]**1 + g - y[2]
    F[3] = a*x[3]**6 + b*x[3]**5 + c*x[3]**4 + d*x[3]**3 + e*x[3]**2 + f*x[3]**1 + g - y[3]
    F[4] = a*x[4]**6 + b*x[4]**5 + c*x[4]**4 + d*x[4]**3 + e*x[4]**2 + f*x[4]**1 + g - y[4]
    F[5] = a*x[5]**6 + b*x[5]**5 + c*x[5]**4 + d*x[5]**3 + e*x[5]**2 + f*x[5]**1 + g - y[5]
    F[6] = 6*a*x[3]**5 + 5*b*x[3]**4 + 4*c*x[3]**3 + 3*d*x[3]**2 + 2*e*x[3]**1 + f - s[3]
    F[7] = 6*a*x[5]**5 + 5*b*x[5]**4 + 4*c*x[5]**3 + 3*d*x[5]**2 + 2*e*x[5]**1 + f - s[5]
    return F

zGuess = array([1,1,1,1,1,1,1,1])
z = fsolve(myFunction,zGuess)
print(z)
x_axis = linspace(0,100,100)

y_axis = z[0]*x_axis**6 + z[1]*x_axis**5 + z[2]*x_axis**4 + z[3]*x_axis**3 + z[4]*x_axis**2 + z[5]*x_axis**1 + z[6]
plt.plot(x_axis, y_axis)
plt.show()
</code>```

edit 07.12.17
the whole signal should look like the data of the second example. But the difficulty is in the part of the first example. My suggestion was to use 2 polynoms, but my prof would prefer an polynom x<20 and an e function x>20. The overlapping of both should also be very smooth.

答:
Well fsolve find the roots of a function, does not really do a non-linear fit. I must admit I don't actually quite get what you want to achieve with your code. If you want to do a nonlinear fit (since you are talking about exponential functions here) you may want to check my notebook here https://github.com/michelucci/Regression-with-Python/blob/master/(Non)%20linear%20fit%20in%20Python.ipynb that I hope can point you in the right direction. It contains first a part on linear regression and then a non-linear tutorial.

You can check curve_fit() python function in the scipy.optimize library. That should help you with what you want to do.

Let me know if that helps you.

You may also want to check this link to better understand what a non-linear fit is https://en.wikipedia.org/wiki/Nonlinear_regression

Best, Umberto

Title: Solving an Equation System in SciPy

Body:
i am trying to fit an exponential curve through three given Points. But i get only very wrong results of fsolve or actual 0. I need this for my Bachelor Thesis so if anyone knows a better solution for the problem, it would be very kind to tell me this solution.

from numpy import *
from scipy.optimize import *

def myFunction(variables):
    x1 = 1
    y1 = 100
    x2 = 5
    y2 = 50
    x3 = 10
    y3 = 1
    (a,k,b) = variables

    y1 = a*exp(-x1*k)+b
    y2 = a*exp(-x2*k)+b
    y3 = a*exp(-x3*k)+b
    #0 = a*k**2 * exp(-x1+k)
    return ([a, k, b])

z = fsolve(myFunction,(1,0.1,5))
print(z)

this is my problem, i need to fit an e function through this 3 given points, and in addition the second derivation of the forumla should be 0

edit: 06.12.17
in some way i have now an improvement with a polynom, but does not really fit like it should.
The second Maximum should not be there.. :D

from numpy import *
from scipy.optimize import *
import matplotlib.pyplot as plt

def myFunction(z):
    a = z[0]
    b = z[1]
    c = z[2]
    d = z[3]
    e = z[4]
    f = z[5]
    g = z[6]

    x = [0, 10 ,15 ,20 ,50 ,100]
    y = [10 ,90 ,100 ,90 ,50 ,10]
    s = [0, 10, 1, 0, 0, 0]

    F = empty((8))
    F[0] = a*x[0]**6 + b*x[0]**5 + c*x[0]**4 + d*x[0]**3 + e*x[0]**2 + f*x[0]**1 + g - y[0]
    F[1] = a*x[1]**6 + b*x[1]**5 + c*x[1]**4 + d*x[1]**3 + e*x[1]**2 + f*x[1]**1 + g - y[1]
    F[2] = a*x[2]**6 + b*x[2]**5 + c*x[2]**4 + d*x[2]**3 + e*x[2]**2 + f*x[2]**1 + g - y[2]
    F[3] = a*x[3]**6 + b*x[3]**5 + c*x[3]**4 + d*x[3]**3 + e*x[3]**2 + f*x[3]**1 + g - y[3]
    F[4] = a*x[4]**6 + b*x[4]**5 + c*x[4]**4 + d*x[4]**3 + e*x[4]**2 + f*x[4]**1 + g - y[4]
    F[5] = a*x[5]**6 + b*x[5]**5 + c*x[5]**4 + d*x[5]**3 + e*x[5]**2 + f*x[5]**1 + g - y[5]
    F[6] = 6*a*x[3]**5 + 5*b*x[3]**4 + 4*c*x[3]**3 + 3*d*x[3]**2 + 2*e*x[3]**1 + f - s[3]
    F[7] = 6*a*x[5]**5 + 5*b*x[5]**4 + 4*c*x[5]**3 + 3*d*x[5]**2 + 2*e*x[5]**1 + f - s[5]
    return F

zGuess = array([1,1,1,1,1,1,1,1])
z = fsolve(myFunction,zGuess)
print(z)
x_axis = linspace(0,100,100)

y_axis = z[0]*x_axis**6 + z[1]*x_axis**5 + z[2]*x_axis**4 + z[3]*x_axis**3 + z[4]*x_axis**2 + z[5]*x_axis**1 + z[6]
plt.plot(x_axis, y_axis)
plt.show()

edit 07.12.17
the whole signal should look like the data of the second example. But the difficulty is in the part of the first example. My suggestion was to use 2 polynoms, but my prof would prefer an polynom x<20 and an e function x>20. The overlapping of both should also be very smooth.