问:
What is the scope of global variables between two functions
I am but confused over here. Should I declare a variable a global variable if it is already set in a function?
I mean

```<code>def function1():
   global var1, var2
   var1 = 2
   var2 = 3

def function2():
   global var1, var2    <-------Should i mention in every function where I use those variable?
   ans = var1 + var 2
</code>```

If it is not required, then can I do like this ?

```<code>def function 1():
    var1 = 2
    var2 = 4

def funciton2():
   ans = var1+var2

def function3():
   global var1, var2
   (no codes here)
</code>```

Is there a way to get list of all variables used in script and sort out which of them are global ?

答:
You need to use global in any function that will assign a value to that variable. global tells the function that the name isn't in its local namespace. When you just use the variable, python will try the local namespace, not find the variable, and then fall back to the global namespace. When you try to set a variable, python can't know whether you meant a local variable that happens to have the same name or a global one. Hence the global decoration.

In your first example, you need global in function1 because you assign the variables.

```<code>def function1():
   global var1, var2
   var1 = 2
   var2 = 3
</code>```

You don't need it in function2 because you only use them, you don't assign anything to them.

```<code>def function2():
   ans = var1 + var2
</code>```

Body:
I am but confused over here. Should I declare a variable a global variable if it is already set in a function?
I mean

def function1():
   global var1, var2
   var1 = 2
   var2 = 3

def function2():
   global var1, var2    <-------Should i mention in every function where I use those variable?
   ans = var1 + var 2

If it is not required, then can I do like this ?

def function 1():
    var1 = 2
    var2 = 4

def funciton2():
   ans = var1+var2

def function3():
   global var1, var2
   (no codes here)

Is there a way to get list of all variables used in script and sort out which of them are global ?

Body:
You need to use global in any function that will assign a value to that variable. global tells the function that the name isn't in its local namespace. When you just use the variable, python will try the local namespace, not find the variable, and then fall back to the global namespace. When you try to set a variable, python can't know whether you meant a local variable that happens to have the same name or a global one. Hence the global decoration.

In your first example, you need global in function1 because you assign the variables.

def function1():
   global var1, var2
   var1 = 2
   var2 = 3

You don't need it in function2 because you only use them, you don't assign anything to them.

def function2():
   ans = var1 + var2


来源: stackexchange

问:
Get Blobs with no metadata
I am setting blob metadata of all the blobs in a container using an azure function. But due to huge number of blobs the function time outs. If I run the function again it again starts getting the blobs which already have metadata. Is there a way in which I can get only the blobs which do not have metadata?</p>

答: The question does not contain examples, but maybe it is possible to specify parameters in the call to get more accurately what you want?</p>

ContentLicense: CC BY-SA 4.0

Title: Get Blobs with no metadata


问:
How to exclude embeded Tomcat in Spring Boot application
How can we exclude embedded Tomcat server from Spring Boot application so that we can run that jar on JBoss Server?</p>

答:
Add the <exclusions> tag in dependency with <artificatId> as 'spring-boot-starter-web'

```<code><exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
</exclusions>
</code>```

Your final dependency should look like:

```<code><dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
</dependencies>
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Add the <exclusions> tag in dependency with <artificatId> as 'spring-boot-starter-web'

<exclusions>
    <exclusion>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-tomcat</artifactId>
    </exclusion>
</exclusions>

Your final dependency should look like:

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
</dependencies>


答:
You can use globals() to give you a dictionary of global variables.
You only need to use the keyword global if you plan to update a global variable, not if you are trying to access its value

You do need to assign them outside of the function so in your case

```<code>var1 = 1 # outside function, can be used as global variable
var2 = 2

def function1():
   global var1, var2
   var1 = 2 # as global is used, from here on var1 will have the value 2
   var2 = 3

def function2():
# as you are not assigning a value to var1,2 but only access their value so
# you do not need to use the global keyword
   ans = var1 + var2
</code>```

Title: What is the scope of global variables between two functions

Body:
You can use globals() to give you a dictionary of global variables.
You only need to use the keyword global if you plan to update a global variable, not if you are trying to access its value

You do need to assign them outside of the function so in your case

var1 = 1 # outside function, can be used as global variable
var2 = 2

def function1():
   global var1, var2
   var1 = 2 # as global is used, from here on var1 will have the value 2
   var2 = 3

def function2():
# as you are not assigning a value to var1,2 but only access their value so
# you do not need to use the global keyword
   ans = var1 + var2


问:
Does anyone have a backup strategy for SQL Azure databases?
I'm using SQL Azure on a project and it works great.  The problem is that the usual backup features do not exist.  I have exported the database a couple of times using SQLAzureMW ( http://sqlazuremw.codeplex.com/ ) but this tool is now choking trying to download the database data with bcp.  In any case, it's not as nice a solution as SQL Server backups.

Is anyone aware of a commercial or open source tool, or other technique, for making reliable backups of SQL Azure databases?  This is really a showstopper.

答: SQL Azure will support PIT (Point in time) backup/restore (mainly restore) later this year (2011), CTP in summer. There is some (little) preliminary info here info here.</p>

ContentLicense: CC BY-SA 2.5


问:
start adb server in wireless mode without connecting actual device via usb
sometimes, I forget to carry USB cable and need to connect android phone over wifi to use adb!! But the problem is adb can't be started in tcpip mode without connecting phone via USB!! what should I do??</p>

答:
you either need to have a device connected or an running emulator for using following command:

adb tcpip 5555

what if you don't have usb cable for some reason? what to do? here's a solution. If you run an android emulator, above command will work but draw back is , it take too much time (few minutes to be specific). So what's the fastest solution,

Well, install AnBox. Its also an emulator which opens much faster, within few seconds. now, you can run above command:

adb tcpip 5555

to start adb in tcpip mode

use below command to connect to your android phone over wifi

adb connect :5555


问:
ReactJS conditionally combining 2 states in a loop
im attempting to convert a vue project to a react based project and im facing the following problem. I wish to combine 2 different states together via a loop conditionally. Here is what my code looks like :

```<code>transitions:{
             {id : 1 , is_done : true , is_cancelled : false} ,
             {id : 2 , is_done : false , is_cancelled: false}
                       }
state_class_mapping: {}

pending_state_class: {
         #bunch of styling
        },
        done_state_class: {
          #bunch of styling
        },
        cancelled_state_class: {
          #bunch of styling
        },
        current_state_class: {
         #bunch of styling
        }
</code>```

Next , what i wish to do is to run through the transition state , and combine the styling with each transition based on the conditions : is_done and is_cancelled. The code below is an idea of what im trying to accomplish , but i know it would not work.

```<code>#in my code , transitions is taken from an api endpoint

        var that = this;
        var newState = {}
        this.state.transition.forEach(transition => {
          if (transition.is_done) {
            #Code to "combine" the styling and the transition
          } else if (transition.is_cancelled) {
           #Code to "combine" the styling and the transition
          } else {
           #Code to "combine" the styling and the transition
          }
        })
         this.setState(state_class_mapping:newState);
    })
</code>```

After which , i would use the setState to update the state_class_mapping

The end state should look  a little something like :

```<code>state_class_mapping: {
           {id : 1 ,
            is_done : true ,
            is_cancelled : false ,
            rect : xxxx ,  #extracted from the styling
            fill : xxxx ,
            } ,
                       }
</code>```

答:
TLDR;

Spread Operators to combine objects.

So, your transition state looks like this;

```<code>transitions = [
  {id : 1 , is_done : true , is_cancelled : false} ,
  {id : 2 , is_done : false , is_cancelled: false}
]
</code>```

And to combine with another state based on the transition what you could do is create a function that takes in transition and spit out new state like;

```<code>const giveMeNewState = (transition) => {
   if(transition.is_done){
     return { ...transition,
       ...{
          newShinyState: true,
          somethingElse: true
       }
     }
   }
   return { ...transition, ...{ defaultStyle: "abc" } };
}
</code>```

And then later call the function to get the states.

EXTRA:

But in this case what I would like to do is create a map with key of state and value of style properties. like;

```<code> const stateMap = {
    "COMPLETE": {
       showShinyCompleteButton: true
    },
    "LOADING": {
       showLoadingSpinner: true
    }
 }

</code>```

and then later setState using stateMap[transition] to return the state and avoid using jumble of if and else altogether. But its not always that you can avoid using if and else altogether.

Body:
im attempting to convert a vue project to a react based project and im facing the following problem. I wish to combine 2 different states together via a loop conditionally. Here is what my code looks like :

transitions:{
             {id : 1 , is_done : true , is_cancelled : false} ,
             {id : 2 , is_done : false , is_cancelled: false}
                       }
state_class_mapping: {}

pending_state_class: {
         #bunch of styling
        },
        done_state_class: {
          #bunch of styling
        },
        cancelled_state_class: {
          #bunch of styling
        },
        current_state_class: {
         #bunch of styling
        }

Next , what i wish to do is to run through the transition state , and combine the styling with each transition based on the conditions : is_done and is_cancelled. The code below is an idea of what im trying to accomplish , but i know it would not work.

#in my code , transitions is taken from an api endpoint

        var that = this;
        var newState = {}
        this.state.transition.forEach(transition => {
          if (transition.is_done) {
            #Code to "combine" the styling and the transition
          } else if (transition.is_cancelled) {
           #Code to "combine" the styling and the transition
          } else {
           #Code to "combine" the styling and the transition
          }
        })
         this.setState(state_class_mapping:newState);
    })

After which , i would use the setState to update the state_class_mapping

The end state should look  a little something like :

state_class_mapping: {
           {id : 1 ,
            is_done : true ,
            is_cancelled : false ,
            rect : xxxx ,  #extracted from the styling
            fill : xxxx ,
            } ,
                       }

Body:
TLDR;

Spread Operators to combine objects.

So, your transition state looks like this;

transitions = [
  {id : 1 , is_done : true , is_cancelled : false} ,
  {id : 2 , is_done : false , is_cancelled: false}
]

And to combine with another state based on the transition what you could do is create a function that takes in transition and spit out new state like;

const giveMeNewState = (transition) => {
   if(transition.is_done){
     return { ...transition,
       ...{
          newShinyState: true,
          somethingElse: true
       }
     }
   }
   return { ...transition, ...{ defaultStyle: "abc" } };
}

And then later call the function to get the states.

EXTRA:

But in this case what I would like to do is create a map with key of state and value of style properties. like;

 const stateMap = {
    "COMPLETE": {
       showShinyCompleteButton: true
    },
    "LOADING": {
       showLoadingSpinner: true
    }
 }

and then later setState using stateMap[transition] to return the state and avoid using jumble of if and else altogether. But its not always that you can avoid using if and else altogether.


问:
Trouble Installing babel's "plugin-proposal-export-default-from"
I'm very new to React/Javascript/dependency stuff so the other answers I've seen for similar questions were not entirely clear to me:

I'm trying to implement a pie chart for my react project as described here: https://canvasjs.com/react-charts/pie-chart/

I created my project with create-react-app and then ran npm install canvasjs inside.

Then I get the following error when running npm start: "Add @babel/plugin-proposal-export-default-from (https://git.io/vb4yH) to the 'plugins' section of your Babel config to enable transformation."

When looking up the error, I found this website: https://babeljs.io/docs/en/babel-plugin-proposal-export-default-from ,which says to run the following command:

npm install --save-dev @babel/plugin-proposal-export-default-from

This wasn't working (would get a warning about needing to install dependencies), so I read online that to modify Babel, you had to run npm run eject and then change the Python path version to 2.7. I did that and now the command works to install the packages.

I found this old discussion where people mention it being a bug: https://github.com/babel/babel/issues/7293

They said to change stuff in the babel.config.js file as a solution, but I don't know where that file is located (it doesn't appear when I search it up). I'm on a Mac OS.

Any help would be greatly appreciated!

答:
You have to create the file at the same location as your package.json file.

This is how the file contents looks like

```

    /* eslint-disable func-names */
    module.exports = function (api) {
      const presets = [
        '@babel/preset-env',
        '@babel/preset-react',
        '@babel/preset-flow'
      ];
      const plugins = [
        [
          '@babel/plugin-transform-spread',
          {
            loose: true
          }
        ],
        [
          '@babel/plugin-proposal-class-properties',
          {
            loose: true
          }
        ],
        '@babel/plugin-transform-runtime'
      ];

      /** this is just for minimal working purposes,
         * for testing larger applications it is
         * advisable to cache the transpiled modules in
         * node_modules/.bin/.cache/@babel/register* */
      api.cache(false);

      return {
        presets,
        plugins
      };
    };

```

Body:
You have to create the file at the same location as your package.json file.

This is how the file contents looks like

    /* eslint-disable func-names */
    module.exports = function (api) {
      const presets = [
        '@babel/preset-env',
        '@babel/preset-react',
        '@babel/preset-flow'
      ];
      const plugins = [
        [
          '@babel/plugin-transform-spread',
          {
            loose: true
          }
        ],
        [
          '@babel/plugin-proposal-class-properties',
          {
            loose: true
          }
        ],
        '@babel/plugin-transform-runtime'
      ];

      /** this is just for minimal working purposes,
         * for testing larger applications it is
         * advisable to cache the transpiled modules in
         * node_modules/.bin/.cache/@babel/register* */
      api.cache(false);

      return {
        presets,
        plugins
      };
    };


问:
MySQL query slow querying table on primary key
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

```<code>+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
</code>```

create table:

```<code>CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code>```

答:
Try using the minimum size of id as possible.  If it's a numeric key that you know will never be larger than a few million, you could use a MEDIUMINT UNSIGNED and save yourself a byte for each record over an INT, which might speed up searches a little.  Still, 3 GB is an awful lot for just 350,000 rows.

It sounds like you might also get some bang for your buck by using the partitioning feature to split your table up into logical units.  You might want to Google "mysql vertical partitioning" in particular; if there are large columns that you don't access frequently, it would be much more efficient to move them out into a separate table and only query it when you need it.

Body:
So I have a table that's being used basically like a NoSQL setup. The structure is:

id bigint primary key
data mediumblob
modified timestamp

It has around 350k rows. The queries that run on it are all structured as follows:

select data from table where id=XXX;

The table engine is InnoDB. I'm noticing that sometimes queries run against this table are rather slow. Sometimes they take 3 seconds to run. The table is 3 GB on disk and I gave the innodb_buffer_pool_size 4G.

Is there anything I'm missing here? Are there any settings I can tweak to improve performance?

Edit: As requested explain output:

+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
| id | select_type | table    | type  | possible_keys | key     | key_len | ref   | rows | Extra |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+
|  1 | SIMPLE      | cache    | const | PRIMARY       | PRIMARY | 8       | const |    1 |       |
+----+-------------+----------+-------+---------------+---------+---------+-------+------+-------+

create table:

CREATE TABLE `cache` (
  `id` bigint(20) unsigned NOT NULL DEFAULT '0',
  `data` mediumblob,
  `modified` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


问:
How to add toastr JS notification on application level in Ruby on Rails
I am using toastr gem for my notifications. I am trying to add a toastr notification to my application whenever a method on my application_controller.rb is active.

```<code>rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

    def user_not_authorized
      toastr.info('You cannot access this page.', 'info')
      redirect_to contacts_path
    end
</code>```

As you can see I tried to add toastrfunction on my controller, however this doesn't work. How can I show this toastr notification whenever this method hits or simply whenever a non-admin user access an unathorized page?

答:
To build on the first answer, this is what I did in my app. Added what I wanted to show to flash in the controller and then show the flash messages in toastr

I'm using the great slim extension there, add it with gem 'slim-rails' and save this file as _messages.html.slim, you can then include it in your layout file.

```<code>- flash.each do |name, msg|
  javascript:
    window.onload = function() {
      var name = "#{name}";

      if (name == 'info' || name == 'notice') {
        toastr.info("#{msg}");
      }
      else if (name == 'success') {
        toastr.success("#{msg}");
      }
      else if (name == 'error') {
        toastr.error("#{msg}");
      }
      else {
        toastr.info("#{msg}");
      }
    };
</code>```

Body:
I am using toastr gem for my notifications. I am trying to add a toastr notification to my application whenever a method on my application_controller.rb is active.

rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized

    def user_not_authorized
      toastr.info('You cannot access this page.', 'info')
      redirect_to contacts_path
    end

As you can see I tried to add toastrfunction on my controller, however this doesn't work. How can I show this toastr notification whenever this method hits or simply whenever a non-admin user access an unathorized page?

Body:
To build on the first answer, this is what I did in my app. Added what I wanted to show to flash in the controller and then show the flash messages in toastr

I'm using the great slim extension there, add it with gem 'slim-rails' and save this file as _messages.html.slim, you can then include it in your layout file.

- flash.each do |name, msg|
  javascript:
    window.onload = function() {
      var name = "#{name}";

      if (name == 'info' || name == 'notice') {
        toastr.info("#{msg}");
      }
      else if (name == 'success') {
        toastr.success("#{msg}");
      }
      else if (name == 'error') {
        toastr.error("#{msg}");
      }
      else {
        toastr.info("#{msg}");
      }
    };


问:
Why can't an inherited protected constructor be made public?
Consider:

```<code>class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}
</code>```

Why can't an inherited protected constructor be made public, while an inherited protected member function can?

答:
Unlike other members, the accessibility of the using-declaration that introduced the inherited constructor is ignored.

[namespace.udecl]/19,

(emphasis mine)

A synonym created by a using-declaration has the usual accessibility for a member-declaration. A using-declarator that names a constructor does not create a synonym; instead, the additional constructors are accessible if they would be accessible when used to construct an object of the corresponding base class, and the accessibility of the using-declaration is ignored.

Body:
Consider:

class A
{
protected:
    A(int) {}
    void f(int) {}

public:
    A() {}
};

class B : public A
{
public:
    using A::A;
    using A::f;
};

int main()
{
    B().f(1); // ok
    B(1); // error: 'A::A(int)' is protected within this context
}

Why can't an inherited protected constructor be made public, while an inherited protected member function can?


问:
How to get a list of all months from current month to a month in the past using moment.js
I'm trying to generate a list of months starting from April 2020 to a month in the past ( October 2019 ) using moment.js.

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script></code>```

I get only 5 months as a result. Could anyone please help?

答:
Something like this?

const start = moment().startOf('month')
const end = moment('10-01-2018', 'MM-DD-YYYY')

let results = []
let current = start
while (current.format('MMMM YYYY') !== end.format('MMMM YYYY')) {
  results.push(current.format('MMMM YYYY'))
  current = current.subtract(1, 'month')
}
// need to add current one last time because the loop will have ended when it is equal to the end date, and will not have added it
results.push(current.format('MMMM YYYY'))

console.log(results)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script></code>```

Body:
I'm trying to generate a list of months starting from April 2020 to a month in the past ( October 2019 ) using moment.js.

const start = moment().startOf('month')
const startMonth = moment('10-01-2019', 'MM-DD-YYYY').format('MMMM YYYY')
const month = moment().startOf('month').format('MM')
for (let i = 0; i < month; i++) {
  const m = start.subtract(1, 'month').format('MMMM YYYY')
  if (m === startMonth) {
    break;
  }
  console.log(m)
}

I get only 5 months as a result. Could anyone please help?

Body:
Something like this?

const start = moment().startOf('month')
const end = moment('10-01-2018', 'MM-DD-YYYY')

let results = []
let current = start
while (current.format('MMMM YYYY') !== end.format('MMMM YYYY')) {
  results.push(current.format('MMMM YYYY'))
  current = current.subtract(1, 'month')
}
// need to add current one last time because the loop will have ended when it is equal to the end date, and will not have added it
results.push(current.format('MMMM YYYY'))

console.log(results)

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js" integrity="sha256-5oApc/wMda1ntIEK4qoWJ4YItnV4fBHMwywunj8gPqc=" crossorigin="anonymous"></script>


问:
JSONDecoder crashing on TestFlight / AppStore
I am working on my Apple Watch app. Most of my components use JSON and use the Swift Codable protocol to decode JSON.
Now I wanted to prepare my release, but I received a message by a Beta tester that the App was always crashing on his Series 3.

After I installed the TestFlight build on my Series 3 I could reproduce the issue.
The crash logs from TestFlight and the crash logs extracted from my iPhone indicate that the crash is happening while the JSON gets decoded.

I have rather complex JSON structures, but I did not do any changes to them since the last update. Furthermore, decoding JSON works fine on Xcode builds (also on Series 3) and on newer Apple Watches (Series 4 + 5). I am struggling to find out what could cause the issue.
I discovered a post in the Apple developer forums with a similar issue, but without a solution to it: https://forums.developer.apple.com/thread/124627

Here's a part of the Stacktrace of my crash log:

```<code>Date/Time:           2020-02-05 08:37:42.9924 +0100
Launch Time:         2020-02-05 08:37:40.0000 +0100
OS Version:          Watch OS 6.1.2 (17S5792a)
Release Type:        User
Baseband Version:    4.40.02
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x4d9aefc8 __pthread_kill + 8
1   libsystem_pthread.dylib         0x4da260be pthread_kill + 108
2   libsystem_c.dylib               0x4d9383a4 abort + 84
3   libswiftCore.dylib              0x6cffbade swift_vasprintf+ 2341598 (char**, char const*, char*) + 0
4   libswiftCore.dylib              0x6d00932c swift::TargetMetadata<swift::InProcess>::getGenericArgs+ 2396972 () const + 0
5   libswiftCore.dylib              0x6d00508c _swift_initClassMetadataImpl+ 2379916 (swift::TargetClassMetadata<swift::InProcess>*, swift::ClassLayoutFlags, unsigned long, swift::TypeLayout const* const*, unsigned long*, bool) + 28
6   libswiftCore.dylib              0x6d005c86 swift_initClassMetadata2 + 22
7   libswiftCore.dylib              0x6cfdc6fc type metadata completion function for _KeyedDecodingContainerBox + 50
8   libswiftCore.dylib              0x6d00a6c2 swift::MetadataCacheEntryBase<(anonymous namespace)::GenericCacheEntry, void const*>::doInitialization+ 2401986 (swift::ConcurrencyControl&, swift::MetadataCompletionQueueEntry*, swift::MetadataRequest) + 178
9   libswiftCore.dylib              0x6d003a0c swift_getGenericMetadata + 1124
10  libswiftCore.dylib              0x6cdf4210 KeyedDecodingContainer.init<A>+ 213520 (_:) + 40
11  libswiftFoundation.dylib        0x6d156e0a __JSONDecoder.container<A>+ 323082 (keyedBy:) + 678
12  libswiftFoundation.dylib        0x6d1a3a1c protocol witness for Decoder.container<A>+ 637468 (keyedBy:) in conformance __JSONDecoder + 18
13  libswiftFoundation.dylib        0x6d1592b6 protocol witness for Decoder.container<A>+ 332470 (keyedBy:) in conformance __JSONDecoder + 32
14  libswiftCore.dylib              0x6cfdb1cc dispatch thunk of Decoder.container<A>+ 2208204 (keyedBy:) + 24
15  WatchSonos WatchKit Extension   0x00440bf2 0x358000 + 953330
16  WatchSonos WatchKit Extension   0x0043d08c 0x358000 + 938124
17  libswiftCore.dylib              0x6cfdb156 dispatch thunk of Decodable.init+ 2208086 (from:) + 12
18  libswiftFoundation.dylib        0x6d16fbee __JSONDecoder.unbox_+ 424942 (_:as:) + 4014
19  libswiftFoundation.dylib        0x6d156816 JSONDecoder.decode<A>+ 321558 (_:from:) + 642
20  libswiftFoundation.dylib        0x6d22af98 dispatch thunk of JSONDecoder.decode<A>+ 1191832 (_:from:) + 28
21  WatchSonos WatchKit Extension   0x0045db0c 0x358000 + 1071884
22  WatchSonos WatchKit Extension   0x00461cce 0x358000 + 1088718
23  WatchSonos WatchKit Extension   0x00461bde 0x358000 + 1088478
24  WatchSonos WatchKit Extension   0x00420ffa 0x358000 + 823290
25  WatchSonos WatchKit Extension   0x00425914 0x358000 + 842004
26  libdispatch.dylib               0x4d851846 _dispatch_call_block_and_release + 10
27  libdispatch.dylib               0x4d8528b8 _dispatch_client_callout + 6
28  libdispatch.dylib               0x4d85c6b0 _dispatch_main_queue_callback_4CF + 868
29  CoreFoundation                  0x4dcdbbaa __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 10
30  CoreFoundation                  0x4dcd7c00 __CFRunLoopRun + 1832
31  CoreFoundation                  0x4dcd723a CFRunLoopRunSpecific + 370
32  GraphicsServices                0x50aebcd0 GSEventRunModal + 96
33  UIKitCore                       0x65c91580 UIApplicationMain + 1730
34  libxpc.dylib                    0x4da73c80 _xpc_objc_main.cold.3 + 152
35  libxpc.dylib                    0x4da649b0 _xpc_objc_main + 184
36  libxpc.dylib                    0x4da668c4 xpc_main + 110
37  Foundation                      0x4e56b0c6 +[NSXPCListener serviceListener] + 0
38  PlugInKit                       0x556d726c 0x556c5000 + 74348
39  WatchKit                        0x5cfe9afe WKExtensionMain + 62
40  WatchKit                        0x5d09f020 main + 10
</code>```

Here's the position in the code that crashes:

    required public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try values.decode(String.self, forKey: .id)

        do {

            if values.contains(.groups) {
                let groups = try values.decode(Dictionary<String, SonosGroup>.self, forKey: .groups)
                self.groups = groups
            }

            if values.contains(.players) {
                let players = try values.decode(Array<SonosPlayer>.self, forKey: .players)
                self.players = players
            }

        }catch let error {
            print("Error decoding groups \(error)")
        }

    }
```

For me this looks like an Apple bug and I filed feedback for it, but this is no solution for the next release.

Does anyone know what's the difference between a TestFlight build and an Xcode release build?
I tried setting a different optimization level, disabling bitcode (not allowed for Apple Watch Apps) and I started replacing Codable with the good old JSONSerialization.

If anyone knows more about it, thank you for that.

Kind regards
Alex

答:
I was having a very similar problem with Encodable and Decodable's in a swift package. Setting DEAD_CODE_STRIPPING = NO in my apps target fixed it. This seems to be a weird leftover of this bug:
https://bugs.swift.org/browse/SR-11564?focusedCommentId=51285&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-51285

Body:
I am working on my Apple Watch app. Most of my components use JSON and use the Swift Codable protocol to decode JSON.
Now I wanted to prepare my release, but I received a message by a Beta tester that the App was always crashing on his Series 3.

After I installed the TestFlight build on my Series 3 I could reproduce the issue.
The crash logs from TestFlight and the crash logs extracted from my iPhone indicate that the crash is happening while the JSON gets decoded.

I have rather complex JSON structures, but I did not do any changes to them since the last update. Furthermore, decoding JSON works fine on Xcode builds (also on Series 3) and on newer Apple Watches (Series 4 + 5). I am struggling to find out what could cause the issue.
I discovered a post in the Apple developer forums with a similar issue, but without a solution to it: https://forums.developer.apple.com/thread/124627

Here's a part of the Stacktrace of my crash log:

Date/Time:           2020-02-05 08:37:42.9924 +0100
Launch Time:         2020-02-05 08:37:40.0000 +0100
OS Version:          Watch OS 6.1.2 (17S5792a)
Release Type:        User
Baseband Version:    4.40.02
Report Version:      104

Exception Type:  EXC_CRASH (SIGABRT)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Triggered by Thread:  0

Application Specific Information:
abort() called

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x4d9aefc8 __pthread_kill + 8
1   libsystem_pthread.dylib         0x4da260be pthread_kill + 108
2   libsystem_c.dylib               0x4d9383a4 abort + 84
3   libswiftCore.dylib              0x6cffbade swift_vasprintf+ 2341598 (char**, char const*, char*) + 0
4   libswiftCore.dylib              0x6d00932c swift::TargetMetadata<swift::InProcess>::getGenericArgs+ 2396972 () const + 0
5   libswiftCore.dylib              0x6d00508c _swift_initClassMetadataImpl+ 2379916 (swift::TargetClassMetadata<swift::InProcess>*, swift::ClassLayoutFlags, unsigned long, swift::TypeLayout const* const*, unsigned long*, bool) + 28
6   libswiftCore.dylib              0x6d005c86 swift_initClassMetadata2 + 22
7   libswiftCore.dylib              0x6cfdc6fc type metadata completion function for _KeyedDecodingContainerBox + 50
8   libswiftCore.dylib              0x6d00a6c2 swift::MetadataCacheEntryBase<(anonymous namespace)::GenericCacheEntry, void const*>::doInitialization+ 2401986 (swift::ConcurrencyControl&, swift::MetadataCompletionQueueEntry*, swift::MetadataRequest) + 178
9   libswiftCore.dylib              0x6d003a0c swift_getGenericMetadata + 1124
10  libswiftCore.dylib              0x6cdf4210 KeyedDecodingContainer.init+ 213520 (_:) + 40
11  libswiftFoundation.dylib        0x6d156e0a __JSONDecoder.container+ 323082 (keyedBy:) + 678
12  libswiftFoundation.dylib        0x6d1a3a1c protocol witness for Decoder.container+ 637468 (keyedBy:) in conformance __JSONDecoder + 18
13  libswiftFoundation.dylib        0x6d1592b6 protocol witness for Decoder.container+ 332470 (keyedBy:) in conformance __JSONDecoder + 32
14  libswiftCore.dylib              0x6cfdb1cc dispatch thunk of Decoder.container+ 2208204 (keyedBy:) + 24
15  WatchSonos WatchKit Extension   0x00440bf2 0x358000 + 953330
16  WatchSonos WatchKit Extension   0x0043d08c 0x358000 + 938124
17  libswiftCore.dylib              0x6cfdb156 dispatch thunk of Decodable.init+ 2208086 (from:) + 12
18  libswiftFoundation.dylib        0x6d16fbee __JSONDecoder.unbox_+ 424942 (_:as:) + 4014
19  libswiftFoundation.dylib        0x6d156816 JSONDecoder.decode+ 321558 (_:from:) + 642
20  libswiftFoundation.dylib        0x6d22af98 dispatch thunk of JSONDecoder.decode+ 1191832 (_:from:) + 28
21  WatchSonos WatchKit Extension   0x0045db0c 0x358000 + 1071884
22  WatchSonos WatchKit Extension   0x00461cce 0x358000 + 1088718
23  WatchSonos WatchKit Extension   0x00461bde 0x358000 + 1088478
24  WatchSonos WatchKit Extension   0x00420ffa 0x358000 + 823290
25  WatchSonos WatchKit Extension   0x00425914 0x358000 + 842004
26  libdispatch.dylib               0x4d851846 _dispatch_call_block_and_release + 10
27  libdispatch.dylib               0x4d8528b8 _dispatch_client_callout + 6
28  libdispatch.dylib               0x4d85c6b0 _dispatch_main_queue_callback_4CF + 868
29  CoreFoundation                  0x4dcdbbaa __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 10
30  CoreFoundation                  0x4dcd7c00 __CFRunLoopRun + 1832
31  CoreFoundation                  0x4dcd723a CFRunLoopRunSpecific + 370
32  GraphicsServices                0x50aebcd0 GSEventRunModal + 96
33  UIKitCore                       0x65c91580 UIApplicationMain + 1730
34  libxpc.dylib                    0x4da73c80 _xpc_objc_main.cold.3 + 152
35  libxpc.dylib                    0x4da649b0 _xpc_objc_main + 184
36  libxpc.dylib                    0x4da668c4 xpc_main + 110
37  Foundation                      0x4e56b0c6 +[NSXPCListener serviceListener] + 0
38  PlugInKit                       0x556d726c 0x556c5000 + 74348
39  WatchKit                        0x5cfe9afe WKExtensionMain + 62
40  WatchKit                        0x5d09f020 main + 10

Here's the position in the code that crashes:

    required public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        self.id = try values.decode(String.self, forKey: .id)

        do {

            if values.contains(.groups) {
                let groups = try values.decode(Dictionary<String, SonosGroup>.self, forKey: .groups)
                self.groups = groups
            }

            if values.contains(.players) {
                let players = try values.decode(Array<SonosPlayer>.self, forKey: .players)
                self.players = players
            }

        }catch let error {
            print("Error decoding groups \(error)")
        }

    }

For me this looks like an Apple bug and I filed feedback for it, but this is no solution for the next release.

Does anyone know what's the difference between a TestFlight build and an Xcode release build?
I tried setting a different optimization level, disabling bitcode (not allowed for Apple Watch Apps) and I started replacing Codable with the good old JSONSerialization.

If anyone knows more about it, thank you for that.

Kind regards
Alex


问:
Java one liner to create a list of String, add contents of another List<String> and return a List
How to create a List of String then add all the contents of another List to it and then return that list??

Consider a function:

```<code>public List<String> foo() {
  return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}
</code>```

A Class MyConstants:

```<code>public MyConstants {
  public static final String myConst = "String from Constant File";
}
</code>```

I am writing a function bar() and need a one liner to return a list:

```<code>public List<String> bar() {
    return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo());
}
</code>```

But addAll() returns boolean. Also, when I tried

```<code>Arrays.asList(return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo()));
</code>```

It is List<Boolean> for pretty obvious reasons.

How can I create a list, add another list to it and then return that combined list?

答:
Thanks to @gene for the answer, I figured out apache-commons one lesser awful way other than Stream or ImmutableList builder. Here it is </p>

```<code>        return ListUtils.union(Arrays.asList(MyConstants.myConst), foo());

</code>```

Body:
How to create a List of String then add all the contents of another List to it and then return that list??

Consider a function:

public List<String> foo() {
  return Arrays.asList("some", "list", "of", "strings", "from", "foo");
}

A Class MyConstants:

public MyConstants {
  public static final String myConst = "String from Constant File";
}

I am writing a function bar() and need a one liner to return a list:

public List<String> bar() {
    return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo());
}

But addAll() returns boolean. Also, when I tried

Arrays.asList(return new ArrayList<String>(Collections.singleTon(MyConstants.myConst)).addAll(foo()));

It is List<Boolean> for pretty obvious reasons.

How can I create a list, add another list to it and then return that combined list?

Body:
Thanks to @gene for the answer, I figured out apache-commons one lesser awful way other than Stream or ImmutableList builder. Here it is

        return ListUtils.union(Arrays.asList(MyConstants.myConst), foo());


问:
Oversampling for text classification in python?
I have a text data frame that I want to classify. But I need to do oversampling first. Please find sample data below:

```<code>df=[['I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am not going to class today','I am not going to class today','I am not going to class today','I am not going to class today'],['Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Negative','Negative','Negative','Negative']]
df=pd.DataFrame(df)
df=df.transpose()
df.columns=['Features','Class']
df
          Features                       Class
0   I am going to class today       Positive
1   I am going to class today       Positive
2   I am going to class today       Positive
3   I am going to class today       Positive
4   I am going to class today       Positive
5   I am going to class today       Positive
6   I am going to class today       Positive
7   I am going to class today       Positive
8   I am going to class today       Positive
9   I am going to class today       Positive
10  I am not going to class today   Negative
11  I am not going to class today   Negative
12  I am not going to class today   Negative
13  I am not going to class today   Negative

oversample = RandomOverSampler(sampling_strategy='minority')
# fit and apply the transform
X_over, y_over = oversample.fit_resample(df['Features'], df['Class'])
# summarize class distribution
print(Counter(y_over))
</code>```

But this is not working and giving me ValueError: Expected 2D array, got 1D array instead:. How can I oversample this data?

答:
I found the problem. I needed to reshape my data.

```<code>X_over, y_over = oversample.fit_resample(df['Features'].values.reshape(-1,1), df['Class'])
</code>```

This is working now.

```<code>Counter({'Positive': 10, 'Negative': 10})
</code>```

Body:
I have a text data frame that I want to classify. But I need to do oversampling first. Please find sample data below:

df=[['I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am going to class today','I am not going to class today','I am not going to class today','I am not going to class today','I am not going to class today'],['Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Positive','Negative','Negative','Negative','Negative']]
df=pd.DataFrame(df)
df=df.transpose()
df.columns=['Features','Class']
df
          Features                       Class
0   I am going to class today       Positive
1   I am going to class today       Positive
2   I am going to class today       Positive
3   I am going to class today       Positive
4   I am going to class today       Positive
5   I am going to class today       Positive
6   I am going to class today       Positive
7   I am going to class today       Positive
8   I am going to class today       Positive
9   I am going to class today       Positive
10  I am not going to class today   Negative
11  I am not going to class today   Negative
12  I am not going to class today   Negative
13  I am not going to class today   Negative

oversample = RandomOverSampler(sampling_strategy='minority')
# fit and apply the transform
X_over, y_over = oversample.fit_resample(df['Features'], df['Class'])
# summarize class distribution
print(Counter(y_over))

But this is not working and giving me ValueError: Expected 2D array, got 1D array instead:. How can I oversample this data?

Body:
I found the problem. I needed to reshape my data.

X_over, y_over = oversample.fit_resample(df['Features'].values.reshape(-1,1), df['Class'])

This is working now.

Counter({'Positive': 10, 'Negative': 10})


问:
Import scss variable into Angular component
Let's say I have the following Angular component:

```<code>// src/app/app.component.html
<stars [customColor]="blue">
</code>```

And I have the following scss variable:

```<code>// src/_styles.scss
$color: blue;
</code>```

How can I use the scss variable instead of duplicating blue?

To clarify, I want to access $color in app.component.html or app.component.ts.

Apparently it's possible to configure Webpack in a React app but I'm not sure if this is possible in Angular.

答:
In your app.component.scss (or star.component.scss) file just import your styles:

```<code>@import './../_style.scss'
</code>```

Then you can use your scss var

Body:
Let's say I have the following Angular component:

// src/app/app.component.html
<stars [customColor]="blue">

And I have the following scss variable:

// src/_styles.scss
$color: blue;

How can I use the scss variable instead of duplicating blue?

To clarify, I want to access $color in app.component.html or app.component.ts.

Apparently it's possible to configure Webpack in a React app but I'm not sure if this is possible in Angular.

Body:
In your app.component.scss (or star.component.scss) file just import your styles:

@import './../_style.scss'

Then you can use your scss var


问:
Next.js server side api call returns 500 internal server error
I'm finally dipping my toe into the world of server side react using Next.js, however I'm pretty stumped with this issue.

I'm making a call to an API from pages/customer-preferences.tsx using isomorphic-unfetch

```<code>CustomerPreferencesPage.getInitialProps = async () => {
  const res = await fetch(API_URL + '/preference-customer');
  const initialData = await res.json();
  return { initialData };
};
</code>```

All works fine locally in dev mode or once built and ran build > start. To host it I'm running it from a docker container node:10, and when I run this locally all is fine also. The issue only happens once it's deployed.

When I navigate to / and then click a link to /customer-preferences all works as expected. But if I refresh the page or load the page directly at /customer-preferences I see this error from Next.js

So the issue only seems to happen when trying to make the API calls from the server and not the client.

I've also setup a simple express server to use instead, but not sure if this is necessary?!

```<code>const express = require('express');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});
</code>```

When checking the server logs I get this:

```<code>FetchError: request to http://xxx failed, reason: getaddrinfo EAI_AGAIN xxx xxx:80
</code>```

Any help would be greatly appreciated.

答:
No, the server setup is not necessary.

This is happening because the browser/client is not capable of resolving your docker container's hostname. As it stands, the only solution I know of is to check for the req object in getInitialProps (so as to determine which environment the fetch will run in) and call the Docker hostname when on server, localhost when on client. E.g.

```<code>async getInitialProps (ctx) {
    if (ctx.req) // ctx.req exists server-side only
    {
        // call docker-host:port
    }
    else {
        // call localhost:port
    }
}
</code>```

Body:
I'm finally dipping my toe into the world of server side react using Next.js, however I'm pretty stumped with this issue.

I'm making a call to an API from pages/customer-preferences.tsx using isomorphic-unfetch

CustomerPreferencesPage.getInitialProps = async () => {
  const res = await fetch(API_URL + '/preference-customer');
  const initialData = await res.json();
  return { initialData };
};

All works fine locally in dev mode or once built and ran build > start. To host it I'm running it from a docker container node:10, and when I run this locally all is fine also. The issue only happens once it's deployed.

When I navigate to / and then click a link to /customer-preferences all works as expected. But if I refresh the page or load the page directly at /customer-preferences I see this error from Next.js

So the issue only seems to happen when trying to make the API calls from the server and not the client.

I've also setup a simple express server to use instead, but not sure if this is necessary?!

const express = require('express');
const next = require('next');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

app.prepare().then(() => {
  const server = express();

  server.all('*', (req, res) => {
    return handle(req, res);
  });

  server.listen(port, err => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
});

When checking the server logs I get this:

FetchError: request to http://xxx failed, reason: getaddrinfo EAI_AGAIN xxx xxx:80

Any help would be greatly appreciated.

Body:
No, the server setup is not necessary.

This is happening because the browser/client is not capable of resolving your docker container's hostname. As it stands, the only solution I know of is to check for the req object in getInitialProps (so as to determine which environment the fetch will run in) and call the Docker hostname when on server, localhost when on client. E.g.

async getInitialProps (ctx) {
    if (ctx.req) // ctx.req exists server-side only
    {
        // call docker-host:port
    }
    else {
        // call localhost:port
    }
}


问:
Get user group info in keyclock in angular application?
I know keycloak set user info in local storage from where you can get a user name and email id etc. But I wanted to know how can I get details of the group(s) user belong to.  </p>

答:
This question is a bit abstract, but to get the group details, this has to be already available in the JWT token.

Once you create a group and user in Keyclock, you have to map the user to the respective group. A user can be part of one or more groups.

Then you have to create a mapper to add the group details in the  JWT token as follows.

Go to:

Clients > your client name > Mappers

Create a new mapper with following details:

Name : Some unique name
Mapper Type : Group membership
Token Claim Name: groups  (this can be any name, and group details will be available in JWT under this name)

Set all the following selectors in "ON" mode.

Save the changes.

Request for a new token and you will see group details added to JWT token on inspection.

This can be accessed using the respective library that is being used at the client side.

For example if you are using oidc-client in angular, then you can access it at user.profile.groups


问:
I am new in C++, I want to know, why the pure virtual function is used in c++ ?. Why to use pure virtual function?
I am new in C++, I want to know, why the pure virtual function is used in c++ ?. Somewhat I know to make class abstract and force all derived Classes to have implementation. But I want to know what is the situation where only pure virtual function can work ?</p>

答:
Assume you have a certain base class defining a type like GeometricForm which has a virtual function float calculateArea(). You cannot calculate the area for GeometricForm because GeometricForm itself does not define a geometric form (hope this is understandable). But you can create a derived class e.g. Circle of this base class which is an actual geometric form.

You now want to be sure that this derived class implements a valid version of your former virtual function calculateArea(), which will be ensured by the compiler.


问:
how to auto load mobile templates by agent in codeigniter?
```<code>dir:
</code>```

```
application
 -controllers
 -models
 -views
 -mobile_views
```

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

答:
Check this

You can do it in two way.
Way 1: Its very simple. In the above answer (the link I have given) add following line in the end of MyController function

```<code>$this->load->_ci_view_path  . = $this->view_type .'/';
</code>```

You are done. You can simply load view like normal view load.

Way 2:
To autoload a view based on user agent, I think you can implement it using hooks. To implement this hooks you need to follow the following steps

Autoload user agent library in autoload.php

$autoload['libraries'] = array('user_agent');

Enable hooks in config.php

$config['enable_hooks'] = TRUE;

Not implement hooks on post_controller_constructor. Add following codes to hooks.php

$hook['post_controller_constructor'][] = array('class'    => 'Loadview',
                                    'function' => 'load',
                                    'filename' => 'loadview.php',
                                    'filepath' => 'hooks'
                                   );

Now create a page named loadview.php under hooks directory having following code

```
class Loadview
{

    public static $MOBILE_PLATFORM = 'mobile';
    public static $DEFAULT_PLATFORM = 'default';

    public function load(){
        $this->CI =& get_instance();
        $view_type = $this->CI->agent->is_mobile() ? self::$MOBILE_PLATFORM : self::$DEFAULT_PLATFORM;
        $this->CI->load->_ci_view_path = $this->CI->load->_ci_view_path . $view_type .'/';
    }

}
```

You are done now. You can simply load view like normal view load.

Body:
dir:

application
 -controllers
 -models
 -views
 -mobile_views

How do I auto load templates at mobile_views when I use $this->load->view and view by iphone or other mobile phone?

Body:
Check this

You can do it in two way.
Way 1: Its very simple. In the above answer (the link I have given) add following line in the end of MyController function

$this->load->_ci_view_path  . = $this->view_type .'/';

You are done. You can simply load view like normal view load.

Way 2:
To autoload a view based on user agent, I think you can implement it using hooks. To implement this hooks you need to follow the following steps

Autoload user agent library in autoload.php

$autoload['libraries'] = array('user_agent');

Enable hooks in config.php

$config['enable_hooks'] = TRUE;

Not implement hooks on post_controller_constructor. Add following codes to hooks.php

$hook['post_controller_constructor'][] = array('class'    => 'Loadview',
                                    'function' => 'load',
                                    'filename' => 'loadview.php',
                                    'filepath' => 'hooks'
                                   );

Now create a page named loadview.php under hooks directory having following code

class Loadview
{

    public static $MOBILE_PLATFORM = 'mobile';
    public static $DEFAULT_PLATFORM = 'default';

    public function load(){
        $this->CI =& get_instance();
        $view_type = $this->CI->agent->is_mobile() ? self::$MOBILE_PLATFORM : self::$DEFAULT_PLATFORM;
        $this->CI->load->_ci_view_path = $this->CI->load->_ci_view_path . $view_type .'/';
    }

}

You are done now. You can simply load view like normal view load.


问:
What does "./bin/www" do in Express 4.x?
I just started to learn about Express 4.0 in my Node.js app, and I found that it generated ./bin/www file, on which only the application server and port settings are written and everything others like middleware and routing is defined in ./app.js file.

However, I'm not sure what this ./bin/www does. I've used Express 3.x and I have always defined server and port settings as well as routing and middleware on the identical ./app.js file, and launched my node app with node app.js. So what's the point of using the ./bin/www? Does it only separate the server and port definition from others?

Right now, when I create the package using express-generator, the package.json includes the following definition:

```<code>"scripts": {
    "start": "node ./bin/www"
}
</code>```

However, I wonder whether I should launch my app using node ./bin/www, or npm start. Which command should I run to start my app?

And also, when I deploy my app to heroku, what should I write in the Procfile file? Is web: node app.js enough?

答:
All the above have answered well.
But in case if you want to use node app.js only like Express 3.* versions. You can follow below:

Because the app.js file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). The module must be loaded in a Node.js file and started via the Node.js file. The Node.js file is ./bin/www in this case. For more info, visit the official documentation.

Neither the bin directory nor the extensionless www file is mandatory for creating an Express app or starting the app. They are just suggestions made by the generator, so feel free to modify them to suit your needs.

To get rid of the www directory and keep things the “Express 3 way”, delete the line that says module.exports = app; at the end of the app.js file, then paste the following code in its place:

```<code>app.set('port', process.env.PORT || 3000)

app.listen(app.get('port'), () => {
  console.log(`Express server listening on port ${app.get('port')}`);
})
</code>```

Next, change "start": "node ./bin/www" in the package.json file.
Since, you have now moved the functionality of ./bin/www back to app.js. Now, start using "start": "node app.js" for running your express app.

Body:
I just started to learn about Express 4.0 in my Node.js app, and I found that it generated ./bin/www file, on which only the application server and port settings are written and everything others like middleware and routing is defined in ./app.js file.

However, I'm not sure what this ./bin/www does. I've used Express 3.x and I have always defined server and port settings as well as routing and middleware on the identical ./app.js file, and launched my node app with node app.js. So what's the point of using the ./bin/www? Does it only separate the server and port definition from others?

Right now, when I create the package using express-generator, the package.json includes the following definition:

"scripts": {
    "start": "node ./bin/www"
}

However, I wonder whether I should launch my app using node ./bin/www, or npm start. Which command should I run to start my app?

And also, when I deploy my app to heroku, what should I write in the Procfile file? Is web: node app.js enough?

Body:
All the above have answered well.
But in case if you want to use node app.js only like Express 3.* versions. You can follow below:

Because the app.js file that was generated by the Express 4 generator is now a Node.js module, it can no longer be started independently as an app (unless you modify the code). The module must be loaded in a Node.js file and started via the Node.js file. The Node.js file is ./bin/www in this case. For more info, visit the official documentation.

Neither the bin directory nor the extensionless www file is mandatory for creating an Express app or starting the app. They are just suggestions made by the generator, so feel free to modify them to suit your needs.

To get rid of the www directory and keep things the “Express 3 way”, delete the line that says module.exports = app; at the end of the app.js file, then paste the following code in its place:

app.set('port', process.env.PORT || 3000)

app.listen(app.get('port'), () => {
  console.log(`Express server listening on port ${app.get('port')}`);
})

Next, change "start": "node ./bin/www" in the package.json file.
Since, you have now moved the functionality of ./bin/www back to app.js. Now, start using "start": "node app.js" for running your express app.


问:
Binary Search Tree Using Classes
I have been trying to implement binary search tree using classes. Every time I try to compile and run the program, the program ends. I have tried many things like making the *root public to access it in main so I can update the root, but somehow it becomes null every time.
Help will be appreciated.
This is for my university project. </p>

```<code>#include <iostream>
using namespace std;
class tree;
class Node {
    friend class tree;
private:
    Node *lchild,*rchild;
    int data;
public:
    Node (int x) {
        data = x;
        lchild = rchild = NULL;
    }
};
class tree {
protected:
    Node* root;
    void inorder(const Node* root)const;
public:
    tree () {
        root = NULL;
    }
    bool insert(int item);
    void inorder() const {inorder(root);};
    Node* getroot() {
        return root;
    }
};
bool tree :: insert(int item) {
    if (root == NULL) {
        Node *temp = new Node(item);
        root = temp;
        return (bool) root;
    }
    if (item < root -> data) {
        insert(item);
    }
    if (item > root -> data) {
        insert(item);
    }
    else if (item == root -> data) {
        cout<<"Duplicate";
        exit (0);
    }
    return (bool) root;
}
void tree :: inorder(const Node *root)const {
    if (root != NULL) {
        inorder(root -> lchild);
        cout<<root -> data;
        inorder(root -> rchild);
    }
}
int main()
{
    tree obj1;
    obj1.insert(3);
    //obj1.insert(4);
    obj1.insert(1);
    //obj1.insert(5);
    obj1.inorder();
}
</code>```

答:
```<code>/* Program to implement Binary Search Tree in c++ using classes and objects  */
#include<iostream>
#include<stdlib.h>
#include<cstdlib>
using namespace std;

struct Node {
    int data;
    Node* left;
    Node* right;
};

class BinaryTree {
    private:
        struct Node* root;
    public:
        BinaryTree() {
            root = NULL;
        }
        Node* createNode(int);
        Node* insertNode(Node*, int);
        Node* deleteNode(Node*, int);
        void inOrder(Node*);
        void preOrder(Node*);
        void postOrder(Node*);
        Node* findMinimum(Node*);

        /* accessor function helps to
        get the root node in main function
        because root is private data member direct access is not possible */
        Node* getRoot() {
            return root;
        }

        /* mutator method helps to update root ptr after insertion
        root is not directly updatable in the main because its private data member */
        void setRoot(Node* ptr) {
            root = ptr;
        }
};

/* Helper function to create a new node in each function call of insertNode */
Node* BinaryTree :: createNode(int n) {
    Node* newNode = new struct Node();
    newNode->data = n;
    newNode->left = NULL;
    newNode->right = NULL;
    return newNode;
}

/* Helps to get inorder predessor to delete the node from tree */
Node* BinaryTree :: findMinimum(Node* rootPtr) {
    while(rootPtr->left != NULL) {
        rootPtr = rootPtr->left;
    }
    return rootPtr;
}

/* insertion of the Node */
Node* BinaryTree :: insertNode(Node* rootPtr, int n) {
    if(rootPtr == NULL) {
        return createNode(n);
    }
    if(n < rootPtr->data) {
        rootPtr->left = insertNode(rootPtr->left, n);
    }
    if(n > rootPtr->data) {
        rootPtr->right = insertNode(rootPtr->right, n);
    }
    return rootPtr;
}

/* function to delete the Node */
Node* BinaryTree :: deleteNode(Node* rootPtr, int n) {
    if(rootPtr == NULL) {
        cout<<"Node to be deleted is not present.!"<<endl;
        return rootPtr;
    }
    else if(n < rootPtr->data) {
        rootPtr->left = deleteNode(rootPtr->left, n);
    } else if(n > rootPtr->data) {
        rootPtr->right = deleteNode(rootPtr->right, n);
    } else {
        if(rootPtr->left == NULL && rootPtr->right == NULL) {
            delete rootPtr;
            rootPtr = NULL;
        }
        else if(root->left == NULL) {
            struct Node* temp = rootPtr;
            rootPtr = rootPtr->right;
            delete temp;
        }
        else if(rootPtr->right == NULL) {
            struct Node* temp = rootPtr;
            rootPtr = rootPtr->left;
            delete temp;
        } else {
            Node* temp = findMinimum(rootPtr->right);
            rootPtr->data = temp->data;
            rootPtr->left = deleteNode(rootPtr->right, temp->data);
        }
    }

    return rootPtr;
}

/* all traversal technique */
void BinaryTree :: inOrder(Node* root) {
    if(root == NULL) {
        return;
    }
    inOrder(root->left);
    cout<<root->data<<"\t";
    inOrder(root->right);
}

void BinaryTree :: preOrder(Node* root) {
    if(root == NULL) return;
    cout<<root->data<<"\t";
    preOrder(root->left);
    preOrder(root->right);
}

void BinaryTree :: postOrder(Node* root) {
    if(root == NULL) return;
    postOrder(root->left);
    postOrder(root->right);
    cout<<root->data<<"\t";
}

int main() {
    BinaryTree l1;
    int ch, ele, res;
    Node* ptr;
    do {
            cout<<"1 - Insert Node\n";
            cout<<"2 - IN-ORDER Traversal\n";
            cout<<"3 - PRE-ORDER Traversal\n";
            cout<<"4 - POST-ORDER Traversal\n";
            cout<<"Enter choice\n";
            cin>>ch;
            switch(ch) {
                case 1:
                    cout<<"Entre element to insert to the List\n";
                    cin>>ele;
                    /* calling insertNode function by passing root ptr to the function,
                       root ptr can be obtained by accessor function getRoot() */
                    ptr = l1.insertNode(l1.getRoot(), ele);
                    /* updating the root ptr*/
                    l1.setRoot(ptr);
                    break;
                case 2:
                    cout<<"---IN-ORDER TRAVERSAL---"<<endl;
                    l1.inOrder(l1.getRoot());
                    cout<<endl;
                    break;
                case 3:
                    cout<<"---PRE-ORDER TRAVERSAL---"<<endl;
                    l1.preOrder(l1.getRoot());
                    cout<<endl;
                    break;
                case 4:
                    cout<<"---POST-ORDER TRAVERSAL---"<<endl;
                    l1.postOrder(l1.getRoot());
                    cout<<endl;
                    break;
                case 5:
                    cout<<"Enter node to be deleted."<<endl;
                    cin>>ele;
                    ptr = l1.deleteNode(l1.getRoot(), ele);
                    l1.setRoot(ptr);
                default: cout<<"Invalid choice"<<endl;
            }
    } while(ch >=1 && ch <= 5);
    return 0;
}
</code>```

Title: Binary Search Tree Using Classes

Body:
I have been trying to implement binary search tree using classes. Every time I try to compile and run the program, the program ends. I have tried many things like making the *root public to access it in main so I can update the root, but somehow it becomes null every time.
Help will be appreciated.
This is for my university project.

#include <iostream>
using namespace std;
class tree;
class Node {
    friend class tree;
private:
    Node *lchild,*rchild;
    int data;
public:
    Node (int x) {
        data = x;
        lchild = rchild = NULL;
    }
};
class tree {
protected:
    Node* root;
    void inorder(const Node* root)const;
public:
    tree () {
        root = NULL;
    }
    bool insert(int item);
    void inorder() const {inorder(root);};
    Node* getroot() {
        return root;
    }
};
bool tree :: insert(int item) {
    if (root == NULL) {
        Node *temp = new Node(item);
        root = temp;
        return (bool) root;
    }
    if (item < root -> data) {
        insert(item);
    }
    if (item > root -> data) {
        insert(item);
    }
    else if (item == root -> data) {
        cout<<"Duplicate";
        exit (0);
    }
    return (bool) root;
}
void tree :: inorder(const Node *root)const {
    if (root != NULL) {
        inorder(root -> lchild);
        cout<<root -> data;
        inorder(root -> rchild);
    }
}
int main()
{
    tree obj1;
    obj1.insert(3);
    //obj1.insert(4);
    obj1.insert(1);
    //obj1.insert(5);
    obj1.inorder();
}


问:
Convert nested array of objects to object of key-value pairs using reducer
I have an observable output like below. I want to convert this data to desired format(proivded below). I am partially successful forming key value pairs but couldn't figure out how to send only one field(that is for which selected is true) from the cars array to final output.

***Observable Output****

```<code>[{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]
</code>```

****Desired Format*****

```<code>{John:[ford, fiat], Alex:[tesla,honda]}
</code>```

***Code used*****

```<code>const results = item.reduce((r,{name,cars}) => (r[name]=cars,r), {})
</code>```

//This gives me complete cars object but i need only name from it(and that too for selected true ones).

Edit 1: Do not want to have empty record in the final object. For eg, if Alex does not have any Cars Selected True then i do not want Alex:[] in the final object.

答:
this snippet will help</p>

```<code> const array = [{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]

const newArray = array.reduce((acc, rec) => {
  const cars = rec.cars.filter(c => c.selected)

  return cars.length ? {...acc, [rec.name]: cars.map(c => c.name)} : acc
}, {})

console.log(newArray)
</code>```

Body:
I have an observable output like below. I want to convert this data to desired format(proivded below). I am partially successful forming key value pairs but couldn't figure out how to send only one field(that is for which selected is true) from the cars array to final output.

***Observable Output****

[{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]

****Desired Format*****

{John:[ford, fiat], Alex:[tesla,honda]}

***Code used*****

const results = item.reduce((r,{name,cars}) => (r[name]=cars,r), {})

//This gives me complete cars object but i need only name from it(and that too for selected true ones).

Edit 1: Do not want to have empty record in the final object. For eg, if Alex does not have any Cars Selected True then i do not want Alex:[] in the final object.

Body:
this snippet will help

 const array = [{
  "name":"John",
  "age":30,
  "cars": [
      { "selected":true,  "name":"Ford", "models": "Mustang"},
      { "selected":false, "name":"BMW", "models": "320" },
      { "selected":true, "name":"Fiat", "models":"500" }
  ]
 },
 {
  "name":"alex",
  "age":40,
  "cars": [
      { "selected":true,  "name":"tesla", "models": "x"},
      { "selected":false, "name":"merc", "models": "300" },
      { "selected":true, "name":"honda", "models":"accord" }
   ]
  }
]

const newArray = array.reduce((acc, rec) => {
  const cars = rec.cars.filter(c => c.selected)

  return cars.length ? {...acc, [rec.name]: cars.map(c => c.name)} : acc
}, {})

console.log(newArray)


问:
How to get new time in Java?
What is the correct way of getting the updated time in Java?

```<code>    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    java.util.Date today = Calendar.getInstance().getTime();
    String currTime = dateFormat.format(today);

    System.out.println(currTime);
    try {
        Thread.sleep(2000);
        System.out.println("2s delayed"); //2000 milliseconds delay
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    System.out.println(currTime);
</code>```

This will give me something like this:

```<code>2016/04/07 12:39:05.281

2s delayed

2016/04/07 12:39:05.281
</code>```

As you see it is the same exact time, even after the 2s delay.

12:39:07.281 is the correct time for the second output.

Why am I not getting this?

答:
I have an easier method of doing it.....

But it is a bit different to your code.....

```<code>import java.util.Scanner;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class d_and_t
{
    public static void main(String[] args)
    {
        Scanner sc= new Scanner (System.in);
        System.out.println("Enter the place for time... for ex... IST...");
        String a=sc.nextLine();
        System.out.println("the time and date is   ........");
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMM-dd");
        System.out.println(dt.format(new Date()));
    }
}

</code>```

Here you have the option to get time for whichever place you want...

BufferedReader method.......

```<code>import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.io.*;
public class d_and_t
{
    public static void main(String[] args)
    {
        Scanner sc= new Scanner (System.in);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the place for time... for ex... IST...");
        try{
            String a=br.readLine();
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("the time and date is   ........");
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMM-dd");
        System.out.println(dt.format(new Date()));
    }
}

</code>```

Title: How to get new time in Java?

Body:
What is the correct way of getting the updated time in Java?

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss.SSS");
    java.util.Date today = Calendar.getInstance().getTime();
    String currTime = dateFormat.format(today);

    System.out.println(currTime);
    try {
        Thread.sleep(2000);
        System.out.println("2s delayed"); //2000 milliseconds delay
    } catch(InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
    System.out.println(currTime);

This will give me something like this:

2016/04/07 12:39:05.281

2s delayed

2016/04/07 12:39:05.281

As you see it is the same exact time, even after the 2s delay.

12:39:07.281 is the correct time for the second output.

Why am I not getting this?

Body:
I have an easier method of doing it.....

But it is a bit different to your code.....

import java.util.Scanner;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
public class d_and_t
{
    public static void main(String[] args)
    {
        Scanner sc= new Scanner (System.in);
        System.out.println("Enter the place for time... for ex... IST...");
        String a=sc.nextLine();
        System.out.println("the time and date is   ........");
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMM-dd");
        System.out.println(dt.format(new Date()));
    }
}

Here you have the option to get time for whichever place you want...

BufferedReader method.......

import java.util.Date;
import java.text.SimpleDateFormat;
import java.util.TimeZone;
import java.io.*;
public class d_and_t
{
    public static void main(String[] args)
    {
        Scanner sc= new Scanner (System.in);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter the place for time... for ex... IST...");
        try{
            String a=br.readLine();
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("the time and date is   ........");
        SimpleDateFormat dt = new SimpleDateFormat("yyyy-MMM-dd");
        System.out.println(dt.format(new Date()));
    }
}


问:
How to draw HTML class cards
I need to use HTML class cards to show certain data on my page.

This is the style that I'm using.

```<code><style>
.column {
  float: left;
  width: 25%;
  padding: 0 10px;
}

.row {margin: 0 -5px;}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  padding: 16px;
  text-align: center;
  background-color: #f1f1f1;
}
</style>
</code>```

This is the HTML code that I'm using to draw the card.

```<code><div class="col-md-8">
            <div class="row">
                <div class="column">
                    <div id="roomList" class="card">
                    </div>
                </div>
            </div>
        </div>
</code>```

I'm using ajax to load the data from SQL. After the data is loaded to ajax the data is appended to the roomList in order to create the card.

```<code> $.ajax({
        url: '/HouseKeeping/OutOfOrderTXN/RoomList',
        dataType: 'json',
        method: 'GET',
        success: function (data) {
            debugger;
            $.each(data, function (index, eachRoomList) {
                $('#roomList').append(
                    '<div class="row"><div class="column"><div class="card"> data-room-id="' + eachRoomList.Id + '" data-room-name="' + eachRoomList.RoomName + '"</div></div></div>>');
            })
        },
        error: function (error) {

        }
    });
</code>```

+ eachRoomList.RoomName + The data which is loaded to this are eg=100,101,102

But it doesn't work. Below is a picture of how my class card is drawn.

The data is not shown inside the class 'card' for eg-100 should be shown inside the class 'card'
whats wrong with my code.I'm a beginner so help me pls

enter image description here

答:
If your ajax request is successful,there is a problem in appending the child.
Your class="card" div is not closed.
Can you try

```<code>$('#roomList').append(`<div class="row"><div class="column">   <div class="card" data-room-id="${eachRoomList.Id}" data-room-name="${eachRoomLi[![enter image description here][1]][1]st.RoomName}">${eachRoomList.RoomName}</div></div></div>`);
</code>```

Title: How to draw HTML class cards

Body:
I need to use HTML class cards to show certain data on my page.

This is the style that I'm using.

This is the HTML code that I'm using to draw the card.

I'm using ajax to load the data from SQL. After the data is loaded to ajax the data is appended to the roomList in order to create the card.

 $.ajax({
        url: '/HouseKeeping/OutOfOrderTXN/RoomList',
        dataType: 'json',
        method: 'GET',
        success: function (data) {
            debugger;
            $.each(data, function (index, eachRoomList) {
                $('#roomList').append(
                    '

 data-room-id="' + eachRoomList.Id + '" data-room-name="' + eachRoomList.RoomName + '"

>');
            })
        },
        error: function (error) {

        }
    });

+ eachRoomList.RoomName + The data which is loaded to this are eg=100,101,102

But it doesn't work. Below is a picture of how my class card is drawn.

The data is not shown inside the class 'card' for eg-100 should be shown inside the class 'card'
whats wrong with my code.I'm a beginner so help me pls

enter image description here

Body:
If your ajax request is successful,there is a problem in appending the child.
Your class="card" div is not closed.
Can you try

$('#roomList').append(`<div class="row"><div class="column">   <div class="card" data-room-id="${eachRoomList.Id}" data-room-name="${eachRoomLi[![enter image description here][1]][1]st.RoomName}">${eachRoomList.RoomName}</div></div></div>`);


问:
Maximum mark in Subject with Staff name
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;
```

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

答:
It seems that You are looking for the following query:</p>

```<code>SELECT
    ST.STAFF_NAME,
    SB.SUBJECT_NAME,
    MAX(M.VALUE) AS MAX_MARK
FROM
    STAFF     ST
    JOIN SUBJECT   SB ON SB.STAFF_ID = ST.STAFF_ID
    JOIN MARK      M ON M.SUBJECT_ID = SB.SUBJECT_ID
GROUP BY
    ST.STAFF_ID,
    ST.STAFF_NAME,
    SB.SUBJECT_ID,
    SB.SUBJECT_NAME
ORDER BY
    MAX_MARK DESC;
</code>```

Title: Maximum mark in Subject with Staff name

Body:
Write a query to display list of staff name, subject name handled, maximum mark scored in that subject. Give an alias to the maximum mark as max_mark. Sort the result based on maximum mark in descending.

This is the schema diagram.

This is the code I have tried.

select distinct
       staff_name,
       subject_name,
       max(value) over (partition by sb.staff_id) as max_mark
from   subject sb
       inner join staff st
       on st.staff_id=sb.staff_id
       inner join mark m
       on m.subject_id=sb.subject_id
order by max_mark desc;

I was abled to pass one testcase but I could not abled to pass second testcase and I don't know what second testcase is and also I am not getting what I have done wrong in my above code.Is there any way of getting solution for this problem.

Body:
It seems that You are looking for the following query:

SELECT
    ST.STAFF_NAME,
    SB.SUBJECT_NAME,
    MAX(M.VALUE) AS MAX_MARK
FROM
    STAFF     ST
    JOIN SUBJECT   SB ON SB.STAFF_ID = ST.STAFF_ID
    JOIN MARK      M ON M.SUBJECT_ID = SB.SUBJECT_ID
GROUP BY
    ST.STAFF_ID,
    ST.STAFF_NAME,
    SB.SUBJECT_ID,
    SB.SUBJECT_NAME
ORDER BY
    MAX_MARK DESC;


问:
table.addItem is not adding the value to my table
When I add the table.addContainerProperty manually (all of them) it works, adding all items i ask for.

When I use a for to create the table.addContainerProperty I cannot add values using my button, or with the for that should add all my values.

Why? I cannot find it anywhere...

```<code>package br.com.Metrics;

import com.vaadin.Application; import
com.vaadin.ui.Button; import
com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table; import
com.vaadin.ui.Window;

import br.com.cflex.table.*;

/**  * The Application's "main" class
*/ @SuppressWarnings("serial") public class MyVaadinApplication extends Application {
    private Window window;
    private Table table;

    @Override
    public void init()
    {
        window = new Window("My Vaadin Application");

        table = new Table("Teste de tabela");
        table.addItem();
        table.addContainerProperty("Nome", String.class, null);

        for(int i=0; i<10;i++){
            table.addContainerProperty(i,Integer.class, null);
            table.addItem(new Object[] {"2",new Integer(159),new Integer(1473)}, null);
        }

        for(int i=0; i<10; i++){
            table.addItem(new Object[] {"3",new Integer(159),new Integer(1473)}, null);
        }

        table.addItem(new Object[] {"4",new Integer(159),new Integer(1473)}, null);

        Button button = new Button("Press Me !");
        button.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
             table.addItem(new Object[] {"Nicolaus",new Integer(159),new Integer(1473)}, null);
            }
        });
        window.addComponent(table);
        window.addComponent(button);
        setMainWindow(window);
    }
  }
</code>```

答:
I found out why...

when inserting data in a table using .addItem the array that you must provide to this method MUST have the exact same number of itens as the table columns.

otherwise it will not add them or tell you that.

Body:
When I add the table.addContainerProperty manually (all of them) it works, adding all items i ask for.

When I use a for to create the table.addContainerProperty I cannot add values using my button, or with the for that should add all my values.

Why? I cannot find it anywhere...

package br.com.Metrics;

import com.vaadin.Application; import
com.vaadin.ui.Button; import
com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table; import
com.vaadin.ui.Window;

import br.com.cflex.table.*;

/**  * The Application's "main" class
*/ @SuppressWarnings("serial") public class MyVaadinApplication extends Application {
    private Window window;
    private Table table;

    @Override
    public void init()
    {
        window = new Window("My Vaadin Application");

        table = new Table("Teste de tabela");
        table.addItem();
        table.addContainerProperty("Nome", String.class, null);

        for(int i=0; i<10;i++){
            table.addContainerProperty(i,Integer.class, null);
            table.addItem(new Object[] {"2",new Integer(159),new Integer(1473)}, null);
        }

        for(int i=0; i<10; i++){
            table.addItem(new Object[] {"3",new Integer(159),new Integer(1473)}, null);
        }

        table.addItem(new Object[] {"4",new Integer(159),new Integer(1473)}, null);

        Button button = new Button("Press Me !");
        button.addListener(new Button.ClickListener() {
            public void buttonClick(ClickEvent event) {
             table.addItem(new Object[] {"Nicolaus",new Integer(159),new Integer(1473)}, null);
            }
        });
        window.addComponent(table);
        window.addComponent(button);
        setMainWindow(window);
    }
  }


问:
Selenium click() method on angular.js site
I am scraping an angular.js site. My initial link has a search button. I find by xpath and click with no issues. After I click search, I want to be able to click each of the athletes in the table to go to their info pages, but I am not having success with the click method. The links are attached to their names. </p>

```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException

TIMEOUT = 5

driver = webdriver.Firefox()
driver.set_page_load_timeout(TIMEOUT)
url = 'https://n.rivals.com/search#?formValues=%7B%22sport%22:%22Football%22,%22recruit_year%22:2021,%22offer_and_visit_type%22:%5B%22Offer%22%5D,%22prospect_profiles.prospect_colleges.offer%22:true,%22page_number%22:1,%22page_size%22:50%7D'

try:
    driver.get(url)
except TimeoutException:
    pass

search_button = driver.find_element_by_xpath('//*[@id="articles"]/div/div[2]/div/div/div[1]/form/div[2]/div[5]/button')
search_button.click();
#below is where I tried, but could not get to click
first_athlete = driver.find_element_by_xpath('//*[@id="content_"]/td[1]/div[2]/a')
first_athlete.click();
</code>```

答:
If you want to search for all athletes and you have the name of athletes with you, you can use CSS selector as well.

```<code>athelete = driver.find_elements_by_css_selector(`#content_ > td > div > a[href *="donovan-jackson"]);
athelete.click();
</code>```

This code will give you a unique web element for each player.

Thanks

Body:
I am scraping an angular.js site. My initial link has a search button. I find by xpath and click with no issues. After I click search, I want to be able to click each of the athletes in the table to go to their info pages, but I am not having success with the click method. The links are attached to their names.

from selenium import webdriver
from selenium.common.exceptions import TimeoutException

TIMEOUT = 5

driver = webdriver.Firefox()
driver.set_page_load_timeout(TIMEOUT)
url = 'https://n.rivals.com/search#?formValues=%7B%22sport%22:%22Football%22,%22recruit_year%22:2021,%22offer_and_visit_type%22:%5B%22Offer%22%5D,%22prospect_profiles.prospect_colleges.offer%22:true,%22page_number%22:1,%22page_size%22:50%7D'

try:
    driver.get(url)
except TimeoutException:
    pass

search_button = driver.find_element_by_xpath('//*[@id="articles"]/div/div[2]/div/div/div[1]/form/div[2]/div[5]/button')
search_button.click();
#below is where I tried, but could not get to click
first_athlete = driver.find_element_by_xpath('//*[@id="content_"]/td[1]/div[2]/a')
first_athlete.click();

Body:
If you want to search for all athletes and you have the name of athletes with you, you can use CSS selector as well.

athelete = driver.find_elements_by_css_selector(`#content_ > td > div > a[href *="donovan-jackson"]);
athelete.click();

This code will give you a unique web element for each player.

Thanks