问:
class file contains wrong class error while accessing jar file
I am trying to create a JAR file for my two source codes Serial.java and DBaccess.java.

I am doing this as a learning exercise ,the classes do not do anything,they are dummy classes.

OS - Windows 10

JDK - GraalVM

Listing of my source code.(Serial.java)

```<code>public class Serial
{

    void open()
    {
        System.out.println("Serial Port Opened - 0");
    }
}
</code>```

Listing of my source code.(DBaccess.java)

```<code>public class DBaccess
{

    String DBname = "MySerialDB";

    void write()
    {
        System.out.println("Data Written to DB - W");
    }

    void read()
    {
        System.out.println("Data Read from DB - R");
    }
}
</code>```

I have compiled them to .class files using javac

javac DBaccess.java

javac Serial.java

I  created a folder

```<code>H:\myclass\com\mydomain\util
</code>```

and manually copied the class files to util directory

and created a jar file myjar.jar of this format

```<code>H:\myclass>H:\graalvm\bin\jar tf myjar.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/mydomain/
com/mydomain/util/
com/mydomain/util/DBaccess.class
com/mydomain/util/Serial.class
</code>```

I want my source code JMainEntry.java to access the classes in the above jar file myjar.jar.

JMainEntry.java

```<code>//Main Class of the Program

import com.mydomain.util.*;

public class JMainEntry
{
    public static void main (String[] Args)
    {

        Serial myS = new Serial();
        myS.open();

        DBaccess myDB = new DBaccess();

        myDB.write();
        myDB.read();
    }
}
</code>```

When i compile the code

```<code>H:\jar-compile>H:\graalvm\bin\javac -cp myjar.jar JMainEntry.java
</code>```

I am getting the error

```<code>bad class file: myjar.jar(/com/mydomain/util/Serial.class)
    class file contains wrong class: Serial
    Please remove or make sure it appears in the correct subdirectory of the classpath.
</code>```

I am not able to understand why javac is complaining like this,Can anyone help?

答:
bad class file: myjar.jar(/com/mydomain/util/Serial.class)

Make sure you declare

```<code>package com.mydomain.util
</code>```

at the top of all .java files in the directory com/mydomain/util, including Serial.java. To understand this better, read about packages.

Body:
I am trying to create a JAR file for my two source codes Serial.java and DBaccess.java.

I am doing this as a learning exercise ,the classes do not do anything,they are dummy classes.

OS - Windows 10

JDK - GraalVM

Listing of my source code.(Serial.java)

public class Serial
{

    void open()
    {
        System.out.println("Serial Port Opened - 0");
    }
}

Listing of my source code.(DBaccess.java)

public class DBaccess
{

    String DBname = "MySerialDB";

    void write()
    {
        System.out.println("Data Written to DB - W");
    }

    void read()
    {
        System.out.println("Data Read from DB - R");
    }
}

I have compiled them to .class files using javac

javac DBaccess.java

javac Serial.java

I  created a folder

H:\myclass\com\mydomain\util

and manually copied the class files to util directory

and created a jar file myjar.jar of this format

H:\myclass>H:\graalvm\bin\jar tf myjar.jar
META-INF/
META-INF/MANIFEST.MF
com/
com/mydomain/
com/mydomain/util/
com/mydomain/util/DBaccess.class
com/mydomain/util/Serial.class

I want my source code JMainEntry.java to access the classes in the above jar file myjar.jar.

JMainEntry.java

//Main Class of the Program

import com.mydomain.util.*;

public class JMainEntry
{
    public static void main (String[] Args)
    {

        Serial myS = new Serial();
        myS.open();

        DBaccess myDB = new DBaccess();

        myDB.write();
        myDB.read();
    }
}

When i compile the code

H:\jar-compile>H:\graalvm\bin\javac -cp myjar.jar JMainEntry.java

I am getting the error

bad class file: myjar.jar(/com/mydomain/util/Serial.class)
    class file contains wrong class: Serial
    Please remove or make sure it appears in the correct subdirectory of the classpath.

I am not able to understand why javac is complaining like this,Can anyone help?

Body:
bad class file: myjar.jar(/com/mydomain/util/Serial.class)

Make sure you declare

package com.mydomain.util

at the top of all .java files in the directory com/mydomain/util, including Serial.java. To understand this better, read about packages.


来源: stackexchange

问:
How to delete spacing after row is complete in c++?
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to happen when the last row is full and no date is carried over.</p>
```<code>// Extracted..
#include <iostream>

         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
          std::cout << day << " ";
         }
         if (day != days_per)
         {
          std::cout << " ";
         }
         }
</code>```

答:
you dont need to delete anything, just dont produce it. Your probelm is here

```<code>         if (day >= 9)
        {
            std::cout << day << '\n';
        }
        else
        {
            std::cout << day << '\n' << " ";
        }
</code>```

when you come to the end of a line you do a line feed if even it was the last day.

change to

```<code>     if (day >= 9)
     {
        std::cout << day;
        if (day != days_per) std::cout << '\n';
     }
     else
     {
        std::cout << day << '\n' << " ";
     }
</code>```

you dont need it on the other path because thats never hit at the end of the month (day is alwasy 2 digits)

ContentLicense: CC BY-SA 4.0

Body:
I have been working on a project. I am limited to using a few libraries so any additional library would not be helpful. So far my project works, but I am noticing an extra space after the last row is completed. How do I fix this extra spacing issue? please help! There's a space at the bottom... and this only seems to happen when the last row is full and no date is carried over.

// Extracted..
#include <iostream>

         if (day >= 9)
         {
            std::cout << day;
         }
         else
         {
          std::cout << day << " ";
         }
         if (day != days_per)
         {
          std::cout << " ";
         }
         }

Body:
you dont need to delete anything, just dont produce it. Your probelm is here

         if (day >= 9)
        {
            std::cout << day << '\n';
        }
        else
        {
            std::cout << day << '\n' << " ";
        }

when you come to the end of a line you do a line feed if even it was the last day.

change to

     if (day >= 9)
     {
        std::cout << day;
        if (day != days_per) std::cout << '\n';
     }
     else
     {
        std::cout << day << '\n' << " ";
     }

you dont need it on the other path because thats never hit at the end of the month (day is alwasy 2 digits)


问:
Automatic "fancy" comment insertion with Vim
I like to have comments like this in my C code:

```<code>/********************************************************
 * Blah
 ********************************************************/
</code>```

But I get tired of typing all those asterisks, and copy/pasting can also get annoying. I was wondering if I could possibly create a macro with Vim so that if I press (for example) CTRL+L, it'll automatically insert that structure in my code and align the cursor in the middle (where the actual comment is written).

Any advice would be appreciated. Thanks!

答:
Heh, just today I was beefing up my own support for this (as these headers are mandated by company coding standard).

```<code>iabbrev //== // (96 equal characters)<Enter>//<Enter>// (96 equal characters)<C-O>k
iabbrev //-- // (96 dashes)<Enter>//<Enter>// (96 dashes)<C-O>k
</code>```

These allow me to type //== and when I press space the whole thing is entered and I'm left with the cursor "in the middle" where I want it.

So- for the OP, if you want to use Ctrl-L, do something like this:

```<code>inoremap <C-L> /*****<Enter> * <Enter>*****<C-O>k
</code>```

(I like abbreviations myself, though...)

Since there are other points in our coding standard where we need to extend dashes and equals out to column 100, I whipped this up today:

```<code>iabbrev <expr> === InsertTo99Width('===')
iabbrev <expr> --- InsertTo99Width('---')

function! InsertTo99Width(insertion)
    let l:line = getline('.')
    let l:linelen = strlen(l:line)
    let l:col = col('.')
    let l:numchars = (99 - col)

    let l:inserted = a:insertion
    if (l:linelen <= l:col) && (l:numchars > 0)
        let l:numchars += len(l:inserted)
        while len(l:inserted) < l:numchars
            let l:inserted = l:inserted . l:inserted
        endwhile
        return l:inserted[0 : l:numchars]
    else
        return l:inserted
    endif
endfunction
</code>```

(I'm sort of a vim scripting newb so there may be an easier way to make a string of N characters long, but this allows arbitrary strings of arbitrary length to be repeated so if you like dash-space-equal-space or something, it'll still look "nice".)

Anyway finally- you can use <expr> in the inoremap too if you want, so you can make your asterisks go to a set width based on the output of a function.  There's a lot of power in there, but it may take some fiddling to get it just the way you want...

ContentLicense: CC BY-SA 3.0

Body:
I like to have comments like this in my C code:

/********************************************************
 * Blah
 ********************************************************/

But I get tired of typing all those asterisks, and copy/pasting can also get annoying. I was wondering if I could possibly create a macro with Vim so that if I press (for example) CTRL+L, it'll automatically insert that structure in my code and align the cursor in the middle (where the actual comment is written).

Any advice would be appreciated. Thanks!

Body:
Heh, just today I was beefing up my own support for this (as these headers are mandated by company coding standard).

iabbrev //== // (96 equal characters)<Enter>//<Enter>// (96 equal characters)<C-O>k
iabbrev //-- // (96 dashes)<Enter>//<Enter>// (96 dashes)<C-O>k

These allow me to type //== and when I press space the whole thing is entered and I'm left with the cursor "in the middle" where I want it.

So- for the OP, if you want to use Ctrl-L, do something like this:

inoremap <C-L> /*****<Enter> * <Enter>*****<C-O>k

(I like abbreviations myself, though...)

Since there are other points in our coding standard where we need to extend dashes and equals out to column 100, I whipped this up today:

iabbrev <expr> === InsertTo99Width('===')
iabbrev <expr> --- InsertTo99Width('---')

function! InsertTo99Width(insertion)
    let l:line = getline('.')
    let l:linelen = strlen(l:line)
    let l:col = col('.')
    let l:numchars = (99 - col)

    let l:inserted = a:insertion
    if (l:linelen <= l:col) && (l:numchars > 0)
        let l:numchars += len(l:inserted)
        while len(l:inserted) < l:numchars
            let l:inserted = l:inserted . l:inserted
        endwhile
        return l:inserted[0 : l:numchars]
    else
        return l:inserted
    endif
endfunction

(I'm sort of a vim scripting newb so there may be an easier way to make a string of N characters long, but this allows arbitrary strings of arbitrary length to be repeated so if you like dash-space-equal-space or something, it'll still look "nice".)

Anyway finally- you can use <expr> in the inoremap too if you want, so you can make your asterisks go to a set width based on the output of a function.  There's a lot of power in there, but it may take some fiddling to get it just the way you want...


问:
"cannot unpack non-iterable NoneType object" after Windows 11 update
I have an auto-click program to check my office attendance.
However, this program do not work after Windows 11 update yesterday.
The part of the program code and error message (not a full code) is below:

Program:

```<code>#!/usr/bin/env python
# coding: utf-8

# In[ ]:
import pyautogui
import time

# Find and Click ERP icon
pyautogui.doubleClick('erp.png')

# Find and Click Personal button
while True:
    try:
        pyautogui.click('personal.png')
        break
    except:
        time.sleep(0.1)
</code>```

Error:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_11732/4182218478.py in <module>
      7
      8 # Find and Click ERP icon
----> 9 pyautogui.doubleClick('erp.png')
     10
     11 # Find and Click Personal button
</code>```

Nothing is changed, including the filename and directory.
I don't understand the reason for the error.

答:
It works!
The icon shape of the first png image file is changed due to Windows 11 update. I replaced the png file from the old to the new version, and it does not have any errors.</p>

Body:
I have an auto-click program to check my office attendance.
However, this program do not work after Windows 11 update yesterday.
The part of the program code and error message (not a full code) is below:

Program:

#!/usr/bin/env python
# coding: utf-8

# In[ ]:
import pyautogui
import time

# Find and Click ERP icon
pyautogui.doubleClick('erp.png')

# Find and Click Personal button
while True:
    try:
        pyautogui.click('personal.png')
        break
    except:
        time.sleep(0.1)

Error:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
C:\Users\ADMINI~1\AppData\Local\Temp/ipykernel_11732/4182218478.py in <module>
      7
      8 # Find and Click ERP icon
----> 9 pyautogui.doubleClick('erp.png')
     10
     11 # Find and Click Personal button

Nothing is changed, including the filename and directory.
I don't understand the reason for the error.


问:
Automatically deploying docker-compose on DigitalOcean via Github
I am a newbie when it comes to docker.
I have a web app that contains 4 services. I manage to create a docker-compose for it.

I would like now to publish it.
My plan is to

upload the whole repository with the compose file and the source codes to a private repository in github.

then create a droplet in digital ocean

I would like to be able to publish the code easily through github only. that it will be automatically uploaded to the server and restart the required services.
what would be the best approach?

答:
Yes, there is. There is an App platefrom in Digitalocean. Once you use it to deploy your docker image and whenever you update docker image via github, your site will be rebuilding (ci/cd).
I hope this can be help for you.</p>


问:
Update a variable after executing a future function
I have a function called ff which takes 2 images, and returns an outputimage , I"d like to update the original image, when the user taps on any of the style images, and display the outputimage instead of the original one . I know I should use setstate somehow, but I'm confused on how and where

code :

```<code>Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();

  var original_image = showtime.loadoriginalImage(originalImagePath);

  var style_image = showtime.loadStyleImage(styleImagePath);

  var output_image = showtime.transfer(await original_image, await style_image);
  return output_image;
}

class second extends StatefulWidget {
  const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;

  @override
  State<second> createState() => _secondState();
}

class _secondState extends State<second> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(
                  child: Image.file(File(widget.image
                      .path))))), // this is the original image which i'd like to replace once user taps on the style image
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: CarouselSlider.builder(
          itemCount: imageList.length,
          options: CarouselOptions(
            autoPlay: true,
            aspectRatio: 2.0,
            enlargeCenterPage: true,
          ),
          itemBuilder: (context, index, realIdx) {
            return Container(
                child: Center(
              child: GestureDetector(
                  onTap: () => ff(imageList[index], widget.image.path),
                  child: Image.network(imageList[index],
                      fit: BoxFit.cover, width: 1000)),
            ));
          },
        ),
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}
</code>```

答:
Try this:</p>
```<code>Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();

  var original_image = showtime.loadoriginalImage(originalImagePath);

  var style_image = showtime.loadStyleImage(styleImagePath);

  var output_image = showtime.transfer(await original_image, await style_image);
  return output_image;
}

class second extends StatefulWidget {
  const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;

  @override
  State<second> createState() => _secondState();
}

class _secondState extends State<second> {

  late XFile _image;

  initState(){
    _image = widget.image;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(
                  child: Image.file(File(image
                      .path))))), // this is the original image which i'd like to replace once user taps on the style image
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: CarouselSlider.builder(
          itemCount: imageList.length,
          options: CarouselOptions(
            autoPlay: true,
            aspectRatio: 2.0,
            enlargeCenterPage: true,
          ),
          itemBuilder: (context, index, realIdx) {
            return Container(
                child: Center(
              child: GestureDetector(
onTap: () {
  ff(imageList[index], widget.image.path).then((value){
   setState((){
     _image = value;
   });
  });
},                  child: Image.network(imageList[index],
                      fit: BoxFit.cover, width: 1000)),
            ));
          },
        ),
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}
</code>```

Body:
I have a function called ff which takes 2 images, and returns an outputimage , I"d like to update the original image, when the user taps on any of the style images, and display the outputimage instead of the original one . I know I should use setstate somehow, but I'm confused on how and where

code :

Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();

  var original_image = showtime.loadoriginalImage(originalImagePath);

  var style_image = showtime.loadStyleImage(styleImagePath);

  var output_image = showtime.transfer(await original_image, await style_image);
  return output_image;
}

class second extends StatefulWidget {
  const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;

  @override
  State<second> createState() => _secondState();
}

class _secondState extends State<second> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(
                  child: Image.file(File(widget.image
                      .path))))), // this is the original image which i'd like to replace once user taps on the style image
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: CarouselSlider.builder(
          itemCount: imageList.length,
          options: CarouselOptions(
            autoPlay: true,
            aspectRatio: 2.0,
            enlargeCenterPage: true,
          ),
          itemBuilder: (context, index, realIdx) {
            return Container(
                child: Center(
              child: GestureDetector(
                  onTap: () => ff(imageList[index], widget.image.path),
                  child: Image.network(imageList[index],
                      fit: BoxFit.cover, width: 1000)),
            ));
          },
        ),
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}

Body:
Try this:

Future ff(String styleImagePath, String originalImagePath) async {
  ImageTransferFacade showtime = ImageTransferFacade();

  var original_image = showtime.loadoriginalImage(originalImagePath);

  var style_image = showtime.loadStyleImage(styleImagePath);

  var output_image = showtime.transfer(await original_image, await style_image);
  return output_image;
}

class second extends StatefulWidget {
  const second({
    Key? key,
    required this.image,
  }) : super(key: key);

  final XFile image;

  @override
  State<second> createState() => _secondState();
}

class _secondState extends State<second> {

  late XFile _image;

  initState(){
    _image = widget.image;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body: SingleChildScrollView(
          child: Container(
              padding: EdgeInsets.all(16),
              child: Card(
                  child: Image.file(File(image
                      .path))))), // this is the original image which i'd like to replace once user taps on the style image
      bottomNavigationBar: BottomAppBar(
        color: Colors.white,
        child: CarouselSlider.builder(
          itemCount: imageList.length,
          options: CarouselOptions(
            autoPlay: true,
            aspectRatio: 2.0,
            enlargeCenterPage: true,
          ),
          itemBuilder: (context, index, realIdx) {
            return Container(
                child: Center(
              child: GestureDetector(
onTap: () {
  ff(imageList[index], widget.image.path).then((value){
   setState((){
     _image = value;
   });
  });
},                  child: Image.network(imageList[index],
                      fit: BoxFit.cover, width: 1000)),
            ));
          },
        ),
      ),
      floatingActionButton: const FloatingActionButton(onPressed: null),
    );
  }
}


问:
AWS event bridge rule role not attaching to event bridge when creating via CloudFormation
I have a Cloudformation template to create an event bridge rule with target to a central event bus running in another account. When i run the below code , both IAM role and event bridge is getting created but the IAM role is not getting attached to eventbridge rule. Below is the yaml template i am using.

Please see the attached screenshot also.

```<code>AWSTemplateFormatVersion: 2010-09-09
Resources:
    EventRuleRegion1:
        Type: AWS::Events::Rule
        Properties:
            Description: Event rule to send events to monitoring account event bus
            EventBusName: default
            EventPattern:
                source:
                    - aws.ec2

            Name: ec2-lifecycle-events2
            RoleArn: !GetAtt
                - EventBridgeIAMrole
                - Arn
            State: ENABLED
            Targets:
                - Arn: >-
                    arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
                  Id: 'central-eventbus-sydney'

    EventBridgeIAMrole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: 2012-10-17
                Statement:
                    - Effect: Allow
                      Principal:
                        Service: !Sub events.amazonaws.com
                      Action: 'sts:AssumeRole'
            Path: /
            Policies:
                - PolicyName: PutEventsDestinationBus
                  PolicyDocument:
                    Version: 2012-10-17
                    Statement:
                        - Effect: Allow
                          Action:
                            - 'events:PutEvents'
                          Resource:
                            - >-
                              arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
</code>```

Manually Created Event rule which shows the role created and attached.

Policy in the role

```<code>{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "events:PutEvents"
            ],
            "Resource": [
                "arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney"
            ]
        }
    ]
}
</code>```

答:
Cross-account permissions are not set using role, but EventBus resource permissions. From [docs][1]:

The permissions for an event bus are granted or denied using a resource-based policy attached to the event bus.

To do this in CloudFormation, you have to develop your own custom resource.

Update

You haven't specified RoleArn for your target. This is different RoleArn that you have now.

Body:
I have a Cloudformation template to create an event bridge rule with target to a central event bus running in another account. When i run the below code , both IAM role and event bridge is getting created but the IAM role is not getting attached to eventbridge rule. Below is the yaml template i am using.

Please see the attached screenshot also.

AWSTemplateFormatVersion: 2010-09-09
Resources:
    EventRuleRegion1:
        Type: AWS::Events::Rule
        Properties:
            Description: Event rule to send events to monitoring account event bus
            EventBusName: default
            EventPattern:
                source:
                    - aws.ec2

            Name: ec2-lifecycle-events2
            RoleArn: !GetAtt
                - EventBridgeIAMrole
                - Arn
            State: ENABLED
            Targets:
                - Arn: >-
                    arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney
                  Id: 'central-eventbus-sydney'

    EventBridgeIAMrole:
        Type: 'AWS::IAM::Role'
        Properties:
            AssumeRolePolicyDocument:
                Version: 2012-10-17
                Statement:
                    - Effect: Allow
                      Principal:
                        Service: !Sub events.amazonaws.com
                      Action: 'sts:AssumeRole'
            Path: /
            Policies:
                - PolicyName: PutEventsDestinationBus
                  PolicyDocument:
                    Version: 2012-10-17
                    Statement:
                        - Effect: Allow
                          Action:
                            - 'events:PutEvents'
                          Resource:
                            - >-
                              arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney

Manually Created Event rule which shows the role created and attached.

Policy in the role

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "events:PutEvents"
            ],
            "Resource": [
                "arn:aws:events:ap-southeast-2:123456789123:event-bus/central-eventbus-sydney"
            ]
        }
    ]
}


问:
Iterable O(1) insert and random delete collection
I am looking to implement my own collection class.  The characteristics I want are:

Iterable - order is not important

Insertion - either at end or at iterator location, it does not matter

Random Deletion - this is the tricky one.  I want to be able to have a reference to a piece of data which is guaranteed to be within the list, and remove it from the list in O(1) time.

I plan on the container only holding custom classes, so I was thinking a doubly linked list that required the components to implement a simple interface (or abstract class).

Here is where I am getting stuck.  I am wondering whether it would be better practice to simply have the items in the list hold a reference to their node, or to build the node right into them.  I feel like both would be fairly simple, but I am worried about coupling these nodes into a bunch of classes.

I am wondering if anyone has an idea as to how to minimize the coupling, or possibly know of another data structure that has the characteristics I want.

答: It'd be hard to beat a hash map.</p>

Body: It'd be hard to beat a hash map.


问:
Can't get .then to happen after promised timeout is finished in JavaScript

Hey, i am trying to return this console after 1000 milli sec using this promise, but for some reason it consoles before ending the setTime out. Any idea how I can get the console.log to happen after the timeOutPromise is finished?

```<code>const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => new Promise((resolve, reject) => {
  timeOutPromise()
    .then(resolve(console.log(num1 + num2)))
    .catch(reject(Error));
});

thisPromise(1, 2);
</code>```

答:
Your code is calling console.log synchronously when the promise is set up. You need to pass a callback to then, not the result of console.log(). Further, if you already have a promise, no need to wrap it in a promise constructor, just use chaining.

```<code>const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => timeOutPromise()
    .then(() => console.log(num1 + num2))

thisPromise(1, 2);
</code>```

Body:
Hey, i am trying to return this console after 1000 milli sec using this promise, but for some reason it consoles before ending the setTime out. Any idea how I can get the console.log to happen after the timeOutPromise is finished?

const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => new Promise((resolve, reject) => {
  timeOutPromise()
    .then(resolve(console.log(num1 + num2)))
    .catch(reject(Error));
});

thisPromise(1, 2);

Body:
Your code is calling console.log synchronously when the promise is set up. You need to pass a callback to then, not the result of console.log(). Further, if you already have a promise, no need to wrap it in a promise constructor, just use chaining.

const timeOutPromise = () => new Promise(resolve => { setTimeout(() => { resolve(); }, 1000); });

const thisPromise = (num1, num2) => timeOutPromise()
    .then(() => console.log(num1 + num2))

thisPromise(1, 2);


问:
What is a single pipe equivalent in dart?
I'm attempting to convert a piece of PHP code to dart and I came across a few things I've simply never used before, one of which is a single pipe |.  Im not sure what the exact dart equivalent is, if there even is one.

The piece of code in PHP I'm attempting to convert is:

```<code>$cc1 = (chr(ord($c1) / 64) | "\xc0");
</code>```

What I've got so far converted into dart is:

```<code>var cc1 = (String.fromCharCode(c1.codeUnitAt(0) / 64) | "\xc0");
</code>```

However, the single pipe | is giving me a dart error The operator '|' isn't defined for the type 'String'., but as far as I can tell, the php chr should be giving a string as its output, so it brings up the question of if single pipe is actually doing the same thing in dart as it does in PHP?

答:
The operation is bitwise-OR, and the equivalent operator is |.  However, PHP is lenient about types, and Dart is type-safe.  It will not convert strings to integers for you.  You can do:

var cc1 = c1.codeUnitAt(0) | 0xc0;
```
<p><code>cc1</code> will be an <code>int</code>.  If, say, you want it to be a <code>String</code> with the hexadecimal representation, you can do:</p>
<pre class="lang-dart prettyprint-override"><code>var cc1 = (c1.codeUnitAt(0) | 0xc0).toRadixString(16);
</code>```

Body:
I'm attempting to convert a piece of PHP code to dart and I came across a few things I've simply never used before, one of which is a single pipe |.  Im not sure what the exact dart equivalent is, if there even is one.

The piece of code in PHP I'm attempting to convert is:

$cc1 = (chr(ord($c1) / 64) | "\xc0");

What I've got so far converted into dart is:

var cc1 = (String.fromCharCode(c1.codeUnitAt(0) / 64) | "\xc0");

However, the single pipe | is giving me a dart error The operator '|' isn't defined for the type 'String'., but as far as I can tell, the php chr should be giving a string as its output, so it brings up the question of if single pipe is actually doing the same thing in dart as it does in PHP?

Body:
The operation is bitwise-OR, and the equivalent operator is |.  However, PHP is lenient about types, and Dart is type-safe.  It will not convert strings to integers for you.  You can do:

var cc1 = c1.codeUnitAt(0) | 0xc0;

cc1 will be an int.  If, say, you want it to be a String with the hexadecimal representation, you can do:

var cc1 = (c1.codeUnitAt(0) | 0xc0).toRadixString(16);


问:
.htaccess page redirect
I have dynamically created image links coming to my index.html page. basically they look like:
http://catdeoderant.com/index.html?catpart=view&catimage=13

How do I use .htaccess to redirect these links to:
http://catdeoderant.com/stinkycats/gallery.php

I need it where when you click on an image the redirect happens. I also need the variables to be passed to the redirected page. The first variable will always be =view, but the second could be any number.

One more thing, since it's an index.html page, any link to index.html with no variables should not get redirected.

Thanks all, and I do love cats, but sometimes they do stink!

答:
Use the following rule:

```<code><IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{QUERY_STRING}  ^catpart=view&catimage=([0-9]+)$
  RewriteRule ^/index.html$  /stinkycats/gallery.php [R=301,L]
</IfModule>
</code>```

Edited on advice from LazyOne.

Expected result:

index.html => index.html

index.html?foo=bar => index.html

index.html?catpart=view => index.html

index.html?catpart=view&catimage=foobar => index.html

index.html?catpart=view&catimage=13 => /stinkycats/gallery.php?catpart=view&catimage=13

I never used %{QUERY_STRING} before but it should be close to what you are trying to do according to this documentation http://fantomaster.com/faarticles/rewritingurls.txt

Title: .htaccess page redirect

Body:
Use the following rule:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteCond %{QUERY_STRING}  ^catpart=view&catimage=([0-9]+)$
  RewriteRule ^/index.html$  /stinkycats/gallery.php [R=301,L]
</IfModule>

Edited on advice from LazyOne.

Expected result:

index.html => index.html

index.html?foo=bar => index.html

index.html?catpart=view => index.html

index.html?catpart=view&catimage=foobar => index.html

index.html?catpart=view&catimage=13 => /stinkycats/gallery.php?catpart=view&catimage=13

I never used %{QUERY_STRING} before but it should be close to what you are trying to do according to this documentation http://fantomaster.com/faarticles/rewritingurls.txt


问:
Out of Order Execution, How to Solve True Dependency?
I was reading about OOOE (Out of Order Execution) and read about how we can solve false dependencies (By using renaming).

But my question is, how can we solve true dependency (RAW - read after write)?

For example:

```<code>R1=R2+R3 #1
R1=R4+R5 #2
R9=R1 #3
</code>```

Renaming won't be helpful here in case CPU chose to run #2 before #1.

答:
There is no way to really avoid them, that's why RAW hazards are called true dependencies.  Instructions have to wait for their inputs to be ready before they can execute.  (With OoO exec, normally CPUs will dispatch the oldest-ready-first instructions / uops to execution units, for example on Intel CPUs.)

True dependencies aren't something you "solve" in the sense of making them go away, they're the essence of computation, the way multiple computations on the same numbers are glued together to form an algorithm.  Other hazards (WAR and WAW) are just implementation details, reusing the same architectural register for something different.

Sometimes you can structure an algorithm to have shorter dependency chains, once things are already nailed down into machine code, the CPU pretty much just has to respect them, with at best out-of-order exec to overlap independent dep chains.

For loads, in theory there's value-prediction, but AFAIK no real CPU is doing that.  Mispredictions are expensive, just like for branches.  That's why you'd only want to consider that for high-latency stuff like loads that miss in cache, otherwise the gains won't outweigh the costs.  (Even then, it's not done because the gains don't outweigh the costs even for loads, including the power / area cost of building a predictor.)  As Paul Clayton points out, branch prediction is a form of value prediction (predicting the condition the load was based on).  The more instructions you can keep in flight at once with OoO exec, the more you stand to lose from mispredicts, but real CPUs do predict / speculate for memory disambiguation (whether a load reloads an earlier store to an unknown address or not), and (on CPUs like x86 with strongly-ordered memory models) speculating that early loads will turn out to be allowed; as well as the well known case of control dependencies (branch prediction + speculative execution).

The only thing that helps directly with dependency chains is keeping instruction latencies low.  e.g. in the case of your example, #3 is just a register copy, which modern x86 CPUs can do with zero latency (mov-elimination), so another instruction dependent on R9 wouldn't have to wait an extra cycle beyond #2 producing a result, because it's handled during register renaming instead of by an execution unit reading an input and producing an output the normal way.

Obviously bypass forwarding from the outputs of execution units to the inputs of the same or others is essential to keep latency low, same as in an in-order classic RISC pipeline.

Or more conventionally, by improving execution units, like AMD Bulldozer family had 2-cycle latency for most SIMD integer instructions, but that improved to 1 cycle for AMD's next design, Zen.  (Scalar integer stuff like add was always 1 cycle on any sane high-performance CPU.)

OoO exec with a large enough window size lets you overlap multiple dep chains in parallel (as in this experiment, and of course software should aim to have enough instruction-level parallelism (ILP) for the CPU to find and exploit.  (See Why does mulss take only 3 cycles on Haswell, different from Agner's instruction tables? (Unrolling FP loops with multiple accumulators) for an example of doing that by summing into multiple accumulators for a dot-product.)

This is also useful for in-order CPUs if done statically by a compiler, where techniques like "software pipelining" are a big deal to overlap execution of multiple loop iterations because HW isn't finding that parallelism for you.  Or for OoO exec CPUs with a limited window size, for loops with long but not loop-carried dependency chains within each iteration.

As long as you're bottlenecked on something other than latency / dependency chains, true dependencies aren't the problem.  e.g. a front-end bottleneck, ideally maxed out at the pipeline width, and/or all relevant back-end execution units busy every cycle, mean that you couldn't get more work through the pipeline even if it was independent.

Of course, in a lot of code there are enough dependencies, including through memory, to not reach that ideal situation.

Simultaneous Multithreading (SMT) can help to keep the back-end fed with work to do, increasing throughput by having the front-end of one physical core read multiple instruction streams, acting as multiple logical cores.  This effectively creates ILP out of thread-level parallelism, which is useful if software can scale efficiently to more threads, exposing enough TLP to keep  all the logical cores busy.

Related:

Modern Microprocessors A 90-Minute Guide!

How many CPU cycles are needed for each assembly instruction? - that's not how it works on superscalar OoO exec CPUs; latency or throughput or a front-end bottleneck might be the relevant thing.

What considerations go into predicting latency for operations on modern superscalar processors and how can I calculate them by hand?

Body:
I was reading about OOOE (Out of Order Execution) and read about how we can solve false dependencies (By using renaming).

But my question is, how can we solve true dependency (RAW - read after write)?

For example:

R1=R2+R3 #1
R1=R4+R5 #2
R9=R1 #3

Renaming won't be helpful here in case CPU chose to run #2 before #1.


问:
Why is the Spring framework called "non-intrusive"?
Spring framework is NON - INTRUSIVE.

Can you please elaborate this?

Thank You :)

答:
No matter what the language direction, generally speaking, a framework is too intrusive, which is a voice of criticism, so I guess it is not because of this that non intrusiveness has become a "selling point" of publicity.

For example, spring and struts 2 use annotations, configuration files, conventions or reflection (other languages may be other ways) to achieve non-invasive, and the compilation and operation does not have formal dependence on the framework API.

But in essence, without this framework, our program simply cannot run correctly. These so-called annotations are customized. When and how they are processed are different. Think about the migration from gson to Jackson. The migration has costs and risks. Do you need users to write a new one?

In addition, how high is the probability of real migration? It feels very small.

ContentLicense: CC BY-SA 2.5


问:
Why is Firestore triggers (for Cloud Functions) ordering not guaranteed?
I suppose Firestore triggers for cloud functions are using PubSub.

PubSub supports ordering of messages with the same ordering key and in the same region. For Firestore triggers, the ordering key could be the document id.

Ordering would be especially useful for the onUpdate trigger.

答:
Since you're running on an auto-scaling, distributed infrastructure, there are a lot of things that influence the order of execution.

For example if some writes happen in quick succession, one/some of them might require that Cloud Functions spins up a new instance for that write, which then will experience a cold start. Other writes might be handled on existing/warm instances, and there's no way to say which happens first.

Any form of synchronization would require significant effort, which for the vast majority of the cases isn't needed. If you need any synchronization between the invocations, it is up to your Cloud Functions code itself to implement that.


问:
LARAVEL: Data not showing on a page but works fine for other page
Im having a bit of a weird problem as a similar piece of code works for another page but it won't work for this, I can add to the database using my website but when trying to show the data it comes up as blank. Im not exactly sure what I am doing wrong and its starting to frustrate me, here's some code

Index.blade.php

```<code><div class="panel panel-primary">
  <div class="panel-heading">
    <h3 class="panel-title"><a href="{{ route('marketthreads.show', $thread->id) }}">{{ $thread->subject }}</a></h3>
  </div>
  <div class="panel-body">
      <p class="list-group-item-text">{{ \Illuminate\Support\Str::limit($thread->thread,100) }}
          <br>
          <br>
          {{ $thread->id }}
      </p>
  </div>
</code>```

The Controller

```<code>    public function show(Marketthreads $marketthreads)
{
    return view('marketplace.details', compact('marketthreads'));
}
</code>```

Web file (routes)

```<code>Route::resource('/marketthreads', App\Http\Controllers\MarketthreadsController::class);
</code>```

Details.blade.php (the file im trying to show the data on)

Details.blade

As I mentioned before this works for another page that I have done and it shows the data but it pulls data from another table I don't think that matters too much

Hopefully someone can help me out, thank you :)

答: You are using $thread which is undefined. In your controller you are passing $marketthreads to the view via compact('marketthreads'). So you should change $thread to $marketthreads

Body:
Im having a bit of a weird problem as a similar piece of code works for another page but it won't work for this, I can add to the database using my website but when trying to show the data it comes up as blank. Im not exactly sure what I am doing wrong and its starting to frustrate me, here's some code

Index.blade.php

id) }}">{{ $thread->subject }}

{{ \Illuminate\Support\Str::limit($thread->thread,100) }}

          {{ $thread->id }}

The Controller

    public function show(Marketthreads $marketthreads)
{
    return view('marketplace.details', compact('marketthreads'));
}

Web file (routes)

Route::resource('/marketthreads', App\Http\Controllers\MarketthreadsController::class);

Details.blade.php (the file im trying to show the data on)

Details.blade

As I mentioned before this works for another page that I have done and it shows the data but it pulls data from another table I don't think that matters too much

Hopefully someone can help me out, thank you :)


答: The Lua programming language version that Roblox uses, LuaU (or Luau), is actually open-source since November of 2021. You can find it here. The math library can be found in this file called lmathlib.cpp and it contains the math.noise function along with internal functions to calculate it, perlin (main function), grad, lerp, and fade. It's a quite complicated thing I can't explain myself, but I have converted it into Lua here.

Title: How does Roblox's math.noise() deal with negative inputs?

Body:
While messing around with noise outside of Roblox, I realized Perlin/Simplex Noise does not like negative inputs.  Remembering Roblox has a noise function, I tried there, and found out negative numbers do work nicely for Roblox's math.noise().  Does anybody know how they made this work, or how to get negative numbers to work for Perlin/Simplex noise in general?

The Simplex Noise I am using (copied from here but changed to have the bitwise and operation):

local function bit_and(a, b) --bitwise and operation
    local p, c = 1, 0
    while a > 0 and b > 0 do
        local ra, rb = a%2, b%2

        if (ra + rb) > 1 then
            c = c + p
        end

        a = (a - ra) / 2
        b = (b - rb) / 2
        p = p * 2
    end

    return c
end

-- 2D simplex noise

local grad3 = {
    {1,1,0},{-1,1,0},{1,-1,0},{-1,-1,0},
    {1,0,1},{-1,0,1},{1,0,-1},{-1,0,-1},
    {0,1,1},{0,-1,1},{0,1,-1},{0,-1,-1}
}

local  p = {151,160,137,91,90,15,
    131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
    190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
    88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
    77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
    102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
    135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
    5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
    223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
    129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
    251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
    49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
    138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180}
local perm = {}
for i=0,511 do
    perm[i+1] = p[bit_and(i, 255) + 1]
end

local function dot(g, ...)
    local v = {...}
    local sum = 0
    for i=1,#v do
        sum = sum + v[i] * g[i]
    end
    return sum
end

local noise = {}

function noise.produce(xin, yin)
    local n0, n1, n2    -- Noise contributions from the three corners
    -- Skew the input space to determine which simplex cell we're in
    local F2 = 0.5*(math.sqrt(3.0)-1.0)
    local s = (xin+yin)*F2; -- Hairy factor for 2D
    local i = math.floor(xin+s)
    local j = math.floor(yin+s)
    local G2 = (3.0-math.sqrt(3.0))/6.0
    local t = (i+j)*G2
    local X0 = i-t -- Unskew the cell origin back to (x,y) space
    local Y0 = j-t
    local x0 = xin-X0 -- The x,y distances from the cell origin
    local y0 = yin-Y0
    -- For the 2D case, the simplex shape is an equilateral triangle.
    -- Determine which simplex we are in.
    local i1, j1 -- Offsets for second (middle) corner of simplex in (i,j) coords
    if x0 > y0 then
        i1 = 1
        j1 = 0 -- lower triangle, XY order: (0,0)->(1,0)->(1,1)
    else
        i1 = 0
        j1 = 1
    end-- upper triangle, YX order: (0,0)->(0,1)->(1,1)
    -- A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
    -- a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
    -- c = (3-sqrt(3))/6
    local x1 = x0 - i1 + G2 -- Offsets for middle corner in (x,y) unskewed coords
    local y1 = y0 - j1 + G2
    local x2 = x0 - 1 + 2 * G2 -- Offsets for last corner in (x,y) unskewed coords
    local y2 = y0 - 1 + 2 * G2
    -- Work out the hashed gradient indices of the three simplex corners
    local ii = bit_and(i, 255)
    local jj = bit_and(j, 255)
    local gi0 = perm[ii + perm[jj+1]+1] % 12
    local gi1 = perm[ii + i1 + perm[jj + j1+1]+1] % 12
    local gi2 = perm[ii + 1 + perm[jj + 1+1]+1] % 12
    -- Calculate the contribution from the three corners
    local t0 = 0.5 - x0 * x0 - y0 * y0
    if t0 < 0 then
        n0 = 0.0
    else
        t0 = t0 * t0
        n0 = t0 * t0 * dot(grad3[gi0+1], x0, y0) -- (x,y) of grad3 used for 2D gradient
    end
    local t1 = 0.5 - x1 * x1 - y1 * y1
    if t1 < 0 then
        n1 = 0.0
    else
        t1 = t1 * t1
        n1 = t1 * t1 * dot(grad3[gi1+1], x1, y1)
    end
    local t2 = 0.5 - x2 * x2 - y2 * y2
    if t2 < 0 then
        n2 = 0.0
    else
        t2 = t2 * t2
        n2 = t2 * t2 * dot(grad3[gi2+1], x2, y2)
    end
    -- Add contributions from each corner to get the final noise value.
    -- The result is scaled to return values in the interval [-1,1].
    return 70.0 * (n0 + n1 + n2)
end

return noise


问:
Epicor ERP can you call an Epicor Function within a Customization
Epicor ERP 10.2.500 has been recently released with the addition of Epicor Functions. They can be called from within Method and Data Directives.

Do anybody has been able to do so with a Form Customization within Epicor?

答:
REST endpoint is the recommended way to perform the function call as pointed out by a-moreng.

If for some reason you cannot use this, you can use a passthrough method to any server-side BO via a customization Adapter. For instance, create an updatable BAQ which you can call from a customization using the DynamicQueryAdapter.

Pick an arbitrary table and field to save the BAQ.

Create three string parameters to store the Function library name, the function name, and a delimited list of parameters.

On the GetList method, create a Base Processing Directive.

Split your delimited parameter list and convert them to the appropriate datatypes.

Use the resulting variables to call your function.

If desired, you can pass return variables into the ttResults of the BAQ


问:
Is there a difference between x++ and ++x in java?
Is there a difference between ++x and x++ in java?</p>

答:
```<code>public static void main(String[] args) {

int a = 1;
int b = a++; // this means b = whatever value a has but, I want to
increment a by 1

System.out.println("a is --> " + a);    //2
System.out.println("b is --> " + b);    //1
a = 1;
b = ++a;  // this means b = a+1

System.out.println("now a is still  --> " + a);    //2
System.out.println("but b is --> " + b);           //2

}
</code>```


问:
Why is my CircularProgressIndicator spinning randomly when the screen loads?
I have a CircularProgressIndicator that is meant to display progress when the user presses a button. However, when I open the screen that uses this class it shows a loading animation and I'm not sure why. When the screen opens, it shouldn't show the animation until the user presses the button.

When the screen opens you see something similar to the animation on this page: https://www.c-sharpcorner.com/article/create-chrome-like-loading-animation/

```<code>class _MsgInputState extends State<MsgInput> with TickerProviderStateMixin {

  AnimationController? controller;

  @override
  void initState() {
    super.initState();
    initialize();

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  void initialize() async {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..addListener(() {
      setState(() {});
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      controller?.forward();
                    },
                    onLongPressDown: (details) async {
                      controller?.forward();
                    },
                    onLongPressUp: () async {
                      controller?.stop();
                      controller?.reset();
                    },
                    child: Text('Record'),
                  ),
                ],
              ),
              Row(
                children: <Widget>[
                  SizedBox(width: 100),
                  CircularProgressIndicator(
                    value: controller?.value,
                    semanticsLabel: 'Linear progress indicator',
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }
</code>```

答:
If the value provided to a CircularProgressIndicator is null it just defaults to a spinnging animation.

In the beginnin controller?.value probably returns null. Change it to value: controller?.value ?? 0 so that while it's null 0 is used as a value.

EDIT:

change

CircularProgressIndicator(
  value: controller?.value,
  semanticsLabel: 'Linear progress indicator',
),
```
<p>to</p>
<pre class="lang-dart prettyprint-override"><code>CircularProgressIndicator(
  value: controller?.value ?? 0,
  semanticsLabel: 'Linear progress indicator',
),
</code>```

Body:
I have a CircularProgressIndicator that is meant to display progress when the user presses a button. However, when I open the screen that uses this class it shows a loading animation and I'm not sure why. When the screen opens, it shouldn't show the animation until the user presses the button.

When the screen opens you see something similar to the animation on this page: https://www.c-sharpcorner.com/article/create-chrome-like-loading-animation/

class _MsgInputState extends State<MsgInput> with TickerProviderStateMixin {

  AnimationController? controller;

  @override
  void initState() {
    super.initState();
    initialize();

  }

  @override
  void dispose() {
    controller?.dispose();
    super.dispose();
  }

  void initialize() async {
    controller = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 3),
    )..addListener(() {
      setState(() {});
    });
  }

@override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Align(
          alignment: Alignment.bottomLeft,
          child: Column(
            children: [
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      controller?.forward();
                    },
                    onLongPressDown: (details) async {
                      controller?.forward();
                    },
                    onLongPressUp: () async {
                      controller?.stop();
                      controller?.reset();
                    },
                    child: Text('Record'),
                  ),
                ],
              ),
              Row(
                children: <Widget>[
                  SizedBox(width: 100),
                  CircularProgressIndicator(
                    value: controller?.value,
                    semanticsLabel: 'Linear progress indicator',
                  ),
                ],
              ),
            ],
          ),
        )
    );
  }

Body:
If the value provided to a CircularProgressIndicator is null it just defaults to a spinnging animation.

In the beginnin controller?.value probably returns null. Change it to value: controller?.value ?? 0 so that while it's null 0 is used as a value.

EDIT:

change

CircularProgressIndicator(
  value: controller?.value,
  semanticsLabel: 'Linear progress indicator',
),

to

CircularProgressIndicator(
  value: controller?.value ?? 0,
  semanticsLabel: 'Linear progress indicator',
),


问:
Could not post data to PHP
I am trying to post some data to the php but i could not send anything and see where the problem is.The codes looks fine to me.In other words, i could not reach inside of if statement.Codes;

```<code><form method="post" action="home.php" name="home" id="home">
    <label for="in_come">enter something: </label><input type="text" name="in_come" id="in_come" /><br/>
</code>```

```<code><?php
echo "outside if";
if(isset($_POST['in_come']))
{
    echo "inside if";
    $income = $_POST['in_come'];

    $registerquery = mysql_query("INSERT INTO income (income) VALUES ('".$in_come."')");
    if ($registerquery)
    {
        echo "sended";
    }
}
?>
</code>```

答:
if echo "inside if"; is not working,
 try

```<code>if (isset($_POST['in_come']) && ($_POST['in_come'] != ""))
</code>```

instead of

```<code>if(isset($_POST['in_come']))
</code>```

Title: Could not post data to PHP

Body:
I am trying to post some data to the php but i could not send anything and see where the problem is.The codes looks fine to me.In other words, i could not reach inside of if statement.Codes;

<form method="post" action="home.php" name="home" id="home">
    enter something: <input type="text" name="in_come" id="in_come" />

<?php
echo "outside if";
if(isset($_POST['in_come']))
{
    echo "inside if";
    $income = $_POST['in_come'];

    $registerquery = mysql_query("INSERT INTO income (income) VALUES ('".$in_come."')");
    if ($registerquery)
    {
        echo "sended";
    }
}
?>

Body:
if echo "inside if"; is not working,
 try

if (isset($_POST['in_come']) && ($_POST['in_come'] != ""))

instead of

if(isset($_POST['in_come']))


问:
LinkedList Custom Implementation Faster than Java LinkedList
I've recently started Cracking the Code Interview and I just got to LinkedLists. I did problem 2.1 to remove duplicate entries from the book's implementation of LinkedList.

When I time the removal of dupes, I see the book's implementation is faster than Java LinkedList.

I've implemented four dupe removal methods, each with a different parameter. The book's LinkedList implementation is referred to as Node.

```<code>    static void removeDupes(LinkedList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            if (integerHashSet.contains(list.get(i))) {
                list.remove(list.get(i));
            } else {
                integerHashSet.add(list.get(i));
            }
        }
    }

    static void removeDupes(ArrayList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            if (integerHashSet.contains(list.get(i))) {
                list.remove(list.get(i));
            } else {
                integerHashSet.add(list.get(i));
            }
        }
    }

   static void removeDupes(Node currentNode) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        while(currentNode != null) {
            if (integerHashSet.contains(currentNode.data)) {
                currentNode.prev.next = currentNode.next;
                if (currentNode.next != null) {
                    currentNode.next.prev = currentNode.prev;
                }
            } else {
                integerHashSet.add(currentNode.data);
            }
            currentNode = currentNode.next;
        }
    }

    static void removeDupesNoBuffer(Node currentNode) {
        while (currentNode != null) {
            Node runnerNode = currentNode;
            while(runnerNode.next != null) {
                if (runnerNode.next.data == currentNode.data) {
                    runnerNode.next = runnerNode.next.next;
                    if (runnerNode.next != null) {
                        runnerNode.next.prev = runnerNode;
                    }
                } else {
                    runnerNode = runnerNode.next;
                }
            }
            currentNode = currentNode.next;
        }
    }
</code>```

Book's LinkedList implementation:

```<code>public class Node {
    Node prev;
    Node next;
    int data;

    Node(int d) {
        data = d;
    }

    void add(int d) {
        Node newNode = new Node(d);
        Node currentNode = this;
        while (currentNode.next != null) {
            currentNode = currentNode.next;
        }
        currentNode.next = newNode;
        newNode.prev = currentNode;
    }
}
</code>```

Each List or Node, I populated with a length of 100000, where each odd index was 0 and everything else was unique.

My results were:

Node: 18ms

Node No Buffer: 5154ms

LinkedList: 2734ms

ArrayList: 1392ms

What am I not understanding?

EDIT:

When I swapped the remove dupes with the LinkedList parameter to an enhanced for loop as pointed out by the comments and solution, it became just as fast.

```<code>    static void removeDupes(LinkedList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for(Integer i : list) {
            if (integerHashSet.contains(i)) {
                list.remove(i);
            } else {
                integerHashSet.add(i);
            }
        }
    }
</code>```

答:
The reason is that your doing it inefficently.  If you use indices to iterate over a linked list the list has to count each node reference to find the correct one.  And then it acts on that one.

Try it like this and see the difference. Counting even values of a linked list of N items.  The second iteration will be much faster.

First, a indexed for loop.

```<code>List<Integer> list1 = new LinkedList<>();
Random r = new Random();
int N = 100_000;
for(int i = 0; i < N; i++) {
    list1.add(r.nextInt(10000));
}
// copy the list
List<Integer> list2 = new LinkedList<>(list1);

System.out.println("Starting list1");
int sumEvens = 0;
for(int i = 0; i < list1.size(); i++) {
    if (list1.get(i) % 2 == 0) {
        sumEvens++;
    }
}
System.out.printf("There were %d even values%n", sumEvens);

</code>```

Now an enhanced forloop which uses an iterator.

```<code>System.out.println("Starting list2");
sumEvens = 0;
for(int i : list2) {
    if ( i%2 == 0) {
        sumEvens++;
    }
}
System.out.printf("There were %d even values%n", sumEvens);
</code>```

Finally, Arraylists are fast at accessing but slow at deleting.  This is because when an item is deleted, all subsequent items must be copied up one cell to close the gap.  But a linked list can delete an item by simply having the previous node point to the following node.  So how a list is to be used drives the selection of the list implementation.

Body:
I've recently started Cracking the Code Interview and I just got to LinkedLists. I did problem 2.1 to remove duplicate entries from the book's implementation of LinkedList.

When I time the removal of dupes, I see the book's implementation is faster than Java LinkedList.

I've implemented four dupe removal methods, each with a different parameter. The book's LinkedList implementation is referred to as Node.

    static void removeDupes(LinkedList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            if (integerHashSet.contains(list.get(i))) {
                list.remove(list.get(i));
            } else {
                integerHashSet.add(list.get(i));
            }
        }
    }

    static void removeDupes(ArrayList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for (int i = 0; i < list.size(); i++) {
            if (integerHashSet.contains(list.get(i))) {
                list.remove(list.get(i));
            } else {
                integerHashSet.add(list.get(i));
            }
        }
    }

   static void removeDupes(Node currentNode) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        while(currentNode != null) {
            if (integerHashSet.contains(currentNode.data)) {
                currentNode.prev.next = currentNode.next;
                if (currentNode.next != null) {
                    currentNode.next.prev = currentNode.prev;
                }
            } else {
                integerHashSet.add(currentNode.data);
            }
            currentNode = currentNode.next;
        }
    }

    static void removeDupesNoBuffer(Node currentNode) {
        while (currentNode != null) {
            Node runnerNode = currentNode;
            while(runnerNode.next != null) {
                if (runnerNode.next.data == currentNode.data) {
                    runnerNode.next = runnerNode.next.next;
                    if (runnerNode.next != null) {
                        runnerNode.next.prev = runnerNode;
                    }
                } else {
                    runnerNode = runnerNode.next;
                }
            }
            currentNode = currentNode.next;
        }
    }

Book's LinkedList implementation:

public class Node {
    Node prev;
    Node next;
    int data;

    Node(int d) {
        data = d;
    }

    void add(int d) {
        Node newNode = new Node(d);
        Node currentNode = this;
        while (currentNode.next != null) {
            currentNode = currentNode.next;
        }
        currentNode.next = newNode;
        newNode.prev = currentNode;
    }
}

Each List or Node, I populated with a length of 100000, where each odd index was 0 and everything else was unique.

My results were:

Node: 18ms

Node No Buffer: 5154ms

LinkedList: 2734ms

ArrayList: 1392ms

What am I not understanding?

EDIT:

When I swapped the remove dupes with the LinkedList parameter to an enhanced for loop as pointed out by the comments and solution, it became just as fast.

    static void removeDupes(LinkedList<Integer> list) {
        HashSet<Integer> integerHashSet = new HashSet<>();
        for(Integer i : list) {
            if (integerHashSet.contains(i)) {
                list.remove(i);
            } else {
                integerHashSet.add(i);
            }
        }
    }

Body:
The reason is that your doing it inefficently.  If you use indices to iterate over a linked list the list has to count each node reference to find the correct one.  And then it acts on that one.

Try it like this and see the difference. Counting even values of a linked list of N items.  The second iteration will be much faster.

First, a indexed for loop.

List<Integer> list1 = new LinkedList<>();
Random r = new Random();
int N = 100_000;
for(int i = 0; i < N; i++) {
    list1.add(r.nextInt(10000));
}
// copy the list
List<Integer> list2 = new LinkedList<>(list1);

System.out.println("Starting list1");
int sumEvens = 0;
for(int i = 0; i < list1.size(); i++) {
    if (list1.get(i) % 2 == 0) {
        sumEvens++;
    }
}
System.out.printf("There were %d even values%n", sumEvens);

Now an enhanced forloop which uses an iterator.

System.out.println("Starting list2");
sumEvens = 0;
for(int i : list2) {
    if ( i%2 == 0) {
        sumEvens++;
    }
}
System.out.printf("There were %d even values%n", sumEvens);

Finally, Arraylists are fast at accessing but slow at deleting.  This is because when an item is deleted, all subsequent items must be copied up one cell to close the gap.  But a linked list can delete an item by simply having the previous node point to the following node.  So how a list is to be used drives the selection of the list implementation.


问:
Permission denied? when executing the example.o (gsl statistics sample)
I downloaded, compiled, and installed the GNU Scientific Library (gsl) on my mac, which locates /usr/local/include/gsl as default.

To test it, I have tried to compile and execute the example C program (found from gsl document).

```<code> #include <stdio.h>
 #include <gsl/gsl_statistics.h>

 int
 main(void)
 {
   double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6};
   double mean, variance, largest, smallest;

   mean     = gsl_stats_mean(data, 1, 5);
   variance = gsl_stats_variance(data, 1, 5);
   largest  = gsl_stats_max(data, 1, 5);
   smallest = gsl_stats_min(data, 1, 5);

   printf ("The dataset is %g, %g, %g, %g, %g\n",
          data[0], data[1], data[2], data[3], data[4]);

   printf ("The sample mean is %g\n", mean);
   printf ("The estimated variance is %g\n", variance);
   printf ("The largest value is %g\n", largest);
   printf ("The smallest value is %g\n", smallest);
   return 0;
 }
</code>```

To compile it,

$ gcc -I /usr/local/include -c example.c

$ ls

example.c    example.o

And, to execute it,

$ ./example.o

-bash: ./example.o: Permission denied

What's happening? Who can run it other than me?

答:
example.o is an object file, not an executable.

According to the documentation (info gsl-ref to read it), this should work (or at least it's close).

```<code>$ gcc -Wall -I/usr/local/include -c example.c
$ gcc -L/usr/local/lib example.o -lgsl -lgslcblas -lm -o example
$ ./example
</code>```

Body:
I downloaded, compiled, and installed the GNU Scientific Library (gsl) on my mac, which locates /usr/local/include/gsl as default.

To test it, I have tried to compile and execute the example C program (found from gsl document).

 #include <stdio.h>
 #include <gsl/gsl_statistics.h>

 int
 main(void)
 {
   double data[5] = {17.2, 18.1, 16.5, 18.3, 12.6};
   double mean, variance, largest, smallest;

   mean     = gsl_stats_mean(data, 1, 5);
   variance = gsl_stats_variance(data, 1, 5);
   largest  = gsl_stats_max(data, 1, 5);
   smallest = gsl_stats_min(data, 1, 5);

   printf ("The dataset is %g, %g, %g, %g, %g\n",
          data[0], data[1], data[2], data[3], data[4]);

   printf ("The sample mean is %g\n", mean);
   printf ("The estimated variance is %g\n", variance);
   printf ("The largest value is %g\n", largest);
   printf ("The smallest value is %g\n", smallest);
   return 0;
 }

To compile it,

$ gcc -I /usr/local/include -c example.c

$ ls

example.c    example.o

And, to execute it,

$ ./example.o

-bash: ./example.o: Permission denied

What's happening? Who can run it other than me?

Body:
example.o is an object file, not an executable.

According to the documentation (info gsl-ref to read it), this should work (or at least it's close).

$ gcc -Wall -I/usr/local/include -c example.c
$ gcc -L/usr/local/lib example.o -lgsl -lgslcblas -lm -o example
$ ./example


问:
Variable Independent of setState
So say I have a Map and somewhere in my code and I want to save its current state. I set Map Two equal to Map One and go on changing the value of Map One hoping to keep the values of Map Two the same for reference. If I call setState(() {}) after I change Map One it seems to update all values of Map Two as well. This is not what I want. I want to set Map Two and not update until I want to save Map One's state again. It's tough to demonstrate this problem in my code without dumping the whole thing so I'll try to illustrate what I'm talking about below. Just ignore that this code won't actually run, this is the idea. The values of Map Two would be used in a widget but for the sake of example, the value is just being printed. This code would theoretically print foo. I want it to print start. In my mind, there should be something like const or final that I'm just missing that sets a variable and doesn't make it relative.</p>
```<code>Map mapOne = {
  'start' : 'start',
  'end' : 'end'
};
late Map mapTwo;

main() {
  mapTwo = mapOne;
  mapOne = {
    'start' : 'foo',
    'end' : 'foo'
  };

  setState(() {});

  print(mapTwo['start']);
}
</code>```

答: I found the answer here. The problem is the difference between mutable and immutable variables. For me, the solution was storing the value I needed in a string rather than a map because maps are mutable where strings are not. The post I referenced earlier has more details.</p>

Title: Variable Independent of setState

Body:
So say I have a Map and somewhere in my code and I want to save its current state. I set Map Two equal to Map One and go on changing the value of Map One hoping to keep the values of Map Two the same for reference. If I call setState(() {}) after I change Map One it seems to update all values of Map Two as well. This is not what I want. I want to set Map Two and not update until I want to save Map One's state again. It's tough to demonstrate this problem in my code without dumping the whole thing so I'll try to illustrate what I'm talking about below. Just ignore that this code won't actually run, this is the idea. The values of Map Two would be used in a widget but for the sake of example, the value is just being printed. This code would theoretically print foo. I want it to print start. In my mind, there should be something like const or final that I'm just missing that sets a variable and doesn't make it relative.

Map mapOne = {
  'start' : 'start',
  'end' : 'end'
};
late Map mapTwo;

main() {
  mapTwo = mapOne;
  mapOne = {
    'start' : 'foo',
    'end' : 'foo'
  };

  setState(() {});

  print(mapTwo['start']);
}


问:
Begginer in Flutter trying to use FireBase auth
So im really just experimenting to get used to flutter with firebase, so first thing im trying to do in my app its an anonymous authenticantion. With the following code im getting the error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()"

Here is my main

```<code>void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}
</code>```

Here is The Sign In screen, where i first tried to use firebase.

```<code>class SignIn extends StatefulWidget {
  const SignIn({Key? key}) : super(key: key);

  @override
  _SignInState createState() => _SignInState();
  }

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[100],
      appBar: AppBar(
        title: Text('Sign In'),
        backgroundColor: Colors.green[500],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:20.0 , horizontal:50.0,),
        child: ElevatedButton(
          child: Text('Sign In'),
          onPressed: () async{
            dynamic result = await _auth.signInAnon();
            if(result == null) {
              print ('failed');}
              else{
                print('Success');
                print(result);
            }
          },
        ),
      ),
    );
  }
}
</code>```

And the auth class where i use signInAnon().

```<code>class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //login anon
  Future signInAnon() async{
    try{
     UserCredential result =  _auth.signInAnonymously() as UserCredential;
     User user = result.user as User;
     return user;
    } catch(e){
        print(e.toString());
        return null;
    }
  }
}
</code>```

I am following an youtube course form about 2 years ago, so i know firebase changed, but a few recent questions here with the same error have been solved changing the code in main like this:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
   runApp(const MyApp());
}
</code>```

After this change the app is showing a white screen and console says it has an error:

Syncing files to device Android SDK built for x86...

E/flutter (15860): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.

E/flutter (15860):

E/flutter (15860): Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp.

E/flutter (15860):

E/flutter (15860): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

E/flutter (15860):

E/flutter (15860): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)

E/flutter (15860):

E/flutter (15860): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)

E/flutter (15860):

E/flutter (15860): #2      main (package:order_beer/main.dart:10:3)

E/flutter (15860):

E/flutter (15860):

If anybody could help me!

答:
Wrap await Firebase.initializeApp(); in a try-catch block like so:

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
   try{
    await Firebase.initializeApp();
   }catch(e){print(e);}
   runApp(const MyApp());
}
</code>```

Body:
So im really just experimenting to get used to flutter with firebase, so first thing im trying to do in my app its an anonymous authenticantion. With the following code im getting the error "[core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp()"

Here is my main

void main() async {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Wrapper(),
    );
  }
}

Here is The Sign In screen, where i first tried to use firebase.

class SignIn extends StatefulWidget {
  const SignIn({Key? key}) : super(key: key);

  @override
  _SignInState createState() => _SignInState();
  }

class _SignInState extends State<SignIn> {

  final AuthService _auth = AuthService();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.green[100],
      appBar: AppBar(
        title: Text('Sign In'),
        backgroundColor: Colors.green[500],
      ),
      body: Container(
        padding: EdgeInsets.symmetric(vertical:20.0 , horizontal:50.0,),
        child: ElevatedButton(
          child: Text('Sign In'),
          onPressed: () async{
            dynamic result = await _auth.signInAnon();
            if(result == null) {
              print ('failed');}
              else{
                print('Success');
                print(result);
            }
          },
        ),
      ),
    );
  }
}

And the auth class where i use signInAnon().

class AuthService {

  final FirebaseAuth _auth = FirebaseAuth.instance;

  //login anon
  Future signInAnon() async{
    try{
     UserCredential result =  _auth.signInAnonymously() as UserCredential;
     User user = result.user as User;
     return user;
    } catch(e){
        print(e.toString());
        return null;
    }
  }
}

I am following an youtube course form about 2 years ago, so i know firebase changed, but a few recent questions here with the same error have been solved changing the code in main like this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
   runApp(const MyApp());
}

After this change the app is showing a white screen and console says it has an error:

Syncing files to device Android SDK built for x86...

E/flutter (15860): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: [core/not-initialized] Firebase has not been correctly initialized.

E/flutter (15860):

E/flutter (15860): Usually this means you've attempted to use a Firebase service before calling Firebase.initializeApp.

E/flutter (15860):

E/flutter (15860): View the documentation for more information: https://firebase.flutter.dev/docs/overview#initialization

E/flutter (15860):

E/flutter (15860): #0      MethodChannelFirebase.initializeApp (package:firebase_core_platform_interface/src/method_channel/method_channel_firebase.dart:99:9)

E/flutter (15860):

E/flutter (15860): #1      Firebase.initializeApp (package:firebase_core/src/firebase.dart:42:31)

E/flutter (15860):

E/flutter (15860): #2      main (package:order_beer/main.dart:10:3)

E/flutter (15860):

E/flutter (15860):

If anybody could help me!

Body:
Wrap await Firebase.initializeApp(); in a try-catch block like so:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
   try{
    await Firebase.initializeApp();
   }catch(e){print(e);}
   runApp(const MyApp());
}


问:
How to remove and add class on scroll JavaScript

const scrollList = document.getElementsByClassName('scrollList');

function scrollLeft() {
    scrollList.scrollLeft -= 50
}

function scrollRight() {
    scrollList.scrollLeft += 50
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#scrollList {
  display: flex;
  overflow: auto;
  width: 100px;
}

.div {
  display: flex;
}</code>```

  <button onclick="scrollLeft()">Scroll Left</button>

Image

Image

Image

Image

Image

Image

<button  onclick="scrollRight()">Scroll Right</button>

```

I have a Horizontal page scroll on div with arrows and I want to hide the left and right arrow when you can't scroll more. I have an gallery so when there is no more images to scroll to I want to hide the button(arrow). So in the beginning I dont want to show the left arrow, and in the end when there is no more images I want to hide the right arrow. How can I do that with javascript?
Thanks for your help!

答:
Let me answer my friend. It might help you. ^_^

<!DOCTYPE html>

Hide scrollbar but keep functionality

Try to scroll inside the div below:

Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling..

```

Body:
const scrollList = document.getElementsByClassName('scrollList');

function scrollLeft() {
    scrollList.scrollLeft -= 50
}

function scrollRight() {
    scrollList.scrollLeft += 50
}

#scrollList {
  display: flex;
  overflow: auto;
  width: 100px;
}

.div {
  display: flex;
}

  <button onclick="scrollLeft()">Scroll Left</button>

Image

Image

Image

Image

Image

Image

<button  onclick="scrollRight()">Scroll Right</button>

I have a Horizontal page scroll on div with arrows and I want to hide the left and right arrow when you can't scroll more. I have an gallery so when there is no more images to scroll to I want to hide the button(arrow). So in the beginning I dont want to show the left arrow, and in the end when there is no more images I want to hide the right arrow. How can I do that with javascript?
Thanks for your help!

Body:
Let me answer my friend. It might help you. ^_^

<!DOCTYPE html>
<html>
<head>
<style>
.example {
  background-color: #eee;
  width: 200px;
  height: 100px;
  border: 1px dotted black;
  overflow-y: scroll; /* Add the ability to scroll */
}

/* Hide scrollbar for Chrome, Safari and Opera */
.example::-webkit-scrollbar {
    display: none;
}

/* Hide scrollbar for IE, Edge and Firefox */
.example {
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}
</style>
</head>
<body>

<h2>Hide scrollbar but keep functionality</h2>
<p>Try to scroll inside the div below:</p>

<div class="example">Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. </div>

</body>
</html>


问:
How do I print something only when a given parameter does not equal an empty string
I am trying to print out different options which are parameters to my function, however, i want my code not to print anything if that specific parameter is an empty string.
The code I have till now:

```<code>def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)

#store answer under user_response
user_response = input("Your answer: ")

return user_response
</code>```

This prints

How are you

good

bad

when parameters are:
("How are you", "good", "bad","","")

but I would like it to print:

How are you

good

bad

without including any options with an empty string

Any help on what I should do?

答:
I just used an if statement before everyone and it worked out fine:
ex:
if(option1 != "")
print("1", option1)
this worked and passed the test</p>

Body:
I am trying to print out different options which are parameters to my function, however, i want my code not to print anything if that specific parameter is an empty string.
The code I have till now:

def ask_question(question, option1, option2, option3, option4):
#print the question onto the screen as well as numbered options
print(question)
print("1 ", option1)
print("2 ", option2)
print("3 ", option3)
print("4 ", option4)

#store answer under user_response
user_response = input("Your answer: ")

return user_response

This prints

How are you

good

bad

when parameters are:
("How are you", "good", "bad","","")

but I would like it to print:

How are you

good

bad

without including any options with an empty string

Any help on what I should do?


问:
Flattening two last dimensions of a tensor in TensorFlow
I'm trying to reshape a tensor from [A, B, C, D] into [A, B, C * D] and feed it into a dynamic_rnn. Assume that I don't know the B, C, and D in advance (they're a result of a convolutional network).

I think in Theano such reshaping would look like this:

```<code>x = x.flatten(ndim=3)
</code>```

It seems that in TensorFlow there's no easy way to do this and so far here's what I came up with:

```<code>x_shape = tf.shape(x)
x = tf.reshape(x, [batch_size, x_shape[1], tf.reduce_prod(x_shape[2:])]
</code>```

Even when the shape of x is known during graph building (i.e. print(x.get_shape()) prints out absolute values, like [10, 20, 30, 40] after the reshaping get_shape() becomes [10, None, None]. Again, still assume the initial shape isn't known so I can't operate with absolute values.

And when I'm passing x to a dynamic_rnn it fails:

```<code>ValueError: Input size (depth of inputs) must be accessible via shape inference, but saw value None.
</code>```

Why is reshape unable to handle this case? What is the right way of replicating Theano's flatten(ndim=n) in TensorFlow with tensors of rank 4 and more?

答:
If you use the tf.keras.models.Model or tf.keras.layers.Layer wrapper, the build method provides a nice way to do this.

Here's an example:

```<code>import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv1D, Conv2D, Conv2DTranspose, Attention, Layer, Reshape

class VisualAttention(Layer):
    def __init__(self, channels_out, key_is_value=True):
        super(VisualAttention, self).__init__()

        self.channels_out = channels_out
        self.key_is_value = key_is_value

        self.flatten_images = None  # see build method
        self.unflatten_images = None  # see build method

        self.query_conv = Conv1D(filters=channels_out, kernel_size=1, padding='same')
        self.value_conv = Conv1D(filters=channels_out, kernel_size=4, padding='same')
        self.key_conv = self.value_conv if key_is_value else Conv1D(filters=channels_out, kernel_size=4, padding='same')

        self.attention_layer = Attention(use_scale=False, causal=False, dropout=0.)

    def build(self, input_shape):
        b, h, w, c = input_shape
        self.flatten_images = Reshape((h*w, c), input_shape=(h, w, c))
        self.unflatten_images = Reshape((h, w, self.channels_out), input_shape=(h*w, self.channels_out))

    def call(self, x, training=True):
        x = self.flatten_images(x)
        q = self.query_conv(x)
        v = self.value_conv(x)

        inputs = [q, v] if self.key_is_value else [q, v, self.key_conv(x)]
        output = self.attention_layer(inputs=inputs, training=training)
        return self.unflatten_images(output)

# test
import numpy as np
x = np.arange(8*28*32*3).reshape((8, 28, 32, 3)).astype('float32')
model = VisualAttention(8)
y = model(x)
print(y.shape)
</code>```

Body:
I'm trying to reshape a tensor from [A, B, C, D] into [A, B, C * D] and feed it into a dynamic_rnn. Assume that I don't know the B, C, and D in advance (they're a result of a convolutional network).

I think in Theano such reshaping would look like this:

x = x.flatten(ndim=3)

It seems that in TensorFlow there's no easy way to do this and so far here's what I came up with:

x_shape = tf.shape(x)
x = tf.reshape(x, [batch_size, x_shape[1], tf.reduce_prod(x_shape[2:])]

Even when the shape of x is known during graph building (i.e. print(x.get_shape()) prints out absolute values, like [10, 20, 30, 40] after the reshaping get_shape() becomes [10, None, None]. Again, still assume the initial shape isn't known so I can't operate with absolute values.

And when I'm passing x to a dynamic_rnn it fails:

ValueError: Input size (depth of inputs) must be accessible via shape inference, but saw value None.

Why is reshape unable to handle this case? What is the right way of replicating Theano's flatten(ndim=n) in TensorFlow with tensors of rank 4 and more?

Body:
If you use the tf.keras.models.Model or tf.keras.layers.Layer wrapper, the build method provides a nice way to do this.

Here's an example:

import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv1D, Conv2D, Conv2DTranspose, Attention, Layer, Reshape

class VisualAttention(Layer):
    def __init__(self, channels_out, key_is_value=True):
        super(VisualAttention, self).__init__()

        self.channels_out = channels_out
        self.key_is_value = key_is_value

        self.flatten_images = None  # see build method
        self.unflatten_images = None  # see build method

        self.query_conv = Conv1D(filters=channels_out, kernel_size=1, padding='same')
        self.value_conv = Conv1D(filters=channels_out, kernel_size=4, padding='same')
        self.key_conv = self.value_conv if key_is_value else Conv1D(filters=channels_out, kernel_size=4, padding='same')

        self.attention_layer = Attention(use_scale=False, causal=False, dropout=0.)

    def build(self, input_shape):
        b, h, w, c = input_shape
        self.flatten_images = Reshape((h*w, c), input_shape=(h, w, c))
        self.unflatten_images = Reshape((h, w, self.channels_out), input_shape=(h*w, self.channels_out))

    def call(self, x, training=True):
        x = self.flatten_images(x)
        q = self.query_conv(x)
        v = self.value_conv(x)

        inputs = [q, v] if self.key_is_value else [q, v, self.key_conv(x)]
        output = self.attention_layer(inputs=inputs, training=training)
        return self.unflatten_images(output)

# test
import numpy as np
x = np.arange(8*28*32*3).reshape((8, 28, 32, 3)).astype('float32')
model = VisualAttention(8)
y = model(x)
print(y.shape)


问:
Recent gyroscope support from Corona SDK seems to be non-responsive
I'm using a recent daily build of the Corona SDK (version 2001.562) to add gyroscope support to an existing application. Unfortunately, I can't seem to get the event-handling function for the gyroscope to fire. The application is running on an iPod touch, version 4.3.3.

I attach the gyroscope to an event handler like so:

```<code>if system.hasEventSource("gyroscope") then
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope on\n");
    io.close(feedbackFile);
    Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
else
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope off\n");
    io.close(feedbackFile);
end
</code>```

When I launch the application on the device, then close it and download the resource files, I find that log.txt contains the line with a timestamp and "gyroscope on". Good so far!

On to the event-handling function:

```<code>local function onGyroscopeDataReceived(event)

    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope reading delta="..event.deltaRotation..",x="..event.xRotation..",y="..event.yRotation..",z="..event.zRotation.."\n");
    io.close(feedbackFile);
end
</code>```

This line of information never appears in the log.txt file!

Please advise. Thanks in advance!

答:
The problem is event.deltaRotation doesn't exist. You might mean event.deltaTime.

Then when you concatenate a nil value, Lua throws an error and your write code never gets completed. (The latest daily build will now print out a message when you encounter a Lua error on a device.)

The documentation shows how to compute your own deltaDegrees or deltaRadians:
http://developer.anscamobile.com/reference/index/events/gyroscope/eventxrotation

Body:
I'm using a recent daily build of the Corona SDK (version 2001.562) to add gyroscope support to an existing application. Unfortunately, I can't seem to get the event-handling function for the gyroscope to fire. The application is running on an iPod touch, version 4.3.3.

I attach the gyroscope to an event handler like so:

if system.hasEventSource("gyroscope") then
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope on\n");
    io.close(feedbackFile);
    Runtime:addEventListener( "gyroscope", onGyroscopeDataReceived )
else
    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope off\n");
    io.close(feedbackFile);
end

When I launch the application on the device, then close it and download the resource files, I find that log.txt contains the line with a timestamp and "gyroscope on". Good so far!

On to the event-handling function:

local function onGyroscopeDataReceived(event)

    feedbackFile = io.open(system.pathForFile("log.txt", system.DocumentsDirectory), "a");
    feedbackFile:write((os.clock()-startupTime).."\tgyroscope reading delta="..event.deltaRotation..",x="..event.xRotation..",y="..event.yRotation..",z="..event.zRotation.."\n");
    io.close(feedbackFile);
end

This line of information never appears in the log.txt file!

Please advise. Thanks in advance!