问:
Error: Cannot reattach ActivatedRouteSnapshot created from a different route
I am trying to implement the RouteReuseStrategy class. It works fine when I navigate to top level paths.

As soon as a path has child paths and I navigate to the child path, then navigate back to a top level path I receive the following error:

Error: Uncaught (in promise): Error: Cannot reattach ActivatedRouteSnapshot created from a different route

I have created a plunker to demonstrate the error. I see the plunker does not work in IE 11, please view it in the latest version of Chrome

Steps to reproduce the error:

Step1:

Step2

Step3

Step4

You can view the error in the console:

I have tried the implementation found on this article

```<code>export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldDetach', route);
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}
</code>```

And the implementation of this stackoverflow answer

```<code>/**
 * reuse-strategy.ts
 * by corbfon 1/6/17
 */

import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';

/** Interface for object which can store both:
 * An ActivatedRouteSnapshot, which is useful for determining whether or not you should attach a route (see this.shouldAttach)
 * A DetachedRouteHandle, which is offered up by this.retrieve, in the case that you do want to attach the stored route
 */
interface RouteStorageObject {
    snapshot: ActivatedRouteSnapshot;
    handle: DetachedRouteHandle;
}

export class CustomReuseStrategy implements RouteReuseStrategy {

    /**
     * Object which will store RouteStorageObjects indexed by keys
     * The keys will all be a path (as in route.routeConfig.path)
     * This allows us to see if we've got a route stored for the requested path
     */
    storedRoutes: { [key: string]: RouteStorageObject } = {};

    /**
     * Decides when the route should be stored
     * If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
     * _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
     * An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
     * @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
     * @returns boolean indicating that we want to (true) or do not want to (false) store that route
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        let detach: boolean = true;
        console.log("detaching", route, "return: ", detach);
        return detach;
    }

    /**
     * Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
     * @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
     * @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
     */
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        let storedRoute: RouteStorageObject = {
            snapshot: route,
            handle: handle
        };

        console.log("store:", storedRoute, "into: ", this.storedRoutes);
        // routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
        this.storedRoutes[route.routeConfig.path] = storedRoute;
    }

    /**
     * Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
     * @param route The route the user requested
     * @returns boolean indicating whether or not to render the stored route
     */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {

        // this will be true if the route has been stored before
        let canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];

        // this decides whether the route already stored should be rendered in place of the requested route, and is the return value
        // at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
        // so, if the route.params and route.queryParams also match, then we should reuse the component
        if (canAttach) {
            let willAttach: boolean = true;
            console.log("param comparison:");
            console.log(this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params));
            console.log("query param comparison");
            console.log(this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams));

            let paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
            let queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);

            console.log("deciding to attach...", route, "does it match?", this.storedRoutes[route.routeConfig.path].snapshot, "return: ", paramsMatch && queryParamsMatch);
            return paramsMatch && queryParamsMatch;
        } else {
            return false;
        }
    }

    /**
     * Finds the locally stored instance of the requested route, if it exists, and returns it
     * @param route New route the user has requested
     * @returns DetachedRouteHandle object which can be used to render the component
     */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

        // return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
        if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;
        console.log("retrieving", "return: ", this.storedRoutes[route.routeConfig.path]);

        /** returns handle when the route.routeConfig.path is already stored */
        return this.storedRoutes[route.routeConfig.path].handle;
    }

    /**
     * Determines whether or not the current route should be reused
     * @param future The route the user is going to, as triggered by the router
     * @param curr The route the user is currently on
     * @returns boolean basically indicating true if the user intends to leave the current route
     */
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.log("deciding to reuse", "future", future.routeConfig, "current", curr.routeConfig, "return: ", future.routeConfig === curr.routeConfig);
        return future.routeConfig === curr.routeConfig;
    }

    /**
     * This nasty bugger finds out whether the objects are _traditionally_ equal to each other, like you might assume someone else would have put this function in vanilla JS already
     * One thing to note is that it uses coercive comparison (==) on properties which both objects have, not strict comparison (===)
     * @param base The base object which you would like to compare another object to
     * @param compare The object to compare to base
     * @returns boolean indicating whether or not the objects have all the same properties and those properties are ==
     */
    private compareObjects(base: any, compare: any): boolean {

        // loop through all properties in base object
        for (let baseProperty in base) {

            // determine if comparrison object has that property, if not: return false
            if (compare.hasOwnProperty(baseProperty)) {
                switch (typeof base[baseProperty]) {
                    // if one is object and other is not: return false
                    // if they are both objects, recursively call this comparison function
                    case 'object':
                        if (typeof compare[baseProperty] !== 'object' || !this.compareObjects(base[baseProperty], compare[baseProperty])) { return false; } break;
                    // if one is function and other is not: return false
                    // if both are functions, compare function.toString() results
                    case 'function':
                        if (typeof compare[baseProperty] !== 'function' || base[baseProperty].toString() !== compare[baseProperty].toString()) { return false; } break;
                    // otherwise, see if they are equal using coercive comparison
                    default:
                        if (base[baseProperty] != compare[baseProperty]) { return false; }
                }
            } else {
                return false;
            }
        }

        // returns true only after false HAS NOT BEEN returned through all loops
        return true;
    }
}
</code>```

Is RouteReuseStrategy ready for child paths? Or is there another way to get RouteReuseStrategy working with paths that contain child paths

答:
Here is a way to generate unique keys for routes in the strategy class.
I had similar problem but once i started generating unique keys the problem disappeared:

```<code>private takeFullUrl(route: ActivatedRouteSnapshot) {
  let next = route;
  // Since navigation is usually relative
  // we go down to find out the child to be shown.
  while (next.firstChild) {
    next = next.firstChild;
  }
  const segments = [];
  // Then build a unique key-path by going to the root.
  while (next) {
    segments.push(next.url.join('/'));
    next = next.parent;
  }
  return compact(segments.reverse()).join('/');
}
</code>```

More on that https://github.com/angular/angular/issues/13869#issuecomment-344403045

Body:
I am trying to implement the RouteReuseStrategy class. It works fine when I navigate to top level paths.

As soon as a path has child paths and I navigate to the child path, then navigate back to a top level path I receive the following error:

Error: Uncaught (in promise): Error: Cannot reattach ActivatedRouteSnapshot created from a different route

I have created a plunker to demonstrate the error. I see the plunker does not work in IE 11, please view it in the latest version of Chrome

Steps to reproduce the error:

Step1:

Step2

Step3

Step4

You can view the error in the console:

I have tried the implementation found on this article

export class CustomReuseStrategy implements RouteReuseStrategy {

    handlers: {[key: string]: DetachedRouteHandle} = {};

    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldDetach', route);
        return true;
    }

    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        console.debug('CustomReuseStrategy:store', route, handle);
        this.handlers[route.routeConfig.path] = handle;
    }

    shouldAttach(route: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldAttach', route);
        return !!route.routeConfig && !!this.handlers[route.routeConfig.path];
    }

    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {
        console.debug('CustomReuseStrategy:retrieve', route);
        if (!route.routeConfig) return null;
        return this.handlers[route.routeConfig.path];
    }

    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.debug('CustomReuseStrategy:shouldReuseRoute', future, curr);
        return future.routeConfig === curr.routeConfig;
    }

}

And the implementation of this stackoverflow answer

/**
 * reuse-strategy.ts
 * by corbfon 1/6/17
 */

import { ActivatedRouteSnapshot, RouteReuseStrategy, DetachedRouteHandle } from '@angular/router';

/** Interface for object which can store both:
 * An ActivatedRouteSnapshot, which is useful for determining whether or not you should attach a route (see this.shouldAttach)
 * A DetachedRouteHandle, which is offered up by this.retrieve, in the case that you do want to attach the stored route
 */
interface RouteStorageObject {
    snapshot: ActivatedRouteSnapshot;
    handle: DetachedRouteHandle;
}

export class CustomReuseStrategy implements RouteReuseStrategy {

    /**
     * Object which will store RouteStorageObjects indexed by keys
     * The keys will all be a path (as in route.routeConfig.path)
     * This allows us to see if we've got a route stored for the requested path
     */
    storedRoutes: { [key: string]: RouteStorageObject } = {};

    /**
     * Decides when the route should be stored
     * If the route should be stored, I believe the boolean is indicating to a controller whether or not to fire this.store
     * _When_ it is called though does not particularly matter, just know that this determines whether or not we store the route
     * An idea of what to do here: check the route.routeConfig.path to see if it is a path you would like to store
     * @param route This is, at least as I understand it, the route that the user is currently on, and we would like to know if we want to store it
     * @returns boolean indicating that we want to (true) or do not want to (false) store that route
     */
    shouldDetach(route: ActivatedRouteSnapshot): boolean {
        let detach: boolean = true;
        console.log("detaching", route, "return: ", detach);
        return detach;
    }

    /**
     * Constructs object of type `RouteStorageObject` to store, and then stores it for later attachment
     * @param route This is stored for later comparison to requested routes, see `this.shouldAttach`
     * @param handle Later to be retrieved by this.retrieve, and offered up to whatever controller is using this class
     */
    store(route: ActivatedRouteSnapshot, handle: DetachedRouteHandle): void {
        let storedRoute: RouteStorageObject = {
            snapshot: route,
            handle: handle
        };

        console.log("store:", storedRoute, "into: ", this.storedRoutes);
        // routes are stored by path - the key is the path name, and the handle is stored under it so that you can only ever have one object stored for a single path
        this.storedRoutes[route.routeConfig.path] = storedRoute;
    }

    /**
     * Determines whether or not there is a stored route and, if there is, whether or not it should be rendered in place of requested route
     * @param route The route the user requested
     * @returns boolean indicating whether or not to render the stored route
     */
    shouldAttach(route: ActivatedRouteSnapshot): boolean {

        // this will be true if the route has been stored before
        let canAttach: boolean = !!route.routeConfig && !!this.storedRoutes[route.routeConfig.path];

        // this decides whether the route already stored should be rendered in place of the requested route, and is the return value
        // at this point we already know that the paths match because the storedResults key is the route.routeConfig.path
        // so, if the route.params and route.queryParams also match, then we should reuse the component
        if (canAttach) {
            let willAttach: boolean = true;
            console.log("param comparison:");
            console.log(this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params));
            console.log("query param comparison");
            console.log(this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams));

            let paramsMatch: boolean = this.compareObjects(route.params, this.storedRoutes[route.routeConfig.path].snapshot.params);
            let queryParamsMatch: boolean = this.compareObjects(route.queryParams, this.storedRoutes[route.routeConfig.path].snapshot.queryParams);

            console.log("deciding to attach...", route, "does it match?", this.storedRoutes[route.routeConfig.path].snapshot, "return: ", paramsMatch && queryParamsMatch);
            return paramsMatch && queryParamsMatch;
        } else {
            return false;
        }
    }

    /**
     * Finds the locally stored instance of the requested route, if it exists, and returns it
     * @param route New route the user has requested
     * @returns DetachedRouteHandle object which can be used to render the component
     */
    retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle {

        // return null if the path does not have a routerConfig OR if there is no stored route for that routerConfig
        if (!route.routeConfig || !this.storedRoutes[route.routeConfig.path]) return null;
        console.log("retrieving", "return: ", this.storedRoutes[route.routeConfig.path]);

        /** returns handle when the route.routeConfig.path is already stored */
        return this.storedRoutes[route.routeConfig.path].handle;
    }

    /**
     * Determines whether or not the current route should be reused
     * @param future The route the user is going to, as triggered by the router
     * @param curr The route the user is currently on
     * @returns boolean basically indicating true if the user intends to leave the current route
     */
    shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean {
        console.log("deciding to reuse", "future", future.routeConfig, "current", curr.routeConfig, "return: ", future.routeConfig === curr.routeConfig);
        return future.routeConfig === curr.routeConfig;
    }

    /**
     * This nasty bugger finds out whether the objects are _traditionally_ equal to each other, like you might assume someone else would have put this function in vanilla JS already
     * One thing to note is that it uses coercive comparison (==) on properties which both objects have, not strict comparison (===)
     * @param base The base object which you would like to compare another object to
     * @param compare The object to compare to base
     * @returns boolean indicating whether or not the objects have all the same properties and those properties are ==
     */
    private compareObjects(base: any, compare: any): boolean {

        // loop through all properties in base object
        for (let baseProperty in base) {

            // determine if comparrison object has that property, if not: return false
            if (compare.hasOwnProperty(baseProperty)) {
                switch (typeof base[baseProperty]) {
                    // if one is object and other is not: return false
                    // if they are both objects, recursively call this comparison function
                    case 'object':
                        if (typeof compare[baseProperty] !== 'object' || !this.compareObjects(base[baseProperty], compare[baseProperty])) { return false; } break;
                    // if one is function and other is not: return false
                    // if both are functions, compare function.toString() results
                    case 'function':
                        if (typeof compare[baseProperty] !== 'function' || base[baseProperty].toString() !== compare[baseProperty].toString()) { return false; } break;
                    // otherwise, see if they are equal using coercive comparison
                    default:
                        if (base[baseProperty] != compare[baseProperty]) { return false; }
                }
            } else {
                return false;
            }
        }

        // returns true only after false HAS NOT BEEN returned through all loops
        return true;
    }
}

Is RouteReuseStrategy ready for child paths? Or is there another way to get RouteReuseStrategy working with paths that contain child paths

Body:
Here is a way to generate unique keys for routes in the strategy class.
I had similar problem but once i started generating unique keys the problem disappeared:

private takeFullUrl(route: ActivatedRouteSnapshot) {
  let next = route;
  // Since navigation is usually relative
  // we go down to find out the child to be shown.
  while (next.firstChild) {
    next = next.firstChild;
  }
  const segments = [];
  // Then build a unique key-path by going to the root.
  while (next) {
    segments.push(next.url.join('/'));
    next = next.parent;
  }
  return compact(segments.reverse()).join('/');
}

More on that https://github.com/angular/angular/issues/13869#issuecomment-344403045


来源: stackexchange

问:
Doctrine schema:update generates the same SQL again and again
Running bin/console doctrine:schema:update --force again and again, it always output 39 queries executed even after clearing cache/restarting php-fpm. So it always execute the same SQL requests again and again...

The SQL looks likes (from --dump-sql)

```<code>ALTER TABLE apply_queue CHANGE cv_id cv_id INT DEFAULT NULL, CHANGE team_id team_id INT DEFAULT NULL;
....
</code>```

And a lot of lines similar to this.

The ApplyQueue class look like:

```<code>/**
 * AppBundle\Entity\ApplyQueue.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\ApplyQueueRepository")
 * @ORM\Table(name="apply_queue")
 */
class ApplyQueue
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Cv")
     * @ORM\JoinColumn(name="cv_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $cv;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Team")
     * @ORM\JoinColumn(name="team_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $team;

    ...
</code>```

}

DBAL config :

```<code>doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci
        types:
            json: Sonata\Doctrine\Types\JsonType
            review_status: AppBundle\Model\Enum\ReviewStatusEnumType
        mapping_types:
            review_status: string
</code>```

The structure of the table:

This is an "old" project that has been upgraded to Symfony 3.4 and MariaDB 10.2.

Thanks

答:
In your app/config/config.yml, check if doctrine cache is enabled as below :

```<code>doctrine:
    orm:
        metadata_cache_driver: redis
</code>```

If so, you will have to flush redis cache:

```<code>php bin/console redis:flushdb --client=CLIENT_NAME -n
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Running bin/console doctrine:schema:update --force again and again, it always output 39 queries executed even after clearing cache/restarting php-fpm. So it always execute the same SQL requests again and again...

The SQL looks likes (from --dump-sql)

ALTER TABLE apply_queue CHANGE cv_id cv_id INT DEFAULT NULL, CHANGE team_id team_id INT DEFAULT NULL;
....

And a lot of lines similar to this.

The ApplyQueue class look like:

/**
 * AppBundle\Entity\ApplyQueue.
 *
 * @ORM\Entity(repositoryClass="AppBundle\Entity\ApplyQueueRepository")
 * @ORM\Table(name="apply_queue")
 */
class ApplyQueue
{
    /**
     * @var int
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Cv")
     * @ORM\JoinColumn(name="cv_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $cv;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Team")
     * @ORM\JoinColumn(name="team_id", referencedColumnName="id", onDelete="CASCADE")
     */
    protected $team;

    ...

}

DBAL config :

doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset: utf8mb4
        default_table_options:
            charset: utf8mb4
            collate: utf8mb4_unicode_ci
        types:
            json: Sonata\Doctrine\Types\JsonType
            review_status: AppBundle\Model\Enum\ReviewStatusEnumType
        mapping_types:
            review_status: string

The structure of the table:

This is an "old" project that has been upgraded to Symfony 3.4 and MariaDB 10.2.

Thanks

Body:
In your app/config/config.yml, check if doctrine cache is enabled as below :

doctrine:
    orm:
        metadata_cache_driver: redis

If so, you will have to flush redis cache:

php bin/console redis:flushdb --client=CLIENT_NAME -n


问:
How to send push notifications to web application and browser?
I have a database in which I insert and send data using java.So I want to send push notifications using java to my web application and getting them in javascript.

I also want to send push notification to my browser.Is there an easy way to do these two things? I have been trying for days but I have not found a well explained tutorial that I can understand.

Thank you in advance.

答:
If you want to display the notifications when the users are surfing your website then you can:

Get the notifications from your server: you can use WebSockets, SSE or long polling with the Fetch API or AJAX.

Display a notification to the user: you can use HTML and CSS or use the the Notification API.

If you want to display the notifications or process the push events even when your website is closed (like native apps) then you must use more advanced technologies. In particular:

you need to use the Push API to send a message from your server to a browser

the push event generated with the Push API activates a callback in the service worker

the service worker process the event and display the notification using the Notification API

For web push I recommend Pushpad (I am the founder), so that you don't have to build from scratch. It has also a Java library.

ContentLicense: CC BY-SA 4.0


问:
position inside getview is getting changed in onCheckedChaneListener which is inside Adapter
I have Created a Listview with CustomAdapter which is having radio button in each row [ Single choice ] bt its resulting wrong after adapter has been setted</p>

```<code>  if (arr_data.get(position).isdefaultCurrency())   holder.radio_currency.setChecked(true);
  } else {
        holder.radio_currency.setChecked(false);
    }
    holder.radio_currency.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                for (int k = 0; k < arr_data.size(); k++) {
                    if (k == position) {
                        arr_data.get(k).setIsdefaultCurrency(true);
                    } else {
                        arr_data.get(k).setIsdefaultCurrency(false);
                    }
                }
            } else {
                arr_data.get(position).setIsdefaultCurrency(false);
            }
            notifyDataSetChanged();
        }
    });
</code>```

答: I think you are making this more complicated than necessary. It appears that you have a list of radio buttons and you want to know which one was selected. Rather than using a list of boolean values, just store a single int with the position of the selected. Alternatively, store something more meaningful to represent the default currency, such as a character '$', etc.

Body:
I have Created a Listview with CustomAdapter which is having radio button in each row [ Single choice ] bt its resulting wrong after adapter has been setted

  if (arr_data.get(position).isdefaultCurrency())   holder.radio_currency.setChecked(true);
  } else {
        holder.radio_currency.setChecked(false);
    }
    holder.radio_currency.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {

                for (int k = 0; k < arr_data.size(); k++) {
                    if (k == position) {
                        arr_data.get(k).setIsdefaultCurrency(true);
                    } else {
                        arr_data.get(k).setIsdefaultCurrency(false);
                    }
                }
            } else {
                arr_data.get(position).setIsdefaultCurrency(false);
            }
            notifyDataSetChanged();
        }
    });


问:
What does 8.309618000000001D-02 mean in QBASIC
I have a QBASIC program that basically consists of formulas and constants, and I want to translate the formulas and constants into a C++ programm. Since the formulas are not rocket science and the program is well documented, I have no problem translating the program, although I have not used or seen QBASIC before.

However, there is an initialization of a variable that reads abc(15) = 9.207134000000001D-02, and I am not sure how to interpret the D-02. I guess I should translate it like abc[15] =0.09207134...., but I'd like to verify if this is correct.

答:
If I recall correctly D-02 means times ten raised to the power minus 2.

So 8.309618000000001D-02 = 8.30961800000000 x 10^(-2)

which is roughly 0.08309618

I also think the D means the type of the number is a double.

EDIT: It's been ages since I wrote any QBASIC code

ContentLicense: CC BY-SA 2.5


问:
Ruby on Rails - Passing a hash as a parameter with link_to_remote Rails 2
am working in Rails version 2.3.8
Hash => agent_list = [[5, "val"], [4, "val"], [3, "val"], [1, "val"]]

```<code><%= link_to_remote "Click Here",
        :url => {
        :controller => "controller",
        :action => "method",
        :id => @p_id,
        :hash_list => hash_list
        },
        :method => 'post' %>
</code>```

The link generated is :

[http://localhost/controller/method/12?hash_list%5B%5D%5B%5D=5&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=4&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=3&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=1&hash_list%5B%5D%5B%5D=val]

Could anyone tell me what is the right way to get something like:
http://localhost/controller/method/12?hash_list=[hash_list]

so that i can use it as params[:agent_list] in my controller method.

P.S. sorry if its a nooby question.

答:
My <%= link_to @item_link_name, show_item_path(item: {id: @item.id}) %>

generates http://localhost:3000/items/show_item?item%5Bid%5D=XXX,

what is recognised by controller as params[:item][:id]

Body:
am working in Rails version 2.3.8
Hash => agent_list = [[5, "val"], [4, "val"], [3, "val"], [1, "val"]]

<%= link_to_remote "Click Here",
        :url => {
        :controller => "controller",
        :action => "method",
        :id => @p_id,
        :hash_list => hash_list
        },
        :method => 'post' %>

The link generated is :

[http://localhost/controller/method/12?hash_list%5B%5D%5B%5D=5&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=4&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=3&hash_list%5B%5D%5B%5D=val&hash_list%5B%5D%5B%5D=1&hash_list%5B%5D%5B%5D=val]

Could anyone tell me what is the right way to get something like:
http://localhost/controller/method/12?hash_list=[hash_list]

so that i can use it as params[:agent_list] in my controller method.

P.S. sorry if its a nooby question.


问:
Data returned from service is not displaying in component in angular 2
I have a component that calls a service and returns data, as shown. The data is not displaying on the HTML page. What did I miss? roots array is coming back as an array of an array, but the data is correct and I believe the HTML is correct also

New to Angular 2 so any help will be greatly appreciated

The root component.

```<code>export class RootsComponent implements OnInit {
    private baseRootEndpoint: string = 'http://localhost:59534/api/admin';

    private isUploadBtn: boolean = true;
    private dbops: number = 0;
    private msg: string = '';
    private dataForm: FormGroup;
    private imageData;
    private contentType;
    private fileLength;
    public roots: Root[];
    private isLoading = true;
    @Input() root: Root;

    constructor(private http: Http, private _rootService : RootService,  fb:FormBuilder) {
    }

    ngOnInit() {
       this.roots = [];
       this.getRoots();
    }

    //call the service and bring back a list of roots

    getRoots() {
        debugger;
        var me = this;
        this._rootService.get(this.baseRootEndpoint).subscribe(
            data => me.roots.push(JSON.parse(data._body)),
            error => me.msg = error
        );
        this.isLoading = false;
    }
}

//simple service
@Injectable()
export class RootService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
       debugger;
       return this._http.get(url);

    }
}

<div class="container-fluid">
    <div class="row">
        <div class="header">
            <h4 class="title">   Roots</h4>
        </div>

        <div class="col-lg-10 col-lg-offset-1" *ngIf="!isLoading">
            <table>
                <thead>
                    <tr>
                        <th>Root Name</th>
                        <th>Root</th>
                        <th>Definition</th>
                    </tr>
                </thead>
                <tbody>
                    <tr  *ngFor="let root of roots[0]" let id="index">
                        <td>{{root.DescriptiveName}}</td>
                        <td><img src="{{root.Root}}" name="rootImage" /></td>
                        <td></td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>
</code>```

答:
So in angular 2/4 we have to work with observables to let the component know it will be changed so in service:

```<code>roots: Observable<Array<Root>>;
getRoots() {
    debugger;
    var me = this;
    this._rootService.get(this.baseRootEndpoint).subscribe(
        data => me.roots = (JSON.parse(data._body)),
        error => me.msg = error
    );
    this.isLoading = false;
}
</code>```

Then in your HTML:

```<code>*ngFor="let root of roots | async"
</code>```

This async flag implies we are resolving the observable we have in our observable, if you want to avoid using an async pipe you can subscribe to the variable in your ngOnInit and let it print to a seperate Array

If there is any problem feel free to contact me :) Good luck!

PS: it would help alot if you would show us your JSON output and tell us if the error gets called or not.

Body:
I have a component that calls a service and returns data, as shown. The data is not displaying on the HTML page. What did I miss? roots array is coming back as an array of an array, but the data is correct and I believe the HTML is correct also

New to Angular 2 so any help will be greatly appreciated

The root component.

export class RootsComponent implements OnInit {
    private baseRootEndpoint: string = 'http://localhost:59534/api/admin';

    private isUploadBtn: boolean = true;
    private dbops: number = 0;
    private msg: string = '';
    private dataForm: FormGroup;
    private imageData;
    private contentType;
    private fileLength;
    public roots: Root[];
    private isLoading = true;
    @Input() root: Root;

    constructor(private http: Http, private _rootService : RootService,  fb:FormBuilder) {
    }

    ngOnInit() {
       this.roots = [];
       this.getRoots();
    }

    //call the service and bring back a list of roots

    getRoots() {
        debugger;
        var me = this;
        this._rootService.get(this.baseRootEndpoint).subscribe(
            data => me.roots.push(JSON.parse(data._body)),
            error => me.msg = error
        );
        this.isLoading = false;
    }
}

//simple service
@Injectable()
export class RootService {
    constructor(private _http: Http) { }

    get(url: string): Observable<any> {
       debugger;
       return this._http.get(url);

    }
}

   Roots

                        Root Name
                        Root
                        Definition

                        {{root.DescriptiveName}}

Body:
So in angular 2/4 we have to work with observables to let the component know it will be changed so in service:

roots: Observable<Array<Root>>;
getRoots() {
    debugger;
    var me = this;
    this._rootService.get(this.baseRootEndpoint).subscribe(
        data => me.roots = (JSON.parse(data._body)),
        error => me.msg = error
    );
    this.isLoading = false;
}

Then in your HTML:

*ngFor="let root of roots | async"

This async flag implies we are resolving the observable we have in our observable, if you want to avoid using an async pipe you can subscribe to the variable in your ngOnInit and let it print to a seperate Array

If there is any problem feel free to contact me :) Good luck!

PS: it would help alot if you would show us your JSON output and tell us if the error gets called or not.


问:
Excel VBA, getting range from an inactive sheet
This script works fine when I'm viewing the "Temp" sheet. But when I'm in another sheet then the copy command fails. It gives an Application-defined or object-defined error:

```<code>Sheets("Temp").Range(Cells(1), Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial
</code>```

I can use this script instead, but then I have problems with pasting it:

```<code>Sheets("Temp").Columns(1).Copy
Sheets("Overview").Range("C40").PasteSpecial
</code>```

I don't want to activate the "Temp" sheet to get this.

What else can I do?

答:
This will do, I don't like to use (xlDown) in case a cell is empty.

```<code>Dim lRow As Long
lRow = Sheets("Temp").Cells(Cells.Rows.Count, "A").End(xlUp).Row

With Sheets("Temp")
     .Range("A1:A" & lRow).Copy Sheets("Overview").Range("C40")
End With
</code>```

Or if you want to just use Columns...

```<code>Sheets("Temp").Columns(1).SpecialCells(xlCellTypeConstants).Copy Destination:=Sheets("Overview").Range("C40")
</code>```

Body:
This script works fine when I'm viewing the "Temp" sheet. But when I'm in another sheet then the copy command fails. It gives an Application-defined or object-defined error:

Sheets("Temp").Range(Cells(1), Cells(1).End(xlDown)).Copy
Sheets("Overview").Range("C40").PasteSpecial

I can use this script instead, but then I have problems with pasting it:

Sheets("Temp").Columns(1).Copy
Sheets("Overview").Range("C40").PasteSpecial

I don't want to activate the "Temp" sheet to get this.

What else can I do?

Body:
This will do, I don't like to use (xlDown) in case a cell is empty.

Dim lRow As Long
lRow = Sheets("Temp").Cells(Cells.Rows.Count, "A").End(xlUp).Row

With Sheets("Temp")
     .Range("A1:A" & lRow).Copy Sheets("Overview").Range("C40")
End With

Or if you want to just use Columns...

Sheets("Temp").Columns(1).SpecialCells(xlCellTypeConstants).Copy Destination:=Sheets("Overview").Range("C40")


问:
Task Await Call misunderstanding
Can anyone explain to me how this makes sense? It was an answer in another post that I asked (Does await new Task(async () => Actually halt execution until finished?) and I'm not really understanding part of the comment...

An asynchronous wait -- await -- waits for a task to complete. That's
  why its called "await".

It is asynchronous because if the task is not complete then await
  returns to the caller and does other work on this thread until the
  task is complete, at which time the work that follows the await is
  scheduled to execute.

Make sure you understand that await is an operator on tasks. It is not
  a calling convention on calls. Any expression of awaitable type can be
  awaited; don't fall into the trap of believing that await makes a call
  asynchronous. The called method is already asynchronous; the task that
  is returned is the thing that is awaited.

How does it "wait for the task to complete" but at the same time "returns to the caller and does other work"?

Thanks!

FOLLOW-UP:

I've seen the responses, so what should happen in the following pseudo-code example? Which tasks in which order would actually happen?

```<code>await new Task(async () =>
{
    //Do stuff 1
    Thread.Sleep(10000);
}

EventLog.Write("Do Stuff 2");

await new Task(async () =>
{
    //Do stuff 3
    Thread.Sleep(10000);
}
</code>```

Would "Do Stuff 1" execute, then wait, then "Do Stuff 2" would happen, then "Do Stuff 3"? Or would "Do Stuff 1" execute and then immediately "Do Stuff 2" followed by "Do Stuff 3"?

答:
Not all work requires the CPU, or a thread.

Imagine you are making a HTTP request to a web service.  Or streaming a file from disk or a network location.  In these cases, the request is being handled by another hardware component such as a network adapter or disk controller.

What if there's latency on the network, and it's going to take a long time to get the response back?  You could sit there blocking, waiting for the response.  Or you could use that time to do something else.

This is where async and await are really useful.  When you await a method which is doing I/O (e.g. disk or network), it's basically saying saying "please let me know when this task is complete".  Then you will return the caller so you can do other work (maybe CPU bound, maybe I/O bound).

When the task that you awaited is finished, the rest of the method after the await statement is then run.  This is called a continuation - the local state is captured at the time of the await statement, and it simply continues where it left off.

A good analogy I have heard is making breakfast.  Let's say you are having a cup of coffee and toast.  Boiling the kettle takes 2 minutes.  You could stand there and wait for the kettle to boil, then make your coffee and toast.  Or you could kick off the boiling task, go and make your toast, and then when you hear the whistling kettle, your "making coffee" task continues from where it left off.  Which is more efficient?

In your example, you would get the following, in this order:

Wait 10 seconds (Do stuff 1)

Write to event log (Do stuff 2)

Wait 10 seconds (Do stuff 3)

We will not continue past each await call until the Task that you're awaiting is complete.  In this case, you're awaiting an async Task, so it's actually a Task<Task> (because the async delegate itself uses a Task).  But I think the outer await unwraps both Task and when the outermost Task is complete the continuation is scheduled.

Title: Task Await Call misunderstanding

Body:
Can anyone explain to me how this makes sense? It was an answer in another post that I asked (Does await new Task(async () => Actually halt execution until finished?) and I'm not really understanding part of the comment...

An asynchronous wait -- await -- waits for a task to complete. That's
  why its called "await".

It is asynchronous because if the task is not complete then await
  returns to the caller and does other work on this thread until the
  task is complete, at which time the work that follows the await is
  scheduled to execute.

Make sure you understand that await is an operator on tasks. It is not
  a calling convention on calls. Any expression of awaitable type can be
  awaited; don't fall into the trap of believing that await makes a call
  asynchronous. The called method is already asynchronous; the task that
  is returned is the thing that is awaited.

How does it "wait for the task to complete" but at the same time "returns to the caller and does other work"?

Thanks!

FOLLOW-UP:

I've seen the responses, so what should happen in the following pseudo-code example? Which tasks in which order would actually happen?

await new Task(async () =>
{
    //Do stuff 1
    Thread.Sleep(10000);
}

EventLog.Write("Do Stuff 2");

await new Task(async () =>
{
    //Do stuff 3
    Thread.Sleep(10000);
}

Would "Do Stuff 1" execute, then wait, then "Do Stuff 2" would happen, then "Do Stuff 3"? Or would "Do Stuff 1" execute and then immediately "Do Stuff 2" followed by "Do Stuff 3"?


问:
ExecShellResult doesn't like my pipes
I wrote the following ExecShellResult fragment in cfengine v2.2.1a:

```<code>control:
    active_interface_mac = ( ExecShellResult(/sbin/ifconfig ${active_interface} | /usr/bin/grep 'ether ' | /usr/bin/cut -f2 -d' ') )
    ...
    time_drift = ( ExecShellResult(/usr/sbin/ntpdate -d pool.ntp.org 2>/dev/null | /usr/bin/grep -o 'offset.*sec' | /usr/bin/cut -f2 -d' ') )
    ...
shellcommands:
    "/bin/echo ${time_drift}" inform=true syslog=true
</code>```

When running the above from the command line, it obviously works fine:

```<code>$ ntpdate ...
0.183693
</code>```

However, if run inside cfengine, I get a syntax error:

```<code>$ cfagent -qIK
Executing script /bin/echo /usr/bin/cut...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo /usr/: /usr/bin/cut
cfengine: Finished script /bin/echo /usr/bin/cut
cfengine:
Executing script /bin/echo  option requires an argument -- d usage...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  opti: option requires an argument -- d usage
cfengine: Finished script /bin/echo  option requires an argument -- d usage
cfengine:
Executing script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  cut : cut -b list [-n] [file ...] cut -c list [file ...] cut -f list [-s] [-d delim] [file ...]
cfengine: Finished script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]
</code>```

Note the error is being displayed when we run the echo command under shellcommands:. By then, the ${time_drift} variable has been already evaluated, and its result shows we invoke cut's -d option incorrectly, complaining that we didn't pass anything to -d which is obviously not true.

This is baffling, because ${active_interface_mac} uses the same syntax and works perfectly.

I tried replacing the second grep with | tail -1 | sed 's///', another grep -o [0-9]*.[0-9] or anything else I could think of, including /usr/bin/cut -f1 -d'${spc}'. I apparently can't use awk because cfengine interprets $(NF) as parentheses which are part of ExecShellResult, even when escaped.

What other options do I have to get my actual seconds value extracted from ntpdate's output?

答:
I'm unsure about cfengine 2, I don't see what would trip it up in your example
but for cfengine 3:

```<code>bundle agent main
{
  vars:

    "ntpdate_s"
      string => execresult( "/usr/sbin/ntpdate -d pool.ntp.org 2> /dev/null | /usr/bin/awk '/offset .* sec/ {print $10}'", useshell ),
      if => not( isvariable( offset ) );

  reports:
    "Mac address of wlan0 $(sys.hardware_mac[wlan0])";
    "Offset is $(ntpdate_s)";
}
</code>```

Output:

```<code>R: Mac address of wlan0 5c:e0:c5:9f:f3:8f
R: Offset is 0.027672
</code>```

Title: ExecShellResult doesn't like my pipes

Body:
I wrote the following ExecShellResult fragment in cfengine v2.2.1a:

control:
    active_interface_mac = ( ExecShellResult(/sbin/ifconfig ${active_interface} | /usr/bin/grep 'ether ' | /usr/bin/cut -f2 -d' ') )
    ...
    time_drift = ( ExecShellResult(/usr/sbin/ntpdate -d pool.ntp.org 2>/dev/null | /usr/bin/grep -o 'offset.*sec' | /usr/bin/cut -f2 -d' ') )
    ...
shellcommands:
    "/bin/echo ${time_drift}" inform=true syslog=true

When running the above from the command line, it obviously works fine:

$ ntpdate ...
0.183693

However, if run inside cfengine, I get a syntax error:

$ cfagent -qIK
Executing script /bin/echo /usr/bin/cut...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo /usr/: /usr/bin/cut
cfengine: Finished script /bin/echo /usr/bin/cut
cfengine:
Executing script /bin/echo  option requires an argument -- d usage...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  opti: option requires an argument -- d usage
cfengine: Finished script /bin/echo  option requires an argument -- d usage
cfengine:
Executing script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]...(timeout=0,uid=-1,gid=-1)
cfengine:/bin/echo  cut : cut -b list [-n] [file ...] cut -c list [file ...] cut -f list [-s] [-d delim] [file ...]
cfengine: Finished script /bin/echo  cut -b list [-n] [file ...]        cut -c list [file ...]        cut -f list [-s] [-d delim] [file ...]

Note the error is being displayed when we run the echo command under shellcommands:. By then, the ${time_drift} variable has been already evaluated, and its result shows we invoke cut's -d option incorrectly, complaining that we didn't pass anything to -d which is obviously not true.

This is baffling, because ${active_interface_mac} uses the same syntax and works perfectly.

I tried replacing the second grep with | tail -1 | sed 's///', another grep -o [0-9]*.[0-9] or anything else I could think of, including /usr/bin/cut -f1 -d'${spc}'. I apparently can't use awk because cfengine interprets $(NF) as parentheses which are part of ExecShellResult, even when escaped.

What other options do I have to get my actual seconds value extracted from ntpdate's output?

Body:
I'm unsure about cfengine 2, I don't see what would trip it up in your example
but for cfengine 3:

bundle agent main
{
  vars:

    "ntpdate_s"
      string => execresult( "/usr/sbin/ntpdate -d pool.ntp.org 2> /dev/null | /usr/bin/awk '/offset .* sec/ {print $10}'", useshell ),
      if => not( isvariable( offset ) );

  reports:
    "Mac address of wlan0 $(sys.hardware_mac[wlan0])";
    "Offset is $(ntpdate_s)";
}

Output:

R: Mac address of wlan0 5c:e0:c5:9f:f3:8f
R: Offset is 0.027672


问:
Java FileWriter add column to csv
I'm writing a couple of arrays to a CSV and I have a problem creating a 2nd column.

I can write the first column no problem. When I try to append to the 2nd column it writers to the 2nd column but at the end of the first column.

```<code>  public void printCSV() throws IOException{

    // file writer
    FileWriter writer = new FileWriter("file path");

    for(int i = 0; i < myArray.length; i++){

    if(myArray[0][i] == null){
        writer.append(" ");
    }else{

        writer.append(myArray[0][i]);
        writer.append("\n");
    }

        } // end of for loop

    for(int i = 0; i < emptyResults.length; i++){

        writer.append(",");
        writer.append(String.valueOf(emptyResults[i]));
        writer.append("\n");

    }

    writer.close();

}
</code>```

Example output:

```<code>                   column1 column2
                    entry1
                    entry2
                    entry3
                    entry4
                            entry1
                            entry2
                            entry3
</code>```

what I'd like:

```<code>                    column1 column2
                    entry1  entry1
                    entry2  entry2
                    entry3  entry3
</code>```

When I write the 2nd array to the csv I force the write to another column using the "," but it won't start writing at row 1.

Any ideas?

Thanks.

Solution: A single loop with a new line with every loop.

```<code>   for(int i = 0; i < 128; i++){

    if(myArray[0][i] == null){
        writer.append(" ");
    }else{

        writer.append("\n");
        writer.append(myArray[0][i]+","+emptyResults[i]);

    }
</code>```

答:
from your code &  explanation i am assuming that both arrays will be of same size.Try this</p>

```<code>public void printCSV() throws IOException{

    // file writer
    FileWriter writer = new FileWriter("file.txt");

    for(int i = 0 ; i < myArray.length && i < emptyResults.length; i++){

    if(myArray[0][i] == null){
        writer.append(" "+String.valueOf(emptyResults[i]));
    }else{

        writer.append(myArray[0][i]+" "+String.valueOf(emptyResults[i]));
        writer.append("\n");
    }

        } // end of for loop
    writer.close();

}
</code>```

Title: Java FileWriter add column to csv

Body:
I'm writing a couple of arrays to a CSV and I have a problem creating a 2nd column.

I can write the first column no problem. When I try to append to the 2nd column it writers to the 2nd column but at the end of the first column.

  public void printCSV() throws IOException{

    // file writer
    FileWriter writer = new FileWriter("file path");

    for(int i = 0; i < myArray.length; i++){

    if(myArray[0][i] == null){
        writer.append(" ");
    }else{

        writer.append(myArray[0][i]);
        writer.append("\n");
    }

        } // end of for loop

    for(int i = 0; i < emptyResults.length; i++){

        writer.append(",");
        writer.append(String.valueOf(emptyResults[i]));
        writer.append("\n");

    }

    writer.close();

}

Example output:

                   column1 column2
                    entry1
                    entry2
                    entry3
                    entry4
                            entry1
                            entry2
                            entry3

what I'd like:

                    column1 column2
                    entry1  entry1
                    entry2  entry2
                    entry3  entry3

When I write the 2nd array to the csv I force the write to another column using the "," but it won't start writing at row 1.

Any ideas?

Thanks.

Solution: A single loop with a new line with every loop.

   for(int i = 0; i < 128; i++){

    if(myArray[0][i] == null){
        writer.append(" ");
    }else{

        writer.append("\n");
        writer.append(myArray[0][i]+","+emptyResults[i]);

    }

Body:
from your code &  explanation i am assuming that both arrays will be of same size.Try this

public void printCSV() throws IOException{

    // file writer
    FileWriter writer = new FileWriter("file.txt");

    for(int i = 0 ; i < myArray.length && i < emptyResults.length; i++){

    if(myArray[0][i] == null){
        writer.append(" "+String.valueOf(emptyResults[i]));
    }else{

        writer.append(myArray[0][i]+" "+String.valueOf(emptyResults[i]));
        writer.append("\n");
    }

        } // end of for loop
    writer.close();

}


Title: How to use pandas to shift the last row to the first

Body:
So I have a dataframe that looks like this:

                         #1                     #2
1980-01-01               11.6985                126.0
1980-01-02               43.6431                134.0
1980-01-03               54.9089                130.0
1980-01-04               63.1225                126.0
1980-01-05               72.4399                120.0

What I want to do is to shift the first row of the first column (11.6985) down 1 row, and then the last row of the first column (72.4399) would be shifted to the first row, first column, like so:

                         #1                     #2
1980-01-01               72.4399                126.0
1980-01-02               11.6985                134.0
1980-01-03               43.6431                130.0
1980-01-04               54.9089                126.0
1980-01-05               63.1225                120.0

The idea is that I want to use these dataframes to find an R^2 value for every shift, so I need to use all the data or it might not work. I have tried to use pandas.Dataframe.shift():

print(data)

#Output
1980-01-01               11.6985                126.0
1980-01-02               43.6431                134.0
1980-01-03               54.9089                130.0
1980-01-04               63.1225                126.0
1980-01-05               72.4399                120.0

print(data.shift(1,axis = 0))

1980-01-01                   NaN                  NaN
1980-01-02               11.6985                126.0
1980-01-03               43.6431                134.0
1980-01-04               54.9089                130.0
1980-01-05               63.1225                126.0

So it just shifts both columns down and gets rid of the last row of data, which is not what I want.

Any advice?

Body:
I don't think you could do this with shift, but one way is to use iloc:

In [11]: res = df.iloc[np.arange(-1, len(df)-1)]

In [12]: res
Out[12]:
                 #1     #2
1980-01-05  72.4399  120.0
1980-01-01  11.6985  126.0
1980-01-02  43.6431  134.0
1980-01-03  54.9089  130.0
1980-01-04  63.1225  126.0

In [13]: res.index = df.index

In [14]: res
Out[14]:
                 #1     #2
1980-01-01  72.4399  120.0
1980-01-02  11.6985  126.0
1980-01-03  43.6431  134.0
1980-01-04  54.9089  130.0
1980-01-05  63.1225  126.0

If you want this as a new column (just for #1):

In [21]: df.iloc[np.arange(-1, len(df)-1), 0]
Out[21]:
1980-01-05    72.4399
1980-01-01    11.6985
1980-01-02    43.6431
1980-01-03    54.9089
1980-01-04    63.1225
Name: #1, dtype: float64

In [22]: df.iloc[np.arange(-1, len(df)-1), 0].values
Out[22]: array([ 72.4399,  11.6985,  43.6431,  54.9089,  63.1225])

In [23]: df["new#1"] = df.iloc[np.arange(-1, len(df)-1), 0].values

In [24]: df
Out[24]:
                 #1     #2    new#1
1980-01-01  11.6985  126.0  72.4399
1980-01-02  43.6431  134.0  11.6985
1980-01-03  54.9089  130.0  43.6431
1980-01-04  63.1225  126.0  54.9089
1980-01-05  72.4399  120.0  63.1225


问:
Loop for converting files
I have many files I want to convert from sas7bdat to Rds using R, I am using the following code:

```<code>name <- read_sas("C:/Users/Desktop/Files/name.sas7bdat")
saveRDS(name, file = "C:/Users/Desktop/RDSfiles/name.Rds")
</code>```

but there are too many files I would like to use a loop to optimize to process, any ideas?

Thank you very much!!

答:
This is simple loop that I would use:

```<code>path_sas7bdat <- "C:/Users/Desktop/Files/"
path_RDS <- "C:/Users/Desktop/RDSfiles/"

files <- list.files(path_sas7bdat, pattern = "sas7bdat")

for(i in files) {
    saveRDS(read_sas(paste0(path_sas7bdat, i)),
            paste0(path_RDS, gsub("sas7bdat", "RDS", i)))
}
</code>```

PS.: check saveRDS option collapse = FALSE for speed.

Title: Loop for converting files

Body:
I have many files I want to convert from sas7bdat to Rds using R, I am using the following code:

name <- read_sas("C:/Users/Desktop/Files/name.sas7bdat")
saveRDS(name, file = "C:/Users/Desktop/RDSfiles/name.Rds")

but there are too many files I would like to use a loop to optimize to process, any ideas?

Thank you very much!!

Body:
This is simple loop that I would use:

path_sas7bdat <- "C:/Users/Desktop/Files/"
path_RDS <- "C:/Users/Desktop/RDSfiles/"

files <- list.files(path_sas7bdat, pattern = "sas7bdat")

for(i in files) {
    saveRDS(read_sas(paste0(path_sas7bdat, i)),
            paste0(path_RDS, gsub("sas7bdat", "RDS", i)))
}

PS.: check saveRDS option collapse = FALSE for speed.


问:
Filter array by index and save it to another array
I´m trying to filter all values in name where id = 1 and save to an array.

This is the output I get from my WS:

[{id=1; name=Des Moines; }, {id=2; name=Cedar Rapids; }, {id=3; name=Yakima; },{id=4; name=Fort Dodge; }, {id=1; name=Iowa City; }]

if I try get property it splits my content.

Could anyone help me out on how to get the desire output?

答:
That's JSON data, you should consider parse the data into an object , there are a lot of JSON java parsers , you could read something about GSON:

https://github.com/google/gson/blob/master/UserGuide.md


问:
Is it possible to roll back CREATE TABLE and ALTER TABLE statements in major SQL databases?
I am working on a program that issues DDL. I would like to know whether CREATE TABLE and similar DDL can be rolled back in

Postgres

MySQL

SQLite

et al

Describe how each database handles transactions with DDL.

答:
Can't be done with MySQL it seems, very dumb, but true... (as per the accepted answer)

"The CREATE TABLE statement in InnoDB is processed as a single
  transaction. This means that a ROLLBACK from the user does not undo
  CREATE TABLE statements the user made during that transaction."

https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html

Tried a few different ways and it simply won't roll back..

Work around is to simply set a failure flag and do "drop table tblname" if one of the queries failed..


问:
how to replace an rx java expression with lambda?
I keep getting expression can be replaced with a lambda for Java 8. How do I go about that? Here's one of the expressions I get that message on:

```<code>Observable.create(new ObservableOnSubscribe<Pair>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Pair> observableEmitter) throws Exception { ...
</code>```

any idea?

答:
This is how a lambda for this is created:

```<code>observableEmitter -> {
    // your code here
}
</code>```

You don't need the anonymous function or anything like that.

Putting it in the given code:

```<code>Observable.create(observableEmitter -> {
    // your code here
});
</code>```

You just replace the new ObservableOnSubs... bit with the lambda.

Body:
I keep getting expression can be replaced with a lambda for Java 8. How do I go about that? Here's one of the expressions I get that message on:

Observable.create(new ObservableOnSubscribe<Pair>() {
            @Override
            public void subscribe(@io.reactivex.annotations.NonNull ObservableEmitter<Pair> observableEmitter) throws Exception { ...

any idea?

Body:
This is how a lambda for this is created:

observableEmitter -> {
    // your code here
}

You don't need the anonymous function or anything like that.

Putting it in the given code:

Observable.create(observableEmitter -> {
    // your code here
});

You just replace the new ObservableOnSubs... bit with the lambda.


问:
Setting memory address of nodes in C++
I seem to be having trouble understanding how to build a function that adds nodes into a linked list.

Thus far, i have this.

```<code>void StringList::add(string value){
StringNode *temp = new StringNode;
temp->data = value;
temp->next = NULL;

if(head==NULL){
    head = temp;
    temp = NULL;
}
</code>```

I do not understand how I can set the memory address for the previous node each time i add to the list. Ideally, I would have given myself a tail node, however i was provided a driver and a header file which are to remain unchanged. Any insight would be appreciated.

答:
The easiest way to solve this is certainly to use an std::list:

```<code>list<string> l { "blue", "red", "white" };
l.push_back("yellow");
</code>```

If you're obliged to use memory allocation for educational purpose, and you have to go through manual memory allocation, and things like that, you have to iterate through the list to find the last node:

```<code>...
if(head==NULL){
   ...
}
else {
    StringNode *i=head;
    while (i->next)  // stops when the next element is NULL, so last element
        i = i->next;
    i->next = tmp;   // i is last element, so just connect to the new node
}
</code>```

Title: Setting memory address of nodes in C++

Body:
I seem to be having trouble understanding how to build a function that adds nodes into a linked list.

Thus far, i have this.

void StringList::add(string value){
StringNode *temp = new StringNode;
temp->data = value;
temp->next = NULL;

if(head==NULL){
    head = temp;
    temp = NULL;
}

I do not understand how I can set the memory address for the previous node each time i add to the list. Ideally, I would have given myself a tail node, however i was provided a driver and a header file which are to remain unchanged. Any insight would be appreciated.

Body:
The easiest way to solve this is certainly to use an std::list:

list<string> l { "blue", "red", "white" };
l.push_back("yellow");

If you're obliged to use memory allocation for educational purpose, and you have to go through manual memory allocation, and things like that, you have to iterate through the list to find the last node:

...
if(head==NULL){
   ...
}
else {
    StringNode *i=head;
    while (i->next)  // stops when the next element is NULL, so last element
        i = i->next;
    i->next = tmp;   // i is last element, so just connect to the new node
}


问:
python create slice object from string
I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement

```<code>class getslice:
    def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))
</code>```

thanks in advance.

Edit: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).

答:
Here's another method (just a consolidation of the others posted here):

```<code>def make_slice(expr):
    def to_piece(s):
        return s and int(s) or None
    pieces = map(to_piece, expr.split(':'))
    if len(pieces) == 1:
        return slice(pieces[0], pieces[0] + 1)
    else:
        return slice(*pieces)
</code>```

Example usages:

```<code>In [1]: make_slice(':')
Out[1]: slice(None, None, None)

In [2]: make_slice(':-2')
Out[2]: slice(None, -2, None)

In [3]: x = [1, 2, 3]

In [4]: x[make_slice('::-1')]
Out[4]: [3, 2, 1]
</code>```

OwnerDisplayName: gatoatigrado

Title: python create slice object from string

Body:
I'd like to create a slice object from a string; right now the only way seems through a cumbersome hacky eval statement

class getslice:
    def __getitem__(self, idx): return idx[0]
eval("getslice()[%s, 1]" %(":-1"))

thanks in advance.

Edit: Sorry if the original prompt was not clear, the input in this case was ":-1". The point was to parse the string. Ignacio Vazquez-Abrams's response at least solved the problem (and seems to work with reverse indexing as well), but I think my solution above is still more clear if not conceptually clean (and will work correctly if Python ever changes slicing syntax).

LastEditorDisplayName: gatoatigrado

Body:
Here's another method (just a consolidation of the others posted here):

def make_slice(expr):
    def to_piece(s):
        return s and int(s) or None
    pieces = map(to_piece, expr.split(':'))
    if len(pieces) == 1:
        return slice(pieces[0], pieces[0] + 1)
    else:
        return slice(*pieces)

Example usages:

In [1]: make_slice(':')
Out[1]: slice(None, None, None)

In [2]: make_slice(':-2')
Out[2]: slice(None, -2, None)

In [3]: x = [1, 2, 3]

In [4]: x[make_slice('::-1')]
Out[4]: [3, 2, 1]


问:
ANT build- Deleting multiple dirsets
I have added a target in a build file to delete backups that are older than 4 days by using a timestamp:

```<code>    <tstamp>
        <format pattern="MM/DD/yyyy HH:MM aa" offset="-4" property="backup.deletedate" />
    </tstamp>
    <echo message="Deleting log directories created on or before ${backup.deletedate}" />
    <delete verbose="true">
        <dirset dir="${backup.dir}/CI">
            <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
        </dirset>
        <dirset dir="${backup.dir}/DEV_MASTER">
            <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
        </dirset>
    </delete>
</code>```

However it ony deletes from the first directory (CI) and skips the second.

How can I set it to remove from BOTH directories?

答:
Merge your dirsets.</p>

```<code><delete verbose="true">
    <dirset dir="${backup.dir}" includes="CI,DEV_MASTER">
        <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
    </dirset>
</delete>
</code>```

Title: ANT build- Deleting multiple dirsets

Body:
I have added a target in a build file to delete backups that are older than 4 days by using a timestamp:

    <tstamp>
        <format pattern="MM/DD/yyyy HH:MM aa" offset="-4" property="backup.deletedate" />
    </tstamp>
    <echo message="Deleting log directories created on or before ${backup.deletedate}" />
    <delete verbose="true">
        <dirset dir="${backup.dir}/CI">
            <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
        </dirset>
        <dirset dir="${backup.dir}/DEV_MASTER">
            <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
        </dirset>
    </delete>

However it ony deletes from the first directory (CI) and skips the second.

How can I set it to remove from BOTH directories?

Body:
Merge your dirsets.

<delete verbose="true">
    <dirset dir="${backup.dir}" includes="CI,DEV_MASTER">
        <date datetime="${backup.deletedate}" when="before" checkdirs="true" />
    </dirset>
</delete>


问:
Why is InfiniteIterator not repeating an ArrayIterator?
Putting these SPL iterators together this way:

```<code>$iterator = new LimitIterator(
    new InfiniteIterator(
        new ArrayIterator(range(1, 3))
    ),
    0,
    5
);

echo implode(', ', iterator_to_array($iterator));
</code>```

I would expect to get this output: 1, 2, 3, 1, 2.

After iterating the first time over the ArrayIterator (1, 2, 3), the InfiniteIterator should rewind the ArrayIterator and start from beginning, until the limit of the LimitIterator is reached (1, 2, 3, 1, 2).

But actually its output is 1, 2, 3. Can somebody explain this to me?

答:
Your combination of iterators is working as expected. If you iterate it with foreach

```<code>foreach ($iterator as $number) {
    echo $number;
}
</code>```

You'll get the expected output 12312.

The problem is actually when you convert it back to an array with iterator_to_array.

You need to set the second parameter ($use_keys) to false (the default is true), or it will overwrite the repeated keys.

```<code>echo implode(', ', iterator_to_array($iterator, false));
</code>```

Body:
Putting these SPL iterators together this way:

$iterator = new LimitIterator(
    new InfiniteIterator(
        new ArrayIterator(range(1, 3))
    ),
    0,
    5
);

echo implode(', ', iterator_to_array($iterator));

I would expect to get this output: 1, 2, 3, 1, 2.

After iterating the first time over the ArrayIterator (1, 2, 3), the InfiniteIterator should rewind the ArrayIterator and start from beginning, until the limit of the LimitIterator is reached (1, 2, 3, 1, 2).

But actually its output is 1, 2, 3. Can somebody explain this to me?

Body:
Your combination of iterators is working as expected. If you iterate it with foreach

foreach ($iterator as $number) {
    echo $number;
}

You'll get the expected output 12312.

The problem is actually when you convert it back to an array with iterator_to_array.

You need to set the second parameter ($use_keys) to false (the default is true), or it will overwrite the repeated keys.

echo implode(', ', iterator_to_array($iterator, false));


问:
Assertion Failure: UI Testing Failure - Failure fetching attributes for element
When UI testing in Xcode(7.2 and 7.3), my tests sometimes fail with a rather generic error:

Assertion Failure: UI Testing Failure - Failure fetching attributes for element

I tend to get this error when calling .hittable or .tap() on an element but I cannot tell why. I've checked that the elements I'm dealing with all have their accessibility settings correctly setup and that any container views that they are in don't have accessibilty enabled. Alas, this doesn't seem to resolve the problem.

The console log reveals:

```<code>UI Testing Failure - Failure fetching attributes for element <XCAccessibilityElement: 0x7e68ae50> pid: 89032, context: 4D9272C7-3024-4062-B0FA-E16EF426F17A, payload: {
    pid = 89032;
    "uid.elementID" = 1432;
    "uid.elementOrHash" = 2125772976;
}: Error Domain=XCTestManagerErrorDomain Code=13 "Error copying attributes -25202" UserInfo={NSLocalizedDescription=Error copying attributes -25202}
</code>```

I've tried searching around and managed to find it's already been logged but there appears to be no current solution (radar link) even for Xcode 7.3.

It seems that sometimes if I restart the simulator/device this error doesn't happen but this isn't a nice solution.

答:
I encountered this as well. In my case, the server is returning multiple typeahead search query results in quick succession.  The target element pops up quickly, but is not consistently hittable until the final query.  I solved this by waiting for existence of the element in the first query initially, via XCTWaiter.  Then put a sleep to encompass the time of all the query results and then waiting for element being hittable.  DO NOT use hittable for the first query result as this will fail because hittable also checks if elements can be tapped, but the UI is changing too quickly for the element to be tapped.

It would be better if you could trigger just the final query for testing purposes or via the code base.  I also considered using UIPasteboard to avoid multiple typeahead queries, but, as far as I can tell, this is not available to XCTest.

Body:
When UI testing in Xcode(7.2 and 7.3), my tests sometimes fail with a rather generic error:

Assertion Failure: UI Testing Failure - Failure fetching attributes for element

I tend to get this error when calling .hittable or .tap() on an element but I cannot tell why. I've checked that the elements I'm dealing with all have their accessibility settings correctly setup and that any container views that they are in don't have accessibilty enabled. Alas, this doesn't seem to resolve the problem.

The console log reveals:

UI Testing Failure - Failure fetching attributes for element <XCAccessibilityElement: 0x7e68ae50> pid: 89032, context: 4D9272C7-3024-4062-B0FA-E16EF426F17A, payload: {
    pid = 89032;
    "uid.elementID" = 1432;
    "uid.elementOrHash" = 2125772976;
}: Error Domain=XCTestManagerErrorDomain Code=13 "Error copying attributes -25202" UserInfo={NSLocalizedDescription=Error copying attributes -25202}

I've tried searching around and managed to find it's already been logged but there appears to be no current solution (radar link) even for Xcode 7.3.

It seems that sometimes if I restart the simulator/device this error doesn't happen but this isn't a nice solution.


问:
MYSQL database create using knex
How to create database using knex npm?

Here it is MYSQL query

```<code>create database 'test'
</code>```

I want to convert this query using knex.

答:
There is no special API for creating DB in knex, probably because knex usually connects to already created DB and to be honest database creation is pretty rare operation.

Npm package knex-db-manager (https://vincit.github.io/knex-db-manager/) can do also database maintenance tasks and has separate superuser and normal user connection.

Title: MYSQL database create using knex

Body:
How to create database using knex npm?

Here it is MYSQL query

create database 'test'

I want to convert this query using knex.


问:
Pinterest Style Masonry Grid with Angular 5
This Masonry grid has to take into account both differing height and widths. Any hint on how to do this?</p>

答: Bootstrap has an implementation of this called card-columns. It works very well for your requirements.


问:
Kafka log retention time per topic in server.properties
I would like to lower the retention period for one of the Kafka topics. I want the rest of the topics to still use the default retention time (7 days).
I know that we can set this through terminal: bin/kafka-topics.sh --zookeeper XXX --alter --topic XXXX --config retention.ms=86400000.
I was wondering if there is a way to do this so that it is set in server.properties and can be used in the future. For example, for the default retention time, we have log.retention.minutes = XXX.

EDIT: after some research, I noticed that per-topic configurations should better be done this way in ZK (https://issues.apache.org/jira/browse/KAFKA-554). But I'm still wondering if I can do this programmatically rather than using kafka-topics.sh.

答:
If you only want some topics to have a different retention time, I'm afraid you will have to specify it when creating them using kafka-topics.sh.

In server.properties you can only specify configurations that apply to all topics that don't have overrides.


问:
VS 2015 Python Environments Greyed Out
I'm just getting started with Python and I want to use Visual Studio 2015 Community Edition (VS) for writing my code.  However, after diligently following the instructions on GitHub (1) Install PTVS 2.2.2 (2) Install Windows Python 3.4.4, VS cannot find the Python interpreter and run the code.  When I attempt to do so for VS manually via Options > Python Tools > Environment Option, all the buttons are greyed out (I cannot enter information) as well as the Python Environment Window

I've tried uninstalling, reinstalling, repairing and modifying VS, PTVS and Python 3.4 but to no avail.  Is there something I'm missing?  Much appreciate the help!

答:
It seems Visual Studio 2015 Community Edition does not like Python 3.6.
If you just edit the registry:

```<code>KEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\PythonTools\Interpreters
</code>```

as Luciano suggested, and replace the version key from 3.6 to 3.5 it works.

Title: VS 2015 Python Environments Greyed Out

Body:
It seems Visual Studio 2015 Community Edition does not like Python 3.6.
If you just edit the registry:

KEY_CURRENT_USER\Software\Microsoft\VisualStudio\14.0\PythonTools\Interpreters

as Luciano suggested, and replace the version key from 3.6 to 3.5 it works.


答:
create a new column with the desired ordering and then just sort the rows.</p>

```<code>df['new_col'] = range(1, len(df)+1)
df['new_col'].loc[len(df)-1] = 0
df['new_col'].loc[0] = len(df)
df = df.reset_index()
</code>```

Body:
So I have a dataframe that looks like this:

                         #1                     #2
1980-01-01               11.6985                126.0
1980-01-02               43.6431                134.0
1980-01-03               54.9089                130.0
1980-01-04               63.1225                126.0
1980-01-05               72.4399                120.0

What I want to do is to shift the first row of the first column (11.6985) down 1 row, and then the last row of the first column (72.4399) would be shifted to the first row, first column, like so:

                         #1                     #2
1980-01-01               72.4399                126.0
1980-01-02               11.6985                134.0
1980-01-03               43.6431                130.0
1980-01-04               54.9089                126.0
1980-01-05               63.1225                120.0

The idea is that I want to use these dataframes to find an R^2 value for every shift, so I need to use all the data or it might not work. I have tried to use pandas.Dataframe.shift():

print(data)

#Output
1980-01-01               11.6985                126.0
1980-01-02               43.6431                134.0
1980-01-03               54.9089                130.0
1980-01-04               63.1225                126.0
1980-01-05               72.4399                120.0

print(data.shift(1,axis = 0))

1980-01-01                   NaN                  NaN
1980-01-02               11.6985                126.0
1980-01-03               43.6431                134.0
1980-01-04               54.9089                130.0
1980-01-05               63.1225                126.0

So it just shifts both columns down and gets rid of the last row of data, which is not what I want.

Any advice?

Body:
create a new column with the desired ordering and then just sort the rows.

df['new_col'] = range(1, len(df)+1)
df['new_col'].loc[len(df)-1] = 0
df['new_col'].loc[0] = len(df)
df = df.reset_index()


问:
How do I remove the CMS and Media buttons from the Backend interface?
I have many icons across the top of the page when I first log in on the backend. I've been able to remove some icons by disabling plugins like
the Rainlab Blog and Builder, but Dashboard, CMS, and Media remain there. How can I remove them?

From the official documentation on extending plugins I found this:

```<code>Event::listen('backend.menu.extendItems', function($manager) {

    $manager->removeMainMenuItem('October.Cms', 'cms');
    $manager->removeSideMenuItem('October.Cms', 'cms', 'pages');

});
</code>```

But I haven't found which plugin I can add this listener code to, nor the names of the Dashboard and CMS items.

Does someone know? I'll post a solution if I can find one...

答:
Instead of creating a plugin you can use ACL Group.
Create one group that don't have the authorization to use "CMS" and "Media" and add an admin to it.</p>

Body:
I have many icons across the top of the page when I first log in on the backend. I've been able to remove some icons by disabling plugins like
the Rainlab Blog and Builder, but Dashboard, CMS, and Media remain there. How can I remove them?

From the official documentation on extending plugins I found this:

Event::listen('backend.menu.extendItems', function($manager) {

    $manager->removeMainMenuItem('October.Cms', 'cms');
    $manager->removeSideMenuItem('October.Cms', 'cms', 'pages');

});

But I haven't found which plugin I can add this listener code to, nor the names of the Dashboard and CMS items.

Does someone know? I'll post a solution if I can find one...


问:
Modal/Popup Changing Start Position if Scrolling Prior to Click
Good morning everyone. I have a novice JS question that I need help clearing up. First off I am an extreme beginner and self taught so forgive any ignorance.

I am building a new website for a business and one of the pages has a grid of products for customers. Each product has a button which creates a modal to give more information about the product. I am using a JS I found online to have DIFFERENT Modals inside some of these other modals. If you click the modal in question (star fish or sea horse) after scrolling the page first, the modals appear further down and cut off by the screen.

example: https://my.duda.co/preview/27d7a4cc?device=desktop&pageId=30782523

I know the author of the JS included a var to reposition the modal if the user had scrolled but it is not working in my favor or there is something more I need to do and don't have the knowledge for it.

I also know the code is sloppy and probably redundant in some places, I am not an expert. My JSFiddle: https://jsfiddle.net/shnt7vwu

```<code><script>
var $html = $(document.documentElement);
var $modal = $('.modal-container');
function showModal() {
$html.css('overflow', 'hidden');
$modal.show().css('overflow', 'auto');
}
function hideModal() {
$html.css('overflow', 'visible');
$modal.show().css('overflow','visible')
}
$('.modal-btn').on('click', showModal);
$('.modal-close').on('click', hideModal);
</script>
<script>
var scrollTop = '';
var newHeight = '100';
$(window).bind('scroll', function() {
scrollTop = $( window ).scrollTop();
newHeight = scrollTop + 100;
});
$('.popup-trigger').click(function(e) {
e.stopPropagation();
if(jQuery(window).width() < 767) {
$(this).after( $(this).nextAll('.popup:first') );
$(this).nextAll('.popup:first').show().addClass
('popup-mobile').css('top', 0);
$('html, body').animate({
scrollTop: $(this).nextAll('.popup:first').offset().top
}, 500);
} else {
$('.popup').hide();
$(this).nextAll('.popup:first').removeClass('popup-mobile').css
('top', newHeight).toggle();
};
});
$('html').click(function() {
$('.popup').hide();
});
$('.popup-btn-close').click(function(e){
$(this).parent().hide();
});
$('.popup').click(function(e){
e.stopPropagation();
});
</script>
</code>```

答:
You can place your whole 'div body grid' stuff inside a div with overflow-y enabled, then have your modals with vh:100 hidden outside

Just disable all the modals, div property until the correct user action is taken.

This way you can avoid calculations which may break between platforms and in edge cases.


问:
Simple Program in Drracket Scheme
I'm trying to design a program in DrRacket which takes in two variables (a and b) and returns b.
How would this be done?</p>

答: I am assuming you are using the beginner language in DrRacket. In DrRacket you can associate value to variables using define. e.x (define A 10). If we wanted to make this a function in racket, we could do  (define (always10 n) A) where as we make a function that takes in n which is useless in this case, as it does nothing, and returns a previously defined term called A. With your question it is the same, except it takes in one extra variable and it returns the second parameter. it would be written as (define (someFunction a b) b). If we called someFunction we would have to provide it 2 arguements of any type and it would return the second one. (someFunction "hello" A) => 10. Next I encourage you to make a function that takes in 2 numbers and return their sum.

Title: Simple Program in Drracket Scheme


Body:
Not sure about the performance, but you could try numpy.roll:

import numpy as np
print(df.apply(np.roll, shift=1))

#                 #1     #2
#1980-01-01  72.4399  120.0
#1980-01-02  11.6985  126.0
#1980-01-03  43.6431  134.0
#1980-01-04  54.9089  130.0
#1980-01-05  63.1225  126.0

To shift column #1 only:

df['#1'] = np.roll(df['#1'], shift=1)

print(df)
#                 #1     #2
#1980-01-01  72.4399  126.0
#1980-01-02  11.6985  134.0
#1980-01-03  43.6431  130.0
#1980-01-04  54.9089  126.0
#1980-01-05  63.1225  120.0


问:
Highlight menu item for the current page user is on
I'm trying to highlight this menu item so the user can see the page they are currently on. It can be bold or underlined, whatever really. If it can be done only using CSS that would be ideal.

here's what my inspect element looks like for the page :

Any help is much appreciated. Thanks!

答:
It's just an example:

```<code>li.current-menu-item {
    // Your style Below */
    text-decoration: underline;
}
</code>```

or

```<code>li.current-menu-item a {
    /* Your style Below */
    border-bottom: 1px solid #dd614a;
}
</code>```

Body:
It's just an example:

li.current-menu-item {
    // Your style Below */
    text-decoration: underline;
}

or

li.current-menu-item a {
    /* Your style Below */
    border-bottom: 1px solid #dd614a;
}


问:
Using “com.worklight.common.WLPreferences” to export the component raising security concern
A malicious application on the same device can cause a crash by submitting malformed data to the exported components. To overcome such vulnerability, how can one implement data validation mechanism?</p>

答: The “com.worklight.common.WLPreferences” activity is added to a MobileFirst hybrid application for adding a preferences screen to  application where certain connection parameters can be edited during the execution of the app. This is a feature that is meant for use in the development environment and not recommended for use in production environment. On a production environment, one can remove this activity from the AndroidManifest.xml file to resolve this vulnerability. </p>


问:
Adding --aot to cli breaks app angular
So I have an Angular app using the dynamic forms, which works fine. but when I add --aot to my cli command I get the error Property 'controls' does not exist on type 'AbstractControl'. I've tried using methods from the documentation. Still I get error. My code attached below.Cause I've been through the documentation. Or maybe it's something I'm missing

import { Component, ElementRef, NgZone, OnInit, ViewChild } from '@angular/core'

    import { FormControl, ReactiveFormsModule, FormGroup, FormArray, FormBuilder, Validators } from "@angular/forms"
    import { Router, ActivatedRoute } from '@angular/router'
    import { Location } from '@angular/common'
    import { CreateEventService } from './create-event.service'
    import { Http, Headers } from '@angular/http'

      @Component({
        selector: 'create-event',
        templateUrl: './create-event.component.html',
        styleUrls: ['./create-event.component.css'],
        providers: [ CreateEventService ]
      })
      export class CreateEventComponent implements OnInit {

      event: any
      tables: string[] = []
      searchControl: FormControl
      ticketForm: FormGroup
      ticketPrices: number[] = []

      @ViewChild("search")
      public searchElementRef: ElementRef

      constructor(private router: Router,private _http: Http, private ngZone: NgZone, private _fb: FormBuilder) { }

      ngOnInit() {
        this.ticketForm = this._fb.group({
            tickets: this._fb.array([
                this.initTicket(),
            ])
        })
        this.searchControl = new FormControl()
      }

      initTicket() {
          return this._fb.group({
              ticketName: [''],
              ticketPrice: [''],
              ticketLimit: ['', Validators.required]
          })
      }

      addTicket() {
          const control = <FormArray>this.ticketForm.controls['tickets']
          control.push(this.initTicket())
      }

      removeTicket(i: number) {
          const control = <FormArray>this.ticketForm.controls['tickets']
          control.removeAt(i)
          this.tables.splice(i, 1)
          //console.log(this.tables)
      }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form [formGroup]="ticketForm" novalidate>
          <div formArrayName="tickets" class="row">
              <div *ngFor="let ticket of ticketForm.controls.tickets.controls let i=index" class="row">
                  <div class="col m7 s12" [formGroupName]="i">
                    <div class="col m5 s12">
                        <input type="text" formControlName="ticketName" placeholder="e.g. Regular, VIP">
                    </div>
                    <div class="col m4 s6">
                        <input type="number" formControlName="ticketPrice" placeholder='Ticket Price &#8358'>
                    </div>
                    <div class="col m3 s6">
                      <input type="number" formControlName="ticketLimit" placeholder="Quantity">
                    </div>
                  </div>
                  <div class="col m2 s2">
                    <br>
                       1" (click)="removeTicket(i)"><i class="fa fa-trash"></i>
                  </div>
              </div>
          </div>
          <div class="col">
              <h6>Add another ticket <i class="fa fa-plus"></i></h6>
          </div>
</form></code>```

答:
When compiling Angular template with AOT compiler, the factories are created in Typescript, which keep the type hinting.

So, you said in your TS that ticketForm is a FormGroup. So you can access ticketForm.controls, which is a map of AbstractControls. Then, accessing ticketForm.controls.tickets will give you an AbstractControl.

If you look at the documentation you can see that AbstractControl does not have a controls attribute. That's why the AOT compiler trigger an error, because it adds typings to the HTML template.

Possible solution :

You can add a getter in your TS, to allow access to the tickets FormArray

```<code>get ticketsFormArray(): FormArray {
    return this.ticketForm.controls['tickets'] as FormArray
}
</code>```

And use it in your template

```<code><div *ngFor="let ticket of ticketsFormArray.controls let i=index" class="row">
...
</div>
</code>```

Title: Adding --aot to cli breaks app angular

Body:
So I have an Angular app using the dynamic forms, which works fine. but when I add --aot to my cli command I get the error Property 'controls' does not exist on type 'AbstractControl'. I've tried using methods from the documentation. Still I get error. My code attached below.Cause I've been through the documentation. Or maybe it's something I'm missing

import { Component, ElementRef, NgZone, OnInit, ViewChild } from '@angular/core'

    import { FormControl, ReactiveFormsModule, FormGroup, FormArray, FormBuilder, Validators } from "@angular/forms"
    import { Router, ActivatedRoute } from '@angular/router'
    import { Location } from '@angular/common'
    import { CreateEventService } from './create-event.service'
    import { Http, Headers } from '@angular/http'

      @Component({
        selector: 'create-event',
        templateUrl: './create-event.component.html',
        styleUrls: ['./create-event.component.css'],
        providers: [ CreateEventService ]
      })
      export class CreateEventComponent implements OnInit {

      event: any
      tables: string[] = []
      searchControl: FormControl
      ticketForm: FormGroup
      ticketPrices: number[] = []

      @ViewChild("search")
      public searchElementRef: ElementRef

      constructor(private router: Router,private _http: Http, private ngZone: NgZone, private _fb: FormBuilder) { }

      ngOnInit() {
        this.ticketForm = this._fb.group({
            tickets: this._fb.array([
                this.initTicket(),
            ])
        })
        this.searchControl = new FormControl()
      }

      initTicket() {
          return this._fb.group({
              ticketName: [''],
              ticketPrice: [''],
              ticketLimit: ['', Validators.required]
          })
      }

      addTicket() {
          const control = <FormArray>this.ticketForm.controls['tickets']
          control.push(this.initTicket())
      }

      removeTicket(i: number) {
          const control = <FormArray>this.ticketForm.controls['tickets']
          control.removeAt(i)
          this.tables.splice(i, 1)
          //console.log(this.tables)
      }

}

<form [formGroup]="ticketForm" novalidate>

                        <input type="text" formControlName="ticketName" placeholder="e.g. Regular, VIP">

                        <input type="number" formControlName="ticketPrice" placeholder='Ticket Price &#8358'>

                      <input type="number" formControlName="ticketLimit" placeholder="Quantity">

                       1" (click)="removeTicket(i)">

Add another ticket

</form>

Body:
When compiling Angular template with AOT compiler, the factories are created in Typescript, which keep the type hinting.

So, you said in your TS that ticketForm is a FormGroup. So you can access ticketForm.controls, which is a map of AbstractControls. Then, accessing ticketForm.controls.tickets will give you an AbstractControl.

If you look at the documentation you can see that AbstractControl does not have a controls attribute. That's why the AOT compiler trigger an error, because it adds typings to the HTML template.

Possible solution :

You can add a getter in your TS, to allow access to the tickets FormArray

get ticketsFormArray(): FormArray {
    return this.ticketForm.controls['tickets'] as FormArray
}

And use it in your template

<div *ngFor="let ticket of ticketsFormArray.controls let i=index" class="row">
...
</div>