问:
Overload -> arrow operator in shared_ptr<interface> instance with no pure virtual destructor in interface
I'm trying to overload the -> operator to eventually execute something along the lines:

```<code>MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();
</code>```

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

```<code>#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}
</code>```

Output:

```<code>current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0
</code>```

To reiterate:
This code doesn't compile:

```<code>sharedPtrWrapper->Toggle();
</code>```

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

```<code>void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}
</code>```

答:
You don't need your wrapper at all.

```<code>shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>();
</code>```

wont work because MyInterface is an abstract class.  But, just like you can do

```<code>MyInterface *myInstance = new A();
</code>```

To have a MyInterface * that points to a concrete derived object, you can use

```<code>std::shared_ptr<MyInterface> sharedPtr = std::make_shared<A>();
</code>```

To get a std::shared_ptr<MyInterface> that points to a concrete derived object.  You can then use sharedPtr to access Toggle like

```<code>sharedPtr->Toggle();
</code>```

You can see that working in this live example

Body:
I'm trying to overload the -> operator to eventually execute something along the lines:

MyInterface *myInstance = (MyInterface *)(new A());
myInstance->Toggle(); //this works wonderfully

std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);

//the next line doesn't compile, I would like to achieve something like this, but even
//sharedPtrWrapper.get()->Toggle();
//would be nice to achieve, is this possible?
sharedPtrWrapper->Toggle();

//this works:
sharedPtrWrapper->operator->()->Toggle();

Note: I have no control over MyInterface, cannot implement the pure virtual destructor.

Here is what I tried (the below code runs):

#import <memory>
#import <iostream>

struct MyInterface {
    virtual bool Toggle() = 0;
};

class A : public MyInterface {
public:
    bool Toggle() {
        stateEnabled = !stateEnabled;
        std::cout<<"current state " << stateEnabled << std::endl;
        return true;
    }
private:
    bool stateEnabled = false;
};

template <typename T>
class Wrapper {
private:
    T *unsafePointer = nullptr;
public:
    Wrapper<T>()
    { }

    T *operator->() const {
        return unsafePointer;
    }
    T *getInner() {
        return unsafePointer;
    }
    Wrapper<T>(T *stuff) {
        unsafePointer = stuff;
    }

    ~Wrapper<T>() {}
};

int main(int argc, const char * argv[]) {
    MyInterface *myInstance = (MyInterface *)(new A());
    myInstance->Toggle();

    Wrapper<MyInterface> wrapperS(myInstance);
    wrapperS->Toggle();

    std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(myInstance);
    sharedPtrWrapper->operator->()->Toggle();
    sharedPtrWrapper.operator->()->operator->()->Toggle();

    sharedPtrWrapper.get()->operator->()->Toggle();

    (*sharedPtrWrapper).operator->()->Toggle();

    return 0;
}

Output:

current state 1
current state 0
current state 1
current state 0
current state 1
current state 0
Program ended with exit code: 0

To reiterate:
This code doesn't compile:

sharedPtrWrapper->Toggle();

How to make it compile?

Edit : I'm using a wrapper because I have no control over the MyInterface, I get it from a library, also shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>(myInstance); doesn't compile, because of the missing pure virtual destructor from the above mentioned interface.

Edit2: Example library usage in pseudocode:

void firstcallbackFromLib(Framework *framework) {
    MyInterface *myInstance = framework->getInstance();

    {
        Wrapper<MyInterface> wrapperS(myInstance);
        std::shared_ptr<Wrapper<MyInterface>> sharedPtrWrapper = std::make_shared<Wrapper<MyInterface>>(wrapperS);
        //assign sharedPtrWrapper and framework to static instances
    }
}
void myFunction() {
    sharedPtrWrapper->Toggle(); //this doesn't work, this is what i'm trying to achieve
    sharedPtrWrapper->operator->()->Toggle(); //this ugly thing works

}
void lastUninitCallbackFromLibrary() {
    MyInterface *p = sharedPtrWrapper.get()->getInner();
    framework->releaseInterface(p);
    //etc
}

Body:
You don't need your wrapper at all.

shared_ptr<MyInterface> mySharedPointer = std::make_shared<MyInterface>();

wont work because MyInterface is an abstract class.  But, just like you can do

MyInterface *myInstance = new A();

To have a MyInterface * that points to a concrete derived object, you can use

std::shared_ptr<MyInterface> sharedPtr = std::make_shared<A>();

To get a std::shared_ptr<MyInterface> that points to a concrete derived object.  You can then use sharedPtr to access Toggle like

sharedPtr->Toggle();

You can see that working in this live example


来源: stackexchange

问:
Jackson, how define a default type impl for interface field?
I need to deserialize a JSON to a Java class with a Serializable field.
In the following Java class the value field is an interface, the idea is that the view can send values of types: String, Double, Long and ArrayList. If I change the type of value field from Serializable to Object, it works as expected.

public class UpdateAttribute implements Serializable {
    //..
    // There is something like: @JsonImplType(Object.class)
    private Serializable value;
}
```

My question is, there is such a way to define a default class type to the value field? Something like: @JsonImplType(Object.class)?

答:
The solution to this problem is use an annotation from jackson-databind module.
A similiar question was asked here: Jackson - How to specify a single implementation for interface-referenced deserialization?.

public class UpdateAttribute implements Serializable {
    //..
    @JsonDeserialize(as = Object.class)
    private Serializable value;
}
```

<p>However, there is a detail to be considered. The <code>setValue</code> method of <code>UpdateAttribute</code> can't be declared with a <code>Serializable</code> argument. Because Jackson don't know about the casting from <code>Object</code> to <code>Serializable</code>. Therefore, the final class should look like:</p>

<pre class="lang-java prettyprint-override"><code>public class UpdateAttribute implements Serializable {

    @JsonDeserialize(as = Object.class)
    private Serializable value;

    public void setValue(Object value) {
        this.value = (Serializable) value;
    }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I need to deserialize a JSON to a Java class with a Serializable field.
In the following Java class the value field is an interface, the idea is that the view can send values of types: String, Double, Long and ArrayList. If I change the type of value field from Serializable to Object, it works as expected.

public class UpdateAttribute implements Serializable {
    //..
    // There is something like: @JsonImplType(Object.class)
    private Serializable value;
}

My question is, there is such a way to define a default class type to the value field? Something like: @JsonImplType(Object.class)?

Body:
The solution to this problem is use an annotation from jackson-databind module.
A similiar question was asked here: Jackson - How to specify a single implementation for interface-referenced deserialization?.

public class UpdateAttribute implements Serializable {
    //..
    @JsonDeserialize(as = Object.class)
    private Serializable value;
}

However, there is a detail to be considered. The setValue method of UpdateAttribute can't be declared with a Serializable argument. Because Jackson don't know about the casting from Object to Serializable. Therefore, the final class should look like:

public class UpdateAttribute implements Serializable {

    @JsonDeserialize(as = Object.class)
    private Serializable value;

    public void setValue(Object value) {
        this.value = (Serializable) value;
    }
}


问:
iterate array of object and save values
I have this objects in Javascript:

```<code>products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}
</code>```

I want to group the articles_ids in the same family.
I want get this result:

```<code>grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}
</code>```

I try with forEach and filter methods, but I dont know how to make this with perform mode.

答:
loop on products and use a map where key is family and value is article id.
Then keep adding article ids for a family in the map.</p>

Title: iterate array of object and save values

Body:
I have this objects in Javascript:

products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}

I want to group the articles_ids in the same family.
I want get this result:

grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}

I try with forEach and filter methods, but I dont know how to make this with perform mode.


问:
TypeError: Object of type Decimal is not JSON serializable during Django data migration
I added a postgres JsonField in my model, and created data migration for it.

new_column = pg_fields.JSONField(default=dict, encoder=DjangoJSONEncoder)

Same logic is used for future data(in save() of model) and for historic data(data migration).

This is the format of data I am trying to save

```<code>data = {
        'premium': obj.amount * obj.persons,
    }
proposal.new_column = data
proposal.save()
</code>```

Here, obj is the instance of some other model, and amount is the DecimalField of that model.

The logic runs fine in save() method of model class.
But on running data migration, I am getting this error
TypeError: Object of type Decimal is not JSON serializable

Stacktrace

```<code>Traceback (most recent call last):
  File "./manage.py", line 21, in <module>
    execute_from_command_line(sys.argv)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle
    fake_initial=fake_initial,
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
    self.code(from_state.apps, schema_editor)
  File "/home/simarpreet/Aegon/jarvis/insurance/travel/proposal/migrations/0006_auto_20191111_1943.py", line 34, in repopulate_slab_in_proposals
    proposal.save()
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base
    force_update, using, update_fields,
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 851, in _save_table
    forced_update)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 900, in _do_update
    return filtered._update(values) > 0
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/query.py", line 760, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1429, in execute_sql
    cursor = super().execute_sql(result_type)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
    cursor.execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/psycopg2/_json.py", line 78, in getquoted
    s = self.dumps(self.adapted)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/contrib/postgres/fields/jsonb.py", line 27, in dumps
    return json.dumps(obj, **options)
  File "/usr/lib/python3.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable
</code>```

But as per the documentation of Django data migration (https://docs.djangoproject.com/en/2.2/topics/migrations/) , Django can serialze the decimal.Decimal value. Following is the screenshot for reference.

Can someone suggest why am I getting this error?

答:
I was getting this issue because I forgot to run migration after adding the encoder

new_column = pg_fields.JSONField(default=dict, encoder=DjangoJSONEncoder)

Running migration again python manage.py migrate solved the problem.

Posting the solution in case someone else does such things like me.

Body:
I added a postgres JsonField in my model, and created data migration for it.

new_column = pg_fields.JSONField(default=dict, encoder=DjangoJSONEncoder)

Same logic is used for future data(in save() of model) and for historic data(data migration).

This is the format of data I am trying to save

data = {
        'premium': obj.amount * obj.persons,
    }
proposal.new_column = data
proposal.save()

Here, obj is the instance of some other model, and amount is the DecimalField of that model.

The logic runs fine in save() method of model class.
But on running data migration, I am getting this error
TypeError: Object of type Decimal is not JSON serializable

Stacktrace

Traceback (most recent call last):
  File "./manage.py", line 21, in <module>
    execute_from_command_line(sys.argv)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/__init__.py", line 375, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 323, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 364, in execute
    output = self.handle(*args, **options)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wrapped
    res = handle_func(*args, **kwargs)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 234, in handle
    fake_initial=fake_initial,
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/executor.py", line 245, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/migration.py", line 124, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/migrations/operations/special.py", line 190, in database_forwards
    self.code(from_state.apps, schema_editor)
  File "/home/simarpreet/Aegon/jarvis/insurance/travel/proposal/migrations/0006_auto_20191111_1943.py", line 34, in repopulate_slab_in_proposals
    proposal.save()
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 741, in save
    force_update=force_update, update_fields=update_fields)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 779, in save_base
    force_update, using, update_fields,
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 851, in _save_table
    forced_update)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/base.py", line 900, in _do_update
    return filtered._update(values) > 0
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/query.py", line 760, in _update
    return query.get_compiler(self.db).execute_sql(CURSOR)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1429, in execute_sql
    cursor = super().execute_sql(result_type)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1100, in execute_sql
    cursor.execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 99, in execute
    return super().execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 67, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 76, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/psycopg2/_json.py", line 78, in getquoted
    s = self.dumps(self.adapted)
  File "/home/simarpreet/Envs/j/lib/python3.7/site-packages/django/contrib/postgres/fields/jsonb.py", line 27, in dumps
    return json.dumps(obj, **options)
  File "/usr/lib/python3.7/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/usr/lib/python3.7/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/usr/lib/python3.7/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/usr/lib/python3.7/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Decimal is not JSON serializable

But as per the documentation of Django data migration (https://docs.djangoproject.com/en/2.2/topics/migrations/) , Django can serialze the decimal.Decimal value. Following is the screenshot for reference.

Can someone suggest why am I getting this error?


问:
How do I get my navigation items to center in my nav?

I can't figure out why my mobile navigation items (green boxes) are not centering.

I've tried commenting out all other bits of code and I still see the block. It looks like the core of the problem is that space is applied between the ul and the individual_nav_items, but I have no idea where it's coming from.

The body tag wrapping is the black box in the image.

  @media screen and (max-width: 740px) {
  nav {
    display: block;
    background-color: red;
  }
  ul {
    display: flex;
    flex-direction: column;
    border: solid;
    border-color: blue;
  }
  .individual_nav_item {
    border: solid;
    border-color: lawngreen;
    text-decoration: none;
    color: black;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <button onclick="toggleNav()" id="mobileNav" class="hamburger hamburger--slider" type="button">
    <span class="hamburger-box" >
      <span class="hamburger-inner"> </span>
    </span>
  </button>

  <ul>
    Home
    About Us
    FAQ
    Contact
  </ul>
</nav></code>```

答:
Is the following CSS displaying what you are trying to achieve ?

@media screen and (max-width: 740px) {

nav {
    display: block;
    background-color: red;
  }

  ul {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 0;
    padding: 0;
    align-items: center;
    border: solid;
    border-color: blue;
  }

  .individual_nav_item {
    border: solid;
    border-color: lawngreen;
    text-decoration: none;
    color: black;
    width: 100%;
  }```

Body:
I can't figure out why my mobile navigation items (green boxes) are not centering.

I've tried commenting out all other bits of code and I still see the block. It looks like the core of the problem is that space is applied between the ul and the individual_nav_items, but I have no idea where it's coming from.

The body tag wrapping is the black box in the image.

  @media screen and (max-width: 740px) {
  nav {
    display: block;
    background-color: red;
  }
  ul {
    display: flex;
    flex-direction: column;
    border: solid;
    border-color: blue;
  }
  .individual_nav_item {
    border: solid;
    border-color: lawngreen;
    text-decoration: none;
    color: black;
  }

  <button onclick="toggleNav()" id="mobileNav" class="hamburger hamburger--slider" type="button">

  </button>

    Home
    About Us
    FAQ
    Contact


问:
Problem with window.open in FireFox
I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything.  I understand that solution is very simple, but I think today is not my lucky day :)

Simple example. I try to call a web method from JavaScript and download a file.

Client code:

```<code> <script language="javascript" type="text/javascript">
         function Test() {
             PageMethods.Test(onCompleted);
         }

         function onCompleted(result) {
             window.open(result);
         }
    </script>

........

 <asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

    <div>
     <input type=button value="Download" onclick="Test()"/>

    </div>
</code>```

Server side:

```<code>[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}
</code>```

Folder 'Files' lies in root folder of Web application.

For IE and Chrome, this code is working fine, and I can download the file.  But in Firefox, I get an error:

Server Error in '/' Application.

HTTP Error 400 - Bad Request.

and in url I can see for example:
http://localhost:1406/\Files\test.zip

How can I return the correct path to zip file?

答:
Replacing the following lines

```<code>[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}
</code>```

with these might work...

```<code>[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\\\Files\\test.zip";
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Problem with window.open in FireFox

Body:
I have problem with downloading files in Firefox. I tried to find solution in old posts but I didn't find anything.  I understand that solution is very simple, but I think today is not my lucky day :)

Simple example. I try to call a web method from JavaScript and download a file.

Client code:

........

 <asp:ScriptManager ID="ScriptManager" runat="server" EnablePageMethods="true">
    </asp:ScriptManager>

     <input type=button value="Download" onclick="Test()"/>

Server side:

[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}

Folder 'Files' lies in root folder of Web application.

For IE and Chrome, this code is working fine, and I can download the file.  But in Firefox, I get an error:

Server Error in '/' Application.

HTTP Error 400 - Bad Request.

and in url I can see for example:
http://localhost:1406/\Files\test.zip

How can I return the correct path to zip file?

Body:
Replacing the following lines

[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\Files\\test.zip";
}

with these might work...

[System.Web.Services.WebMethod]
public static string Test()
{
  return "\\\\Files\\test.zip";
}


问:
How do I execute a PowerShell script automatically using Windows task scheduler?
I have one PowerShell script which sends emails. I want to execute that script automatically, every 1 minute. How can I do it, using task scheduler?

Currently I have created a task and provided the path of my script. But that scheduler opens my script, instead of executing.

I am using Windows 7 Professional and PowerShell version 2.0.5.

答:
None of posted solutions worked for me.
Workaround, which worked:

create a run.bat and put inside
powershell.exe -file "C:\...\script.ps1"

then set Action to Program/Script: "C:\...\run.bat"


问:
How memory work in assembly 16 bits using DOSBOX
I'm trying to understand how memory works in assembly

```<code>a dd 'aa'
b db 'aaa'
</code>```

this will work just fine and in memory I'll have:
61 61 00 00 61 61 61 ...

but if I to this

```<code>d dd 'aaa'
</code>```

I get a compilation error saying: 'Value out of range'

Why is that? And if you could get me some documentation or something to understand better it would be nice. Thanks

答:
dd stands for "define doubleword". It's for declaring four byte variables. What are you trying to do by placing a two byte text string there?

I'm not sure if placing a four byte string under a dd will work. At least it would make more sense.

Body:
I'm trying to understand how memory works in assembly

a dd 'aa'
b db 'aaa'

this will work just fine and in memory I'll have:
61 61 00 00 61 61 61 ...

but if I to this

d dd 'aaa'

I get a compilation error saying: 'Value out of range'

Why is that? And if you could get me some documentation or something to understand better it would be nice. Thanks


问:
Connecting PostgreSQL installed in docker inside Hyper-V Ubuntu from Windows 10 PgAdmin
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

```<code>sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres
</code>```

Step 2: Create a database

```<code>docker exec -it pg_test bash
psql -U postgres
create database mytestdb
</code>```

Step 3: Get the ip address

```<code>sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2
</code>```

Step 4: pg_hba.conf

```<code>host    all             all             0.0.0.0/0               md5
</code>```

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck

答:
You may want to check that pg_hba.conf is not restricted to local. It should not be the case for docker image but you never know.

See: https://www.postgresql.org/docs/9.1/auth-pg-hba-conf.html

Also, there is a typo: POSTGRES_PASSWOR=admin is missing D, it should be POSTGRES_PASSWORD=admin.

Body:
I need help in connecting PostgreSQL which is installed in Docker inside HyperV ubuntu 18.4 from Windows 10 PgAdmin. So far I tried the following

Step 1: Install Postgres in Docker (Ubuntu running on Hyper-V)

sudo docker run -p 5432:5432 --name pg_test -e POSTGRES_PASSWORD=admin -d postgres

Step 2: Create a database

docker exec -it pg_test bash
psql -U postgres
create database mytestdb

Step 3: Get the ip address

sudo docker inspect pg_test | grep IPAddress
//returned with 172.17.0.2

Step 4: pg_hba.conf

host    all             all             0.0.0.0/0               md5

Step 5: When I try to connect from Windows PgAdmin 4, I get this below error -
Note: I have also tried using UBUNTU VM IP address, but no luck


问:
Center multi-line SCNtext on macOS SceneKit
This code, on macOS Catalina

```<code>    scnView.scene = SCNScene()
    scnView.allowsCameraControl = true
    let root = scnView.scene!.rootNode
    let txt = SCNText(string: "This\nis\ncentered", extrusionDepth: 0)
    txt.font = NSFont.init(name: "Helvetica", size: 35)
    txt.string = NSAttributedString(string: "This\nis\ncentered", attributes: [.foregroundColor : NSColor.black])
    txt.flatness = 0.1
    txt.containerFrame = CGRect(origin: .zero, size: CGSize(width: 800, height: 200))
    txt.alignmentMode = CATextLayerAlignmentMode.right.rawValue
    txt.firstMaterial?.diffuse.contents = NSColor.black
    let txtNode = SCNNode(geometry: txt)
    root.addChildNode(txtNode)
</code>```

Produces this output

Which does not center the lines within the container rectangle.

I looked at this and a few others, and it seems around 2015 this didn't work on iOS, but did work on macOS.

One thing that has changed since 2015 is that the string constant is no longer kCAAlignmentCenterbut CATextLayerAlignmentMode.center.rawValue. I tried right and justified, which are also ignored.

答:
If you're looking to use an attributed string, it looks like alignmentMode is disabled so it can rely on the attributed string's paragraph style. Here's the extension I'm using to quickly center an attributed string.

```<code>extension NSAttributedString {
    func centered() -> NSAttributedString {
        let ps = NSMutableParagraphStyle()
        ps.alignment = NSTextAlignment.center
        let newString = NSMutableAttributedString(attributedString: self)
        newString.addAttribute(.paragraphStyle, value: ps, range: NSRange(location: 0, length: newString.length))
        return newString
    }
}
</code>```

Body:
This code, on macOS Catalina

    scnView.scene = SCNScene()
    scnView.allowsCameraControl = true
    let root = scnView.scene!.rootNode
    let txt = SCNText(string: "This\nis\ncentered", extrusionDepth: 0)
    txt.font = NSFont.init(name: "Helvetica", size: 35)
    txt.string = NSAttributedString(string: "This\nis\ncentered", attributes: [.foregroundColor : NSColor.black])
    txt.flatness = 0.1
    txt.containerFrame = CGRect(origin: .zero, size: CGSize(width: 800, height: 200))
    txt.alignmentMode = CATextLayerAlignmentMode.right.rawValue
    txt.firstMaterial?.diffuse.contents = NSColor.black
    let txtNode = SCNNode(geometry: txt)
    root.addChildNode(txtNode)

Produces this output

Which does not center the lines within the container rectangle.

I looked at this and a few others, and it seems around 2015 this didn't work on iOS, but did work on macOS.

One thing that has changed since 2015 is that the string constant is no longer kCAAlignmentCenterbut CATextLayerAlignmentMode.center.rawValue. I tried right and justified, which are also ignored.

Body:
If you're looking to use an attributed string, it looks like alignmentMode is disabled so it can rely on the attributed string's paragraph style. Here's the extension I'm using to quickly center an attributed string.

extension NSAttributedString {
    func centered() -> NSAttributedString {
        let ps = NSMutableParagraphStyle()
        ps.alignment = NSTextAlignment.center
        let newString = NSMutableAttributedString(attributedString: self)
        newString.addAttribute(.paragraphStyle, value: ps, range: NSRange(location: 0, length: newString.length))
        return newString
    }
}


答:
URL don´t allow for backslashes.

If the file is located at \Files\test.zip on your windows webserver root the correct url to the file is http:///Files/test.zip

Title: Problem with window.open in FireFox


问:
Clicking on a button with changing xpath
I just started working with Selenium webdriver to try automate clicking a button in a discord chat based on preconditions. The problem I am having is being able to classify this button.

For starters, the HTML code is as follows:

```<code><div tabindex="0" class="reactionInner-15NvIl" aria-label="♥, press to react" aria-pressed="false" role="button"><img src="/assets/1afd3c799f3e158662a70498e83e2a87.svg" alt="♥" draggable="false" class="emoji"><div class="reactionCount-2mvXRV" style="min-width: 9px;">1</div></div>
</code>```

What I first tried to do was to find_element_by_xpath:

```<code>driver.find_element_by_xpath('/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[48]/div[1]/div[2]/div[2]/div[1]/div/div').click()
</code>```

But, when a new opportunity for this reaction comes up, the xpath changes:

```<code>/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[50]/div[1]/div[2]/div[2]/div[1]/div/div
</code>```

Notice the only part changing it the div[48] to div[50]

The next thing I tried was to find_element_by_class_name:

```<code>element = driver.find_element_by_class_name('reactionInner-15NvIl')
driver.execute_script("arguments[0].click();", element)
</code>```

The reason I did this was because I was having a problem with simply doing:

```<code>driver.find_element_by_class_name('reactionInner-15NvIl').click()
</code>```

That code would give me an error saying Message: element click intercepted: Element
...
 is not clickable at point (405, 94). Other element would receive the click: ... and the code wouldn't run. The program runs with the execute_script but it just isn't doing anything, the button is not being clicked. So if anyone has any idea how to be able to click this button, any help would be appreciated!

答:
You can use xpath in a better way than navigate between the divs, like you did the first time.

First of all, if you can change the HTML to use id, or name, thats better.

In this case, you could use this xpath:

//div[@class = "reactionInner-15NvIl"]

When searching by class, this could return multiple results, so use the function find_elements_by_xpath, and then choose the exactly one

Body:
I just started working with Selenium webdriver to try automate clicking a button in a discord chat based on preconditions. The problem I am having is being able to classify this button.

For starters, the HTML code is as follows:

1

What I first tried to do was to find_element_by_xpath:

driver.find_element_by_xpath('/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[48]/div[1]/div[2]/div[2]/div[1]/div/div').click()

But, when a new opportunity for this reaction comes up, the xpath changes:

/html/body/div/div[1]/div/div[2]/div/div/div/div[2]/div[2]/div[2]/div[1]/div[1]/div/div/div[50]/div[1]/div[2]/div[2]/div[1]/div/div

Notice the only part changing it the div[48] to div[50]

The next thing I tried was to find_element_by_class_name:

element = driver.find_element_by_class_name('reactionInner-15NvIl')
driver.execute_script("arguments[0].click();", element)

The reason I did this was because I was having a problem with simply doing:

driver.find_element_by_class_name('reactionInner-15NvIl').click()

That code would give me an error saying Message: element click intercepted: Element
...
 is not clickable at point (405, 94). Other element would receive the click: ... and the code wouldn't run. The program runs with the execute_script but it just isn't doing anything, the button is not being clicked. So if anyone has any idea how to be able to click this button, any help would be appreciated!


问:
Group objects by one of its params with javascript
Basically I would want to transform this

```<code>[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]
</code>```

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

```<code>[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];
</code>```

Would really not mind using lodash for this but couldn't find the correct array method.

答:
You can achieve this by simply looping over your existing array and pushing the results to a newly created multidimensional array. This is, in my opinion, is the most readable way.

const mainArray = [
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
];

// create an empty array to store our results
const result = [];

mainArray.forEach(x => {
  const key = x.key;
  // Instantiate a new array if it does not exist
  // for the given key.
  if (!result[key]) {
   result[key] = [];
  }

  // push the object to the array
  result[key].push(x)
});

console.log(result);```

Body:
Basically I would want to transform this

[
  { key: 0, name: 'Some name' },
  { key: 0, name: 'Some name' },
  { key: 1, name: 'Some name' },
  { key: 1, name: 'Some name' },
]

To this where every object with the key of  0 would go into the first array and every object with the key of 1 would go into the second array.

[
  [
    { key: 0, name: 'Some name' },
    { key: 0, name: 'Some name' },
  ],
  [
    { key: 1, name: 'Some name' },
    { key: 1, name: 'Some name' },
  ],
];

Would really not mind using lodash for this but couldn't find the correct array method.


问:
How to print a message only once in a loop
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }
</code>```

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

```<code>2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file
</code>```

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }
</code>```

答:
I am not sure if this is what you meant

```<code>for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            flag log = false;
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                if(!flag)
                {

                     cout << "There is/are negative number(s) or zero(s) in the array
                              imported from your text file." << endl;
                     flag = true;
                }
            }
        }
    }
</code>```

Adding the flag boolean variable would allow the statement "there are negative numbers.." to be printed once.

Body:
I am using for loops combined with if statements to read integers from a text file into a two-dimensional array.

This is my code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;

            }
        }
    }

This code will read in the first 6 integers (max_row * max_column) from a text file into ArrB.

If  -1 exists in the first 6 integers, it will exit the loop and print out "The array does not have enough integers".

If there is no -1 in the first 6 integers, then it will check all 6 integers to see if there are any other negative numbers or zero.

If there are negative numbers or zero, I want it to still print out the array, then print out the error message (There is/are negative number(s) or zero(s) in the array imported from your text file) ONLY ONCE.

For example, this is my text file. As you can see, there is no -1 in the first 6 numbers, but there is a -7.

So, ideally, the result should be something like:

2 4 5 6 9 -7

There is/are negative number(s) or zero(s) in the array imported from your text file

But this is what I am getting if I run my code above:

-------------------------------------UPDATE--------------------------------------

Figured it out based on @ZedLepplin 's comment

Here is the code:

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }
            cout << *(*(ArrB + i) + j) << " ";
        }
    }
    if (invalidnum == true) {
        cout << "There is/are negative number(s) or zero(s) in the array imported from your text file." << endl;
    }

Body:
I am not sure if this is what you meant

for (int i = 0; i < MAX_ROWS;i++) {
        for (int j = 0; j < MAX_COLUMNS; j++) {
            flag log = false;
            inFile >> ArrB[i][j];
            if (ArrB[i][j] == -1) {
                bad = true;
                cout << "The array does not have enough integers" << endl;
                break;
            }
            else {
                if (ArrB[i][j] < 1) {
                    invalidnum = true;
                }
            }

            if (invalidnum = true) {
                cout << *(*(ArrB + i) + j) << " ";
                if(!flag)
                {

                     cout << "There is/are negative number(s) or zero(s) in the array
                              imported from your text file." << endl;
                     flag = true;
                }
            }
        }
    }

Adding the flag boolean variable would allow the statement "there are negative numbers.." to be printed once.


问:
How can i get WhatsApp like menu from BottomNavigationBar using flutter?
I am trying to design a WhatsApp-like menu from BottomNavigationBar for one of my applications which is written in flutter.

I have tried designing with PopupMenuButton class but it will cover the BottomNavigation also.

I need a popup like menu which is above the BottomNavigationBar something like below

答:
the PopupMenuButton opens up a menu just above the button so it blocked the bottom bar. I found a workaround, instead of using PopupMenuButton, try using a BottomAppBar with the IconButton as one of the children, then use showBottomSheetso it won't block the BottomAppBar.

Note: Most of my codes are just placeholders to mimic the layout of your image, you need to rewrite most of them to match your needs. The key is using showBottomSheet for your problem.

```<code>import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 70,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Icon(Icons.home),
              Icon(Icons.alarm),
              MyMiddleIcon(),
              Icon(Icons.album),
              Icon(Icons.assignment_ind),
            ],
          ),
        ),
        shape: CircularNotchedRectangle(),
        color: Colors.blueGrey[50],
      ),
    );
  }
}

class MyMiddleIcon extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IconButton(
        icon: Icon(Icons.add),
        onPressed: () {
          showBottomSheet(
              context: context,
              builder: (context) => Container(
                color: Colors.red[100],
                height: 250,
                width: double.infinity,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Icon(Icons.home),
                        Icon(Icons.hot_tub),
                        Icon(Icons.hourglass_empty),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Icon(Icons.home),
                        Icon(Icons.hot_tub),
                        Icon(Icons.hourglass_empty),
                      ],
                    ),
                  ],
                ),
              ));
        });
  }
}
</code>```

Body:
the PopupMenuButton opens up a menu just above the button so it blocked the bottom bar. I found a workaround, instead of using PopupMenuButton, try using a BottomAppBar with the IconButton as one of the children, then use showBottomSheetso it won't block the BottomAppBar.

Note: Most of my codes are just placeholders to mimic the layout of your image, you need to rewrite most of them to match your needs. The key is using showBottomSheet for your problem.

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 70,
          child: Row(
            mainAxisSize: MainAxisSize.max,
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              Icon(Icons.home),
              Icon(Icons.alarm),
              MyMiddleIcon(),
              Icon(Icons.album),
              Icon(Icons.assignment_ind),
            ],
          ),
        ),
        shape: CircularNotchedRectangle(),
        color: Colors.blueGrey[50],
      ),
    );
  }
}

class MyMiddleIcon extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return IconButton(
        icon: Icon(Icons.add),
        onPressed: () {
          showBottomSheet(
              context: context,
              builder: (context) => Container(
                color: Colors.red[100],
                height: 250,
                width: double.infinity,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: <Widget>[
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Icon(Icons.home),
                        Icon(Icons.hot_tub),
                        Icon(Icons.hourglass_empty),
                      ],
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: <Widget>[
                        Icon(Icons.home),
                        Icon(Icons.hot_tub),
                        Icon(Icons.hourglass_empty),
                      ],
                    ),
                  ],
                ),
              ));
        });
  }
}


问:
reading JSON element using JS
I am receiving a JSON object from a PHP get request. It looks like this:

```<code>data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}
</code>```

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

```<code>eti=data["emp_type_id"];
var myVar = eti[0];
</code>```

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.

答:
```<code>var eti = data.emp_type_id;
var myVar = eti[0];

for(var key in myVar){
    myVar[key];
}
</code>```

Title: reading JSON element using JS

Body:
I am receiving a JSON object from a PHP get request. It looks like this:

data == {"user_id":"7","emp_type_id":[{"0":"11","1":"10"}]}

I need to access the items within emp_type_id ("11" and "10" in this case).

I am able to access user_id just fine using data["user_id"] but can't figure out how to get the other items. I tried variations of:

eti=data["emp_type_id"];
var myVar = eti[0];

I'll want to loop through all items in emp_type_id eventually and add them to a JS array.


问:
The specified type member 'Date' is not supported in LINQ to Entities. DbFunctions.TruncateTime()
```<code>Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == DbFunctions.TruncateTime(DateTime.Now.Date))
           .Where(q => q.Order == id)
           .FirstOrDefault();
</code>```

When I try to run the above statement, I get the following error:

The specified type member 'Date' is not supported in LINQ to Entities

I thought that DbFunctions.TruncateTime() method would solve this problem as suggested in many posts I have seen, however I still get the error. I also tried to just apply the method to the database value but I still get the same error.

```<code>Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == DateTime.Now.Date)
           .Where(q => q.Order == id)
           .FirstOrDefault();
</code>```

答:
You need to pull DateTime into variable before LINQ:

```<code>var dateOfNow = DateTime.Now.Date;

Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == dateOfNow)
           .Where(q => q.Order == id)
           .FirstOrDefault();
</code>```

Body:
Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == DbFunctions.TruncateTime(DateTime.Now.Date))
           .Where(q => q.Order == id)
           .FirstOrDefault();

When I try to run the above statement, I get the following error:

The specified type member 'Date' is not supported in LINQ to Entities

I thought that DbFunctions.TruncateTime() method would solve this problem as suggested in many posts I have seen, however I still get the error. I also tried to just apply the method to the database value but I still get the same error.

Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == DateTime.Now.Date)
           .Where(q => q.Order == id)
           .FirstOrDefault();

Body:
You need to pull DateTime into variable before LINQ:

var dateOfNow = DateTime.Now.Date;

Question question =
         db.Questions
           .Where(q => DbFunctions.TruncateTime(q.Day.DayDate) == dateOfNow)
           .Where(q => q.Order == id)
           .FirstOrDefault();


问:
Forcibly stop the execution of the function in the cfc component
Does anyone know how I can forcibly stop a function execution in the cfc component if it works for more than a certain time? Either it may be piece of code, not a whole function, i.e. if it has completed in 5 seconds, I take some actions, otherwise others.</p>

答:
The only way to stop an arbitrary piece of code is to run it in a separate thread and then terminating after a set amount of time. This can be done by calling out to a separate page with a request timeout set or using cfthread.

For example with thread...
(Note.... as Alex pointed out you can use timeout on cfthread)

```<code><cfthread action="run" name="runForLimitedTime">
    ... code, call to function, etc ...
</cfthread>

<cfset sleep(5000) />

<cfif cfthread.runForLimitedTime.status eq "COMPLETED">
    <cfthread action="join" />
<cfelse>
    <cfthread action="terminate" name="runForLimitedTime" />
</cfif>
</code>```

Alternatively with a separate page...

```<code><!--- calling page --->

<cfset error = false />
<cftry>
    <cfhttp url="pageSetupForSpecificCall.cfm?timeout=5" throwonerror="true" />
    <cfcatch>
        <cfset error = true />
    </cfcatch>
</cftry>

<cfif error>
    something
<cfelse>
    something else
</cfif>

<!--- pageSetupForSpecificCall.cfm --->

<cfsetting requesttimeout="#url.timeout#" />

...do things...
</code>```

Body:
The only way to stop an arbitrary piece of code is to run it in a separate thread and then terminating after a set amount of time. This can be done by calling out to a separate page with a request timeout set or using cfthread.

For example with thread...
(Note.... as Alex pointed out you can use timeout on cfthread)

<cfthread action="run" name="runForLimitedTime">
    ... code, call to function, etc ...
</cfthread>

<cfset sleep(5000) />

<cfif cfthread.runForLimitedTime.status eq "COMPLETED">
    <cfthread action="join" />
<cfelse>
    <cfthread action="terminate" name="runForLimitedTime" />
</cfif>

Alternatively with a separate page...

<!--- calling page --->

<cfset error = false />
<cftry>
    <cfhttp url="pageSetupForSpecificCall.cfm?timeout=5" throwonerror="true" />
    <cfcatch>
        <cfset error = true />
    </cfcatch>
</cftry>

<cfif error>
    something
<cfelse>
    something else
</cfif>

<!--- pageSetupForSpecificCall.cfm --->

<cfsetting requesttimeout="#url.timeout#" />

...do things...


问:
PHP - PHPUnit - Handle fails inside try/catch for mocked object
I have the issues when an assertion fails is caught by the testing code "try-catch" block, giving the result false test result.

The be more precise I created a piece of code to reproduce the issue:

TestUnit.php

```<code>namespace MyNamespace;

class TestUnit
{
    private $service = null;

    public function setDependency($service)
    {
        $this->service = $service;
    }

    public function test($data)
    {
        $data++;
        try {
            $this->service->save($data);
            return 1;
        } catch (\Exception $e) {
            // Here we catch that we cannot save
        }
    }
}
</code>```

ServiceDependency.php

```<code>namespace MyNamespace;

class ServiceDependency
{
    public function save($item)
    {
        echo $item;
    }
}
</code>```

TestUnitTest.php

```<code>namespace MyNamespace;

class TestUnitTest extends \PHPUnit_Framework_TestCase
{
    public function testMethod()
    {
        $mydata = 5;
        $expectedData = 7;

        $testUnit = new TestUnit();
        $dependentService = $this->createMock(ServiceDependency::class);
        $dependentService->expects($this->any())
            ->method('save')
            ->will($this->returnCallback(function($data) use($expectedData) {
                var_dump($data == $expectedData);
                $this->assertEquals($data, $expectedData, "This should fail!");
                $this->assertTrue(false, "This should fail also!");
            }));
        $testUnit->setDependency($dependentService);
        $testUnit->test($mydata);
    }
}
</code>```

The test restul runned:

PHPUnit 5.6.3 by Sebastian Bergmann and contributors.

1 / 1 (100%)/--path--/TestUnitTest.php:16:

bool(false)

Time: 211 ms, Memory: 10.00MB

OK (1 test, 1 assertion)

What really happens here is that an assertion throws a PHPUnit_Framework_ExpectationFailedException that is caught by TestUnit::test() try/catch block.

How can I bypass this kind of issues?

答:
I just ran into the same problem trying to test some methods that should fire events.
I'm mocking an event dispatcher/handler/obsever/[insert name here] class that is wrapped in a try & catch from the caller.

To get around the problem I created a trait (as I use it in multiple test classes) who's job is to store the results and assert them once outside the try and catch.

In my example I'm checking the events are called in the correct order. (Code has been simplified for clarity)

trait EventStackTrait
{
    protected $expectedEventStack = [];

    protected $actualEventStack = [];

    /**
     * Check the correct events are called
     * @param array $eventStack expected events in order
     * @return void
     */
    protected function createMockEventHandlerWithStack( array $eventStack )
    {
        $this->expectedEventStack = $eventStack;
        $this->actualEventStack = [];

        $event = $this->createMock( \Event::class );

        $event->expects( $this->any() )
              ->method( 'dispatch' )
              ->with(
                  $this->callback( function ( $subject )
                  {
                      $this->actualEventStack[] = $subject;
                      return true;
                  }
                  )
              )
              ->will( $this->returnValue( true ) );
    }

    protected function assertAllEventsWhereCalled( ?string $message = null )
    {
        $this->assertEquals( $this->expectedEventStack, $this->actualCallerStack, 'Events not as expected' );
    }
}
```

<p>Then in the test class</p>

<pre class="lang-php prettyprint-override"><code>class FoobarTest extends PHPUnit\Framework\TestCase
{
    use EventStackTrait;

    public function testAddFromArrayFiresEvents()
    {
        $this->createMockEventHandlerWithStack(
            [
                BeforeCreate::EVENT,
                Created::EVENT,
            ]
        );

        $foobar = new \Foobar();
        $foobar->addFromArray( [ .... ] );

        $this->assertAllEventsWhereCalled();
    }
}
</code>```

(Note I'm fairly new to unit test, so there's probably a better way)

Body:
I have the issues when an assertion fails is caught by the testing code "try-catch" block, giving the result false test result.

The be more precise I created a piece of code to reproduce the issue:

TestUnit.php

namespace MyNamespace;

class TestUnit
{
    private $service = null;

    public function setDependency($service)
    {
        $this->service = $service;
    }

    public function test($data)
    {
        $data++;
        try {
            $this->service->save($data);
            return 1;
        } catch (\Exception $e) {
            // Here we catch that we cannot save
        }
    }
}

ServiceDependency.php

namespace MyNamespace;

class ServiceDependency
{
    public function save($item)
    {
        echo $item;
    }
}

TestUnitTest.php

namespace MyNamespace;

class TestUnitTest extends \PHPUnit_Framework_TestCase
{
    public function testMethod()
    {
        $mydata = 5;
        $expectedData = 7;

        $testUnit = new TestUnit();
        $dependentService = $this->createMock(ServiceDependency::class);
        $dependentService->expects($this->any())
            ->method('save')
            ->will($this->returnCallback(function($data) use($expectedData) {
                var_dump($data == $expectedData);
                $this->assertEquals($data, $expectedData, "This should fail!");
                $this->assertTrue(false, "This should fail also!");
            }));
        $testUnit->setDependency($dependentService);
        $testUnit->test($mydata);
    }
}

The test restul runned:

PHPUnit 5.6.3 by Sebastian Bergmann and contributors.

1 / 1 (100%)/--path--/TestUnitTest.php:16:

bool(false)

Time: 211 ms, Memory: 10.00MB

OK (1 test, 1 assertion)

What really happens here is that an assertion throws a PHPUnit_Framework_ExpectationFailedException that is caught by TestUnit::test() try/catch block.

How can I bypass this kind of issues?

Body:
I just ran into the same problem trying to test some methods that should fire events.
I'm mocking an event dispatcher/handler/obsever/[insert name here] class that is wrapped in a try & catch from the caller.

To get around the problem I created a trait (as I use it in multiple test classes) who's job is to store the results and assert them once outside the try and catch.

In my example I'm checking the events are called in the correct order. (Code has been simplified for clarity)

trait EventStackTrait
{
    protected $expectedEventStack = [];

    protected $actualEventStack = [];

    /**
     * Check the correct events are called
     * @param array $eventStack expected events in order
     * @return void
     */
    protected function createMockEventHandlerWithStack( array $eventStack )
    {
        $this->expectedEventStack = $eventStack;
        $this->actualEventStack = [];

        $event = $this->createMock( \Event::class );

        $event->expects( $this->any() )
              ->method( 'dispatch' )
              ->with(
                  $this->callback( function ( $subject )
                  {
                      $this->actualEventStack[] = $subject;
                      return true;
                  }
                  )
              )
              ->will( $this->returnValue( true ) );
    }

    protected function assertAllEventsWhereCalled( ?string $message = null )
    {
        $this->assertEquals( $this->expectedEventStack, $this->actualCallerStack, 'Events not as expected' );
    }
}

Then in the test class

class FoobarTest extends PHPUnit\Framework\TestCase
{
    use EventStackTrait;

    public function testAddFromArrayFiresEvents()
    {
        $this->createMockEventHandlerWithStack(
            [
                BeforeCreate::EVENT,
                Created::EVENT,
            ]
        );

        $foobar = new \Foobar();
        $foobar->addFromArray( [ .... ] );

        $this->assertAllEventsWhereCalled();
    }
}

(Note I'm fairly new to unit test, so there's probably a better way)


问:
VHDL OR logic with 32 bit vector
```<code>zero <= result_i(31) OR result_i(30) OR result_i(29) OR result_i(28)
        OR result_i(27) OR result_i(26) OR result_i(25) OR result_i(24)
        OR result_i(23) OR result_i(22) OR result_i(21) OR result_i(20)
        OR result_i(19) OR result_i(18) OR result_i(17) OR result_i(16)
        OR result_i(15) OR result_i(14) OR result_i(13) OR result_i(12)
        OR result_i(11) OR result_i(10) OR result_i(9) OR result_i(8)
        OR result_i(7) OR result_i(6) OR result_i(5) OR result_i(4)
        OR result_i(3) OR result_i(2) OR result_i(1) OR result_i(0);
</code>```

How can I make this shorter?

答:
You can achieve it with vhdl revision  2008

VHDL-2008 defines unary operators, like these:

```<code>outp <= and "11011";

outp <= xor "11011";
</code>```

So in your case it would be:

```<code>zero <= or result_i;
</code>```

Title: VHDL OR logic with 32 bit vector

Body:
zero <= result_i(31) OR result_i(30) OR result_i(29) OR result_i(28)
        OR result_i(27) OR result_i(26) OR result_i(25) OR result_i(24)
        OR result_i(23) OR result_i(22) OR result_i(21) OR result_i(20)
        OR result_i(19) OR result_i(18) OR result_i(17) OR result_i(16)
        OR result_i(15) OR result_i(14) OR result_i(13) OR result_i(12)
        OR result_i(11) OR result_i(10) OR result_i(9) OR result_i(8)
        OR result_i(7) OR result_i(6) OR result_i(5) OR result_i(4)
        OR result_i(3) OR result_i(2) OR result_i(1) OR result_i(0);

How can I make this shorter?

Body:
You can achieve it with vhdl revision  2008

VHDL-2008 defines unary operators, like these:

outp <= and "11011";

outp <= xor "11011";

So in your case it would be:

zero <= or result_i;


问:
kubernetes: selector field missing in kompose
I have a docker-compose.yml file we have been using to set up our development environment.

The file declares some services, all of them more or less following the same pattern:

```<code>services:

   service_1:
      image: some_image_1
      enviroment:
        - ENV_VAR_1
        - ENV_VAR_2
     depends_on:
        - another_service_of_the_same_compose_file
</code>```

In the view of migrating to kubernetes, when running:

```<code>kompose convert -f docker-compose.yml
</code>```

produces, for each service, a pair of deployment/service manifests.

Two questions about the deployment generated:

1.

the examples in the official documentation seem to hint that the selector field is needed for a Deployment to be aware of the pods to manage.

However the deployment manifests created do not include a selector field, and are as follows:

```<code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert -f docker-compose.yml
    kompose.version: 1.6.0 (e4adfef)
  creationTimestamp: null
  labels:
    io.kompose.service: service_1
  name: service_1
spec:
  replicas: 1
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        io.kompose.service: service_1
    spec:
      containers:
      - image: my_image
        name: my_image_name
        resources: {}
      restartPolicy: Always
status: {}
</code>```

2.

the apiVersion in the generated deployment manifest is extensions/v1beta1, however the examples in the Deployments section of the official documentation default to apps/v1.
The recommendation seems to be

for versions before 1.9.0 use apps/v1beta2

Which is the correct version to use? (using kubernetes 1.8)

答:
In kubernetes 1.16 the deployment's spec.selector became required. Kompose (as of 1.20) does not yet do this automatically. You will have to add this to every *-deployment.yaml file it creates:

```<code>  selector:
    matchLabels:
      io.kompose.service: alignment-processor
</code>```

If you use an IDE like jetbrains you can use the following search/replace patterns on the folder where you put the conversion results:

Search for this multiline regexp:

```<code>    io.kompose.service: (.*)
  name: \1
spec:
  replicas: 1
  template:
</code>```

Replace with this pattern:

```<code>    io.kompose.service: $1
  name: $1
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: $1
  template:
</code>```

The (.*) captures the name of the service, the \1 matches the (first and only) capture, and the $1 substitutes the capture in the replacement.

You will also have to substitute all extensions/v1beta1 with apps/v1 in all *-deployment.yaml files.

I also found that secrets have to massaged a bit but this goes beyond the scope of this question.

Body:
I have a docker-compose.yml file we have been using to set up our development environment.

The file declares some services, all of them more or less following the same pattern:

services:

   service_1:
      image: some_image_1
      enviroment:
        - ENV_VAR_1
        - ENV_VAR_2
     depends_on:
        - another_service_of_the_same_compose_file

In the view of migrating to kubernetes, when running:

kompose convert -f docker-compose.yml

produces, for each service, a pair of deployment/service manifests.

Two questions about the deployment generated:

1.

the examples in the official documentation seem to hint that the selector field is needed for a Deployment to be aware of the pods to manage.

However the deployment manifests created do not include a selector field, and are as follows:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    kompose.cmd: kompose convert -f docker-compose.yml
    kompose.version: 1.6.0 (e4adfef)
  creationTimestamp: null
  labels:
    io.kompose.service: service_1
  name: service_1
spec:
  replicas: 1
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        io.kompose.service: service_1
    spec:
      containers:
      - image: my_image
        name: my_image_name
        resources: {}
      restartPolicy: Always
status: {}

2.

the apiVersion in the generated deployment manifest is extensions/v1beta1, however the examples in the Deployments section of the official documentation default to apps/v1.
The recommendation seems to be

for versions before 1.9.0 use apps/v1beta2

Which is the correct version to use? (using kubernetes 1.8)

Body:
In kubernetes 1.16 the deployment's spec.selector became required. Kompose (as of 1.20) does not yet do this automatically. You will have to add this to every *-deployment.yaml file it creates:

  selector:
    matchLabels:
      io.kompose.service: alignment-processor

If you use an IDE like jetbrains you can use the following search/replace patterns on the folder where you put the conversion results:

Search for this multiline regexp:

    io.kompose.service: (.*)
  name: \1
spec:
  replicas: 1
  template:

Replace with this pattern:

    io.kompose.service: $1
  name: $1
spec:
  replicas: 1
  selector:
    matchLabels:
      io.kompose.service: $1
  template:

The (.*) captures the name of the service, the \1 matches the (first and only) capture, and the $1 substitutes the capture in the replacement.

You will also have to substitute all extensions/v1beta1 with apps/v1 in all *-deployment.yaml files.

I also found that secrets have to massaged a bit but this goes beyond the scope of this question.


答:
Just store the message and print it where and when you want. Some psuedo-code:</p>

```<code>std::string message;
for (int i = 0; i < N; ++i)
{
    for (int j = 0; j< M; ++j)
    {
        if (smth)
        {
            message {"Your message"};
            break; // note that after break,
                   // you are still in the outer loop
        }
        else if (smth else)
        {
            message {"Your message"};
        }
    }
    // print it here
}
// or here, or wherever you want to
</code>```

Title: How to print a message only once in a loop

Body:
Just store the message and print it where and when you want. Some psuedo-code:

std::string message;
for (int i = 0; i < N; ++i)
{
    for (int j = 0; j< M; ++j)
    {
        if (smth)
        {
            message {"Your message"};
            break; // note that after break,
                   // you are still in the outer loop
        }
        else if (smth else)
        {
            message {"Your message"};
        }
    }
    // print it here
}
// or here, or wherever you want to


问:
Transforming values passing between two SQL DBs in Node project
In my Node project I am querying one SQL database and am then, as necessary, transforming the data, and then writing it to another SQL database. In order to handle situations where I needed to write a string value to the receiving database, but the value might be null (and I didn't want to write "null" to the db), I handled it this way:

```<code>const sqlStringOrNull = function (value) {
  return value ? "'" + value + "'" : null;
};
</code>```

That worked fine for first few situations where the sending db used 'varchars'. But now I have a situation where the db being queried has char(9) values. And, as far as I can tell, even if the value itself is, say, 4 characters long, the remaining characters will be passed on as empty spaces. So with my current implementation, while I don't get errors, when I console log my query being passed, I see values like this: '1234     '.

My question is, first of all, is this what's happening? Will a char(9) value in SQL Server, always have 9 characters, even if the actual value is fewer than that?

And, if so, how I can amend my function to trim values when that's the case? What I tried was this:

```<code>const sqlStringOrNull = function (value) {
  if (value) {
    value = "'" + value + "'";
    return value.trim();
  } else if (!value) {
    return null;
  }
};
</code>```

This didn't give me any errors, but it also didn't seem to trim the values as expected. What am I missing here? How can I handle the data so that, when it's a string, it ends up being trimmed?

答:
Yes, columns with CHAR datatype will always return fixed length data, padding any short values with empty space.

As for your second code block, you should call .trim() before adding the single quotes, e.g.:

```<code>const sqlStringOrNull = function (value) {
  if (value) {
    return "'" + (value.trim ? value.trim() : value) + "'";
  } else {
    return null;
  }
};
</code>```

Body:
In my Node project I am querying one SQL database and am then, as necessary, transforming the data, and then writing it to another SQL database. In order to handle situations where I needed to write a string value to the receiving database, but the value might be null (and I didn't want to write "null" to the db), I handled it this way:

const sqlStringOrNull = function (value) {
  return value ? "'" + value + "'" : null;
};

That worked fine for first few situations where the sending db used 'varchars'. But now I have a situation where the db being queried has char(9) values. And, as far as I can tell, even if the value itself is, say, 4 characters long, the remaining characters will be passed on as empty spaces. So with my current implementation, while I don't get errors, when I console log my query being passed, I see values like this: '1234     '.

My question is, first of all, is this what's happening? Will a char(9) value in SQL Server, always have 9 characters, even if the actual value is fewer than that?

And, if so, how I can amend my function to trim values when that's the case? What I tried was this:

const sqlStringOrNull = function (value) {
  if (value) {
    value = "'" + value + "'";
    return value.trim();
  } else if (!value) {
    return null;
  }
};

This didn't give me any errors, but it also didn't seem to trim the values as expected. What am I missing here? How can I handle the data so that, when it's a string, it ends up being trimmed?

Body:
Yes, columns with CHAR datatype will always return fixed length data, padding any short values with empty space.

As for your second code block, you should call .trim() before adding the single quotes, e.g.:

const sqlStringOrNull = function (value) {
  if (value) {
    return "'" + (value.trim ? value.trim() : value) + "'";
  } else {
    return null;
  }
};


问:
DISABLE TRIGGER ALL with Laravel DB Seeding Error
I have inherited a project. They have used a database seeder. They have this method;

```<code>private function cleanDatabase()
    {
        foreach ($this->tables as $tableName) {
            DB::statement("ALTER TABLE $tableName DISABLE TRIGGER ALL");
            DB::statement("TRUNCATE TABLE $tableName CASCADE");
            DB::statement("ALTER TABLE $tableName ENABLE TRIGGER ALL");
        }
    }
</code>```

When I run the php artisan db:seed I get the error;

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRIGGER ALL' at line 1

This is the only script with it in, so something must be wrong here. I have never used DISABLE TRIGGER ALL in my life so not even sure what it does.

答:
I had to take the long way out, since there doesn't seem to be another way:

drop the trigger, run the migration, recreate the trigger.

```<code>DB::statement('DROP TRIGGER IF EXISTS `contract_quantities_after_update`');
DB::statement('UPDATE contract_quantities SET unit_price=(SELECT unit_price FROM contracts WHERE id=contract_quantities.contract_id)');
DB::statement('CREATE TRIGGER `contract_quantities_after_update` AFTER UPDATE ON `contract_quantities` FOR EACH ROW UPDATE contracts SET quantity=(SELECT IFNULL(SUM(quantity),0) FROM contract_quantities WHERE contract_id=NEW.contract_id) WHERE id=NEW.contract_id');
</code>```

Body:
I have inherited a project. They have used a database seeder. They have this method;

private function cleanDatabase()
    {
        foreach ($this->tables as $tableName) {
            DB::statement("ALTER TABLE $tableName DISABLE TRIGGER ALL");
            DB::statement("TRUNCATE TABLE $tableName CASCADE");
            DB::statement("ALTER TABLE $tableName ENABLE TRIGGER ALL");
        }
    }

When I run the php artisan db:seed I get the error;

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'TRIGGER ALL' at line 1

This is the only script with it in, so something must be wrong here. I have never used DISABLE TRIGGER ALL in my life so not even sure what it does.

Body:
I had to take the long way out, since there doesn't seem to be another way:

drop the trigger, run the migration, recreate the trigger.

DB::statement('DROP TRIGGER IF EXISTS `contract_quantities_after_update`');
DB::statement('UPDATE contract_quantities SET unit_price=(SELECT unit_price FROM contracts WHERE id=contract_quantities.contract_id)');
DB::statement('CREATE TRIGGER `contract_quantities_after_update` AFTER UPDATE ON `contract_quantities` FOR EACH ROW UPDATE contracts SET quantity=(SELECT IFNULL(SUM(quantity),0) FROM contract_quantities WHERE contract_id=NEW.contract_id) WHERE id=NEW.contract_id');


问:
Passing variables from a geometry shader to a fragment shader
I have an GLSL geometry shader that looks like the following:

```<code>#version 150

uniform mat4 p;
uniform mat4 mv;
uniform mat3 nm;

layout(points) in;
layout(triangle_strip, max_vertices = 200) out;

out vec4 test;

void main() {
    for (int i = 0; i < gl_in.length(); i++) {
        ....
        gl_Position = p * mv * gl_in[i].gl_Position;
        test = vec4(1.0, 0.0, 0.0, 0.0);
        EmitVertex();
        ....
        EndPrimitive();
    }
}
</code>```

However when I try to access "test" in my fragment shader my application crashes. Here is my fragment shader:

```<code>#version 150

out vec4 fColor;
in vec4 test;

void main(void) {
    fColor = vec4(test.x, 1.0, 0.4, 0);
}
</code>```

Can someone help me to pass a variable from the geometry to the fragment shader? varying is deprecated in #version 150.

答:
You need to declare test as input in your fragment shader (I wonder why the shader compiles):</p>

```<code>in vec4 test;
</code>```

Body:
I have an GLSL geometry shader that looks like the following:

#version 150

uniform mat4 p;
uniform mat4 mv;
uniform mat3 nm;

layout(points) in;
layout(triangle_strip, max_vertices = 200) out;

out vec4 test;

void main() {
    for (int i = 0; i < gl_in.length(); i++) {
        ....
        gl_Position = p * mv * gl_in[i].gl_Position;
        test = vec4(1.0, 0.0, 0.0, 0.0);
        EmitVertex();
        ....
        EndPrimitive();
    }
}

However when I try to access "test" in my fragment shader my application crashes. Here is my fragment shader:

#version 150

out vec4 fColor;
in vec4 test;

void main(void) {
    fColor = vec4(test.x, 1.0, 0.4, 0);
}

Can someone help me to pass a variable from the geometry to the fragment shader? varying is deprecated in #version 150.

Body:
You need to declare test as input in your fragment shader (I wonder why the shader compiles):

in vec4 test;


问:
Parent to child communication without event
I have string parameter in child component that I need to show in my parent component.
It should be done when the page is loading. So, not on click or any other event.

How do you manage to do this?

So far I didn't find any answer that would fit my solution.

答:
So ruling out communication via events, you have the following options:

Communicate via a shared service. This is a common strategy, no example required.

Pass an object from the parent to the child. If the child updates a property on the the object reference, the parent will also see that updated value (albeit without notifications).

Demo: https://stackblitz.com/edit/angular-h7h5xl

The principle:

Parent creates an object and passes it to the child

parent.ts

```<code>obj = { value: ''; };
</code>```

parent.html

```<code><child [obj]="obj"></child>
</code>```

The child receives the object and updates a property on it.

child.ts

```<code>@Input() obj: { value: string };

someMethod(): void {
  // update obj, which both parent and child reference
  this.obj.value = 'CHILD';
}
</code>```

End result: whenever the parent reads from the property, it will see the value that the child has set.

Edit:

As Michael D points out, I chose to pass an object through rather than a string because object references are passed around rather than literal values.

Body:
So ruling out communication via events, you have the following options:

Communicate via a shared service. This is a common strategy, no example required.

Pass an object from the parent to the child. If the child updates a property on the the object reference, the parent will also see that updated value (albeit without notifications).

Demo: https://stackblitz.com/edit/angular-h7h5xl

The principle:

Parent creates an object and passes it to the child

parent.ts

obj = { value: ''; };

parent.html

<child [obj]="obj"></child>

The child receives the object and updates a property on it.

child.ts

@Input() obj: { value: string };

someMethod(): void {
  // update obj, which both parent and child reference
  this.obj.value = 'CHILD';
}

End result: whenever the parent reads from the property, it will see the value that the child has set.

Edit:

As Michael D points out, I chose to pass an object through rather than a string because object references are passed around rather than literal values.


问:
Reduce the oracle PL/SQL statement
I am a new in PL/SQL. After hours of learning, I have some
I have a few curious questions. Example I have a SQL statement like this:

```<code>SELECT ShipperName, OrderID, NumberOfOrders, ...
FROM Orders
</code>```

Can we declare a variable that hold the "list select" like list_select = 'ShipperName, OrderID, NumberOfOrders, ... '
And then replace the select statement with the "list select" we was declared?

```<code>SELECT list_select
FROM Orders
</code>```

And other question, Can we reduce the SQL statement like the Image . I was try this in Oracle SQL Developer, the compiler is ok but when I ran the test I was got an error "by segment".

Any help is appreciated and thank for help.

答:
For your first question, You may search for "EXECUTE IMMEDIATE" statement which is used for dynamic query execution. So you may try something like below -

```<code>EXECUTE IMMEDIATE 'SELECT ' || YOUR_COMMA_DELIMITED_COLUMNS_LIST || ' FROM Orders';
</code>```

For 2nd, Please post the sample data and expected result.

Title: Reduce the oracle PL/SQL statement

Body:
I am a new in PL/SQL. After hours of learning, I have some
I have a few curious questions. Example I have a SQL statement like this:

SELECT ShipperName, OrderID, NumberOfOrders, ...
FROM Orders

Can we declare a variable that hold the "list select" like list_select = 'ShipperName, OrderID, NumberOfOrders, ... '
And then replace the select statement with the "list select" we was declared?

SELECT list_select
FROM Orders

And other question, Can we reduce the SQL statement like the Image . I was try this in Oracle SQL Developer, the compiler is ok but when I ran the test I was got an error "by segment".

Any help is appreciated and thank for help.

Body:
For your first question, You may search for "EXECUTE IMMEDIATE" statement which is used for dynamic query execution. So you may try something like below -

EXECUTE IMMEDIATE 'SELECT ' || YOUR_COMMA_DELIMITED_COLUMNS_LIST || ' FROM Orders';

For 2nd, Please post the sample data and expected result.


问:
How do I create an abstract base class in JavaScript?
Is it possible to simulate abstract base class in JavaScript? What is the most elegant way to do it?

Say, I want to do something like:

```<code>var cat = new Animal('cat');
var dog = new Animal('dog');

cat.say();
dog.say();
</code>```

It should output:

```<code>meow
bark
</code>```

答:
You might want to check out Dean Edwards' Base Class: http://dean.edwards.name/weblog/2006/03/base/

Alternatively, there is this example / article by Douglas Crockford on classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html

OwnerDisplayName: Sabya

Body:
Is it possible to simulate abstract base class in JavaScript? What is the most elegant way to do it?

Say, I want to do something like:

var cat = new Animal('cat');
var dog = new Animal('dog');

cat.say();
dog.say();

It should output:

meow
bark

LastEditorDisplayName: Eddie

OwnerDisplayName: Ian Oxley

ContentLicense: CC BY-SA 2.5


问:
Find the Values of multiple layer childs (using loop???)
I was not sure about how to search for this so was really unsuccessful. I will just start from data classes that i have,

Here is the TrainingPlan Entity (example)

```<code>@Data
@Entity
@Table(name = "TRAINING_PLAN")
@JsonIgnoreProperties({"trainings"})
public class TrainingPlan {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@Column(name = "CURRENT_PHASE")
private int currentPhase;

@Column(name = "PREVIOUS_TRAINING_PLAN_ID")
private Long previousTrainingPlanId;

@OneToMany(mappedBy = "trainingPlan", fetch = FetchType.LAZY)
private List<Training> trainings = new ArrayList<Training>();
</code>```

Here is the Training Entity (example)

```<code>@Data
@Entity
@Table(name = "TRAINING")
public class Training {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "TRAINING_PLAN_ID")
private TrainingPlan trainingPlan;
</code>```

I hope i will be able to explain this clearly, so what i am trying to achieve here is to get Trainings from all previous (TrainingPlan) phases.

How it works - when next (New TrainingPlan) plan phase is created it references the old Plan with the previousPlanId so it recognises its parent (its like layers).

So, for example, if TrainingPlan has phase 2, i can easily get Trainings from phase 1 in a similar way to this:

```<code>    public List<Training> trainingsFromPreviousPhase(TrainingPlan plan, List<TrainingPlan> planList) {
    List<Training> previousPhaseTrainings = new ArrayList<Training>();

    if (plan.getPreviousTrainingPlanId() != null) {
        TrainingPlan previousPlanPhase = planList.parallelStream()
                .filter(e -> e.getId() == plan.getPreviousTrainingPlanId()).findAny().get();
        previousPhaseTrainings = previousPlanPhase.getTrainings();

}
    return previousPhaseTrainings;
}
</code>```

Now the problem is if a plan is at Phase 5, i need to get the trainings from all 4 previous phases, and this is where i get stuck, cant think of a method to automatically loop that. I hope i explained this not too hard to understand. Any advices or questions are welcome.

What i need here is something similar to:

```<code>List<List<Training>> getTrainingsFromAllPreviousPhases()
</code>```

答:
You could loop through all plan phases like this:

```<code>TrainingPlan currentPlan = plan;
List<Training> allTrainings = new ArrayList<>();
while (cirrentPlan.getPreviousTrainingPlanId() != null) {
    TrainingPlan previousPlanPhase = planList.parallelStream()
        .filter(e -> e.getId() == currentPlan.getPreviousTrainingPlanId()).findAny().get();
    allTrainings.addAll(previousPlanPhase.getTrainings());
    currentPlan = previousPlanPhase;
}

</code>```

However, to avoid repeatedly going through the list of plans to find the one by id, I'd propose to keep them in a map:

```<code>Map<Long, TrainingPlan> planMap = planList.stream()
    .collect(Collectors.toMap(TrainingPlan::getId, Function.identity());
</code>```

Then the code could be simplified (both visually, and in terms of O(n) complexity):

```<code>TrainingPlan currentPlan = plan;
List<Training> allTrainings = new ArrayList<>();
while (currentPlan.getPreviousTrainingPlanId() != null) {
    TrainingPlan previousPlanPhase = planMap.get(currentPlan.getPreviousTrainingPlanId());
    allTrainings.addAll(previousPlanPhase.getTrainings());
    currentPlan = previousPlanPhase;
}
</code>```

Body:
I was not sure about how to search for this so was really unsuccessful. I will just start from data classes that i have,

Here is the TrainingPlan Entity (example)

@Data
@Entity
@Table(name = "TRAINING_PLAN")
@JsonIgnoreProperties({"trainings"})
public class TrainingPlan {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@Column(name = "CURRENT_PHASE")
private int currentPhase;

@Column(name = "PREVIOUS_TRAINING_PLAN_ID")
private Long previousTrainingPlanId;

@OneToMany(mappedBy = "trainingPlan", fetch = FetchType.LAZY)
private List<Training> trainings = new ArrayList<Training>();

Here is the Training Entity (example)

@Data
@Entity
@Table(name = "TRAINING")
public class Training {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "ID")
private Long id;

@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "TRAINING_PLAN_ID")
private TrainingPlan trainingPlan;

I hope i will be able to explain this clearly, so what i am trying to achieve here is to get Trainings from all previous (TrainingPlan) phases.

How it works - when next (New TrainingPlan) plan phase is created it references the old Plan with the previousPlanId so it recognises its parent (its like layers).

So, for example, if TrainingPlan has phase 2, i can easily get Trainings from phase 1 in a similar way to this:

    public List<Training> trainingsFromPreviousPhase(TrainingPlan plan, List<TrainingPlan> planList) {
    List<Training> previousPhaseTrainings = new ArrayList<Training>();

    if (plan.getPreviousTrainingPlanId() != null) {
        TrainingPlan previousPlanPhase = planList.parallelStream()
                .filter(e -> e.getId() == plan.getPreviousTrainingPlanId()).findAny().get();
        previousPhaseTrainings = previousPlanPhase.getTrainings();

}
    return previousPhaseTrainings;
}

Now the problem is if a plan is at Phase 5, i need to get the trainings from all 4 previous phases, and this is where i get stuck, cant think of a method to automatically loop that. I hope i explained this not too hard to understand. Any advices or questions are welcome.

What i need here is something similar to:

List<List<Training>> getTrainingsFromAllPreviousPhases()

Body:
You could loop through all plan phases like this:

TrainingPlan currentPlan = plan;
List<Training> allTrainings = new ArrayList<>();
while (cirrentPlan.getPreviousTrainingPlanId() != null) {
    TrainingPlan previousPlanPhase = planList.parallelStream()
        .filter(e -> e.getId() == currentPlan.getPreviousTrainingPlanId()).findAny().get();
    allTrainings.addAll(previousPlanPhase.getTrainings());
    currentPlan = previousPlanPhase;
}

However, to avoid repeatedly going through the list of plans to find the one by id, I'd propose to keep them in a map:

Map<Long, TrainingPlan> planMap = planList.stream()
    .collect(Collectors.toMap(TrainingPlan::getId, Function.identity());

Then the code could be simplified (both visually, and in terms of O(n) complexity):

TrainingPlan currentPlan = plan;
List<Training> allTrainings = new ArrayList<>();
while (currentPlan.getPreviousTrainingPlanId() != null) {
    TrainingPlan previousPlanPhase = planMap.get(currentPlan.getPreviousTrainingPlanId());
    allTrainings.addAll(previousPlanPhase.getTrainings());
    currentPlan = previousPlanPhase;
}