问:
Ruby class evaluation, validates_inclusion_of with dynamic data
If I have an ActiveRecord model as follows

```<code>class Foo < ActiveRecord::Base
  validates_inclusion_of :value, :in => self.allowed_types

  def self.allowed_types
    # some code that returns an enumerable
  end
end
</code>```

This doesn't work because the allowed_types method hasn't been defined at the time where the validation is evaluated. All the fixes I can think of basically all revolve around moving the method definition above the validation so that it's available when needed.

I appreciate that this may be more of a coding style question than anything (I want all my validations at the top of the model and methods at the bottom) but I feel there should be some kind of solution to this, possibly involving lazy evaluation of the initial model load?

is what I want to do even possible? Should I just be defining the method above the validation or is there a better validation solution to acheive what I want.

答:
You should be able to use the lambda syntax for this purpose. Perhaps like this:

```<code>class Foo < ActiveRecord::Base
  validates_inclusion_of :value, :in => lambda { |foo| foo.allowed_types }

  def allowed_types
    # some code that returns an enumerable
  end
end
</code>```

This way it will evaluate the lambda block at every validation and pass the instance of Foo to the block. It will then return the value from allowed_types in that instance so that it can be validated dynamically.

Also note that I removed self. from the allowed_types method declaration because that would create a class method instead of an instance method which is what you want here.

Body:
If I have an ActiveRecord model as follows

class Foo < ActiveRecord::Base
  validates_inclusion_of :value, :in => self.allowed_types

  def self.allowed_types
    # some code that returns an enumerable
  end
end

This doesn't work because the allowed_types method hasn't been defined at the time where the validation is evaluated. All the fixes I can think of basically all revolve around moving the method definition above the validation so that it's available when needed.

I appreciate that this may be more of a coding style question than anything (I want all my validations at the top of the model and methods at the bottom) but I feel there should be some kind of solution to this, possibly involving lazy evaluation of the initial model load?

is what I want to do even possible? Should I just be defining the method above the validation or is there a better validation solution to acheive what I want.

Body:
You should be able to use the lambda syntax for this purpose. Perhaps like this:

class Foo < ActiveRecord::Base
  validates_inclusion_of :value, :in => lambda { |foo| foo.allowed_types }

  def allowed_types
    # some code that returns an enumerable
  end
end

This way it will evaluate the lambda block at every validation and pass the instance of Foo to the block. It will then return the value from allowed_types in that instance so that it can be validated dynamically.

Also note that I removed self. from the allowed_types method declaration because that would create a class method instead of an instance method which is what you want here.


来源: stackexchange

问:
yii\base\ErrorException Cannot use a scalar value as an array
```<code>'rowOptions' =>function($dataProvider) use($isAccountingTeamOrAdmin){
        $value = 0.00;
        $results = array($dataProvider);
        $params = isset(\Yii::$app->request->queryParams) ? \Yii::$app->request->queryParams : '';
        if($results){
            $value = Yii::$app->payroll->getPayrollAmountForFloodViewHistory($results, $isAccountingTeamOrAdmin, $params);
        }
        if($value > 0){
            return false;
        }else{
            return true;
        }
    },
</code>```

This line $results = array($dataProvider); how to implement ??

答:
you can use the method getData() from your dataprovider

$results = $dataProvider->getData();

ContentLicense: CC BY-SA 4.0

Body:
'rowOptions' =>function($dataProvider) use($isAccountingTeamOrAdmin){
        $value = 0.00;
        $results = array($dataProvider);
        $params = isset(\Yii::$app->request->queryParams) ? \Yii::$app->request->queryParams : '';
        if($results){
            $value = Yii::$app->payroll->getPayrollAmountForFloodViewHistory($results, $isAccountingTeamOrAdmin, $params);
        }
        if($value > 0){
            return false;
        }else{
            return true;
        }
    },

This line $results = array($dataProvider); how to implement ??


问:
Root check identifies some android non devices as rooted - Dotfuscator
I'm using Preemptive protection dotfuscator for Root detection in my Android App, it works fine but it detects some non-rooted devices as rooted. How do I solve this?

Devices detect as rooted

Samsung A72, Samsung A50, Samsung S20, Huawei P30

I'm using Xamarin in Visual Studio 2019 for implementation

答: This is a bug in dotfuscator 6.4</p>

Body: This is a bug in dotfuscator 6.4


问:
In R , a calculation question like Solver
There are warehouse figures in below dataframe, currently know the data ship_in and ship_out_forecast.
Now I want to fix ship_out_forecast figures, make it's reasonable (the result as 'ship_out_forecast_checked' in attached image)

Below are the constraint condition：

cumsum(ship_in)-cumsum(ship_out_forecast_checked)>= 0

ship_out_forecast_checked>0

'ship_out_forecast_checked'<='ship_out_forecast'

library(tidyverse)
mdate <- c(44593,44594,44595,44596,44597,44598,44599,44600,44601,44602,44603,44604,44605,44606,44607,44593,44594,44595,44596,44597,44598,44599,44600,44601,44602,44603,44604,44605,44606,44607)
category <- c("A","A","A","A","A","A","A","A","A","A","A","A","A","A","A","B","B","B","B","B","B","B","B","B","B","B","B","B","B","B")
ship_in <- c(20,0,0,0,5,0,0,0,0,7,0,0,0,0,0,1,0,0,7,30,0,0,0,0,25,0,0,0,0,0)
ship_out_forecast <- c(12,15,13,11,3,5,8,14,8,11,1,9,16,9,3,29,10,28,0,21,12,23,22,23,19,1,2,16,15,9)

warehouse_data <- data.frame(mdate,category,ship_in,ship_out_forecast) %>%
  mutate(mdate=as.Date(mdate,origin='1900-1-1'))
```

答:
Using https://stackoverflow.com/a/70945868/3358272 as a starting point with Reduce_frame:

Reduce_frame <- function(data, expr, init) {
  expr <- substitute(expr)
  out <- rep(init[1][NA], nrow(data))
  for (rn in seq_len(nrow(data))) {
    out[rn] <- init <- eval(expr, envir = data[rn,])
  }
  out
}
```
<p>Assuming you want to group by <code>category</code> (which can be removed easily if not), we can do this:</p>
<pre class="lang-r prettyprint-override"><code>warehouse_data %>%
  group_by(category) %>%
  mutate(
    ending_inventory = Reduce_frame(cur_data(), max(0, init + ship_in - ship_out_forecast), init = 0)
  ) %>%
  ungroup()
# # A tibble: 30 x 5
#    mdate      category ship_in ship_out_forecast ending_inventory
#    <date>     <chr>      <dbl>             <dbl>            <dbl>
#  1 2022-02-03 A             20                12                8
#  2 2022-02-04 A              0                15                0
#  3 2022-02-05 A              0                13                0
#  4 2022-02-06 A              0                11                0
#  5 2022-02-07 A              5                 3                2
#  6 2022-02-08 A              0                 5                0
#  7 2022-02-09 A              0                 8                0
#  8 2022-02-10 A              0                14                0
#  9 2022-02-11 A              0                 8                0
# 10 2022-02-12 A              7                11                0
# # ... with 20 more rows
</code>```

Body:
Using https://stackoverflow.com/a/70945868/3358272 as a starting point with Reduce_frame:

Reduce_frame <- function(data, expr, init) {
  expr <- substitute(expr)
  out <- rep(init[1][NA], nrow(data))
  for (rn in seq_len(nrow(data))) {
    out[rn] <- init <- eval(expr, envir = data[rn,])
  }
  out
}

Assuming you want to group by category (which can be removed easily if not), we can do this:

warehouse_data %>%
  group_by(category) %>%
  mutate(
    ending_inventory = Reduce_frame(cur_data(), max(0, init + ship_in - ship_out_forecast), init = 0)
  ) %>%
  ungroup()
# # A tibble: 30 x 5
#    mdate      category ship_in ship_out_forecast ending_inventory
#    <date>     <chr>      <dbl>             <dbl>            <dbl>
#  1 2022-02-03 A             20                12                8
#  2 2022-02-04 A              0                15                0
#  3 2022-02-05 A              0                13                0
#  4 2022-02-06 A              0                11                0
#  5 2022-02-07 A              5                 3                2
#  6 2022-02-08 A              0                 5                0
#  7 2022-02-09 A              0                 8                0
#  8 2022-02-10 A              0                14                0
#  9 2022-02-11 A              0                 8                0
# 10 2022-02-12 A              7                11                0
# # ... with 20 more rows


问:
Site with different authentication for site students and staff in Django?
I am trying to create a Django web app with two types of users, Students and Staff. The problem is Students must login with their full name and id number (where name is non-unique, and id number operates as password), but I do not believe there is a way for Django to allow name to be non-unique (USERNAME_FIELD constant must be unique). Staff have a different login, they can login with regular username and password (username must be unique). Also, because there are two types of users, I do not know what to put for the AUTH_USER_MODEL constant in settings.py, since there can only be one model for this. What is the best way to set up the app without running into these problems?</p>

答:
If I understood your question properly, you want to keep the usernames of students "non-unique" and you want to differentiate them with unique passwords (Id number).

Django doesn't allow this because it is not a good practice. Why don't you consider keeping "Id number" and "name" as a password (which is again not a good practice to keep "name" as a password but will work in Django)?

Otherwise, if you want to do what you are trying to do, then you can code your own method for authentication instead of using Django's inbuilt method. This may not be that secure but I think your approach itself is not secure so this might work for you.


问:
How do I prevent JAXB from binding superclass methods of the @XmlRootElement when marshalling?
I have a class that is annotated as the @XmlRootElement with @XmlAccessorType(XmlAccessType.NONE).  The problem that I am having is that the superclass's methods are being bound, when I do not want them to be bound, and cannot update the class.  I am hoping there is an annotation that I can put on the root element class to prevent this from happening.

Example:

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Person extends NamedObject {

    @XmlElement
    public String getId() { ... }

}
</code>```

I would expect that only the methods annotated @XmlElement on Person would be bound and marshalled, but the superclass's methods are all being bound, as well.  The resulting XML then has too much information.

How do I prevent the superclass's methods from being bound without having to annotate the superclass, itself?

答:
I'm facing the exact same problem.
My superclass does not handle any JAXB annotations (it doesn't have to) and I would like my subclass not to include superclass properties while marshalling.

Adding the XmlAccesorType on superclass cannot be the solution as I have no way to modify the superclass.

Is there any other solution?

OwnerDisplayName: Matt Fisher

ContentLicense: CC BY-SA 2.5

Body:
I have a class that is annotated as the @XmlRootElement with @XmlAccessorType(XmlAccessType.NONE).  The problem that I am having is that the superclass's methods are being bound, when I do not want them to be bound, and cannot update the class.  I am hoping there is an annotation that I can put on the root element class to prevent this from happening.

Example:

@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class Person extends NamedObject {

    @XmlElement
    public String getId() { ... }

}

I would expect that only the methods annotated @XmlElement on Person would be bound and marshalled, but the superclass's methods are all being bound, as well.  The resulting XML then has too much information.

How do I prevent the superclass's methods from being bound without having to annotate the superclass, itself?

LastEditorDisplayName: Matt Fisher

OwnerDisplayName: Laurent


问:
Angular MatAccordion is displayed flat by default
I'm using mat-accordion component in my application, however even though it is clearly stated in the documentation here -> https://material.angular.io/components/expansion/overview#expansion-overview the default displayMode is border + raised. When I run the example code for expansion panel from the link above in my app, it shows as flat. When I try to explicitly set displayMode property to 'default' it shows as flat. What am I missing?</p>

答:
Most likely something else is overwriting your css. It can happen when css is bleeding from other components if they use ::ng-deep, :host etc. The use of !important even on encapsulated styles might be overwriting. This is just a guess.

This adds the raised effect. Add this to your component stylesheet and observe if normal visuals return.

.mat-expansion-panel:not([class*=mat-elevation-z]) {
    box-shadow: 0 3px 1px -2px #0003,0 2px 2px #00000024,0 1px 5px #0000001f !important;
}
```

If they return then something is indeed overwriting material default css. Find the problem and fix it.

Body:
Most likely something else is overwriting your css. It can happen when css is bleeding from other components if they use ::ng-deep, :host etc. The use of !important even on encapsulated styles might be overwriting. This is just a guess.

This adds the raised effect. Add this to your component stylesheet and observe if normal visuals return.

.mat-expansion-panel:not([class*=mat-elevation-z]) {
    box-shadow: 0 3px 1px -2px #0003,0 2px 2px #00000024,0 1px 5px #0000001f !important;
}

If they return then something is indeed overwriting material default css. Find the problem and fix it.


问:
HTML Emails: The Use Case for Nested Tables
I'm relatively new to HTML Email Development, and I'm trying to wrap my head around nested tables, specifically WHEN to nest a table, create a tr tag pair, or add a td tag pair.
Below is a code snippet from a real-world example of an HTML Email located at this URL to illustrate the basis of my confusion: https://reallygoodemails.com/emails/save-30-for-our-winter-sale/live

Our Winter Sale gets better

WINTER SALE: 30% OFF. FREE SHIPPING AVAILABLE WITH AN ACCOUNT. LEARN MORE.

```

There are SIX tables here and—although I understand what Table 1 and Table 6 are doing—the other four tables are confusing.

Table 2 looks like it defines the wrapper for the page. But doesn’t Table 1 do that already? If so, why is it there?

Table 3 and Table 4 look like they both act as the main container for the HTML email template, since they both define the width of the main table. But I don’t understand why Table 3 is necessary when Table 4 specifies the same width of 600px?

Table 5 has a class of “Column-1”, but there isn’t a class labelled “Column-1” in the stylesheets found in the head of the document, so why is it there?

These observations, among others, have made me realize that there is a TON of variation in HTML Email Development whenever nested tables are concerned. So much so that it makes it difficult to derive a general rule of thumb for table, tr, and td use. But from what I can see:

Tables are used for cutting the page into blocks and specifying the size of said blocks.

Tr tag pairs are used for defining separate sections in an HTML Email Template.

Td tag pairs are used for content placement (in child tables) or content formatting (in parent tables).

Can anyone validate my observations or, better yet, give me a more detailed explanation of WHEN to make a new table, tr, or td in the context of HTML Email Development?

Thanks in advance!

P.S. Please correct me if I am wrong on any of my observations. I truly want to learn the nuances of this field to the best of my ability.

答:
Generally in HTML, using tables for creating layout is considered a bad practice, but I guess in email HTML it is more acceptable because support for old applications is very important so using modern layout tools is problematic.

Simply putting,

 tags define an entire table (or table layout),
 tags define a table row, and  tags define a single cell within a row. You can never put content directly inside a row, it's always table -> row -> cell even if it's a row with only one cell.

A nested table inside a cell allows cutting that cell into smaller areas.

Body:
I'm relatively new to HTML Email Development, and I'm trying to wrap my head around nested tables, specifically WHEN to nest a table, create a tr tag pair, or add a td tag pair.
Below is a code snippet from a real-world example of an HTML Email located at this URL to illustrate the basis of my confusion: https://reallygoodemails.com/emails/save-30-for-our-winter-sale/live

Our Winter Sale gets better

WINTER SALE: 30% OFF. FREE SHIPPING AVAILABLE WITH AN ACCOUNT. LEARN MORE.

There are SIX tables here and—although I understand what Table 1 and Table 6 are doing—the other four tables are confusing.

Table 2 looks like it defines the wrapper for the page. But doesn’t Table 1 do that already? If so, why is it there?

Table 3 and Table 4 look like they both act as the main container for the HTML email template, since they both define the width of the main table. But I don’t understand why Table 3 is necessary when Table 4 specifies the same width of 600px?

Table 5 has a class of “Column-1”, but there isn’t a class labelled “Column-1” in the stylesheets found in the head of the document, so why is it there?

These observations, among others, have made me realize that there is a TON of variation in HTML Email Development whenever nested tables are concerned. So much so that it makes it difficult to derive a general rule of thumb for table, tr, and td use. But from what I can see:

Tables are used for cutting the page into blocks and specifying the size of said blocks.

Tr tag pairs are used for defining separate sections in an HTML Email Template.

Td tag pairs are used for content placement (in child tables) or content formatting (in parent tables).

Can anyone validate my observations or, better yet, give me a more detailed explanation of WHEN to make a new table, tr, or td in the context of HTML Email Development?

Thanks in advance!

P.S. Please correct me if I am wrong on any of my observations. I truly want to learn the nuances of this field to the best of my ability.

Body:
Generally in HTML, using tables for creating layout is considered a bad practice, but I guess in email HTML it is more acceptable because support for old applications is very important so using modern layout tools is problematic.

Simply putting, <table></table> tags define an entire table (or table layout), <tr> tags define a table row, and <td> tags define a single cell within a row. You can never put content directly inside a row, it's always table -> row -> cell even if it's a row with only one cell.

A nested table inside a cell allows cutting that cell into smaller areas.


问:
How to represent as a matrix a 4-column dataframe, where column 0 specifies row, columns 1-2 specify column range, and column 3 specifies entry
I have a four-column data frame, given as follows: Column zero consists of text labels chosen from a list ['A','B','C','D'] with possible repetitions. Columns one-two are labelled, start and stop, where the former is less than the latter, and column three, intensity, is a float. For each label, none of the corresponding intervals formed using [start,stop] overlap.

A simple example is given by:

```<code>import numpy as np
import pandas as pd
labels=['A','B','C','D']
d = {'label': ['A','B','A','C','D','B','A'],'start': [1, 2,6,4,1,8,12], 'stop':
[4,4,9,6,7,11,16],'intensity':[8,2,4,6,7,1,5]}
df = pd.DataFrame(data=d)
print(df)

  label  start  stop  intensity
0     A      1     4          8
1     B      2     4          2
2     A      6     9          4
3     C      4     6          6
4     D      1     7          7
5     B      8    11          1
6     A     12    16          5
</code>```

I wish to create a matrix, M, having four (=len(labels)) rows and 16 columns. (The number of columns must be at least the maximum entry in df['stop']. Whether it's larger doesn't matter). For each integer k between 0 and 6, the index of df['label'][k] in labels specifies a row of my matrix M. The entries in columns d[start][k] to d[stop][k] of this row should all equal d['intensity'][k]. All other entries of M equal zero.

For example, label A corresponds to rows 0, 2, and 6. In row 0, entries in columns 1-4 equal 8, entries in columns 6-9 equal 4, and entries in columns 12-16 equal 5.

I'd like to do this in the most pythonic way using list operations and at most one loop.

答:
another way using explode

```<code>df['range'] = df.apply(lambda r: list(range(r['start'], r['stop']+1)), axis=1)
df.explode('range').set_index(['label', 'range'])[['intensity']].unstack()
</code>```

Body:
I have a four-column data frame, given as follows: Column zero consists of text labels chosen from a list ['A','B','C','D'] with possible repetitions. Columns one-two are labelled, start and stop, where the former is less than the latter, and column three, intensity, is a float. For each label, none of the corresponding intervals formed using [start,stop] overlap.

A simple example is given by:

import numpy as np
import pandas as pd
labels=['A','B','C','D']
d = {'label': ['A','B','A','C','D','B','A'],'start': [1, 2,6,4,1,8,12], 'stop':
[4,4,9,6,7,11,16],'intensity':[8,2,4,6,7,1,5]}
df = pd.DataFrame(data=d)
print(df)

  label  start  stop  intensity
0     A      1     4          8
1     B      2     4          2
2     A      6     9          4
3     C      4     6          6
4     D      1     7          7
5     B      8    11          1
6     A     12    16          5

I wish to create a matrix, M, having four (=len(labels)) rows and 16 columns. (The number of columns must be at least the maximum entry in df['stop']. Whether it's larger doesn't matter). For each integer k between 0 and 6, the index of df['label'][k] in labels specifies a row of my matrix M. The entries in columns d[start][k] to d[stop][k] of this row should all equal d['intensity'][k]. All other entries of M equal zero.

For example, label A corresponds to rows 0, 2, and 6. In row 0, entries in columns 1-4 equal 8, entries in columns 6-9 equal 4, and entries in columns 12-16 equal 5.

I'd like to do this in the most pythonic way using list operations and at most one loop.

Body:
another way using explode

df['range'] = df.apply(lambda r: list(range(r['start'], r['stop']+1)), axis=1)
df.explode('range').set_index(['label', 'range'])[['intensity']].unstack()


问:
How to serialize Prisma Object in NestJS?
I have tried using Class Transformer, but it doesn't make any sense since Prisma doesn't need Entity, and Prisma Type cannot be Exclude()
Is there any way to exclude key from Prisma object e.g. createdAt or password? Thank you</p>

答:
I did it this way

In file: user.entity.ts

```<code>import { Role, User as UserPrisma } from '@prisma/client';
import { Exclude } from 'class-transformer';

export class User implements UserPrisma {
  id: string;
  name: string;
  email: string;

  @Exclude()
  password: string;

  @Exclude()
  role: Role;

  createdAt: Date;
  updatedAt: Date;
}
</code>```

Body:
I did it this way

In file: user.entity.ts

import { Role, User as UserPrisma } from '@prisma/client';
import { Exclude } from 'class-transformer';

export class User implements UserPrisma {
  id: string;
  name: string;
  email: string;

  @Exclude()
  password: string;

  @Exclude()
  role: Role;

  createdAt: Date;
  updatedAt: Date;
}


问:
What is the correct way to create a struct at a specific address in C?
C++ has a neat feature where you can create an object at a specific memory address as shown here.

This is particularly useful with mmap like so:

```<code>void *ptr = mmap(0, length, prot, flags, fd, offset);

A *ptrA = new (ptr) A;
</code>```

What is the correct way to replicate this with just C-style structs? Would it just be this?

```<code>void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;
</code>```

答:
This is valid because no memory usage constraints are enforced in C.</p>
```<code>void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;
</code>```

Body:
C++ has a neat feature where you can create an object at a specific memory address as shown here.

This is particularly useful with mmap like so:

void *ptr = mmap(0, length, prot, flags, fd, offset);

A *ptrA = new (ptr) A;

What is the correct way to replicate this with just C-style structs? Would it just be this?

void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;

Body:
This is valid because no memory usage constraints are enforced in C.

void *ptr = mmap(0, sizeof(A), prot, flags, fd, offset);

A *ptrA = (A*) ptr;


问:
Using group by and order by to fetch top row
I have a table with 3 rows released,major,minor. I want to pick the latest version in every release. I want to get 6_9_8,4_0_2,3_4_3 which are the latest version in that release.

I tried the below query but it returns everything.

 select releaseId,major,minor from release_table group by releaseId  order by major desc,minor desc

releaseId
major
minor

6
0
1

6
4
1

6
9
8

4
0
1

4
0
2

3
0
1

3
4
3

3
0
5

答:
```<code>with p as (
select rowid=row_number() over (partition by releaseid order by major desc, minor desc),
*
from mytable
)
select releaseid, major, minor
from p
where rowid=1
</code>```


问:
Can't import the named export 'Directive' from non EcmaScript module (only default export is available)
this is a ionic angular project that i'm working on, i'm using ng-lazyload-image plugin Link. when i start compiling it showing errors like this.</p>
```<code>Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19

Can't import the named export 'Directive' from non EcmaScript module (only default export is available)
</code>```

答:
This means your bundler resolves .mjs files, however it doesn't know that they are ESM modules. On webpack, you can add the following to rules.

webpack.config.js (in project root)

```<code>module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.mjs$/,
          include: /node_modules/,
          type: "javascript/auto"
        }
      ]
    }
  }
}

</code>```

https://webpack.js.org/configuration/

Body:
this is a ionic angular project that i'm working on, i'm using ng-lazyload-image plugin Link. when i start compiling it showing errors like this.

Error: ./node_modules/ng-lazyload-image/fesm2015/ng-lazyload-image.mjs 401:10-19

Can't import the named export 'Directive' from non EcmaScript module (only default export is available)

Body:
This means your bundler resolves .mjs files, however it doesn't know that they are ESM modules. On webpack, you can add the following to rules.

webpack.config.js (in project root)

module.exports = {
  configureWebpack: {
    module: {
      rules: [
        {
          test: /\.mjs$/,
          include: /node_modules/,
          type: "javascript/auto"
        }
      ]
    }
  }
}

https://webpack.js.org/configuration/


问:
Is it possible for a keyboard key to not generate a scancode?
I have recently moved to Linux full time, and am enjoying the learning curve. However, one particular thing has me stumped big time: Some of the Fn key combinations on my laptop are not working, spec. Volume up/down, Mute, etc. Combinations that are working include WLAN, Sleep, Video cycle, numeric pad, etc. I can rule out a H/W fault, since the keys worked perfectly fine on Windows 7 (although only when the hotkeys software by the laptop maker was installed).

I have scoured the net for possible explanations, and have come across the concepts of scancode (HW dependent), keycode and keysym. I think I understand the basics, and have found that console and X have their own mappings, and need to be remapped separately. The console uses the kernel mapping of scancodes to keycodes, but X for some reason has its own mapping. For my part, I have tried:

Set the boot parameter atkbd.softraw=0

Switched to console mode by Ctrl + Alt + F1

Used showkey --scancodes. Unfortunately, the keys that I am trying to get working do not show any scancode output

Used dmesg to see if any Unknown key pressed events have occured, but none found.

In my desperation, tried acpi_listen to see if the keys were actually firing any acpi events instead, only sleep and video cycle keys do, others do not output anything

At this point, I thought maybe I should try getting scancodes from the X environment itself, using xev, but no luck.

I have come here as a last resort only. I hope somebody has a good explanation as to why some of the function key combinations are not generating any output in the tools I have tried above. If it helps, I am using Linux Mint 17.3 Cinnamon, and the laptop is made by HCL. evtest shows the keyboard device to be AT Translated Set 2 keyboard. If more info is needed, I would be happy to oblige. Thanks.

EDIT: No relevant BIOS setting is available.

Confession: All my knowledge on this is based on what I have been reading up on Arch wiki, Ubuntu wiki, a whole lot of forum posts and other websites. So, if I am technically wrong about something, please bear with me, and correct me. I love learning this stuff :)

答:
Yes, some keys on USB keyboards might not generate a scan code sent via the USB HID keyboard protocol but instead use a different USB protocol to communicate some user input. From what you've described, that's most likely what's happening here. You may be able to use programs from the evmu-tools package (that's the Debian name) or the older evtest program to find out more about what your particular device is doing for things that appear not to be sending keyboard scan codes.

(It also seems, from reading The Unix & Linux SE question "How to get all my keys to send keycodes" that there's something going on with keycodes above 255, but I'm not clear on what's going on there.)

There's also an error in your understanding of the layering:

The console uses the kernel mapping of scancodes to keycodes, but X for some reason has its own mapping.

This is not quite correct. The kernel maps scan codes to keycodes between 1 and 255; you can see this mapping with getkeycodes(8) and change it with setkeycodes(8) or udev. (The Arch Wiki page Map scancodes to keycodes has many details on this.) Not all scan codes have a mapping to a keycode; receipt of a scan code with no translation entry are what you would have seen in dmesg, had there been any.

Only after the scan code is converted to a kernel keycode do the console and X11 have access to these; each has its own mechanism to translate keycodes to actions.

Note that the console program showkey -s does not show actual scan codes that have been received; it reads keycodes (as shown by showkey -k) and translates those back into scan codes using the kernel table shown by getkeycodes(8).

ContentLicense: CC BY-SA 3.0


问:
Unable to connect to AWS SDK AmazonEC2Client through C#
I am trying to connect to AWS via the SDK and the examples I am finding say connect via the following method:

```<code>string accessKey = "****************GCDE";
string SecretAccessKey = "****************oeE7";
AmazonEC2Client(accessKey,SecretAccessKey,RegionEndpoint.USWest2);

DescribeInstancesRequest request = new DescribeInstancesRequest();
</code>```

But this throws the following exception...

HResult=0x80131500
Message=AWS was not able to validate the provided access credentials
Source=AWSSDK.Core

答:
After a few hours of head scratching and looking at different samples online, I finally figured it out. Since I am using Microsoft Single Sign ON (SSO), to authenticate a token is required.</p>
```<code>string accessKey = "****************GCDE";
string SecretAccessKey = "****************oeE7";
string sessionToken = "****************oeE7";

var tempCredentials = new SessionAWSCredentials(
            accessKey,
            SecretAccessKey,
            sessionToken);

 var _client = new AmazonEC2Client(tempCredentials,RegionEndpoint.USWest2);
 DescribeInstancesRequest request = new DescribeInstancesRequest();
</code>```

Body:
I am trying to connect to AWS via the SDK and the examples I am finding say connect via the following method:

string accessKey = "****************GCDE";
string SecretAccessKey = "****************oeE7";
AmazonEC2Client(accessKey,SecretAccessKey,RegionEndpoint.USWest2);

DescribeInstancesRequest request = new DescribeInstancesRequest();

But this throws the following exception...

HResult=0x80131500
Message=AWS was not able to validate the provided access credentials
Source=AWSSDK.Core

Body:
After a few hours of head scratching and looking at different samples online, I finally figured it out. Since I am using Microsoft Single Sign ON (SSO), to authenticate a token is required.

string accessKey = "****************GCDE";
string SecretAccessKey = "****************oeE7";
string sessionToken = "****************oeE7";

var tempCredentials = new SessionAWSCredentials(
            accessKey,
            SecretAccessKey,
            sessionToken);

 var _client = new AmazonEC2Client(tempCredentials,RegionEndpoint.USWest2);
 DescribeInstancesRequest request = new DescribeInstancesRequest();


问:
Is .NET Timer more reliable than VB6 Timer
In the good old days of VB6 you could not rely on the timer control to fire at exactly the specified interval. If your program was doing some intense processing the Timer_Tick event is pushed onto the stack and only when it gets to the instruction is it processed, which may be some seconds(?) later.

So my question is - has the .NET timer control been improved such that this can be relied upon to fire at exactly the time interval specified? I guess the above still applies doesn't it? But is it any better than the VB6 version?

Are there any alternatives to using the timer control that ensure that an event fires after a specified interval?

答:
The problem with Timers is that it's OS dependent in a sense. The timer work has to be scheduled by the OS and if there's another high priority process using up a lot of the processing power then it might decide to schedule your code to run at a later time giving more time for another more important line of work to progress.

For the most part newer timers are probably more reliable but they are only as reliable as the subsystem is. I'm not sure if windows implements hardware timers (which are more reliable) or if the .NET VB uses it if it does but from what I've worked with in the past it seems to be hit or miss. Most of the time it's almost dead on within a very small margin and other times I've seen it get delayed by up to a second under certain conditions.

My advice is don't use sleeps and use Timers instead and you shouldn't have very many problems.

P.S: It is relatively difficult for it to happen at EXACT time intervals, there will usually be a couple of milliseconds difference so you shouldn't rely on very very exact Timer granularity.


问:
Is it a good practise to loop through a list and in between the loop you append data to that list?
```<code>a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()
</code>```

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

答:
To answer your question, no, you should not modify a sequence you are iterating over.  See more discussion here: Modifying list while iterating

If I understand you correctly, you want all items in the list until you encounter the first 0.
Example:
a = [1,2,3,4,0]
-> [1,2,3,4]

If so, you can use the index method to find the index of the first 0 in your list, then take a slice to get all elements prior to that index.

```<code>def get_elems(list_in):
    if 0 not in list_in:
        return list_in
    i = list_in.index(0)
    return list_in[:i]
</code>```

Body:
a = [1,2,3,4,0]
def looping_thing():
    append_flag = True
    for i in a:
        if i == 0:
            append_flag = False
        if append_flag:
            a.append(i)
        print(i)
looping_thing()

So in this code i am trying to move the item to back of the list so that i can deal with them only after i encounter value "0" in the list. So is this way of doing is correct in python?

Edit : So seems like i was not that clear. What i am doing here is....from the list i first want to deal with value 0 and execute some block of code..then move onto other value of the list and execute the same block of code. So i am just so to execute block of code "0" has the priority. Here the assumption is that i cannot sort the list and there will always be a "0" value. I hope this make sense.

Body:
To answer your question, no, you should not modify a sequence you are iterating over.  See more discussion here: Modifying list while iterating

If I understand you correctly, you want all items in the list until you encounter the first 0.
Example:
a = [1,2,3,4,0]
-> [1,2,3,4]

If so, you can use the index method to find the index of the first 0 in your list, then take a slice to get all elements prior to that index.

def get_elems(list_in):
    if 0 not in list_in:
        return list_in
    i = list_in.index(0)
    return list_in[:i]


问:
How to set exactly same height for Android bottom navigation bar with these codes?
I am writing codes for Android app. The layout is scrollview fragment is up, and bottom navigation bar down. It displays menu items well and click event works well, however, depending on contents amount displayed in fragment, bottom navigation bar's height is slightly changing.

What solution for this phenomenon? The following is the codes for this:

MainActivity.kt

```<code>package info.shutterpress.idols

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import androidx.databinding.DataBindingUtil.setContentView
import com.google.android.material.bottomnavigation.BottomNavigationView
import info.shutterpress.idols.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    lateinit var view: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        val mBottomNavView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
        mBottomNavView.setupWithNavController(navController)
        mBottomNavView.visibility = View.VISIBLE
        view = mBottomNavView

        val mBottomNavigationView = view as BottomNavigationView
        mBottomNavigationView.setOnNavigationItemSelectedListener { mi ->
            when (mi.itemId) {
                R.id.home_dest -> {
                    navController.navigate(R.id.main_fragment)
                }
                R.id.list_dest -> {
                    navController.navigate(R.id.recyclerview_fragment)
                }
                R.id.quiz_dest -> {
                }
            }
            true
        }
    }
}
</code>```

MainFragment.kt

```<code>package info.shutterpress.idols

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import info.shutterpress.idols.databinding.FragmentMainBinding

class MainFragment : Fragment() {
    lateinit var bind: FragmentMainBinding
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
        return bind.root
    }
}
</code>```

ListFragment.kt

```<code>package info.shutterpress.idols

import android.content.res.TypedArray
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import info.shutterpress.idols.databinding.FragmentRecyclerviewBinding

class ListFragment : Fragment() {
    lateinit var bind: FragmentRecyclerviewBinding
    var title: Array<String>? = null
    var image: TypedArray? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_recyclerview, container, false)
        title = resources.getStringArray(R.array.idols_title_array)
        image = resources.obtainTypedArray(R.array.idols_list_image_array)
        var adapter = IdolsListAdapter(image, title) {
            position -> onListItemClick(position)
        }
        bind.idolsList.adapter = adapter
        return bind.root
    }

    private fun onListItemClick(position: Int) {
        val action = ListFragmentDirections.actionRecyclerviewFragmentToDetailFragment(position)
        findNavController().navigate(action)
    }

    inner class ListHolder(
        view: View,
        private val onItemClicked: (position: Int) -> Unit
    ) : RecyclerView.ViewHolder(view), View.OnClickListener {
        var titleTextView: TextView = view.findViewById(R.id.detail_item_title)
        var imageView: ImageView = view.findViewById(R.id.detail_item_image)

        init {
            view.setOnClickListener(this)
        }

        override fun onClick(v: View) {
            val position = adapterPosition
            onItemClicked(position)
        }
    }

    inner class IdolsListAdapter(
        var image: TypedArray?,
        var title: Array<String>?,
        val onItemClicked: (position: Int) -> Unit) :
        RecyclerView.Adapter<ListHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ListHolder {
            val view = layoutInflater.inflate(R.layout.item_view, parent, false)
            return ListHolder(view, onItemClicked)
        }

        override fun getItemCount() = title!!.size

        override fun onBindViewHolder(holder: ListHolder, position: Int) {
            var _image = image!!.getResourceId(position, -1)
            var _title = title!![position]
            holder.apply {
                titleTextView.text = _title
                imageView.setImageResource(_image)
            }
        }
    }
}
</code>```

DetailFragment.kt

```<code>package info.shutterpress.idols

import android.content.res.TypedArray
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import info.shutterpress.idols.databinding.FragmentDetailBinding

class DetailFragment : Fragment() {
    lateinit var bind: FragmentDetailBinding
    var title: Array<String>? = null
    var image: TypedArray? = null
    var description: Array<String>? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_detail, container, false)

        val args by navArgs<DetailFragmentArgs>()
        var _position = args.positionDatum

        title = resources.getStringArray(R.array.idols_title_array)
        image = resources.obtainTypedArray(R.array.idols_list_image_array)
        description = resources.getStringArray(R.array.idols_description_array)

        bind.writingDetailTitle.text = title!![_position]
        bind.writingDetailImage.setImageResource(image!!.getResourceId(_position, -1))
        bind.writingDetailContent.text = description!![_position]

        return bind.root
    }
}
</code>```

activity_main.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/darkBeige"
        android:layout_margin="0dp"
        android:paddingBottom="0dp"
        android:orientation="vertical"
        tools:context="info.shutterpress.idols.MainActivity">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_main" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            app:menu="@menu/menu_bottom_navigation"
            android:id="@+id/bottom_navigation_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight=".1"
            android:padding="10dp"
            android:theme="@style/Theme.bottomNavApp"
            app:backgroundTint="@color/beige"
            app:background="@color/beige"
            app:itemIconTint="@color/black"
            app:itemTextColor="@color/black" />

    </LinearLayout>
</layout>
</code>```

fragment_detail.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

    </data>

    <LinearLayout
        android:id="@+id/detail_outermost_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:layout_margin="0dp"
        android:background="@color/darkBeige"
        android:gravity="start"
        android:orientation="vertical">
        <TextView
            android:id="@+id/writing_detail_title"
            android:padding="4dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:paddingTop="10dp"
            android:gravity="center"
            android:textSize="35sp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"/>

        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/darkBeige"
            android:paddingTop="0dp"
            android:paddingBottom="0dp"
            android:scrollbarSize="12dip" >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:layout_marginTop="20dp"
                android:background="@color/darkBeige"
                android:gravity="start"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/writing_detail_image"
                    android:layout_width="320dp"
                    android:layout_height="320dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="20dp"
                    app:srcCompat="@drawable/idols1" />

                <TextView
                    android:id="@+id/writing_detail_content"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/darkBeige"
                    android:layout_marginTop="20dp"
                    android:layout_marginBottom="25dp"
                    android:paddingTop="0dp"
                    android:padding="20dp"
                    android:gravity="start"
                    android:textSize="@dimen/text_size_main"
                    android:textColor="#de000000"
                    android:lineSpacingExtra="@dimen/line_spacing_main"/>

            </LinearLayout>
        </ScrollView>
    </LinearLayout>
</layout>
</code>```

fragment_main.xml

```<code><layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:layout_margin="0dp"
        android:background="@color/darkBeige"
        android:gravity="start"
        android:orientation="vertical">
        <TextView
            android:padding="4dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:paddingTop="10dp"
            android:gravity="center"
            android:textSize="35sp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/darkBeige"
            android:layout_margin="0dp"
            android:paddingTop="0dp"
            android:paddingBottom="0dp"
            android:scrollbarSize="12dip" >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:layout_margin="0dp"
                android:background="@color/darkBeige"
                android:gravity="start"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/welcome_message"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/darkBeige"
                    android:layout_margin="0dp"
                    android:paddingTop="0dp"
                    android:padding="20dp"
                    android:gravity="start"
                    android:textSize="@dimen/text_size_main"
                    android:lineSpacingExtra="@dimen/line_spacing_main"
                    android:text="@string/welcome_message"
                    android:textColor="#de000000" />

            </LinearLayout>
        </ScrollView>
    </LinearLayout>
</layout>
</code>```

fragment_recyclerview.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="35dp"
        android:id="@+id/recyclerview_fragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/idols_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:context="info.shutterpress.idols.MainActivity"
            tools:listitem="@layout/item_view"/>

    </LinearLayout>
</layout>
</code>```

答:
I have asked expert and he gave me appropriate solution! This works!

First, from activity_main.xml,

```<code>    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" // this should be 0dp
        android:layout_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_main" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        app:menu="@menu/menu_bottom_navigation"
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".1" // this should be deleted
        android:padding="10dp"
        android:theme="@style/Theme.bottomNavApp"
        app:backgroundTint="@color/beige"
        app:background="@color/beige"
        app:itemIconTint="@color/black"
        app:itemTextColor="@color/black" />
</code>```

This works! It was layout XML problem, not Kotlin code.

Body:
I am writing codes for Android app. The layout is scrollview fragment is up, and bottom navigation bar down. It displays menu items well and click event works well, however, depending on contents amount displayed in fragment, bottom navigation bar's height is slightly changing.

What solution for this phenomenon? The following is the codes for this:

MainActivity.kt

package info.shutterpress.idols

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import androidx.databinding.DataBindingUtil.setContentView
import com.google.android.material.bottomnavigation.BottomNavigationView
import info.shutterpress.idols.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    lateinit var view: View

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView<ActivityMainBinding>(this, R.layout.activity_main)

        val navHostFragment =
            supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
        val navController = navHostFragment.navController
        val mBottomNavView = findViewById<BottomNavigationView>(R.id.bottom_navigation_view)
        mBottomNavView.setupWithNavController(navController)
        mBottomNavView.visibility = View.VISIBLE
        view = mBottomNavView

        val mBottomNavigationView = view as BottomNavigationView
        mBottomNavigationView.setOnNavigationItemSelectedListener { mi ->
            when (mi.itemId) {
                R.id.home_dest -> {
                    navController.navigate(R.id.main_fragment)
                }
                R.id.list_dest -> {
                    navController.navigate(R.id.recyclerview_fragment)
                }
                R.id.quiz_dest -> {
                }
            }
            true
        }
    }
}

MainFragment.kt

package info.shutterpress.idols

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import info.shutterpress.idols.databinding.FragmentMainBinding

class MainFragment : Fragment() {
    lateinit var bind: FragmentMainBinding
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_main, container, false)
        return bind.root
    }
}

ListFragment.kt

package info.shutterpress.idols

import android.content.res.TypedArray
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.findNavController
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.RecyclerView
import info.shutterpress.idols.databinding.FragmentRecyclerviewBinding

class ListFragment : Fragment() {
    lateinit var bind: FragmentRecyclerviewBinding
    var title: Array<String>? = null
    var image: TypedArray? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_recyclerview, container, false)
        title = resources.getStringArray(R.array.idols_title_array)
        image = resources.obtainTypedArray(R.array.idols_list_image_array)
        var adapter = IdolsListAdapter(image, title) {
            position -> onListItemClick(position)
        }
        bind.idolsList.adapter = adapter
        return bind.root
    }

    private fun onListItemClick(position: Int) {
        val action = ListFragmentDirections.actionRecyclerviewFragmentToDetailFragment(position)
        findNavController().navigate(action)
    }

    inner class ListHolder(
        view: View,
        private val onItemClicked: (position: Int) -> Unit
    ) : RecyclerView.ViewHolder(view), View.OnClickListener {
        var titleTextView: TextView = view.findViewById(R.id.detail_item_title)
        var imageView: ImageView = view.findViewById(R.id.detail_item_image)

        init {
            view.setOnClickListener(this)
        }

        override fun onClick(v: View) {
            val position = adapterPosition
            onItemClicked(position)
        }
    }

    inner class IdolsListAdapter(
        var image: TypedArray?,
        var title: Array<String>?,
        val onItemClicked: (position: Int) -> Unit) :
        RecyclerView.Adapter<ListHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) : ListHolder {
            val view = layoutInflater.inflate(R.layout.item_view, parent, false)
            return ListHolder(view, onItemClicked)
        }

        override fun getItemCount() = title!!.size

        override fun onBindViewHolder(holder: ListHolder, position: Int) {
            var _image = image!!.getResourceId(position, -1)
            var _title = title!![position]
            holder.apply {
                titleTextView.text = _title
                imageView.setImageResource(_image)
            }
        }
    }
}

DetailFragment.kt

package info.shutterpress.idols

import android.content.res.TypedArray
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.navArgs
import info.shutterpress.idols.databinding.FragmentDetailBinding

class DetailFragment : Fragment() {
    lateinit var bind: FragmentDetailBinding
    var title: Array<String>? = null
    var image: TypedArray? = null
    var description: Array<String>? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        bind = DataBindingUtil.inflate(inflater, R.layout.fragment_detail, container, false)

        val args by navArgs<DetailFragmentArgs>()
        var _position = args.positionDatum

        title = resources.getStringArray(R.array.idols_title_array)
        image = resources.obtainTypedArray(R.array.idols_list_image_array)
        description = resources.getStringArray(R.array.idols_description_array)

        bind.writingDetailTitle.text = title!![_position]
        bind.writingDetailImage.setImageResource(image!!.getResourceId(_position, -1))
        bind.writingDetailContent.text = description!![_position]

        return bind.root
    }
}

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/darkBeige"
        android:layout_margin="0dp"
        android:paddingBottom="0dp"
        android:orientation="vertical"
        tools:context="info.shutterpress.idols.MainActivity">

        <androidx.fragment.app.FragmentContainerView
            android:id="@+id/nav_host_fragment"
            android:name="androidx.navigation.fragment.NavHostFragment"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            app:defaultNavHost="true"
            app:navGraph="@navigation/nav_main" />

        <com.google.android.material.bottomnavigation.BottomNavigationView
            app:menu="@menu/menu_bottom_navigation"
            android:id="@+id/bottom_navigation_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight=".1"
            android:padding="10dp"
            android:theme="@style/Theme.bottomNavApp"
            app:backgroundTint="@color/beige"
            app:background="@color/beige"
            app:itemIconTint="@color/black"
            app:itemTextColor="@color/black" />

    </LinearLayout>
</layout>

fragment_detail.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

    </data>

    <LinearLayout
        android:id="@+id/detail_outermost_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:layout_margin="0dp"
        android:background="@color/darkBeige"
        android:gravity="start"
        android:orientation="vertical">
        <TextView
            android:id="@+id/writing_detail_title"
            android:padding="4dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:paddingTop="10dp"
            android:gravity="center"
            android:textSize="35sp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"/>

        <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/darkBeige"
            android:paddingTop="0dp"
            android:paddingBottom="0dp"
            android:scrollbarSize="12dip" >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:layout_marginTop="20dp"
                android:background="@color/darkBeige"
                android:gravity="start"
                android:orientation="vertical">

                <ImageView
                    android:id="@+id/writing_detail_image"
                    android:layout_width="320dp"
                    android:layout_height="320dp"
                    android:layout_gravity="center"
                    android:layout_marginTop="20dp"
                    app:srcCompat="@drawable/idols1" />

                <TextView
                    android:id="@+id/writing_detail_content"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/darkBeige"
                    android:layout_marginTop="20dp"
                    android:layout_marginBottom="25dp"
                    android:paddingTop="0dp"
                    android:padding="20dp"
                    android:gravity="start"
                    android:textSize="@dimen/text_size_main"
                    android:textColor="#de000000"
                    android:lineSpacingExtra="@dimen/line_spacing_main"/>

            </LinearLayout>
        </ScrollView>
    </LinearLayout>
</layout>

fragment_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="0dp"
        android:paddingBottom="0dp"
        android:layout_margin="0dp"
        android:background="@color/darkBeige"
        android:gravity="start"
        android:orientation="vertical">
        <TextView
            android:padding="4dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:paddingTop="10dp"
            android:gravity="center"
            android:textSize="35sp"
            android:textColor="#FFFFFF"
            android:textStyle="bold"/>

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/darkBeige"
            android:layout_margin="0dp"
            android:paddingTop="0dp"
            android:paddingBottom="0dp"
            android:scrollbarSize="12dip" >
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:paddingTop="0dp"
                android:paddingBottom="0dp"
                android:layout_margin="0dp"
                android:background="@color/darkBeige"
                android:gravity="start"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/welcome_message"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@color/darkBeige"
                    android:layout_margin="0dp"
                    android:paddingTop="0dp"
                    android:padding="20dp"
                    android:gravity="start"
                    android:textSize="@dimen/text_size_main"
                    android:lineSpacingExtra="@dimen/line_spacing_main"
                    android:text="@string/welcome_message"
                    android:textColor="#de000000" />

            </LinearLayout>
        </ScrollView>
    </LinearLayout>
</layout>

fragment_recyclerview.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <data>
    </data>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="35dp"
        android:id="@+id/recyclerview_fragment">

        <androidx.recyclerview.widget.RecyclerView
            android:id="@+id/idols_list"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
            tools:context="info.shutterpress.idols.MainActivity"
            tools:listitem="@layout/item_view"/>

    </LinearLayout>
</layout>

Body:
I have asked expert and he gave me appropriate solution! This works!

First, from activity_main.xml,

    <androidx.fragment.app.FragmentContainerView
        android:id="@+id/nav_host_fragment"
        android:name="androidx.navigation.fragment.NavHostFragment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" // this should be 0dp
        android:layout_weight="1"
        app:defaultNavHost="true"
        app:navGraph="@navigation/nav_main" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        app:menu="@menu/menu_bottom_navigation"
        android:id="@+id/bottom_navigation_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight=".1" // this should be deleted
        android:padding="10dp"
        android:theme="@style/Theme.bottomNavApp"
        app:backgroundTint="@color/beige"
        app:background="@color/beige"
        app:itemIconTint="@color/black"
        app:itemTextColor="@color/black" />

This works! It was layout XML problem, not Kotlin code.


问:
It is possible to get a user id from an android when he using a app?
I want to get a user id / Google id from a app user without Google sign in. Is it possible to identify a user without authentication?

I want to sync data between devices without a login.

Thank you for any tips like classes or anything else.

答:
Is it possible to identify a user without authentication?

No. Identifying a user is basically the literal definition of "authentication". It's like asking if you can get wet without using a liquid.


问:
How to detect the object being double released with Xcode - message sent to deallocated instance?
I am relatively new to Xcode4 and I would like to know how can I identify a double release with it.

In the debugger I see a line like *** -[NSConcreteMutableData release]: message sent to deallocated instance 0x60b63fe0.

The problem is that knowing the address doesn't help a lot identifying the object and also the object type doesn't help too much identifying it.

I read http://www.friday.com/bbum/2010/01/10/using-malloc-to-debug-memory-misuse-in-cocoa/ but I did not found this to be too successful.

答: Try using the property retainCount. If an object has a retainCount == 0 then it will be freed. Ultimately you will not be able to send it a release message.


问:
Jira: Add new version via REST
I've been trying to do this via REST using bash in linux and am using the following:

```<code>curl -u${USERNAME}:${PASSWORD} -X POST "http://localhost:8088/rest/api/2/version" -d "{\"fields\": {\"name\": \"1.1\", \"projectId\": 10000, \"id\": \"10002\" }}"
</code>```

Any ideas what I'm doing wrong here?
I don't get any response.

And when I do the following:

```<code>curl -s -u${USERNAME}:${PASSWORD} -X GET "http://localhost:8088/rest/api/2/project/SW/versions" | jq
</code>```

I see no new data.

答:
The answer was in the details:

```<code>curl -u${USERNAME}:${PASSWORD} -H "Content-Type: application/json" -X POST "http://localhost:8088/rest/api/2/version" -d "{\"name\": \"1.1\", \"projectId\": \"10000\", \"id\": \"10002\" }"
</code>```

It needed the headers set and some improvements to the json being sent!

Title: Jira: Add new version via REST

Body:
I've been trying to do this via REST using bash in linux and am using the following:

curl -u${USERNAME}:${PASSWORD} -X POST "http://localhost:8088/rest/api/2/version" -d "{\"fields\": {\"name\": \"1.1\", \"projectId\": 10000, \"id\": \"10002\" }}"

Any ideas what I'm doing wrong here?
I don't get any response.

And when I do the following:

curl -s -u${USERNAME}:${PASSWORD} -X GET "http://localhost:8088/rest/api/2/project/SW/versions" | jq

I see no new data.

Body:
The answer was in the details:

curl -u${USERNAME}:${PASSWORD} -H "Content-Type: application/json" -X POST "http://localhost:8088/rest/api/2/version" -d "{\"name\": \"1.1\", \"projectId\": \"10000\", \"id\": \"10002\" }"

It needed the headers set and some improvements to the json being sent!


问:
How does strncmp using SSE 4.2 avoid reading beyond the page boundaries when loading 16 bytes?
glibc now uses SSE 4.2 to optimize strncmp:

https://github.com/lattera/glibc/blob/master/sysdeps/x86_64/multiarch/strcmp-sse42.S

https://www.strchr.com/strcmp_and_strlen_using_sse_4.2

This can be seen in a debugger:

```<code>   0xf7f20218 <__strncmp_sse4_2+40>    movdqu xmm2, xmmword ptr [edx]
   0xf7f2021c <__strncmp_sse4_2+44>    mov    ecx, eax
 ► 0xf7f2021e <__strncmp_sse4_2+46>    and    ecx, 0xfff
   0xf7f20224 <__strncmp_sse4_2+52>    cmp    ecx, 0xff0
   0xf7f2022a <__strncmp_sse4_2+58>    ja     __strncmp_sse4_2+125                    <__strncmp_sse4_2+125>
</code>```

I'm not steeped in SSE 4.2 for strings, but my understanding is that it allows it to compare up to 16 bytes at a time.  The movdqu xmm2, xmmword ptr [edx] loads 16 bytes from one of the strings.

My question is: If a short string (say 3 bytes) is at the end of a page, with the NULL termination within the page limits, but some of the remaining 13 bytes outside of the page, couldn't that cause a segfault, since we're now trying to load beyond the page we have access to?

This question came up in working on an emulator, which trapped an unconstrained access (that is, a read of memory which my application never wrote to):

```<code>strncmp(0x8064dd8, 0x7ffeff48, 0x4)
WARNING Filling memory at 0x7ffeff60 with 4 unconstrained bytes referenced from 0x818ba90 (strncmp+0x0 in libc.so.6 (0x8ba90))
</code>```

This is perplexing, because:

Why is strncmp of max 4 bytes starting at 0x7ffeff48 reading values from 0x7ffeff60

That is, it doesn't seem to be a bug in the caller, but rather unexpected behavior by strncmp.  Debugging strncmp led me to the SSE 4.2, which explains partially why it's reading beyond the limit set by n: it simply uses SSE 4.2 to load many bytes at once, even if it doesn't need them at all.

Questions:

Is this correct? Does strncmp_sse4_2 read more than n bytes?

Even if it does: Doing 16 bytes at a time should stop at 0x7ffeff58.  Why does it read till 0x7ffeff60?

If so, how does this not potentially cause a page fault?

If so, how do we tell distinguish acceptable read of uninitialized data from cases indicating bugs? E.g. how would Valgrind avoid reporting this as an uninitialized read?

答:
Is this correct? Does strncmp_sse4_2 read more than n bytes?

Yes.

Even if it does: Doing 16 bytes at a time should stop at 0x7ffeff58. Why does it read till 0x7ffeff60?

You are assuming that it started using movdqu from the address you passed in. It likely didn't. It probably aligned the pointers to cache line first.

If so, how does this not potentially cause a page fault?

If you have a 16-byte aligned pointer p, that means p+15 points to the same page as p so you can read 16 bytes from p with impunity.

If so, how do we tell distinguish acceptable read of uninitialized data from cases indicating bugs? E.g. how would Valgrind avoid reporting this as an uninitialized read?

Valgrind does this by interposing its own copy of strcmp (for dynamically linked binaries). Without such interposition, valgrind produces false positives (or, rather valgrind produces true positives which nobody cares or could do anything about).

Body:
glibc now uses SSE 4.2 to optimize strncmp:

https://github.com/lattera/glibc/blob/master/sysdeps/x86_64/multiarch/strcmp-sse42.S

https://www.strchr.com/strcmp_and_strlen_using_sse_4.2

This can be seen in a debugger:

   0xf7f20218 <__strncmp_sse4_2+40>    movdqu xmm2, xmmword ptr [edx]
   0xf7f2021c <__strncmp_sse4_2+44>    mov    ecx, eax
 ► 0xf7f2021e <__strncmp_sse4_2+46>    and    ecx, 0xfff
   0xf7f20224 <__strncmp_sse4_2+52>    cmp    ecx, 0xff0
   0xf7f2022a <__strncmp_sse4_2+58>    ja     __strncmp_sse4_2+125                    <__strncmp_sse4_2+125>

I'm not steeped in SSE 4.2 for strings, but my understanding is that it allows it to compare up to 16 bytes at a time.  The movdqu xmm2, xmmword ptr [edx] loads 16 bytes from one of the strings.

My question is: If a short string (say 3 bytes) is at the end of a page, with the NULL termination within the page limits, but some of the remaining 13 bytes outside of the page, couldn't that cause a segfault, since we're now trying to load beyond the page we have access to?

This question came up in working on an emulator, which trapped an unconstrained access (that is, a read of memory which my application never wrote to):

strncmp(0x8064dd8, 0x7ffeff48, 0x4)
WARNING Filling memory at 0x7ffeff60 with 4 unconstrained bytes referenced from 0x818ba90 (strncmp+0x0 in libc.so.6 (0x8ba90))

This is perplexing, because:

Why is strncmp of max 4 bytes starting at 0x7ffeff48 reading values from 0x7ffeff60

That is, it doesn't seem to be a bug in the caller, but rather unexpected behavior by strncmp.  Debugging strncmp led me to the SSE 4.2, which explains partially why it's reading beyond the limit set by n: it simply uses SSE 4.2 to load many bytes at once, even if it doesn't need them at all.

Questions:

Is this correct? Does strncmp_sse4_2 read more than n bytes?

Even if it does: Doing 16 bytes at a time should stop at 0x7ffeff58.  Why does it read till 0x7ffeff60?

If so, how does this not potentially cause a page fault?

If so, how do we tell distinguish acceptable read of uninitialized data from cases indicating bugs? E.g. how would Valgrind avoid reporting this as an uninitialized read?


问:
International telephone number validation witth RegEx
I need to handle phone number with international codes but I don't need the phone to be a specific format. I've found numerous example on how to apply it for the US, Spain, etc... but none that just allow to enter a number with 00 or +, allow spaces and/or dashes or no space or dashes.

I've got the following expression applied on a Telephone number field in an asp.net MVC 5 application:

```<code>[RegularExpression(@"^\+?\d*$", ErrorMessage = "Not a valid Telephone number.")]
</code>```

At it stands, it handles the following scenarios:

```<code>+19999999999
0019999999999
</code>```

which is fine but it doesn't allow spaces and/or dashes so numbers such as this one:

```<code>+ 1 999 999 99 99
+32 999-999-99-99
+7 999 999-99-99
</code>```

are not considered valid.

How can allow spaces and/or dashes to be included. More specifically, is it possible to ensure that:

there is only 1 space or 1 dash between numbers

Allow no space or no dash (current scenario)

Ensure there is only 1 + sign used

Ensure the number is at least 10 chars long and less than 20 chars.

If 1. is too complicated, can you just tell me how to allow spaces and/or dashes without any specific rules, so a number such as this: -33-999 999+99-99, while being totally wrong will still be valid.

Thanks

Body:
I need to handle phone number with international codes but I don't need the phone to be a specific format. I've found numerous example on how to apply it for the US, Spain, etc... but none that just allow to enter a number with 00 or +, allow spaces and/or dashes or no space or dashes.

I've got the following expression applied on a Telephone number field in an asp.net MVC 5 application:

[RegularExpression(@"^\+?\d*$", ErrorMessage = "Not a valid Telephone number.")]

At it stands, it handles the following scenarios:

+19999999999
0019999999999

which is fine but it doesn't allow spaces and/or dashes so numbers such as this one:

+ 1 999 999 99 99
+32 999-999-99-99
+7 999 999-99-99

are not considered valid.

How can allow spaces and/or dashes to be included. More specifically, is it possible to ensure that:

there is only 1 space or 1 dash between numbers

Allow no space or no dash (current scenario)

Ensure there is only 1 + sign used

Ensure the number is at least 10 chars long and less than 20 chars.

If 1. is too complicated, can you just tell me how to allow spaces and/or dashes without any specific rules, so a number such as this: -33-999 999+99-99, while being totally wrong will still be valid.

Thanks

Body:
  ^(?!\b(0)\1+\b)(\+?\d{1,3}[. -]?)?\(?\d{3}\)?([. -]?)\d{3}\3\d{4}$

This works for number digit validation, country code and it's length.


问:
Error when starting flutter application with Get
I have error when i try to run flutter app using Get:

```<code>Running Gradle task 'assembleDebug'...
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:252:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/cupertino/app.dart:188:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp.router({
        ^^^^^^^^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:292:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
E:/fluttersdk/flutter/packages/flutter/lib/src/cupertino/app.dart:144:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp({
        ^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:275:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/material/app.dart:219:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp.router({
        ^^^^^^^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:322:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/material/app.dart:168:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp({
        ^^^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'E:\fluttersdk\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1052

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'E:\fluttersdk\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1
</code>```

Does anyone know how to fix this? I looked at similar topics and tried the tips from them - nothing helped. Main widget wrap with GetMaterialApp:

```<code>void main() => runApp(GetMaterialApp(home: MainScreen()));
</code>```

答:
I hv same issue. I solved by reducing GetX version into :

```<code>#In pubspec.yaml use get package like below :

get: 4.5.1
</code>```

Others try solution use this way: (But This doesn't work for me)

```<code>#In pubspec.yaml use get package like below :

get: 4.6.1
#remove ^ symbol
</code>```

Body:
I have error when i try to run flutter app using Get:

Running Gradle task 'assembleDebug'...
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:252:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/cupertino/app.dart:188:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp.router({
        ^^^^^^^^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_cupertino_app.dart:292:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
E:/fluttersdk/flutter/packages/flutter/lib/src/cupertino/app.dart:144:9: Context: Found this candidate, but the arguments don't match.
  const CupertinoApp({
        ^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:275:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/material/app.dart:219:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp.router({
        ^^^^^^^^^^^^^^^^^^
../AppData/Local/Pub/Cache/hosted/pub.dartlang.org/get-4.6.1/lib/get_navigation/src/root/get_material_app.dart:322:17: Error: No named parameter with the name 'useInheritedMediaQuery'.
                useInheritedMediaQuery: useInheritedMediaQuery,
                ^^^^^^^^^^^^^^^^^^^^^^
/E:/fluttersdk/flutter/packages/flutter/lib/src/material/app.dart:168:9: Context: Found this candidate, but the arguments don't match.
  const MaterialApp({
        ^^^^^^^^^^^

FAILURE: Build failed with an exception.

* Where:
Script 'E:\fluttersdk\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1052

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'E:\fluttersdk\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 12s
Exception: Gradle task assembleDebug failed with exit code 1

Does anyone know how to fix this? I looked at similar topics and tried the tips from them - nothing helped. Main widget wrap with GetMaterialApp:

void main() => runApp(GetMaterialApp(home: MainScreen()));

Body:
I hv same issue. I solved by reducing GetX version into :

#In pubspec.yaml use get package like below :

get: 4.5.1

Others try solution use this way: (But This doesn't work for me)

#In pubspec.yaml use get package like below :

get: 4.6.1
#remove ^ symbol


问:
Git branch and ls
I'm not sure if this is the right place to ask this, please redirect me if not.

I'm new to git and while learning it I stumbled upon this.
How does git branch branchName and 'ls' work with each other.
For eg:
If I have a master and test branch and test branch has an extra testFile when compared to master branch.
Now, while in the master branch, if I ls, I'll wont see the testFile but after switching to the test branch and ls, I'll see the testFile

```<code>kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git branch
  master
* test
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout master
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'master'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           underConstruction
editor      jquery-1.5.2.min.js          php.php        userManage
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userPages
images      login                        test.php
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout test
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'test'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           test.php
editor      jquery-1.5.2.min.js          php.php        underConstruction
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userManage
images      login                        testFile.txt   userPages
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$
</code>```

But pwd from both branches shows the same location.

So, how does switching branches change the output of ls ( which as I understand is a function of linux) ?

答:
git checkout switches you from one branch to the other.  To do this, it replaces the files in the checked out repository with the ones from the branch.

Your repository is effectively the .git subdirectory.

If you do a ls -a, you'll see it:

```<code>% ls -a -1
.git
.gitignore
...
</code>```

Tracked files are stored in there.  You normally only see the currently checked out branch.  When you checkout a different branch, git grabs the files from .git and you can see them with ls.

Have a look at the answers to this question for more information about how git works: Where can I find a tutorial on Git's internals?

Title: Git branch and ls

Body:
I'm not sure if this is the right place to ask this, please redirect me if not.

I'm new to git and while learning it I stumbled upon this.
How does git branch branchName and 'ls' work with each other.
For eg:
If I have a master and test branch and test branch has an extra testFile when compared to master branch.
Now, while in the master branch, if I ls, I'll wont see the testFile but after switching to the test branch and ls, I'll see the testFile

kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git branch
  master
* test
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout master
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'master'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           underConstruction
editor      jquery-1.5.2.min.js          php.php        userManage
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userPages
images      login                        test.php
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ git checkout test
M   editor/editor_parts/syntax/operator_syntax.js
Switched to branch 'test'
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$ ls
cgi-bin     index.php                    misc           test.php
editor      jquery-1.5.2.min.js          php.php        underConstruction
fileManage  jquery-ui-1.8.11.custom.css  projectManage  userManage
images      login                        testFile.txt   userPages
kiran@kiran-desktop:/media/kiran/Linux_Server/dev$

But pwd from both branches shows the same location.

So, how does switching branches change the output of ls ( which as I understand is a function of linux) ?

Body:
git checkout switches you from one branch to the other.  To do this, it replaces the files in the checked out repository with the ones from the branch.

Your repository is effectively the .git subdirectory.

If you do a ls -a, you'll see it:

% ls -a -1
.git
.gitignore
...

Tracked files are stored in there.  You normally only see the currently checked out branch.  When you checkout a different branch, git grabs the files from .git and you can see them with ls.

Have a look at the answers to this question for more information about how git works: Where can I find a tutorial on Git's internals?


问:
Why this android project is not recognizing AppCompatActivity?
I am new to android programming and trying to build this android project in udacity's basic android course. But after updating to latest android studio bumblebee version, its starting to throws these errors:

Cannot resolve symbol 'v7'

Cannot resolve symbol 'AppCompatActivity'.

The import statement is grayed out.

```<code>import android.support.v7.app.AppCompatActivity;
</code>```

My build.gradle is

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25

    defaultConfig {
        applicationId "com.example.android.explicitintent"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:25.4.0'

}
</code>```

I have tried the following, but still it doesn't work:

Clean Project

Restart and Invalidated cache

Deleted .idea folder and reopened project

But nothing seems to work so far. Your help will be highly appreciated.

答:
Migrate your project to androidx
Steps to do so :- Refactor>Migrate to Androidx
it will download the necessary files your error should be gone !!

Body:
I am new to android programming and trying to build this android project in udacity's basic android course. But after updating to latest android studio bumblebee version, its starting to throws these errors:

Cannot resolve symbol 'v7'

Cannot resolve symbol 'AppCompatActivity'.

The import statement is grayed out.

import android.support.v7.app.AppCompatActivity;

My build.gradle is

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25

    defaultConfig {
        applicationId "com.example.android.explicitintent"
        minSdkVersion 15
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:25.4.0'

}

I have tried the following, but still it doesn't work:

Clean Project

Restart and Invalidated cache

Deleted .idea folder and reopened project

But nothing seems to work so far. Your help will be highly appreciated.


问:
VS Code "Show Search" View is shown as "Source Control"
When I do "Ctrl + Shift + f", the "Show Search" View is displayed but the icon on the Activity Bar show it as Source Control and at the top of the "Show Search" View, the Source Control Repository is being displayed. I have disabled all extensions and look around for a settings that I might messed up but cannot find anything.

Does anyone know how to get the Search icon back for the Show Search View and remove the Source Control repository section from the Search View?

VS Code version is 1.64

答:
simply go to keyboard shortcuts in vscode and search for search:find in files

Then you can easily change your desired shortcut


问:
How to collect a list of random numbers in ranges?
I have a list of numbers not in order 8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205, and it is a very important to me to make this list of numbers in ranges, like this :  8-10,25,47-55,102,107,111,201-205,
I'm familiar with shell scripting, but i couldn't find any solution.

答:
Alright, this is a fun little issue, even though you lack showing your Minimal, Complete, and Verifiable Example (MCVE), it's worth adding another approach.

You can make this task easier by keeping a couple of flag (or state) variables. Simple variables that are either 1 or 0 (true or false) that keep track of whether you have written your first value yet, and whether you are in a sequence of numbers or between ranges of sequential numbers. When you loop over the values, if you keep the last value from the prior iteration, the task become fairly easy.

For example you can do:

#!/bin/bash

list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205

first=0     ## first value written flag
inseq=0     ## in sequence flag

while read -r n; do   ## read each of the sorted values
  ## if first not written, write, set last to current and set first flag
  [ "$first" -eq 0 ] && { printf "%s" "$n"; last="$n"; first=1; continue; }
  ## if current minus last is 1 -- in sequence, set inseq flag
  if ((n - last == 1)); then
    inseq=1
  elif [ "$inseq" -eq 1 ]; then         ## if not sequential
    printf -- "-%s,%s" "$last" "$n"     ## finish with last, output next
    inseq=0                             ## unset inseq flag
  else
    printf ",%s" "$n"                   ## individual number, print
  fi
  last="$n"                             ## set last to current
        ## process substitution sorts list with printf trick
done < <(IFS=$','; printf "%s\n" $list | sort -n)

## output final term either ending sequence or as individual number
if [ "$inseq" -gt 0 ]; then
  printf -- "-%s" "$last"
else
  printf ",%s" "$last"
fi

echo ""   ## tidy up with a newline
```
<p>You state your numbers are not in order, so the <code>while()</code> loop is fed by a process substitution that sorts the values with <code>sort -n</code> before the values are read. (the unquoted <code>$list</code> in the process substitution is intentional)</p>
<p><strong>Example Use/Output</strong></p>
<pre class="lang-none prettyprint-override"><code>$ bash ranges.sh
8-10,25,47-55,102,107,111,201-205
</code>```

Body:
Alright, this is a fun little issue, even though you lack showing your Minimal, Complete, and Verifiable Example (MCVE), it's worth adding another approach.

You can make this task easier by keeping a couple of flag (or state) variables. Simple variables that are either 1 or 0 (true or false) that keep track of whether you have written your first value yet, and whether you are in a sequence of numbers or between ranges of sequential numbers. When you loop over the values, if you keep the last value from the prior iteration, the task become fairly easy.

For example you can do:

#!/bin/bash

list=8,9,10,25,47,48,49,50,51,52,53,54,55,102,107,111,201,202,203,204,205

first=0     ## first value written flag
inseq=0     ## in sequence flag

while read -r n; do   ## read each of the sorted values
  ## if first not written, write, set last to current and set first flag
  [ "$first" -eq 0 ] && { printf "%s" "$n"; last="$n"; first=1; continue; }
  ## if current minus last is 1 -- in sequence, set inseq flag
  if ((n - last == 1)); then
    inseq=1
  elif [ "$inseq" -eq 1 ]; then         ## if not sequential
    printf -- "-%s,%s" "$last" "$n"     ## finish with last, output next
    inseq=0                             ## unset inseq flag
  else
    printf ",%s" "$n"                   ## individual number, print
  fi
  last="$n"                             ## set last to current
        ## process substitution sorts list with printf trick
done < <(IFS=$','; printf "%s\n" $list | sort -n)

## output final term either ending sequence or as individual number
if [ "$inseq" -gt 0 ]; then
  printf -- "-%s" "$last"
else
  printf ",%s" "$last"
fi

echo ""   ## tidy up with a newline

You state your numbers are not in order, so the while() loop is fed by a process substitution that sorts the values with sort -n before the values are read. (the unquoted $list in the process substitution is intentional)

Example Use/Output

$ bash ranges.sh
8-10,25,47-55,102,107,111,201-205