问:
fill a 2D array using a for loop using other 2D arrays
I have two 2D numpy arrays a(N,D) b(M,D) and I want to fill a third array c(M,D*N) which is a function of a and b. If N= 2 and D=3 I want c to be the following:

```<code>c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]
c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2]

c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1]
c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]
</code>```

How can I fill c using a loop (for, while)?

Body:
I have two 2D numpy arrays a(N,D) b(M,D) and I want to fill a third array c(M,D*N) which is a function of a and b. If N= 2 and D=3 I want c to be the following:

c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]
c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2]

c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1]
c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]

How can I fill c using a loop (for, while)?

Body:
Here's a vectorized way leveraging broadcasting, meant for performance efficiency -

bs = b*np.std(b,axis=0,keepdims=True)
c_out = (bs[:,None,:]+a).reshape(len(b),-1)

Sample run -

In [43]: N,M,D = 2,4,3
    ...: np.random.seed(0)
    ...: a = np.random.rand(N,D)
    ...: b = np.random.rand(M,D)
    ...: c = np.zeros((M,D*N))
    ...:
    ...: c[:,0]=b[:,0]*np.std(b[:,0])+a[0,0]
    ...: c[:,1]=b[:,1]*np.std(b[:,1])+a[0,1]
    ...: c[:,2]=b[:,2]*np.std(b[:,2])+a[0,2]
    ...:
    ...: c[:,3]=b[:,0]*np.std(b[:,0])+a[1,0]
    ...: c[:,4]=b[:,1]*np.std(b[:,1])+a[1,1]
    ...: c[:,5]=b[:,2]*np.std(b[:,2])+a[1,2]

In [44]: c
Out[44]:
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])

In [45]: bs = b*np.std(b,axis=0,keepdims=True)
    ...: c_out = (bs[:,None,:]+a).reshape(len(b),-1)

In [46]: c_out
Out[46]:
array([[0.63, 1.05, 0.93, 0.62, 0.75, 0.98],
       [0.62, 1.01, 0.78, 0.61, 0.72, 0.83],
       [0.65, 1.06, 0.63, 0.64, 0.77, 0.67],
       [0.56, 0.72, 0.89, 0.56, 0.43, 0.93]])


来源: stackexchange

问:
Query a single table with relationship database Flask-SQLAlchemy
I've got three tables: User, Role, Department

I want to query all the user with selected following filters:
Department.name , Role.name and User.degree

I can't find a solution to this problem, any suggestion would be great!

Here's my models simplified:

```<code>class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    degree = db.Column(db.String(20),default=None)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

class Department(db.Model):

    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')
</code>```

答:
```<code>session.query(User).filter(
User.department.has(name='some_name)).filter(
User.role.has(name='some_role')).filter(
User.degree == 'some_degree')
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I've got three tables: User, Role, Department

I want to query all the user with selected following filters:
Department.name , Role.name and User.degree

I can't find a solution to this problem, any suggestion would be great!

Here's my models simplified:

class User(UserMixin, db.Model):

    __tablename__ = "users"

    id = db.Column(db.Integer, primary_key=True)
    password_hash = db.Column(db.String(128))
    degree = db.Column(db.String(20),default=None)
    department_id = db.Column(db.Integer, db.ForeignKey('departments.id'))
    role_id = db.Column(db.Integer, db.ForeignKey('roles.id'))

class Department(db.Model):

    __tablename__ = "departments"

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    user = db.relationship('User', backref='department',
                                lazy='dynamic')

class Role(db.Model):

    __tablename__ = 'roles'

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(sqlalchemy.types.NVARCHAR(100), unique=True)
    users = db.relationship('User', backref='role',
                                lazy='dynamic')


问:
Feed intermediate value and evaluate subgraph in a tf.Estimator
I am training a variational autoencoder with tf.Estimator. The model_fn contains an encoder and a decoder and takes images as input. In deployment or evaluation phase, I would like the model to take a randomly sampled latent code as input and only execute the decoder part.

Is a way I can disentangle encoder and decoder from my estimator?

答:
If you use a variable_scope for your decoder you can generate a random sample in your model_fn and then pass that through the decoder again by creating a variable_scope using the same name with reuse=True.

Pseudocode:

def encoder_fn(image, ...):
  ...
  return latent

def decoder_fn(latent, ...):
  ...
  return reconstruction

def model_fn(...):
  ...

  with tf.variable_scope('encoder'):
    predictions['latent'] = encoder_fn(features[...], ...)

  with tf.variable_scope('decoder'):
    predictions['reconstruction'] = decoder_fn(predictions['latent'], ...)

  with tf.variable_scope('sample'):
    random_latent = ...

  with tf.variable_scope('decoder', reuse=True):
    random_reconstruction = decoder_fn(random_latent, ...)

  ...
```

<hr>

<p>For advanced users another protip is if you add the latent code into the features dictionary it will show up under inputs in your exported savedmodel. Since you can just load the savedmodel into a session this means you can easily access and feed the latent codes directly. It's possible to feed more than just placeholders. A feature that really isn't advertised enough.</p>

<p>Example,</p>

<pre class="lang-py prettyprint-override"><code># Train side:
# 1. Create estimator
# 2. Train
# 3. Export savedmodel
def model_fn(...):
  ...

  with tf.variable_scope('encoder'):
    predictions['latent'] = encoder_fn(features[...], ...)
    features['latent'] = predictions['latent']

  with tf.variable_scope('decoder'):
    predictions['reconstruction'] = decoder_fn(predictions['latent'], ...)

  ...

# Client side,
# 1. Launch session
# 2. Load savedmodel

# We can reconstruct images
reconstructed_images = session.run(outputs['reconstruction'], feed_dict={inputs['images'] : my_images))

# And generate directly from latent code
random_images = session.run(outputs['reconstruction'], feed_dict={inputs['latents'] : np.random.normal(...)})

# All in the same graph!
</code>```

Body:
If you use a variable_scope for your decoder you can generate a random sample in your model_fn and then pass that through the decoder again by creating a variable_scope using the same name with reuse=True.

Pseudocode:

def encoder_fn(image, ...):
  ...
  return latent

def decoder_fn(latent, ...):
  ...
  return reconstruction

def model_fn(...):
  ...

  with tf.variable_scope('encoder'):
    predictions['latent'] = encoder_fn(features[...], ...)

  with tf.variable_scope('decoder'):
    predictions['reconstruction'] = decoder_fn(predictions['latent'], ...)

  with tf.variable_scope('sample'):
    random_latent = ...

  with tf.variable_scope('decoder', reuse=True):
    random_reconstruction = decoder_fn(random_latent, ...)

  ...

For advanced users another protip is if you add the latent code into the features dictionary it will show up under inputs in your exported savedmodel. Since you can just load the savedmodel into a session this means you can easily access and feed the latent codes directly. It's possible to feed more than just placeholders. A feature that really isn't advertised enough.

Example,

# Train side:
# 1. Create estimator
# 2. Train
# 3. Export savedmodel
def model_fn(...):
  ...

  with tf.variable_scope('encoder'):
    predictions['latent'] = encoder_fn(features[...], ...)
    features['latent'] = predictions['latent']

  with tf.variable_scope('decoder'):
    predictions['reconstruction'] = decoder_fn(predictions['latent'], ...)

  ...

# Client side,
# 1. Launch session
# 2. Load savedmodel

# We can reconstruct images
reconstructed_images = session.run(outputs['reconstruction'], feed_dict={inputs['images'] : my_images))

# And generate directly from latent code
random_images = session.run(outputs['reconstruction'], feed_dict={inputs['latents'] : np.random.normal(...)})

# All in the same graph!


问:
How to make sure that the character length/set length in a field is set to a particular number when using php?
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

```<code><label>Line Number</label>
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />
</code>```

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}
```

答:
I would suggest using html pattern to make it lighter

```<code><input type="text" name="Line"  pattern="[0-9]{3}" class="form-control" placeholder="Enter Line Number" value="<?php echo $Line; ?>"/>
</code>```

Body:
I have a form field which requires only numbers to be filled and the user should enter 8 digits in order to submit the form. What is the command that I need to use when writing my php/html code?

Tried using max but that also means I can enter 0 and still submit the form. Any thoughts on how to set a length so that you are forced to enter those number digits?

Line Number
 <input type="number" name="Line" class="form-control" max="999" placeholder="Enter Line Number" value="<?php echo $Line; ?>" />

I expect the answer to have 3 digits entered. Nothing less and nothing more. So can be 000 to 999. So even if you want to say 0 you need to enter 000 to submit the form.

if(empty($_POST["Line"])) {
    $error .= '
Please Enter Line Number
';
} else {
    $Line = clean_text($_POST["Line"]);
}

Body:
I would suggest using html pattern to make it lighter

<input type="text" name="Line"  pattern="[0-9]{3}" class="form-control" placeholder="Enter Line Number" value="<?php echo $Line; ?>"/>


问:
Django Rest Framework: Use DELETE on GenericAPIView without implementing Retrieve
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

```<code>class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')
</code>```

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

```<code>from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)
</code>```

Results in:

```<code>Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.
</code>```

答:
Wild guess here but did you use a SimpleRouter or a DefaultRouter to build your urlpatterns?

If so, that's your problem. The router uses a viewset and expects to have all methods implemented. More info here

What you can do is just add your url to urlpatterns like you would normally do on django using the .as_view() method.

Body:
I'm using Django Rest Framework and want to be able to delete a Content instance via DELETE to /api/content/<int:pk>/. I don't want to implement any method to respond to GET requests.

When I include a .retrieve() method as follows, the DELETE request works:

class ContentViewSet(GenericViewSet):
    def get_queryset(self):
        return Content.objects.filter(user=self.request.user)

    def retrieve(self, request, pk=None):
        pass    #this works, but I don't want .retrieve() at all

    def delete(self, request, pk=None):
        content = self.get_object()
        #look up some info info here
        content.delete()
        return Response('return some info')

If I replace .retrieve() with RetrieveModelMixin it also works. However, if I remove both of these, which is what want to do, I get the following error.

django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.

I haven't tested, but I assume the same thing would happen with PUT and PATCH.

My questions are:

How can I allow DELETE without implementing a .retrieve() method, and

Why can't DRF create the urlconf without .retrieve() implemented?

UPDATE: Failing test and complete error traceback caused by removing .retrieve() method

from rest_framework.test import APITestCase, APIClient
from myapp.models import Content

class ContentTestCase(APITestCase):
    def setUp(self):
        self.content = Content.objects.create(title='New content')
        self.client = APIClient()

    def test_DELETE_content(self):
        url = reverse('content-detail', kwargs={'pk':self.content.pk})
        response = self.client.delete(url)
        self.assertEqual(response.status_code, 200)

Results in:

Traceback (most recent call last):
  File "myproject/myapp/tests.py", line 548, in test_DELETE_content
    url = reverse('content-detail', kwargs={'pk':self.content})
  File "python3.6/site-packages/rest_framework/reverse.py", line 50, in reverse
    url = _reverse(viewname, args, kwargs, request, format, **extra)
  File "python3.6/site-packages/rest_framework/reverse.py", line 63, in _reverse
    url = django_reverse(viewname, args=args, kwargs=kwargs, **extra)
  File "python3.6/site-packages/django/urls/base.py", line 90, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "python3.6/site-packages/django/urls/resolvers.py", line 636, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'content-detail' not found. 'content-detail' is not a valid view function or pattern name.


问:
Programmatically change sorting order in Perl
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}
```

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

答:
A generic solution is to use different compare functions.

```<code>my %sorters = (
   by_size_asc  => sub { $data->{$a}{size} <=> $data->{$b}{size} },
   by_size_desc => sub { $data->{$b}{size} <=> $data->{$a}{size} },
   # ...
);

@ARGV
   or die("usage\n");

my $sorter = $sorters{$ARGV[0]}
   or die("Invalid sort function \"$ARGV[0]\".\n");

my @sorted_keys = sort $sorter keys(%$data);
</code>```

You could also use different sort functions, such as when using the great Sort::Key module.

```<code>use Sort::Key qw( ikeysort rikeysort );

my %sorters = (
   by_size_asc  => sub { ikeysort  { $data->{$_}{size} } @_ },
   by_size_desc => sub { rikeysort { $data->{$_}{size} } @_ },
   # ...
);

@ARGV
   or die("usage\n");

my $sorter = $sorters{$ARGV[0]}
   or die("Invalid sort function \"$ARGV[0]\".\n");

my @sorted_keys = $sorter->( keys(%$data) );
</code>```

Body:
I'd like to give the user the possibility to change the sorting order (asc / desc) in a data structure. As far as I know, this is done changing the order of $a and $bin the code, but I'd like to programmatically change this to avoid redundant code.

I made a working example:

use 5.018;
use warnings;

# Supply any argument to change sorting order
my $sorting_direction = $ARGV[0];

my $data = {
          'item1' => {
                         'min'  => 4,
                         'size' => 825,
                         'max'  => 256,
                       },
          'item2' => {
                         'min'  => 4,
                         'size' => 130,
                         'max'  => 65,
                       },
        };

if (defined $sorting_direction) {
    foreach my $item (sort { $$data{$a}{'size'} <=> $$data{$b}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
} else {
    foreach my $item (sort { $$data{$b}{'size'} <=> $$data{$a}{'size'} } keys %{$data} ) {
        say "$item\t", $$data{$item}{'size'};
    }
}

Giving any parameter will change the sorting_direction. Can I do this without the if conditional?

Body:
A generic solution is to use different compare functions.

my %sorters = (
   by_size_asc  => sub { $data->{$a}{size} <=> $data->{$b}{size} },
   by_size_desc => sub { $data->{$b}{size} <=> $data->{$a}{size} },
   # ...
);

@ARGV
   or die("usage\n");

my $sorter = $sorters{$ARGV[0]}
   or die("Invalid sort function \"$ARGV[0]\".\n");

my @sorted_keys = sort $sorter keys(%$data);

You could also use different sort functions, such as when using the great Sort::Key module.

use Sort::Key qw( ikeysort rikeysort );

my %sorters = (
   by_size_asc  => sub { ikeysort  { $data->{$_}{size} } @_ },
   by_size_desc => sub { rikeysort { $data->{$_}{size} } @_ },
   # ...
);

@ARGV
   or die("usage\n");

my $sorter = $sorters{$ARGV[0]}
   or die("Invalid sort function \"$ARGV[0]\".\n");

my @sorted_keys = $sorter->( keys(%$data) );


问:
Wordpress: Woocommerce without e-commerce for affiliate site
I'm building an affiliate site and obviously for every product I use page not post. But pages don't have categories or tags and even if we add them to pages, our pages won't appear on categories' pages and in widget areas of front page.

Woocommerce functionality is perfect but it looks a little bit weird to use it for an affiliate site, not a store. Is it okay to delete e-commerce features (price, add to card and stuff like that) and use the rest of Woocommerce?

答:
Woocommerce is pretty good for e-commerce sites. As you creating affiliate site for that you can hide some functionality of Woocommerce. As you mention you want to hide (price, add to card and stuff like that). You have to use some actions to remove those functionality. Copy following code and place it in your active theme's function.php file.

Note: If you have child theme then you must have to add this code in child theme's function.php file.

```<code>add_action('after_setup_theme','activate_filter') ;
function activate_filter(){
    add_filter('woocommerce_get_price_html', 'hide_price_cartBtn');
}

function hide_price_cartBtn(){
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
}
</code>```

comment if you like to remove more things as you mention stuff like that

Body:
Woocommerce is pretty good for e-commerce sites. As you creating affiliate site for that you can hide some functionality of Woocommerce. As you mention you want to hide (price, add to card and stuff like that). You have to use some actions to remove those functionality. Copy following code and place it in your active theme's function.php file.

Note: If you have child theme then you must have to add this code in child theme's function.php file.

add_action('after_setup_theme','activate_filter') ;
function activate_filter(){
    add_filter('woocommerce_get_price_html', 'hide_price_cartBtn');
}

function hide_price_cartBtn(){
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 );
    remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 );
}

comment if you like to remove more things as you mention stuff like that


问:
How or which Payment system do I need to use for Subscription services which are mentioned as below , Stripe Or Google's In-App Billing?
I'm currently very much confused about with which subscription service to use between any Third-party or Google's In-App billing system.

Let me explain first , I have an app which is providing service to Landlord for Posting their vacant Properties where we are providing free trial 60 Days for full app features & after trial expires I would like to add Subscription Plans as below:

Silver: Less than 50 units (monthly or yearly)

Gold: Less than 51 - 100 units (monthly or yearly)

Platinum 100 and up units (monthly or yearly)

Now I'm exploring options to include to implement this subscription features & found that Stripe would be a good option for me but soon I find out about in-app purchases guidelines where they mentioned that In-app purchases must use Google Play’s payment system & also mentioned , examples of products not currently supported by Google Play In-app Billing:

So , basically there are two questions from my side :

Can I use other payment system or should I need to use Google's Play Billing system ?

For Google's Play system , How can I divide or how many subscriptions items will be there for above subscriptions plans?

Any help would be appreciated!

答:
You can use both services Stripe and Google IAP(In App Purchases) or just 1 of them.

I suggest that you go with Google IAP since you do not have BE(BackEnd) and as I understand would be hard for you to maintain card numbers and everything.

Google IAP provides an SDK so that you can manage subscriptions on the Play Developers Console yourself. It also provides sandbox environment so that you can test it but also Stripe does that.

Here are some references:

https://developer.android.com/google/play/billing/billing_subscriptions
https://developer.android.com/google/play/billing/billing_overview.html

but I guess you have gone through them already. In the company that I previously worked on we were developing a project with pretty much the plans you described above and we used Google IAP and Apple IAP(for iOS/tvOS) without any problems. Furthermore we were able to query Google or Apple for previous subscriptions and let customers actually renew them instead of buying new ones.

As you mentioned the leasers/landlords will not be able to pay electronic bills with Google IAP but you can integrate Paypal/Stripe/BrainTree/WePay or any other alternatives for that.

Having mentioned that I would like to answer your questions now:

1) Yes you can use Stripe instead of Google IAP
2) You can divide subscriptions and you can manage them in your Google Developers Console at https://play.google.com/apps/publish/. However that can happen after you uploaded an .apk in console with in-app-billing dependencies and also permissions.

Hope it helps!!!


问:
How to convert list of list to JavaScript array
I am retrieving  from Sql-server database list of bank account in Python

```<code>Alllist=select_from_db_service(sql,[1],organization)
   if len(Alllist)>0:
        for row in Alllist:
           info_list.append((list(row)))
</code>```

then i am rendering it to an HTML page:
   return render(request,'app/reporting.html',

```<code>{'info_list':info_list,'start_date':start_date,'end_date':end_date})
</code>```

in the HTML page i have two drop list inputs Company and Account_id

```<code><input  type="text" list='List_of_Companies' data-search-in="Company" id="Input1" name="Companyname"  placeholder="Choose a Company"  value="{{ Company}}" >

<input  type="text" list='List_of_Accounts' data-search-in="Account" id="Input2" name="Accountname"  placeholder="Choose an Account ID" value="{{ Account_Id}}" hidden>
        <br>  <br>
</code>```

Both of them greeting the data from info_list return from Python using HTML Datalist:

```<code>    <datalist id="List_of_Companies">
 <select id="filenamelist" size="5"  class="select">
     {% for Company in  info_list %}
     <option value="{{ Company.3 }}">{{  Company.3 }}</option>
     {% endfor %}
     </select>
 </datalist>

   <datalist id="List_of_Accounts">
 <select id="filenamelist" size="5"  class="select">
     {% for Company in  info_list %}
     <option value="{{ Company.0 }}" data-value="{{  Company.3 }}" > {{  Company.3 }}</option>
     {% endfor %}
     </select>
 </datalist>
</code>```

Now pending on the values i get from the Company input i want to present only relevant inputs in the account id input which i am able to do and to show an HTML DataTalbe with only the relevant entries in info_list base on the inputs the user choose on the Company.

I tried the following,In the HTML page in Form tag:

```<code><input  type="text" id="DataTableInput" value="{{ info_list}}" hidden />
</code>```

In JavaScript i tried:

```<code>var dataSet = document.getElementById("DataTableInput").value;
console.log('DataSet' + dataSet)
</code>```

The output looks like :

```<code>DataSet[['39 XXX, 'EUR', 'CS', Company_name', 4, '01-jan-2019'], ['12 XXX',, 'USD, 'CS', 'Company_name2', 5, '01-jan-2019'],
['34 XXX', 'USD', 'CS', Company_name2', 5, '01-jan-2019'],…..]
</code>```

Now i want to iterate over this array and filter only the ones the have the right company name from the input ,but i cant accesses the elements,
thanks in advance,
Nir

答:
Why can't you access the element ? if console.log(dataSet[2]) give you the company name you should be able to do something like this :

function filterByCompanyName(array, name) {
  //assuming index 3 is always the company name of course
  return array.filter(item => item[3] == name);
}

let givenArray = [['39 XXX', 'EUR', 'CS', 'Company_name', 4, '01-jan-2019'], ['12 XXX', 'USD', 'CS', 'Company_name2', 5, '01-jan-2019'],
['34 XXX', 'USD', 'CS', 'Company_name2', 5, '01-jan-2019']];

console.log(filterByCompanyName(givenArray, 'Company_name2'));```

Body:
I am retrieving  from Sql-server database list of bank account in Python

Alllist=select_from_db_service(sql,[1],organization)
   if len(Alllist)>0:
        for row in Alllist:
           info_list.append((list(row)))

then i am rendering it to an HTML page:
   return render(request,'app/reporting.html',

{'info_list':info_list,'start_date':start_date,'end_date':end_date})

in the HTML page i have two drop list inputs Company and Account_id

<input  type="text" list='List_of_Companies' data-search-in="Company" id="Input1" name="Companyname"  placeholder="Choose a Company"  value="{{ Company}}" >

<input  type="text" list='List_of_Accounts' data-search-in="Account" id="Input2" name="Accountname"  placeholder="Choose an Account ID" value="{{ Account_Id}}" hidden>

Both of them greeting the data from info_list return from Python using HTML Datalist:

    <datalist id="List_of_Companies">
 <select id="filenamelist" size="5"  class="select">
     {% for Company in  info_list %}
     <option value="{{ Company.3 }}">{{  Company.3 }}</option>
     {% endfor %}
     </select>
 </datalist>

   <datalist id="List_of_Accounts">
 <select id="filenamelist" size="5"  class="select">
     {% for Company in  info_list %}
     <option value="{{ Company.0 }}" data-value="{{  Company.3 }}" > {{  Company.3 }}</option>
     {% endfor %}
     </select>
 </datalist>

Now pending on the values i get from the Company input i want to present only relevant inputs in the account id input which i am able to do and to show an HTML DataTalbe with only the relevant entries in info_list base on the inputs the user choose on the Company.

I tried the following,In the HTML page in Form tag:

<input  type="text" id="DataTableInput" value="{{ info_list}}" hidden />

In JavaScript i tried:

var dataSet = document.getElementById("DataTableInput").value;
console.log('DataSet' + dataSet)

The output looks like :

DataSet[['39 XXX, 'EUR', 'CS', Company_name', 4, '01-jan-2019'], ['12 XXX',, 'USD, 'CS', 'Company_name2', 5, '01-jan-2019'],
['34 XXX', 'USD', 'CS', Company_name2', 5, '01-jan-2019'],…..]

Now i want to iterate over this array and filter only the ones the have the right company name from the input ,but i cant accesses the elements,
thanks in advance,
Nir


问:
Convert curl command into RestTemplate
I have the following curl expression:

```<code>curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi
</code>```

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

```<code>HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);
</code>```

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?

答:
```<code>  // org.apache.commons.collections.map.HashedMap
  HashedMap requestBody = new HashedMap();
      requestBody.put("api_key", "API_Key");
      requestBody.put("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
       String jsonBody = new ObjectMapper().writeValueAsString(requestBody);
       HttpEntity<String> entity = new HttpEntity<>(jsonBody, headers);

        ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", entity, String.class);
</code>```

Title: Convert curl command into RestTemplate

Body:
I have the following curl expression:

curl --data 'api_key=API_Key' --data-urlencode 'event=[{"user_id":"12345", "event_type":"buy_song"}]' https://someapi

which should be converted into RestTemplate.postForEntity call. I do conversion this way:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
params.add("api_key", "API_Key");
params.add("event", URLEncoder.encode(objectMapper.writeValueAsString(Collections.singletonList(e)), "UTF-8"));

// send
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> response = restTemplate.postForEntity("https://someapi", request, String.class);

Server returns 400 Bad request

I confirm that Jackson's objectmapper serializes the object correctly objectMapper.writeValueAsString(Collections.singletonList(e))

I suspect that I cannot correctly handle the mix of --data and --data-urlencode from example curl in RestTemplate.

Could you please suggest what am I doing wrong?


问:
Mustache how to access specific element of array in arraylist
I have an arraylist "Numlist" with 10 Objects ,

in each Object there's an String[10] array "Num".

How can I access and show a specific string (for ex: Num[8]) ?

So it's a .mustache file , with html and javascripts.
I have an arraylist "Numlist" with 10 Objects ,
Each Object contains a String "name" , and a String[10] "Num"

I can easily access and show "name" use {{name}} ,
But I can not use {{Num.0}} which method I found online ,
to access and show the string in "Num[0]" ,

```<code>{{#Numlist}}
          <div class="data-table">
            <table>
              <tbody>
                <tr>
                    <td >{{name}}</td>
                    <td >{{Num.0}}</td>
                </tr>
              </tbody>
            </table>
          </div>
{{/Numlist}}
</code>```

I expect the output should be a table like

[ name ][String in Num[0]]

But I only got

[ name ][ ]

It seems {{Num.0}} does not work at all.

Is there a another way to access specific element in array ,
or just i use {{num.0}} this method wrong way?

答:
Array elements are accessed with bracket notation - an error is thrown if you use dot notation:

const arr = [1, 2, 3];
console.log(arr..2);```
</div>
</div>
</p>

<p>Use <code>[0]</code>:</p>

```{{Num[0]}}
```

Body:
I have an arraylist "Numlist" with 10 Objects ,

in each Object there's an String[10] array "Num".

How can I access and show a specific string (for ex: Num[8]) ?

So it's a .mustache file , with html and javascripts.
I have an arraylist "Numlist" with 10 Objects ,
Each Object contains a String "name" , and a String[10] "Num"

I can easily access and show "name" use {{name}} ,
But I can not use {{Num.0}} which method I found online ,
to access and show the string in "Num[0]" ,

{{#Numlist}}

                    {{name}}
                    {{Num.0}}

{{/Numlist}}

I expect the output should be a table like

[ name ][String in Num[0]]

But I only got

[ name ][ ]

It seems {{Num.0}} does not work at all.

Is there a another way to access specific element in array ,
or just i use {{num.0}} this method wrong way?

Body:
Array elements are accessed with bracket notation - an error is thrown if you use dot notation:

const arr = [1, 2, 3];
console.log(arr..2);

Use [0]:

{{Num[0]}}


问:
How can I turn a UNIX timestamp into a Google Sheets date value?
I'm using Google Apps Script to retrieve some data through an API. The date that is given to me is a standard ISO 8601 string, and I need to convert that to a date number that will be understood by Google Sheets when I display it (i.e. as the Google Sheets / Excel standard date value)

Currently I'm using a workaround which is passing a string in my cells then converting it through the DATEVALUE() function but it is not optimal, since I cant use that function natively in my script (from my research on the topic).

I want to create a function directly in Google Apps script that converts the Javascript ol' Date() object into a readable value for my spreadsheet.

I've made a few attempts by converting the seconds since 1970 to the number of days since 1900 but I always have a two-hour gap that I can't explain. I suspect it has to do with the fact that I am in UTC+2, but can't really solve it, and adding two hours sounds like a bad fix.

The baseline of what I've gotten to so far is this :

```<code>function toDateNum(string) {

  //Parsing to Unix Timestamp
  date = new Date(string).getTime() / 1000

  //Here I need convert to GSheets date value, add the number of days between 1900-01-01 and 1970-01-01

  return date ;

}
</code>```

I'm looking either for an arithmetic solve for this (converting and adding dates) or for a function integrated in the Google Sheets app that would allow me to work with this. Any suggestions ?

Thanks a lot !

EDIT (with additional clarification)

One of my issues is that the toISOString format returned is not supported by google sheets directly. It will only be read as a string, not as a date value. Currently, I'm working around this by sending the toISOString value in the cells and reformat using DateValue() directly in the table. I'm trying to do that natively in the script.

To the best of my knowledge, the date value supported by Google Sheets (and Excel) is the number of days since 1900-01-01. A simple arithmetic solution should be found (computing a unix timestamp from seconds then to days then add the difference between 1900-01-01 to 1970-01-01) but, then again, I get my two-hour gap that messes everything up.

答:
You can achieve this by using new Date(string*1000), then passing the result to  Utilities.formatDate(). Multiplying the Unix timestamp by 1000 means your argument is in milliseconds, rather than seconds. This Stackoverflow Question has a lot of good info for formatting dates using js.

```<code>function toDateNum(string) {
  //convert unix timestamp to milliseconds rather than seconds
  var d = new Date(string*1000);

  //get timezone of spreadsheet
  var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

  //format date to readable format
  var date = Utilities.formatDate(d, tz, 'dd-MM-yyyy hh:mm:ss a');

  return date;
}
</code>```

This script will use the timezone setting of your spreadsheet, but you can change this to use the time zone of the script or enter one yourself, examples below if you'd like to use these instead:

```<code>//use spreadsheet timezone setting
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

//use script timezone setting
var tz = Session.getScriptTimeZone();

//enter your own time zone
var tz = 'GMT+0';
</code>```

Body:
I'm using Google Apps Script to retrieve some data through an API. The date that is given to me is a standard ISO 8601 string, and I need to convert that to a date number that will be understood by Google Sheets when I display it (i.e. as the Google Sheets / Excel standard date value)

Currently I'm using a workaround which is passing a string in my cells then converting it through the DATEVALUE() function but it is not optimal, since I cant use that function natively in my script (from my research on the topic).

I want to create a function directly in Google Apps script that converts the Javascript ol' Date() object into a readable value for my spreadsheet.

I've made a few attempts by converting the seconds since 1970 to the number of days since 1900 but I always have a two-hour gap that I can't explain. I suspect it has to do with the fact that I am in UTC+2, but can't really solve it, and adding two hours sounds like a bad fix.

The baseline of what I've gotten to so far is this :

function toDateNum(string) {

  //Parsing to Unix Timestamp
  date = new Date(string).getTime() / 1000

  //Here I need convert to GSheets date value, add the number of days between 1900-01-01 and 1970-01-01

  return date ;

}

I'm looking either for an arithmetic solve for this (converting and adding dates) or for a function integrated in the Google Sheets app that would allow me to work with this. Any suggestions ?

Thanks a lot !

EDIT (with additional clarification)

One of my issues is that the toISOString format returned is not supported by google sheets directly. It will only be read as a string, not as a date value. Currently, I'm working around this by sending the toISOString value in the cells and reformat using DateValue() directly in the table. I'm trying to do that natively in the script.

To the best of my knowledge, the date value supported by Google Sheets (and Excel) is the number of days since 1900-01-01. A simple arithmetic solution should be found (computing a unix timestamp from seconds then to days then add the difference between 1900-01-01 to 1970-01-01) but, then again, I get my two-hour gap that messes everything up.

Body:
You can achieve this by using new Date(string*1000), then passing the result to  Utilities.formatDate(). Multiplying the Unix timestamp by 1000 means your argument is in milliseconds, rather than seconds. This Stackoverflow Question has a lot of good info for formatting dates using js.

function toDateNum(string) {
  //convert unix timestamp to milliseconds rather than seconds
  var d = new Date(string*1000);

  //get timezone of spreadsheet
  var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

  //format date to readable format
  var date = Utilities.formatDate(d, tz, 'dd-MM-yyyy hh:mm:ss a');

  return date;
}

This script will use the timezone setting of your spreadsheet, but you can change this to use the time zone of the script or enter one yourself, examples below if you'd like to use these instead:

//use spreadsheet timezone setting
var tz = SpreadsheetApp.getActiveSpreadsheet().getSpreadsheetTimeZone();

//use script timezone setting
var tz = Session.getScriptTimeZone();

//enter your own time zone
var tz = 'GMT+0';


问:
What are the pros and cons of using webworks versus J2ME and vice versa in blackberry development?
I have written some basic applications using J2Me and felt that getting things done in terms of UI/UX were a night mare especially with blackberry OS 5. I then started playing around with Webworks and found it to be better and faster however i keep getting told that it is better to stick with J2ME. Which one is a better choice? Is one limited in features than the other? What will RIM support for the long term future?</p>

答:
From experience, Webworks seems to be easier to develop in terms of UI. But in terms in functionality, there isn't much. I don't know if they've changed this, but before, if there wasn't specific functionality in Webworks, you could create your own by porting the Java code over and creating your own extension.

I would say that using J2ME, would be the better choice if you need more integration with device functionality, rather than UI.

ContentLicense: CC BY-SA 3.0


问:
Bin date values by month from imported CSV in KDB?
I have a .csv file with the following example schema:

```<code>item, date
10,2015.01.01
2,2015.02.01
3,2015.01.15
4,2015.03.01
5,2015.03.01
20,2015.03.01
11,2015.02.01
23,2015.01.21
13,2015.01.31
</code>```

I'm looking to bin the items into year/month/days i.e. 2015-01, 2015-02, 2015-03.
I tried the following line by it doesn't seem to work:

```<code>select item by 1 xbar date.month from table
</code>```

Also tried updating with a new column:

```<code>update column: `mm$date from table
</code>```

It seems that importing the .csv file casts the fields to a symbols. Do i need to explicitly cast this back to a date type first?

How can i print out a table with values binned by a certain time/date criteria?

答:
To apply types when reading in a csv, use 0: as follows:

```<code>q)("ID";enlist ",") 0: `:test.csv
item date
---------------
10   2015.01.01
2    2015.02.01
3    2015.01.15
4    2015.03.01
5    2015.03.01
20   2015.03.01
11   2015.02.01
23   2015.01.21
13   2015.01.31
</code>```

The left argument is a two item list, the "ID" specifies the type of each column (integer, date) and the "," specifies the separator (and the enlist indicates column headers are present).

Then the data can be bucketed by month:

```<code>q)select item by 1 xbar `month$date from ("ID";enlist ",") 0: `:test.csv
date   | item
-------| -----------
2015.01| 10 3 23 13i
2015.02| 2 11i
2015.03| 4 5 20i
</code>```

Alternatively, if you want to have buckets of custom size, you can use bin with a list of dates as bucket dividers. This will give an integer value indicating which bin each date falls, then you can use a dictionary to name the buckets:

```<code>q)b:2015.01.01 2015.02.01 2015.03.01
q)d:(0 1 2)!`month$b
q)select item by d b bin date from ("ID";enlist ",") 0: `:test.csv
date   | item
-------| -----------
2015.01| 10 3 23 13i
2015.02| 2 11i
2015.03| 4 5 20i
</code>```

Note: bin will assign -1 for values below the first divider. Using binr will start counting at 0:

```<code>q)b bin 2014.12.31
-1
q)b binr 2014.12.31
0
</code>```

Body:
I have a .csv file with the following example schema:

item, date
10,2015.01.01
2,2015.02.01
3,2015.01.15
4,2015.03.01
5,2015.03.01
20,2015.03.01
11,2015.02.01
23,2015.01.21
13,2015.01.31

I'm looking to bin the items into year/month/days i.e. 2015-01, 2015-02, 2015-03.
I tried the following line by it doesn't seem to work:

select item by 1 xbar date.month from table

Also tried updating with a new column:

update column: `mm$date from table

It seems that importing the .csv file casts the fields to a symbols. Do i need to explicitly cast this back to a date type first?

How can i print out a table with values binned by a certain time/date criteria?

Body:
To apply types when reading in a csv, use 0: as follows:

q)("ID";enlist ",") 0: `:test.csv
item date
---------------
10   2015.01.01
2    2015.02.01
3    2015.01.15
4    2015.03.01
5    2015.03.01
20   2015.03.01
11   2015.02.01
23   2015.01.21
13   2015.01.31

The left argument is a two item list, the "ID" specifies the type of each column (integer, date) and the "," specifies the separator (and the enlist indicates column headers are present).

Then the data can be bucketed by month:

q)select item by 1 xbar `month$date from ("ID";enlist ",") 0: `:test.csv
date   | item
-------| -----------
2015.01| 10 3 23 13i
2015.02| 2 11i
2015.03| 4 5 20i

Alternatively, if you want to have buckets of custom size, you can use bin with a list of dates as bucket dividers. This will give an integer value indicating which bin each date falls, then you can use a dictionary to name the buckets:

q)b:2015.01.01 2015.02.01 2015.03.01
q)d:(0 1 2)!`month$b
q)select item by d b bin date from ("ID";enlist ",") 0: `:test.csv
date   | item
-------| -----------
2015.01| 10 3 23 13i
2015.02| 2 11i
2015.03| 4 5 20i

Note: bin will assign -1 for values below the first divider. Using binr will start counting at 0:

q)b bin 2014.12.31
-1
q)b binr 2014.12.31
0


问:
CSS border-radius
```<code><style>
  div {border-radius:5px;background:#cccccc;}
  span {display:block;}
</style>

<div>
    <span>First line</span>
    <span>Second line</span>
</div>
</code>```

I want each span to fit inside the div with rounded corners, but they go in front of the div and obscure the rounded corners. If I put rounded corners on each span then you can see a faint outline of each span, even if they have the same background-color as the div.

答:
```<code><style>
 .demo-border-radius {
    width: 100px;
    height: 100px;
    border-radius: 30px;
    border: 2px solid #000;
    overflow: hidden;
  }
</style>
<div class="demo-border-radius">border radius div</div>
</code>```

Title: CSS border-radius

Body:
    First line
    Second line

I want each span to fit inside the div with rounded corners, but they go in front of the div and obscure the rounded corners. If I put rounded corners on each span then you can see a faint outline of each span, even if they have the same background-color as the div.


问:
How to handle NULL values when sorting?
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

```<code>if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql
</code>```

答:
Alternate way on your implementation use union all between filtered data

```<code>.... from table_name where column is not null order by column <desc/asc>
UNION ALL
.... from table_name where column is null
</code>```

Title: How to handle NULL values when sorting?

Body:
I am looking for a way to return NULL values last when sorting either DESC or ASC in SQL (the envelopping code is in Python) and maybe be able to retun the NULL values first depending on some config

I tried replacing the NULL values with numeric values but in the long run I found that it is not a suitable solution since in some cases I need to traceback the origin of the NULL, why I have it and putting a numeric value could influence the work of someone else and give inaccurate results.

if request.sort:
    sql += " order by " + ', '.join([sort.split(':')[0] + " " + sort.split(':')[1] for sort in request.sort])

return sql

Body:
Alternate way on your implementation use union all between filtered data

.... from table_name where column is not null order by column <desc/asc>
UNION ALL
.... from table_name where column is null


问:
How do i output contents of a map using operator <<
I'm trying to output the contents of my map but i'm not sure on how to go about it. i've got the following declarations for a map and a iterator set as private in my header file

```<code>typedef map<long, string> Student;
Student newstudent;
typedef Student::const_iterator studentItr;
studentItr itr;
</code>```

and i have the following declaration in my .cpp

```<code>map<long, string> classname::GetMap()
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
{
    cout << itr->first << " => " <<itr->second << '\n';
}

    return newstudent;
}
</code>```

and this is how i'm trying to pass this into my overloaded operator << function

```<code>ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.GetMap() << '\n';

    return os;
}
</code>```

Usually this would work for any other function but since its a map i get the following error:

no match for 'operator<<' (operand types are 'std::basic_ostream< char >' and 'std::map < long int, std::__cxx11::basic_string< char > > ')|

Could anybody point me in the right direction of what i'm doing wrong

EDIT: Thanks for posting your suggestions i appreciate the help, but i think something isnt right either with my complier or with how i've stated something.

Everytime i try using Student as a type it wont register as a type and i get an error about it.

E.g if i declare this statement

```<code>ostream & operator <<( ostream & os, const Student & R)
</code>```

OR

```<code>Student & classname::GetMap()
</code>```

i get the error:

'Student' does not name a type

This error ultimately is leading to nothing within my statements making any sense and i'm not sure how to fix that

答:
So you seem to have put the output code inside for GetMap function for some reason. Either you want a routine called GetMap which just gets a map, or you want a routine called PrintMap (for instance) which outputs the map. You have half and half. Here's one way to do it

```<code>void classname::PrintMap() const
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
    {
        cout << itr->first << " => " <<itr->second << '\n';
    }
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " ";
    R.printMap();
    os << '\n';
    return os;
}
</code>```

This could be improved, for instance you could pass the stream you want to output to, to the PrintMap function. Like this

```<code>void classname::PrintMap(ostream & os) const
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
    {
        os << itr->first << " => " <<itr->second << '\n';
    }
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " ";
    R.printMap(os);
    os << '\n';
    return os;
}
</code>```

FInally you could follow the common convention and rename PrintMap as operator<< and make it a friend function instead of a member function.

```<code>Student& classname::GetMap()
{
    return newstudent;
}

ostream & operator<<(ostream & os, const Student& s)
{
    for(itr = s.begin(); itr !=s.end(); itr++)
    {
        os << itr->first << " => " <<itr->second << '\n';
    }
    return os;
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.getMap() << '\n';
}
</code>```

Body:
I'm trying to output the contents of my map but i'm not sure on how to go about it. i've got the following declarations for a map and a iterator set as private in my header file

typedef map<long, string> Student;
Student newstudent;
typedef Student::const_iterator studentItr;
studentItr itr;

and i have the following declaration in my .cpp

map<long, string> classname::GetMap()
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
{
    cout << itr->first << " => " <<itr->second << '\n';
}

    return newstudent;
}

and this is how i'm trying to pass this into my overloaded operator << function

ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.GetMap() << '\n';

    return os;
}

Usually this would work for any other function but since its a map i get the following error:

no match for 'operator<<' (operand types are 'std::basic_ostream< char >' and 'std::map < long int, std::__cxx11::basic_string< char > > ')|

Could anybody point me in the right direction of what i'm doing wrong

EDIT: Thanks for posting your suggestions i appreciate the help, but i think something isnt right either with my complier or with how i've stated something.

Everytime i try using Student as a type it wont register as a type and i get an error about it.

E.g if i declare this statement

ostream & operator <<( ostream & os, const Student & R)

OR

Student & classname::GetMap()

i get the error:

'Student' does not name a type

This error ultimately is leading to nothing within my statements making any sense and i'm not sure how to fix that

Body:
So you seem to have put the output code inside for GetMap function for some reason. Either you want a routine called GetMap which just gets a map, or you want a routine called PrintMap (for instance) which outputs the map. You have half and half. Here's one way to do it

void classname::PrintMap() const
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
    {
        cout << itr->first << " => " <<itr->second << '\n';
    }
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " ";
    R.printMap();
    os << '\n';
    return os;
}

This could be improved, for instance you could pass the stream you want to output to, to the PrintMap function. Like this

void classname::PrintMap(ostream & os) const
{
    for(itr = newstudent.begin(); itr !=newstudent.end(); itr++)
    {
        os << itr->first << " => " <<itr->second << '\n';
    }
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " ";
    R.printMap(os);
    os << '\n';
    return os;
}

FInally you could follow the common convention and rename PrintMap as operator<< and make it a friend function instead of a member function.

Student& classname::GetMap()
{
    return newstudent;
}

ostream & operator<<(ostream & os, const Student& s)
{
    for(itr = s.begin(); itr !=s.end(); itr++)
    {
        os << itr->first << " => " <<itr->second << '\n';
    }
    return os;
}

ostream & operator <<( ostream & os, classname & R)
{
    os << " " << R.getMap() << '\n';
}


问:
Hide keyboard on scroll in Flutter
I would like to hide the keyboard on scrolling a SingleChildScrollView with a focused TextFormField.

I added a NotificationListener<ScrollNotification> on top of the SingleChildScrollView, and listen for the ScrollStartNotification. I then call FocusScope.of(context).requestFocus(FocusNode()) to hide the keyboard.

The problem occur when the TextFormField is at the bottom of the screen. When i click it, it gets focus, the keyboard appears and moves the SingleChildScrollView up, which again fires the ScrollStartNotification and hides the keyboard.

答:
Most of the answers with GestureDetector and onPanDown are good but it wasn't enough for me. After playing with it a bit I think I found a much better solution.

```<code>GestureDetector(
  onVerticalDragUpdate: (details) {
    if (details.primaryDelta > 20) {
      FocusScope.of(context).detach();
    }
  },
  child: Widget(),
);
</code>```

If you swipe up the delta is negative so this won't trigger the dismissal, same if you swipe really slowly. You can obviously adjust the delta to make it more or less responsive.
Also, detach() method looks a lot better that providing a new FocusScope.

Title: Hide keyboard on scroll in Flutter

Body:
Most of the answers with GestureDetector and onPanDown are good but it wasn't enough for me. After playing with it a bit I think I found a much better solution.

GestureDetector(
  onVerticalDragUpdate: (details) {
    if (details.primaryDelta > 20) {
      FocusScope.of(context).detach();
    }
  },
  child: Widget(),
);

If you swipe up the delta is negative so this won't trigger the dismissal, same if you swipe really slowly. You can obviously adjust the delta to make it more or less responsive.
Also, detach() method looks a lot better that providing a new FocusScope.


问:
QScopedArrayPointer guarding my data but it is still leaking
```<code>#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>

class MyData{
public:
  MyData() {
    qDebug() << "Construct a data";
  }

  ~MyData() {
    qDebug() << "Delete a data";
  }

private:
  float internal_data_;
};

class MyClass{
  QScopedArrayPointer<MyData> data_;
public:
  MyClass(){
    data_.reset(new MyData[10]);

    throw std::runtime_error("Shit happens");
  }
};

int main(int argc, char *argv[])
{
    MyClass a_class;

    return 1;
}
</code>```

Running this program will output:

```<code>Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
terminate called after throwing an instance of 'std::runtime_error'
  what():  Shit happens
The program has unexpectedly finished.
</code>```

Right before the runtime_error, the variable data_ has been fully created. Why is it that data_ destructor not called?

Also, how do I make sure memory does not leak in this case?

答:
I think the issue is that your exception is uncaught and is being handled by the terminate handler. Since there is no catch to handle the exception, there is no way for the compiler to know how much to "unroll". If you catch the exception, then destruction occurs. You can then of course re-throw it if you like, for example:

```<code>#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>

class MyData{
public:
  MyData() {
    qDebug() << "Construct a data";
  }

  ~MyData() {
    qDebug() << "Delete a data";
  }

private:
  float internal_data_;
};

class MyClass{
  QScopedArrayPointer<MyData> data_;
public:
  MyClass(){
    data_.reset(new MyData[10]);

    throw std::runtime_error("Shit happens");
  }
};

int main(int argc, char *argv[]) {
    try {
        MyClass a_class;
    } catch (const std::runtime_error &) {
        throw;
    }
}
</code>```

Outputs the following:

```<code>$ ./test2
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
terminate called after throwing an instance of 'std::runtime_error'
  what():  Shit happens
Aborted
</code>```

Body:
#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>

class MyData{
public:
  MyData() {
    qDebug() << "Construct a data";
  }

  ~MyData() {
    qDebug() << "Delete a data";
  }

private:
  float internal_data_;
};

class MyClass{
  QScopedArrayPointer<MyData> data_;
public:
  MyClass(){
    data_.reset(new MyData[10]);

    throw std::runtime_error("Shit happens");
  }
};

int main(int argc, char *argv[])
{
    MyClass a_class;

    return 1;
}

Running this program will output:

Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
terminate called after throwing an instance of 'std::runtime_error'
  what():  Shit happens
The program has unexpectedly finished.

Right before the runtime_error, the variable data_ has been fully created. Why is it that data_ destructor not called?

Also, how do I make sure memory does not leak in this case?

Body:
I think the issue is that your exception is uncaught and is being handled by the terminate handler. Since there is no catch to handle the exception, there is no way for the compiler to know how much to "unroll". If you catch the exception, then destruction occurs. You can then of course re-throw it if you like, for example:

#include <QScopedArrayPointer>
#include <QDebug>
#include <stdexcept>

class MyData{
public:
  MyData() {
    qDebug() << "Construct a data";
  }

  ~MyData() {
    qDebug() << "Delete a data";
  }

private:
  float internal_data_;
};

class MyClass{
  QScopedArrayPointer<MyData> data_;
public:
  MyClass(){
    data_.reset(new MyData[10]);

    throw std::runtime_error("Shit happens");
  }
};

int main(int argc, char *argv[]) {
    try {
        MyClass a_class;
    } catch (const std::runtime_error &) {
        throw;
    }
}

Outputs the following:

$ ./test2
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Construct a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
Delete a data
terminate called after throwing an instance of 'std::runtime_error'
  what():  Shit happens
Aborted


答:
You could make an operator << for your map type. (totally untested code)

```<code>ostream & operator <<( ostream & os, const Student & R) {
    for(studentIter itr = R.begin(); itr !=R.end(); itr++){
        os << itr->first << " => " <<itr->second << '\n';
    }
    return os;
}
</code>```

Edit:
Changed the names to match those in your question.

Title: How do i output contents of a map using operator <<

Body:
You could make an operator << for your map type. (totally untested code)

ostream & operator <<( ostream & os, const Student & R) {
    for(studentIter itr = R.begin(); itr !=R.end(); itr++){
        os << itr->first << " => " <<itr->second << '\n';
    }
    return os;
}

Edit:
Changed the names to match those in your question.


问:
Yellow Box Errors/Warnings after React Native Upgrade
I recently upgraded my project from React Native 0.15 to 0.20. I guess this was kind of a leap and I'm quite new to these Yellow Box Warnings. Right now I got 2 warnings as follows.

Warning One:

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  ItemViewPage.

Warning Two:

View #2359 of type RCTView has a shadow set but cannot calculate
  shadow efficiently. Consider setting a background color to fix this,
  or apply the shadow to a more specific component.

Figured out that Warning One was due to using const Radio = require('react-native-simple-radio-button'); instead of import Radio from 'react-native-simple-radio-button';. Once the change was done, Warning One was gone.

For the Warning Two, the page it sends it from has place where it uses shadows.

Styling Code:

```<code>container: {
    overflow: 'hidden',
    width: Dimensions.get('window').width,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.0)',
    shadowColor: '#000000',
    shadowOpacity: 1,
    shadowRadius: 20,
    shadowOffset: {width: 0, height: -5},
    justifyContent: 'center'
}
</code>```

Code:

```<code>renderItem: function (item) {
    var Dimensions = require('Dimensions');
    return (
        <View style={styles.mainContainer}>
            <TouchableHighlight underlayColor="rgba(0,0,0,0)" style={styles.buttonFill}
                                onPress={this.categoryPressed.bind(this, item.categoryId, item.name)}>
                <View style={styles.container}>
                    <KenBurnsImage tension={6} friction={50} imageWidth={Dimensions.get('window').width} imageHeight={Dimensions.get('window').height / 100 * 30} sourceUri={{uri: item.image}} placeholderSource={{uri: './images/placeholder.jpg'}}/>
                    <View>
                        <LinearGradient
                            colors={[processColor('rgba(255, 255, 255, 0.0)'), processColor('rgba(0,0,0,0)'), processColor('rgba(0,0,0,0.7)')]}
                            style={styles.linearGradient}>
                            <View style={styles.allContent}>
                                <View style={styles.imageRowContainer}>
                                    <View style={styles.nameContainer}>
                                        <Text style={styles.textMain}>{item.name}</Text>
                                    </View>
                                    {this._renderItemCountSection(item.itemsCount)}
                                    <View style={styles.continueContainer}>
                                        <Text style={styles.textArrow}></Text>
                                    </View>
                                </View>
                            </View>
                        </LinearGradient>
                    </View>
                </View>
            </TouchableHighlight>

        </View>
    );
}
</code>```

renderItem function is rendering items from the ListView.

As the code states, it already has the Background Color. So why is this warning coming? What is the fix? Thanks in advance.

答:
For warning two

In my case, I deleted shadowOpacity, added it to the shadow color and used RGBA value.

```<code>shadowColor: 'rgba(0,0,0, 0.1)'
</code>```

Body:
I recently upgraded my project from React Native 0.15 to 0.20. I guess this was kind of a leap and I'm quite new to these Yellow Box Warnings. Right now I got 2 warnings as follows.

Warning One:

Warning: React.createElement: type should not be null, undefined,
  boolean, or number. It should be a string (for DOM elements) or a
  ReactClass (for composite components). Check the render method of
  ItemViewPage.

Warning Two:

View #2359 of type RCTView has a shadow set but cannot calculate
  shadow efficiently. Consider setting a background color to fix this,
  or apply the shadow to a more specific component.

Figured out that Warning One was due to using const Radio = require('react-native-simple-radio-button'); instead of import Radio from 'react-native-simple-radio-button';. Once the change was done, Warning One was gone.

For the Warning Two, the page it sends it from has place where it uses shadows.

Styling Code:

container: {
    overflow: 'hidden',
    width: Dimensions.get('window').width,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: 'rgba(255, 255, 255, 0.0)',
    shadowColor: '#000000',
    shadowOpacity: 1,
    shadowRadius: 20,
    shadowOffset: {width: 0, height: -5},
    justifyContent: 'center'
}

Code:

renderItem: function (item) {
    var Dimensions = require('Dimensions');
    return (
        <View style={styles.mainContainer}>
            <TouchableHighlight underlayColor="rgba(0,0,0,0)" style={styles.buttonFill}
                                onPress={this.categoryPressed.bind(this, item.categoryId, item.name)}>
                <View style={styles.container}>
                    <KenBurnsImage tension={6} friction={50} imageWidth={Dimensions.get('window').width} imageHeight={Dimensions.get('window').height / 100 * 30} sourceUri={{uri: item.image}} placeholderSource={{uri: './images/placeholder.jpg'}}/>
                    <View>
                        <LinearGradient
                            colors={[processColor('rgba(255, 255, 255, 0.0)'), processColor('rgba(0,0,0,0)'), processColor('rgba(0,0,0,0.7)')]}
                            style={styles.linearGradient}>
                            <View style={styles.allContent}>
                                <View style={styles.imageRowContainer}>
                                    <View style={styles.nameContainer}>
                                        <Text style={styles.textMain}>{item.name}</Text>
                                    </View>
                                    {this._renderItemCountSection(item.itemsCount)}
                                    <View style={styles.continueContainer}>
                                        <Text style={styles.textArrow}></Text>
                                    </View>
                                </View>
                            </View>
                        </LinearGradient>
                    </View>
                </View>
            </TouchableHighlight>

        </View>
    );
}

renderItem function is rendering items from the ListView.

As the code states, it already has the Background Color. So why is this warning coming? What is the fix? Thanks in advance.

Body:
For warning two

In my case, I deleted shadowOpacity, added it to the shadow color and used RGBA value.

shadowColor: 'rgba(0,0,0, 0.1)'


问:
How do I set activity backstack on Android?
I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

```<code>   ActivityA --> ActivityB --> ActivityC --> ActivityD
</code>```

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

```<code> ActivityF --> ActivityD
 ActivityF finished
</code>```

Current activity:

```<code> ActivityD
</code>```

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

```<code> ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
 ActivityA --> ActivityB --> ActivityC /// click back button
 ActivityA --> ActivityB /// click back button
 ActivityA
</code>```

or

```<code> ActivityA --> ActivityF --> ActivityD /// click back button
 ActivityA --> ActivityF /// click back button
 ActivityA
</code>```

But I want to generate this scenario:

```<code> ActivityA
 --> ActivityB
 --> ActivityC
 --> ActivityD /// click back button
 ActivityC <-- /// click back button
 ActivityB <-- /// click back button
 ActivityA
</code>```

or

```<code> ActivityA
 --> ActivityF
 --> ActivityD /// click back button
 ActivityF <-- /// click back button
 ActivityA <--
</code>```

Update:

I found the solution here

答:
```<code>Intent i = new Intent(F.this, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
</code>```

or

```<code>Intent i = new Intent(F.this, A.class);
startActivity(i);
finish();
</code>```

Body:
I want to set the onBackPress button to start activities that started before orderly. If I don't finish activities that started before when I start another activity, I can show the activity that started before with finish() current activity. This is possible. Because I don't finish any activity. So finish() current activity will cause show activity that started before. But, RAM will be overload when I open 50 activities may be. So because of this problem I need to finish() activity that started before. On the other hand, I want to start the activity that started before orderly when clicking to the back button. For example

   ActivityA --> ActivityB --> ActivityC --> ActivityD

In this scenario, I finish ActivityA, ActivityB, ActivityC orderly. But I want to start ActivityC back press of the ActivityD and I want to start ActivityB on the back press of ActivityC.

Lastly, I have a complex path in the application. And, I navigate to the ActivityD and I finished the ActivityF when my current activity is ActivityF

 ActivityF --> ActivityD
 ActivityF finished

Current activity:

 ActivityD

In this scenario, I want to start the ActivityF not the ActivityC on back button of the ActivityD.

Normally:

 ActivityA --> ActivityB --> ActivityC --> ActivityD /// click back button
 ActivityA --> ActivityB --> ActivityC /// click back button
 ActivityA --> ActivityB /// click back button
 ActivityA

or

 ActivityA --> ActivityF --> ActivityD /// click back button
 ActivityA --> ActivityF /// click back button
 ActivityA

But I want to generate this scenario:

 ActivityA
 --> ActivityB
 --> ActivityC
 --> ActivityD /// click back button
 ActivityC <-- /// click back button
 ActivityB <-- /// click back button
 ActivityA

or

 ActivityA
 --> ActivityF
 --> ActivityD /// click back button
 ActivityF <-- /// click back button
 ActivityA <--

Update:

I found the solution here

Body:
Intent i = new Intent(F.this, A.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP |Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);

or

Intent i = new Intent(F.this, A.class);
startActivity(i);
finish();


问:
mat-nav-list with secondary buttons
How do we properly add a secondary buttons inside a mat-nav-list?

Here is my example:

```<code><mat-nav-list>
  <h3 matSubheader>This is the listview</h3>
    <a mat-list-item [routerLink]="['/detail']">
        <span matLine>Title</span>
        <button mat-icon-button (click)="onAdd()">
        <mat-icon>add</mat-icon>
    </button>
        <button mat-icon-button (click)="onRemove()">
        <mat-icon>delete</mat-icon>
    </button>
    </a>
</mat-nav-list>
</code>```

In this code I expected the onAdd() or onRemove() to execute ALONE, but the page navigates afterward.

Working DEMO

答:
Just to add another solution to the mix... (as another option for other devs). And this solution prevents the need to 'preventDefault' and 'stopImmediatePropagation'.

```<code><mat-list>
    <mat-list-item>
        <a matLine [routerLink]="['/detail']">
            <p matLine>Title</p>
        </a>
        <button mat-icon-button (click)="onAdd()">
            <mat-icon>add</mat-icon>
        </button>
        <button mat-icon-button (click)="onRemove()">
            <mat-icon>delete</mat-icon>
        </button>
    </mat-list-item>
</mat-list>
</code>```

Additionally (we can add multiple rows of text and icon as follows):

```<code><mat-list>
    <mat-list-item>
        <a matLine [routerLink]="['/detail']">
            <mat-icon mat-list-icon>accessibility</mat-icon>
            <p>
              <span>Text Row 1</span>
              <span>Text Row 2</span>
            </p>
        </a>
        <button mat-icon-button (click)="onAdd()">
            <mat-icon>add</mat-icon>
        </button>
        <button mat-icon-button (click)="onRemove()">
          <mat-icon>delete</mat-icon>
        </button>
    </mat-list-item>
</mat-list>
</code>```

And then the following css styles are to be applied:

```<code>.mat-list .mat-list-item a {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: black;
  text-decoration: none;
}

.mat-list .mat-list-item .mat-list-icon {
  float: left;
  margin-right: 0.5em;
}

.mat-list .mat-list-item p span
{
  display: block;
}
</code>```

The above css ensures that the icon is floated to the left with a right margin applied - and that the items are aligned centrally.

The span splits the paragraph rows.

You can also then apply styles to each individual span if required.

Title: mat-nav-list with secondary buttons

Body:
How do we properly add a secondary buttons inside a mat-nav-list?

Here is my example:

<mat-nav-list>

This is the listview

        Title
        <button mat-icon-button (click)="onAdd()">
        <mat-icon>add</mat-icon>
    </button>
        <button mat-icon-button (click)="onRemove()">
        <mat-icon>delete</mat-icon>
    </button>

</mat-nav-list>

In this code I expected the onAdd() or onRemove() to execute ALONE, but the page navigates afterward.

Working DEMO

Body:
Just to add another solution to the mix... (as another option for other devs). And this solution prevents the need to 'preventDefault' and 'stopImmediatePropagation'.

<mat-list>
    <mat-list-item>
        <a matLine [routerLink]="['/detail']">
            <p matLine>Title</p>
        </a>
        <button mat-icon-button (click)="onAdd()">
            <mat-icon>add</mat-icon>
        </button>
        <button mat-icon-button (click)="onRemove()">
            <mat-icon>delete</mat-icon>
        </button>
    </mat-list-item>
</mat-list>

Additionally (we can add multiple rows of text and icon as follows):

<mat-list>
    <mat-list-item>
        <a matLine [routerLink]="['/detail']">
            <mat-icon mat-list-icon>accessibility</mat-icon>
            <p>
              <span>Text Row 1</span>
              <span>Text Row 2</span>
            </p>
        </a>
        <button mat-icon-button (click)="onAdd()">
            <mat-icon>add</mat-icon>
        </button>
        <button mat-icon-button (click)="onRemove()">
          <mat-icon>delete</mat-icon>
        </button>
    </mat-list-item>
</mat-list>

And then the following css styles are to be applied:

.mat-list .mat-list-item a {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: black;
  text-decoration: none;
}

.mat-list .mat-list-item .mat-list-icon {
  float: left;
  margin-right: 0.5em;
}

.mat-list .mat-list-item p span
{
  display: block;
}

The above css ensures that the icon is floated to the left with a right margin applied - and that the items are aligned centrally.

The span splits the paragraph rows.

You can also then apply styles to each individual span if required.


问:
How to limit number of the many in a one-to-many relationships between two tables?
I have a MySQL database with two MySql tables. First is with The first table (table A) has a column with unique values(from values (from 1 to n). In the second table 2 (table B), I have two columns: in the first I have a name and in the second i have values from 1 to n(if i ad an value in the . The second it's updated column in table B is a reference to the first and vice versa. That's done)column in table A.

My Question: Can I limit the number of aparation of times the values from the second in table A appear in table B, specifically to a maximum of 10 times?
An example is this: (with limitation for column val to 3) (the third table would send an error)

```<code>First table:      Second table:        Third table(imaginary)
+---+             +----+-----+          +----+-----+
|val|             |name| val |          |name| val |
+---+             +----+-----+          +----+-----+
| 1 |             |  a |  1  |          |  a |  1  |
| 2 |             |  b |  2  |          |  b |  2  |
+---+             |  c |  1  |          |  c |  1  |
                  |  d |  1  |          |  d |  1  |
                  +----+-----+          |  e |  1  |
                                        +----+-----+
</code>```

PS: Sorry for my english.

答: I think you will need to use a trigger: http://forge.mysql.com/wiki/Triggers#Emulating_Check_Constraints</p>

Body:
I have a MySQL database with two MySql tables. First is with The first table (table A) has a column with unique values(from values (from 1 to n). In the second table 2 (table B), I have two columns: in the first I have a name and in the second i have values from 1 to n(if i ad an value in the . The second it's updated column in table B is a reference to the first and vice versa. That's done)column in table A.

My Question: Can I limit the number of aparation of times the values from the second in table A appear in table B, specifically to a maximum of 10 times?
An example is this: (with limitation for column val to 3) (the third table would send an error)

First table:      Second table:        Third table(imaginary)
+---+             +----+-----+          +----+-----+
|val|             |name| val |          |name| val |
+---+             +----+-----+          +----+-----+
| 1 |             |  a |  1  |          |  a |  1  |
| 2 |             |  b |  2  |          |  b |  2  |
+---+             |  c |  1  |          |  c |  1  |
                  |  d |  1  |          |  d |  1  |
                  +----+-----+          |  e |  1  |
                                        +----+-----+

PS: Sorry for my english.


问:
JavaScript - How do i check execution of my command finished or not?
I want to make a 3D matrix and fill it with values from a text file then make a grid with size 180*90, and color it with respect to values from my matrix,

for example: blue for negative values, red for positive and white for zero values.

I want to store what i read from my text file in a 3D matrix.

but i have problem, when i execute my html file and use
 console.log(myMatrix) it shows me undefined and when i copy-paste for-loop in console,

for example
 console.log(myMatrix[0][0][4]) shows me correct answer which is 90.

so i guess maybe the problem is related to javaScript, because js read all code and when i try console.log(myMatrix[0][0][4]) it shows me undefined because reading file and store in array does not complete but when i use console command because it is in RAM, I can see correct answer.

therefore, i decided to check if reading the file and store it in an array completed, then execute my for-loop to store values from an array to myMatrix. But i do not know how can i do this?

i tried use setTimeout but i thought maybe execution time in my system is different from other system or also network.Also i thought for Callback function but i did not achieved anything. I hope you help me.

this is my code:

```<code><!DOCTYPE html>
<html>
    <head>
        <script src="https://d3js.org/d3.v5.min.js"></script>
    </head>
    <body>

        <div id="grid"></div>
        <script>
        //creat 1670 numbers of matrices with size of 180*90
                var myMatrix = new Array(1670)
                for (var i=0; i<1670; i++){
                    myMatrix[i] = twodmatrix()
                }

                function twodmatrix(){
                    var myMat = new Array(180)
                    for (var i=0; i<180; i++){
                        myMat[i] = new Array(90)
                    }
                    return(myMat)
                }

                var myGrid = new Array(1670)
                for (var i=0; i<1670; i++){
                    myGrid[i] = twodmatrix()}

                var array = new Array()

                    xmlhttp = new XMLHttpRequest();
                    xmlhttp.open("GET", "tempanomaly_new.txt", true);
                    xmlhttp.send();
                    xmlhttp.onreadystatechange=function() {
                        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                            parse(xmlhttp.responseText);
                        }
                    }
                function parse (text) {
                     array = text.split(",");
                     return array
                    //Do something

                }

                function treeDmatrix(){
                var n=0;
                for(var i=0;i<1670;i++){
                    for(var j=0;j<180;j++){
                        for(var k=0; k<90; k++){myMatrix[i][j][k]= array[n];
                                                n +=1;}}}

                }

                /*var mycolor;

                for(var i=0; i<array.length; i++){
                    if (array[i] == 0){ function white(){  mycolor = d3.scalelinear().domain([1,5]).range(["white"])}}
                    else if (array[i] > 0 ){ function red(){ mycolor = d3.scalelinear().domain([1,5]).range(["red"])}}
                    else if (array[i] < 0 ){function blue(){ mycolor = d3.scalelinear().domain([1,5]).range(["blue"])}}
                }

                /* Start make a grid and color it */
                /*
                const BLOCK_SIZE = 30;
                const BLOCK_SPACE = 5;
                const ROW_SIZE = 90;
                const COL_SIZE = 180;

                gridData = new Array(COL_SIZE);
                for (var i = 0; i < COL_SIZE; i++) {
                    gridData[i] = new Array(ROW_SIZE);
                    for (var j = 0; j < ROW_SIZE; j++) {
                        gridData[i][j] = {
                            x: (i + 1) * BLOCK_SIZE + BLOCK_SPACE,
                            y: (j + 1) * BLOCK_SIZE + BLOCK_SPACE,
                            size: BLOCK_SIZE,
                            }}}

    var grid = d3.select("#grid")
    .append("svg")
    .attr("width", "100%")
    .attr("height", "100%")
    .style("color", "#b2b2b2");

    var row = grid.selectAll(".row")
    .data(gridData)
    .enter().append("g")
    .attr("class", "row");

    var column = row.selectAll(".square")
    .data(function(data) { return data; })
    .enter()
    .append("rect")
    .attr("class", "square")
    .attr("x", function(data) { return data.x; })
    .attr("y", function(data) { return data.y; })
    .attr("width", function(data) { return data.size; })
    .attr("height", function(data) { return data.size; })
    .style("stroke", "#222")
    .style("fill", function(data) { return mycolor(data)});*/
        </script>
    </body>
</html>
</code>```

答: The onreadystatechange is an asynchronous function and hence it is most likely be called only after running all of your script. So, you have to wait till your parse function is called and then go ahead with processing the data. I would suggest you to move all your code inside parse and check. Please read about Promise if you really want to do it the correct way.

Body:
I want to make a 3D matrix and fill it with values from a text file then make a grid with size 180*90, and color it with respect to values from my matrix,

for example: blue for negative values, red for positive and white for zero values.

I want to store what i read from my text file in a 3D matrix.

but i have problem, when i execute my html file and use
 console.log(myMatrix) it shows me undefined and when i copy-paste for-loop in console,

for example
 console.log(myMatrix[0][0][4]) shows me correct answer which is 90.

so i guess maybe the problem is related to javaScript, because js read all code and when i try console.log(myMatrix[0][0][4]) it shows me undefined because reading file and store in array does not complete but when i use console command because it is in RAM, I can see correct answer.

therefore, i decided to check if reading the file and store it in an array completed, then execute my for-loop to store values from an array to myMatrix. But i do not know how can i do this?

i tried use setTimeout but i thought maybe execution time in my system is different from other system or also network.Also i thought for Callback function but i did not achieved anything. I hope you help me.

this is my code:

<!DOCTYPE html>


问:
Get last 10 lines of very large text file > 10GB
What is the most efficient way to display the last 10 lines of a very large text file (this particular file is over 10GB). I was thinking of just writing a simple C# app but I'm not sure how to do this effectively.</p>

答:
Using PowerShell, Get-Content big_file_name.txt -Tail 10 where 10 is the number of bottom lines to retrieve.

This has no performance problems.  I ran it on a text file that is over 100 GB and got an instant result.

OwnerDisplayName: Chris Conway


问:
mailcore2 via SMTP Outlook.com gives Error Domain=MCOErrorDomain Code=1 "A stable connection to the server could not be established."
I am setting up outlook.com with mailcore2 on iOS9 in Objective-C.  I have gmail working already with both imap and smtp.  I can fetch emails fine from outlook.com but when I try and send an email I get the following error:

Error Domain=MCOErrorDomain Code=1 "A stable connection to the server
  could not be established."

Below is a sample of my code:

```<code>MCOSMTPSession *session = [[MCOSMTPSession alloc] init];
[session setAuthType:MCOAuthTypeXOAuth2Outlook];
[session setOAuth2Token:accessToken];
[session setUsername:@"user@outlook.com"];
[session setHostname:@"smtp-mail.outlook.com"];
[session setPort:25];  //also tried 587
[session setConnectionType:MCOConnectionTypeStartTLS];  //Also tried MCOConnectionTypeTLS and MCOConnectionTypeClear
[session setCheckCertificateEnabled:false];

MCOSMTPSendOperation *sendOperation = [session sendOperationWithData:data];
[sendOperation start:^(NSError *error) {
}];
</code>```

I also tried the checkAccountOperationWithFrom operation but that also gave the same error.

答:
I am not able to fetch emails from Outlook, can you tell me what are the changes to be done in my Imap Settings.Below is the code i am using..</p>

```<code>session = [[MCOIMAPSession alloc]init];
session.hostname = @"imap-mail.outlook.com";
session.username = @"dummy@outlook.com";
session.password = nil;
session.port = 993;
session.OAuth2Token = accessToken;
session.connectionType = MCOConnectionTypeStartTLS;
session.authType = MCOAuthTypeSASLLogin;
session.checkCertificateEnabled = false;
</code>```

Body:
I am setting up outlook.com with mailcore2 on iOS9 in Objective-C.  I have gmail working already with both imap and smtp.  I can fetch emails fine from outlook.com but when I try and send an email I get the following error:

Error Domain=MCOErrorDomain Code=1 "A stable connection to the server
  could not be established."

Below is a sample of my code:

MCOSMTPSession *session = [[MCOSMTPSession alloc] init];
[session setAuthType:MCOAuthTypeXOAuth2Outlook];
[session setOAuth2Token:accessToken];
[session setUsername:@"user@outlook.com"];
[session setHostname:@"smtp-mail.outlook.com"];
[session setPort:25];  //also tried 587
[session setConnectionType:MCOConnectionTypeStartTLS];  //Also tried MCOConnectionTypeTLS and MCOConnectionTypeClear
[session setCheckCertificateEnabled:false];

MCOSMTPSendOperation *sendOperation = [session sendOperationWithData:data];
[sendOperation start:^(NSError *error) {
}];

I also tried the checkAccountOperationWithFrom operation but that also gave the same error.

Body:
I am not able to fetch emails from Outlook, can you tell me what are the changes to be done in my Imap Settings.Below is the code i am using..

session = [[MCOIMAPSession alloc]init];
session.hostname = @"imap-mail.outlook.com";
session.username = @"dummy@outlook.com";
session.password = nil;
session.port = 993;
session.OAuth2Token = accessToken;
session.connectionType = MCOConnectionTypeStartTLS;
session.authType = MCOAuthTypeSASLLogin;
session.checkCertificateEnabled = false;


问:
VS2017 not showing MVC Controller with view using Entity Framework
I created a normal ASP.NET web application and adding MVC to it manually as I think this is the best way to learn MVC design pattern.

I have created a model and now I am trying to create the controller for that model by right-clicking in the Controller folder > Add > Controller however, not seeing option for "MVC Controller with Views using Entity Framework".

Here's what I have already done:

Added NuGet Package in my solution

Searched other questions that may help but none did.

UPDATE WITH MORE INFORMATION:

The Nuget package I have installed is Microsoft.AspNetCore.Mvc. The problem is that I need to add MVC Controller with views using Entity Framework however, it's not in the list of Controller's folder > Add > Controller

答:
I run into same issue today and the way to fix it was to simply:

move / delete Pages folder from project main directory.

Once you remove the folder you can scaffold the controller with "MVC Controller with view using Entity Framework" option again.
This issue was reported a while ago and was supposed to be fixed but seems to still occur as end of May 2019


问:
jQuery: What to do with the list that sortable('serialize') returns?
With jQuery I'm retrieving positions of a sortable list using 'serialize', like this:

var order = $('ul').sortable('serialize');

The variable 'order' then receives the following:

id[]=2&id[]=3&id[]=1&id[]=4&id[]=5

Now how can I use this data in an ajax call?

This is how I plan to do it, but it's ugly and I can't change the parameter name 'id':

$.post('ajax.php?'+order,{action:'updateOrder'});

Maybe I need to unserialize, then implode the variable 'order' and assign it to just one parameter?

I don't have a problem with the server side code, but I have a problem with the jQuery client site code. The question is, where do I place the 'order' variable in the script?

In the example I gave I added it as a query string:

'ajax.php?'+order

But I would like to pass it as a parameter, just like the action parameter. The following doesn't work, it returns a syntax error:

$.post('ajax.php?'+order,{action:'updateOrder',order});

答:
Regarding the "key" param I used the square brackets in order to get an array.</p>

```<code>var data = $('#cms-form').serialize();
data += '&' + $('.ui-tabs-nav').sortable('serialize', {key:'nav_order[]'});
</code>```

Body:
Regarding the "key" param I used the square brackets in order to get an array.

var data = $('#cms-form').serialize();
data += '&' + $('.ui-tabs-nav').sortable('serialize', {key:'nav_order[]'});


问:
How do I move an object based on its rotation in Processing? (Local axis)
So i'm trying to make a car game in processing, where the car moves just in his local y axis, and it turns by rotating. But i cant figure out how to make it move on the local y axis once it has rotated, that is the part where i need help. I post the code in Processing:</p>

```<code>class CarClass{
  float speed, x, y, steering, w;
  CarClass(){
    speed = 5;
    x = width/2;
    y = height/2;
    steering = radians(0);
    w = 5;
  }

  void display(){
    translate(x, y);
    rotate(steering);
    rectMode(CENTER);
    rect(0, 0, 40, 82);
  }

  void up(){
    y -= speed;
  }
  void down(){
    y += speed;
  }
  void left(){
    steering -= radians(w);
  }
  void right(){
    steering += radians(w);
  }
}

void movement(){
  if(keyPressed) {
    if (keyCode == UP) {
      car.up();
    }
    if (keyCode == DOWN) {
      car.down();
    }
    if (keyCode == LEFT) {
      car.left();
    }
    if (keyCode == RIGHT) {
      car.right();
    }
  }
}

CarClass car;

void setup(){
  size(854,480);
  car = new CarClass();
}

void draw(){
  background(10,10,10);
  car.display();
  movement();
}
</code>```

答:
You have to move the car in the direction, which is defined by the steering angle.

In the window, the x axis points to the left and the y points upwards. The steering angle is measured clockwise from the upwards direction.

The direction vector can be get by the trigonometric functions sin and cos and is:

v = (sin(steering), -cos(steering))

Use this vector to manipulate the position (x, y) of the car:

class CarClass {

    // [...]

    void up(){
        x += sin(steering) * speed;
        y -= cos(steering) * speed;
    }
    void down(){
        x -= sin(steering) * speed;
        y += cos(steering) * speed;
    }

    // [...]
}
```

Body:
So i'm trying to make a car game in processing, where the car moves just in his local y axis, and it turns by rotating. But i cant figure out how to make it move on the local y axis once it has rotated, that is the part where i need help. I post the code in Processing:

class CarClass{
  float speed, x, y, steering, w;
  CarClass(){
    speed = 5;
    x = width/2;
    y = height/2;
    steering = radians(0);
    w = 5;
  }

  void display(){
    translate(x, y);
    rotate(steering);
    rectMode(CENTER);
    rect(0, 0, 40, 82);
  }

  void up(){
    y -= speed;
  }
  void down(){
    y += speed;
  }
  void left(){
    steering -= radians(w);
  }
  void right(){
    steering += radians(w);
  }
}

void movement(){
  if(keyPressed) {
    if (keyCode == UP) {
      car.up();
    }
    if (keyCode == DOWN) {
      car.down();
    }
    if (keyCode == LEFT) {
      car.left();
    }
    if (keyCode == RIGHT) {
      car.right();
    }
  }
}

CarClass car;

void setup(){
  size(854,480);
  car = new CarClass();
}

void draw(){
  background(10,10,10);
  car.display();
  movement();
}