问:
Error creating bean with name 'dataSource' defined in class path resource + Springboot
I'm creating a Springboot application but will be using a external MongoDB over REST. My application properties file is very simple:

application.properties

```<code># Server
server.port=8081
</code>```

My global application file is also very simple. I make a connection to my externally hosted database with a Parse initialization method:

```<code>@SpringBootApplication
@ComponentScan(basePackages = {"com.test", "it.ozimov.springboot"})
public class TmtApplication {

    public static void main(String[] args) {
        SpringApplication.run(TmtApplication.class, args);

        // Database connection
        Parse.initialize("applicationId","restAPIKey", "https://parseapi.back4app.com");

    }
}
</code>```

Why am I getting the following exception?

Exceptions:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 34 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 47 more
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:246)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:183)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 48 more
</code>```

What don't I understand about Springboot? Is it looking for some kind of database initialization because it's running on Hibernate/Tomcat?

答:
Exclude Datasource if you don't use database.

```<code>@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
</code>```

you see this link

Body:
I'm creating a Springboot application but will be using a external MongoDB over REST. My application properties file is very simple:

application.properties

# Server
server.port=8081

My global application file is also very simple. I make a connection to my externally hosted database with a Parse initialization method:

@SpringBootApplication
@ComponentScan(basePackages = {"com.test", "it.ozimov.springboot"})
public class TmtApplication {

    public static void main(String[] args) {
        SpringApplication.run(TmtApplication.class, args);

        // Database connection
        Parse.initialize("applicationId","restAPIKey", "https://parseapi.back4app.com");

    }
}

Why am I getting the following exception?

Exceptions:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Tomcat.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1173)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1067)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:513)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:208)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1138)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1066)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:835)
    at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741)
    ... 34 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.tomcat.jdbc.pool.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588)
    ... 47 more
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:246)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.initializeDataSourceBuilder(DataSourceProperties.java:183)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42)
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 48 more

What don't I understand about Springboot? Is it looking for some kind of database initialization because it's running on Hibernate/Tomcat?

Body:
Exclude Datasource if you don't use database.

@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})

you see this link


来源: stackexchange

问:
Scheme filter but the result list contains indices not values
Is there any easy way to create a kind of filter with the outcome the indices instead of values?

for example:

```<code>'(#true #false #true) -> '(0 2)
</code>```

答:
Of course there is a way to do it; there's many ways to do it. Here's one way.</p>

```<code>(define (func xs)
  (let loop ((index 0) (xs xs))
    (cond ((empty? xs) empty)
          ((car xs) (cons index (loop (add1 index) (cdr xs))))
          (else (loop (add1 index) (cdr xs))))))

(func '(#true #false #true #false #false #true #true))
;; => '(0 2 5 6)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Is there any easy way to create a kind of filter with the outcome the indices instead of values?

for example:

'(#true #false #true) -> '(0 2)

Body:
Of course there is a way to do it; there's many ways to do it. Here's one way.

(define (func xs)
  (let loop ((index 0) (xs xs))
    (cond ((empty? xs) empty)
          ((car xs) (cons index (loop (add1 index) (cdr xs))))
          (else (loop (add1 index) (cdr xs))))))

(func '(#true #false #true #false #false #true #true))
;; => '(0 2 5 6)


问:
Binding routes to wrong method controller
I am using laravel 5.1 app. I
have the bellow routes:

```<code>Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');
</code>```

Also I use RouteServiceProvider like so:

```<code>    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first();
   });

    $router->bind('about', function($about){
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail();
    });

    }
</code>```

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?

答:
Your routes have the same URL, the access conditions are the same. For laravel if you put one string next to the root URL you access both of the routes.

You need to disambiguate the routes like this for example :

```<code>Route::get('thing/{thing}', 'DisplayController@showThingNewRoute');
Route::get('about/{about}', 'DisplayController@showAboutNewRoute');
</code>```

Body:
I am using laravel 5.1 app. I
have the bellow routes:

Route::get('{thing}', 'DisplayController@showThingNewRoute');
Route::get('{about}', 'DisplayController@showAboutNewRoute');

Also I use RouteServiceProvider like so:

    public function boot(Router $router)
    {

    parent::boot($router);

    $router->bind('thing', function($thing){
       return \App\Thing::publish()->where('seo_url', '=', $thing)->first();
   });

    $router->bind('about', function($about){
       return \App\About::publish()->where('seo_url', '=', $about)->firstOrFail();
    });

    }

The problem is that I can't have a route to execute with a second method showAboutNewRoute

What am i doing wrong here?

Body:
Your routes have the same URL, the access conditions are the same. For laravel if you put one string next to the root URL you access both of the routes.

You need to disambiguate the routes like this for example :

Route::get('thing/{thing}', 'DisplayController@showThingNewRoute');
Route::get('about/{about}', 'DisplayController@showAboutNewRoute');


问:
Mysql if value equal condition
Codeigniter code:

```<code>if(Property.Property_for == 1)
$this->db->join('Property_sell','Property_sell.Property_id = Property.ID','left');
else
$this->db->join('Property_rent','Property_rent.Property_id = Property.ID','left');
</code>```

How can I make query like given example?

答:
It looks like you are trying to toggle the join table and column.

```<code>$table = 'rent';
if(Property.Property_for == 1) {
    $table = 'sell';
}
$tableColumn = sprintf('Property_%s', $table);
$this->db->join($tableColumn, $tableColumn . '.Property_id = Property.ID','left');
</code>```

If this is not what you are trying achieve, please expand your question.

Title: Mysql if value equal condition

Body:
Codeigniter code:

if(Property.Property_for == 1)
$this->db->join('Property_sell','Property_sell.Property_id = Property.ID','left');
else
$this->db->join('Property_rent','Property_rent.Property_id = Property.ID','left');

How can I make query like given example?

Body:
It looks like you are trying to toggle the join table and column.

$table = 'rent';
if(Property.Property_for == 1) {
    $table = 'sell';
}
$tableColumn = sprintf('Property_%s', $table);
$this->db->join($tableColumn, $tableColumn . '.Property_id = Property.ID','left');

If this is not what you are trying achieve, please expand your question.


问:
Cloudant in Node.js, How to make a query with multiple results
I am using node.js and ibm bluemix to run the back-end apps. I am using cloudant module. But in github as I search, I only found how to make a query with 1 result. So I want to ask you guys how can I make a query with multiple results. I want to make it in my app.js. My sample database are

```<code>{
  "userid":"chris"
  "time":"12.20",
  "power":"200",
}

{
  "userid":"chris"
  "time":"12.30",
  "power":"250",
}
</code>```

And there will be plenty of data with same userid and different time and power. How do I want to make the query it and publish it with mqtt?

Thanks for your help.

答:
get the sample nodejs and cloudant here :

```<code>git clone https://github.com/IBM-Bluemix/get-started-node
</code>```

you will find a loop on the cloudant db result object :

```<code>mydb.list({ include_docs: true }, function(err, body) {
    if (!err) {
      body.rows.forEach(function(row) {
        if(row.doc.name)
          names.push(row.doc.name);
      });
      response.json(names);
    }
  });
});
</code>```

next in the watson iot platform service i have found a client library for nodejs. Samples here

i think it's easier (for me) to start with the node-red starter boilerplate app.

to store your 3 elements in the doc :

```<code> mydb.insert({ "userid" : "chris","time":"12:20","power":"200" }, function(err, body, header) {
    if (err) {
      return console.log('[mydb.insert] ', err.message);
    }
    response.send("added to the database.");
  });
</code>```

to get them :

```<code>mydb.list({ include_docs: true }, function(err, body) {
    if (!err) {
      body.rows.forEach(function(row) {
        if(row.doc.userid)
                response.send(row.doc.userid+" "+row.doc.power+" "+row.doc.time);
      });
    }
  });
</code>```

Body:
I am using node.js and ibm bluemix to run the back-end apps. I am using cloudant module. But in github as I search, I only found how to make a query with 1 result. So I want to ask you guys how can I make a query with multiple results. I want to make it in my app.js. My sample database are

{
  "userid":"chris"
  "time":"12.20",
  "power":"200",
}

{
  "userid":"chris"
  "time":"12.30",
  "power":"250",
}

And there will be plenty of data with same userid and different time and power. How do I want to make the query it and publish it with mqtt?

Thanks for your help.

Body:
get the sample nodejs and cloudant here :

git clone https://github.com/IBM-Bluemix/get-started-node

you will find a loop on the cloudant db result object :

mydb.list({ include_docs: true }, function(err, body) {
    if (!err) {
      body.rows.forEach(function(row) {
        if(row.doc.name)
          names.push(row.doc.name);
      });
      response.json(names);
    }
  });
});

next in the watson iot platform service i have found a client library for nodejs. Samples here

i think it's easier (for me) to start with the node-red starter boilerplate app.

to store your 3 elements in the doc :

 mydb.insert({ "userid" : "chris","time":"12:20","power":"200" }, function(err, body, header) {
    if (err) {
      return console.log('[mydb.insert] ', err.message);
    }
    response.send("added to the database.");
  });

to get them :

mydb.list({ include_docs: true }, function(err, body) {
    if (!err) {
      body.rows.forEach(function(row) {
        if(row.doc.userid)
                response.send(row.doc.userid+" "+row.doc.power+" "+row.doc.time);
      });
    }
  });


问:
convert latitude and longitude to northing and easting in java?
how to convert latitude and longitude to northing and easting in Java?</p>

答:
I'm assuming you mean UK OSGB easting and northings. The trigonometry behind this one is hilarious, but you can use the JCoord library for this, it makes it easy (if quite CPU intensive).

To follow up on @DD's comments below, there is a gotcha with JCoord, in that you have to make sure you're using the correct datum when converting from Easting/Northing to Lat/Long, and vice versa.

Take @DD's code:

```<code>LatLng latLng = new OSRef(394251,806376).toLatLng();
</code>```

This will return a Lat/Long which uses the OSGB36 datum, i.e. the "flat earth" approximation used on UK maps. This is substantially different to the WSG84 datum used in most applications (including Streetmap), which models the world as a sphere (more or less).

In order to convert to a WGS84 lat/long, you need to make it explicit:

```<code>LatLng latLng = new OSRef(394251,806376).toLatLng();
latLng.toWGS84();
</code>```

This will adjust the lat-long to the correct datum.

Note that the javadoc for OsRef.toLatLng() is very clear about this:

Convert this OSGB grid reference to a latitude/longitude pair using the OSGB36 datum. Note that, the LatLng object may need to be converted to the WGS84 datum depending on the application

Conversion between coordinate datum is not simple. If it looks simple, you're likely doing it wrong.

ContentLicense: CC BY-SA 2.5

Body:
I'm assuming you mean UK OSGB easting and northings. The trigonometry behind this one is hilarious, but you can use the JCoord library for this, it makes it easy (if quite CPU intensive).

To follow up on @DD's comments below, there is a gotcha with JCoord, in that you have to make sure you're using the correct datum when converting from Easting/Northing to Lat/Long, and vice versa.

Take @DD's code:

LatLng latLng = new OSRef(394251,806376).toLatLng();

This will return a Lat/Long which uses the OSGB36 datum, i.e. the "flat earth" approximation used on UK maps. This is substantially different to the WSG84 datum used in most applications (including Streetmap), which models the world as a sphere (more or less).

In order to convert to a WGS84 lat/long, you need to make it explicit:

LatLng latLng = new OSRef(394251,806376).toLatLng();
latLng.toWGS84();

This will adjust the lat-long to the correct datum.

Note that the javadoc for OsRef.toLatLng() is very clear about this:

Convert this OSGB grid reference to a latitude/longitude pair using the OSGB36 datum. Note that, the LatLng object may need to be converted to the WGS84 datum depending on the application

Conversion between coordinate datum is not simple. If it looks simple, you're likely doing it wrong.


问:
Vertically middle align text in a bootstrap column
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

```

Where is the problem ?

答:
You can just add following css code  :

```<code>img {vertical-align: middle;}
</code>```

It align your a tag in the middle of image.

Body:
I need tree cells in tree columns(col-4), with an image, that determines the height of the cell, and vertically middle-aligned text, like this:

This is what I get (CodePen Here):

      Some text red-yellow

      some other text long text some other long text lightgreen-gray

      this is another long long long text that should be here skyblue-violet

Where is the problem ?

Body:
You can just add following css code  :

img {vertical-align: middle;}

It align your a tag in the middle of image.


问:
Put a Linearlayout under the ListView
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>
</code>```

答:
I haven't tried but you try this and let me know:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_alignParentBottom="true" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/leaveGroupButton"
    android:layout_below="@id/groupID">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ListView1">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/addMember"
            android:text="Add New Members"
            android:textSize="18sp"
            android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
</RelativeLayout>
</code>```

Title: Put a Linearlayout under the ListView

Body:
I'm facing problem to put a linearlayout under the listview like what is shown in this image link:

I want the layout with the Add icon and text:"Add New Members" to be displayed under the listview. What am I doing wrong? Pls help me to solve the problem. Thank you very much.

This is the xml file for the layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.thomasbrown.myapplication.MemberActivity"
android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white"
        android:layout_weight="1" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/addMember"
                android:text="Add New Members"
                android:textSize="18sp"
                android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>

</LinearLayout>

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_gravity="bottom|end" />

</LinearLayout>

Body:
I haven't tried but you try this and let me know:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
          xmlns:app="http://schemas.android.com/apk/res-auto"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="match_parent"
          android:background="@android:color/white">

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/groupID"
    android:textSize="20sp"
    android:layout_marginBottom="15dp" />

<Button
    android:text="Leave this group"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/leaveGroupButton"
    android:background="@color/colorPrimary"
    android:layout_alignParentBottom="true" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@id/leaveGroupButton"
    android:layout_below="@id/groupID">

    <ListView
        android:id="@+id/ListView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@android:color/white" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/ListView1">

        <ImageView
            app:srcCompat="@drawable/add"
            android:id="@+id/imageView2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_width="80dp"
            android:layout_height="60dp"
            android:layout_weight="1" />

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/addMember"
            android:text="Add New Members"
            android:textSize="18sp"
            android:textColor="@android:color/holo_red_dark"
            android:layout_weight="1"
            android:layout_gravity="center_vertical" />
    </LinearLayout>
</RelativeLayout>


问:
Numerical solution of exponential equation using Python or other software
I want to find numerical solutions to the following exponential equation where a,b,c,d are constants and I want to solve for r, which is not equal to 1.

a^r + b^r = c^r + d^r                        (Equation 1)

I define a function in order to use Scipy.optimize.fsolve:

```<code>    from scipy.optimize import fsolve
    def func(r,a,b,c,d):
        if r==1:
            return 10**5
        else:
            return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

    fsolve(funcp,0.1, args=(5,5,4,7))
</code>```

However, the fsolve always returns 1 as the solution, which is not what I want. Can someone help me with this issue? Or in general, tell me how to solve (Equation 1). I used an online numerical solver long time ago, but I cannot find it anymore. That's why I am trying to figure it out using Python.

答:
First of your code seems to uses a different equation than your question: 1-r instead of just r.

Valid answers to the equation is 1 and 2.4886 approximately as can be seen here. With the second argument of fsolve you specify a starting estimate. I think due to 0.1 being close to 1 you get that result. Using the 2.1 as starting estimate I get the other answer 2.4886.

```<code>from scipy.optimize import fsolve

def func(r,a,b,c,d):
    if r==1:
        return 10**5
    else:
        return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

print(fsolve(func, 2.1, args=(5,5,4,7)))
</code>```

Chosing a starting estimate is tricky as many give the following error: ValueError: Integers to negative integer powers are not allowed.

Body:
I want to find numerical solutions to the following exponential equation where a,b,c,d are constants and I want to solve for r, which is not equal to 1.

a^r + b^r = c^r + d^r                        (Equation 1)

I define a function in order to use Scipy.optimize.fsolve:

    from scipy.optimize import fsolve
    def func(r,a,b,c,d):
        if r==1:
            return 10**5
        else:
            return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

    fsolve(funcp,0.1, args=(5,5,4,7))

However, the fsolve always returns 1 as the solution, which is not what I want. Can someone help me with this issue? Or in general, tell me how to solve (Equation 1). I used an online numerical solver long time ago, but I cannot find it anymore. That's why I am trying to figure it out using Python.

Body:
First of your code seems to uses a different equation than your question: 1-r instead of just r.

Valid answers to the equation is 1 and 2.4886 approximately as can be seen here. With the second argument of fsolve you specify a starting estimate. I think due to 0.1 being close to 1 you get that result. Using the 2.1 as starting estimate I get the other answer 2.4886.

from scipy.optimize import fsolve

def func(r,a,b,c,d):
    if r==1:
        return 10**5
    else:
        return ( a**(1-r)  +  b**(1-r) ) - ( c**(1-r)  + d**(1-r)  )

print(fsolve(func, 2.1, args=(5,5,4,7)))

Chosing a starting estimate is tricky as many give the following error: ValueError: Integers to negative integer powers are not allowed.


问:
Set value in the second input based on the first input
I have two input fields in Wordpress Options Page. I am calculating the costs and then setting the value in the corresponding input field but it's setting in all of the second input. I want the value to be set only in the corresponding input field.

JSFiddle

$('input[id^="calc_transport_"]').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $('input[id^="calc_m_transport_"]').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table></code>```

答:
The issue is because you're selecting all the elements that being with the calc_m_transport_ id.

To solve this you can firstly use the classes on the elements to select them. From there you can use $(this).siblings() to find the .transport-margin element related to the one the user typed in. Try this:

$('.transport').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $(this).siblings('.transport-margin').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table></code>```

Body:
I have two input fields in Wordpress Options Page. I am calculating the costs and then setting the value in the corresponding input field but it's setting in all of the second input. I want the value to be set only in the corresponding input field.

JSFiddle

$('input[id^="calc_transport_"]').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $('input[id^="calc_m_transport_"]').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}

      1 KG

        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">

      2 KG

        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">

      3 KG

        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">

      4 KG

        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">

      5 KG

        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">

Body:
The issue is because you're selecting all the elements that being with the calc_m_transport_ id.

To solve this you can firstly use the classes on the elements to select them. From there you can use $(this).siblings() to find the .transport-margin element related to the one the user typed in. Try this:

$('.transport').on('change', function() {
  var transport_margin_cost = getRandomNumber();
  $(this).siblings('.transport-margin').val(transport_margin_cost.toFixed(2));
});

function getRandomNumber() {
  var number = 1 + Math.floor(Math.random() * 6);
  return number;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="form-table">
  <tbody>
    <tr>
      <th scope="row">1 KG</th>
      <td>
        <input class="transport text" id="calc_transport_1" name="calc_transport_1" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_1" name="calc_m_transport_1" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">2 KG</th>
      <td>
        <input class="transport text" id="calc_transport_2" name="calc_transport_2" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_2" name="calc_m_transport_2" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">3 KG</th>
      <td>
        <input class="transport text" id="calc_transport_3" name="calc_transport_3" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_3" name="calc_m_transport_3" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">4 KG</th>
      <td>
        <input class="transport text" id="calc_transport_4" name="calc_transport_4" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_4" name="calc_m_transport_4" type="text" value="">
      </td>
    </tr>
    <tr>
      <th scope="row">5 KG</th>
      <td>
        <input class="transport text" id="calc_transport_5" name="calc_transport_5" type="text" value="">
        <input class="transport-margin text" id="calc_m_transport_5" name="calc_m_transport_5" type="text" value="">
      </td>
    </tr>
  </tbody>
</table>


问:
Crystal build fails with "ld: library not found for -lssl"
I've just started a brand new Crystal app, added Kemal, and when building the "Hello World!" app from the Kemal documentation, I get:

$ crystal build --release src/orderprinterlinks.cr
ld: library not found for -lssl
clang: error: linker command failed with exit code 1 (use -v to see invocation)

On OSX 10.12.4

Any ideas why the library is not being found?

答:
FIXED! Error was unrelated to Crystal / Kemal.. running the below command fixes the issue:

xcode-select --install

Seems the XCode CLI tools are removed silently when upgrading XCode versions, so this adds them back in, then everything works!


问:
Is it possible to ignore namespaces in c# when using xPath?
I could be given either of the following xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<dc:video xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:title>
    A vid with Pete
  </dc:title>
  <dc:description>
  Petes vid
  </dc:description>
  <dc:contributor>
    Pete
  </dc:contributor>
  <dc:subject>
    Cat 2
  </dc:subject>
</dc:video>
</code>```

Or:

```<code><?xml version="1.0" encoding="UTF-8"?>
<video>
  <title>
    A vid with Pete
  <title>
  <description>
  Petes vid
  <description>
  <contributor>
    Pete
  <contributor>
  <subject>
    Cat 2
  <subject>
</video>
</code>```

Im trying to access an element:

```<code>string title = xmlDocFromOneLan.SelectSingleNode(@"/video/title").InnerXml;
</code>```

But with xml document 1 it doesnt work due to the namespace.

Is there a way in c# to ignore the namespace using xpath? I simply want to select the node I really dont care about the namespace. (the namespace could be DC DN or DCN etc).

"/video"

would read:

```<code><video></video>
or
<dc:video></video>
or
<dcn:video></video>
</code>```

答: With XPath 1.0 all you can do is /*[local-name() = 'video']/*[local-name() = 'title']. With XPath 2.0 you can use a wildcard /*:video/*:title.

Body:
I could be given either of the following xml:

<?xml version="1.0" encoding="UTF-8"?>
<dc:video xmlns:dc="http://purl.org/dc/elements/1.1/">
  <dc:title>
    A vid with Pete
  </dc:title>
  <dc:description>
  Petes vid
  </dc:description>
  <dc:contributor>
    Pete
  </dc:contributor>
  <dc:subject>
    Cat 2
  </dc:subject>
</dc:video>

Or:

<?xml version="1.0" encoding="UTF-8"?>
<video>
  <title>
    A vid with Pete
  <title>
  <description>
  Petes vid
  <description>
  <contributor>
    Pete
  <contributor>
  <subject>
    Cat 2
  <subject>
</video>

Im trying to access an element:

string title = xmlDocFromOneLan.SelectSingleNode(@"/video/title").InnerXml;

But with xml document 1 it doesnt work due to the namespace.

Is there a way in c# to ignore the namespace using xpath? I simply want to select the node I really dont care about the namespace. (the namespace could be DC DN or DCN etc).

"/video"

would read:

<video></video>
or
<dc:video></video>
or
<dcn:video></video>


问:
Change interpolation brackets - Angular2
I want to use Laravel Blade and AngularJS.

Is some way to change interpolate sintax, change {{text}} for [{text}] or somthing like that?

I already change all components.ts files adding the line:
interpolation: ["{[", "]}"],
 but, where I write blade, app breaks...

Thanks a lot everybody ;)

答:
You can define your Blade content tags in your routes.php file:

```<code>Blade::setContentTags('<%', '%>');
Blade::setEscapedContentTags('<%%', '%%>');
</code>```

EDIT: You can add @ in front of the brackets, so Blade won't render it.

```<code>@{ var }
</code>```

or you can pass the directive for blade not to render part of the HTML using @verbatim keyword.

```<code>@verbatim
<div>
    {{ var }}
</div>
@endverbatim
</code>```

Body:
You can define your Blade content tags in your routes.php file:

Blade::setContentTags('<%', '%>');
Blade::setEscapedContentTags('<%%', '%%>');

EDIT: You can add @ in front of the brackets, so Blade won't render it.

@{ var }

or you can pass the directive for blade not to render part of the HTML using @verbatim keyword.

@verbatim
<div>
    {{ var }}
</div>
@endverbatim


问:
Android lint shows up no issues in Sonarqube
I have setup my project to use with Sonarqube. I was using PMD and Checkstyle to run tests and all of them are successfully logged in Sonarqube console. But last day I decided to add Android lint rules also to my Quality profile. I have activated all Lint rules in a new profile and run the project. Now when I run the project, it is not showing up any errors or issues with this profile. When I run the lint locally I get about 400 issues. What could I be missing?

I am using Sonarqube plugin in Gradle and Sonarqube 6.2 on my server. My Sonarqube configuration is as follows

```<code>apply plugin: "org.sonarqube"

sonarqube {
//noinspection GroovyAssignabilityCheck
    properties {
//noinspection GroovyAssignabilityCheck
        property "sonar.projectName", "MyProject"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectKey", "Testapplication"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectVersion", "1.0"
//noinspection GroovyAssignabilityCheck
        property "sonar.analysis.mode", "publish"
//noinspection GroovyAssignabilityCheck
        property "sonar.language", "java"
//noinspection GroovyAssignabilityCheck
        property "sonar.sources", "src/main/"
//noinspection GroovyAssignabilityCheck
        property "sonar.profile", "FindBugs"
//noinspection GroovyAssignabilityCheck
        property "sonar.host.url", "http://192.168.21.33:9000"
//noinspection GroovyAssignabilityCheck
        property "sonar.login", "admin"
//noinspection GroovyAssignabilityCheck
        property "sonar.password", "admin"
        property "sonar.exclusions","es.miguelprietos.testapplication/R.java"
        property "sonar.android.lint.report", "build/outputs/lint-results.xml"
        property "sonar.binaries", "build/intermediates/classes/debug"
        property "sonar.java.binaries", "build/intermediates/classes/debug"

    }
}
</code>```

I use below command to run my Sonar task (no parameters).

```<code> ./gradlew sonarqube
</code>```

Lint options configured in my Gradle is as below

```<code>   lintOptions {
        // set to true to turn off analysis progress reporting by lint
        quiet true
        // if true, stop the gradle build if errors are found
        abortOnError false
        // if true, only report errors
        ignoreWarnings true
    }
</code>```

答:
Try not ignore warnings:</p>

```<code>lintOptions {
    // set to true to turn off analysis progress reporting by lint
    quiet true
    // if true, stop the gradle build if errors are found
    abortOnError false
    // do not ignore warnings
    warningsAsErrors true
}
</code>```

Body:
I have setup my project to use with Sonarqube. I was using PMD and Checkstyle to run tests and all of them are successfully logged in Sonarqube console. But last day I decided to add Android lint rules also to my Quality profile. I have activated all Lint rules in a new profile and run the project. Now when I run the project, it is not showing up any errors or issues with this profile. When I run the lint locally I get about 400 issues. What could I be missing?

I am using Sonarqube plugin in Gradle and Sonarqube 6.2 on my server. My Sonarqube configuration is as follows

apply plugin: "org.sonarqube"

sonarqube {
//noinspection GroovyAssignabilityCheck
    properties {
//noinspection GroovyAssignabilityCheck
        property "sonar.projectName", "MyProject"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectKey", "Testapplication"
//noinspection GroovyAssignabilityCheck
        property "sonar.projectVersion", "1.0"
//noinspection GroovyAssignabilityCheck
        property "sonar.analysis.mode", "publish"
//noinspection GroovyAssignabilityCheck
        property "sonar.language", "java"
//noinspection GroovyAssignabilityCheck
        property "sonar.sources", "src/main/"
//noinspection GroovyAssignabilityCheck
        property "sonar.profile", "FindBugs"
//noinspection GroovyAssignabilityCheck
        property "sonar.host.url", "http://192.168.21.33:9000"
//noinspection GroovyAssignabilityCheck
        property "sonar.login", "admin"
//noinspection GroovyAssignabilityCheck
        property "sonar.password", "admin"
        property "sonar.exclusions","es.miguelprietos.testapplication/R.java"
        property "sonar.android.lint.report", "build/outputs/lint-results.xml"
        property "sonar.binaries", "build/intermediates/classes/debug"
        property "sonar.java.binaries", "build/intermediates/classes/debug"

    }
}

I use below command to run my Sonar task (no parameters).

 ./gradlew sonarqube

Lint options configured in my Gradle is as below

   lintOptions {
        // set to true to turn off analysis progress reporting by lint
        quiet true
        // if true, stop the gradle build if errors are found
        abortOnError false
        // if true, only report errors
        ignoreWarnings true
    }

Body:
Try not ignore warnings:

lintOptions {
    // set to true to turn off analysis progress reporting by lint
    quiet true
    // if true, stop the gradle build if errors are found
    abortOnError false
    // do not ignore warnings
    warningsAsErrors true
}


问:
Convert a part of a string into upper case
I am automatically obtaining directories from an application but I can't seem to get the actual directories with the correct case of letters.

For example I get $a='C:\test\dir\log\wqerst' but the actual directory is C:\test\dir\log\WQERST.

What I want is to uppercase only wqerst so it would show C:\test\dir\log\WQERST

I've already tried using substring but I don't know how I would be able to connect it to the whole directory once it is uppercase.

答:
As James C. and vonPryz already wrote, there is not much point to get the case sensitive folder path. However you can use this helper method:

```<code>function Get-CaseSensitiveFilePath
{
    Param
    (
        [string]$FilePath
    )
    $parent = Split-Path $FilePath
    $leaf = Split-Path -Leaf $FilePath

    $result = Get-ChildItem $parent | where { $_ -like $leaf }
    $result.FullName
}
</code>```

usage:

```<code>Get-CaseSensitiveFilePath -FilePath 'C:\test\dir\log\WQERST'
</code>```

This will give you the case sensitive folder name but the directory must exist on the computer you execute the script...

Body:
As James C. and vonPryz already wrote, there is not much point to get the case sensitive folder path. However you can use this helper method:

function Get-CaseSensitiveFilePath
{
    Param
    (
        [string]$FilePath
    )
    $parent = Split-Path $FilePath
    $leaf = Split-Path -Leaf $FilePath

    $result = Get-ChildItem $parent | where { $_ -like $leaf }
    $result.FullName
}

usage:

Get-CaseSensitiveFilePath -FilePath 'C:\test\dir\log\WQERST'

This will give you the case sensitive folder name but the directory must exist on the computer you execute the script...


问:
How to embed images in email
I need to embed an image in e-mail. How do I do it?

I do not want to use third party tool, nor am I interested in language specific answer (but it is PHP, in case you are wondering).

I am merely interested in format of resulting e-mail body.

Title: How to embed images in email

Body:
the third way is to base64 encode the image and place it in a data: url

example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAACR0lEQVRYha1XvU4bQRD+bF/JjzEnpUDwCPROywPgB4h0PUWkFEkLposUIYyEU4N5AEpewnkDCiQcjBQpWLiLjk3DrnZnZ3buTv4ae25mZ+Z2Zr7daxljDGpg++Mv978Y5Nhc6+Di5tk9u7/bR3cjY9eOJnMUh3mg5y0roBjk+PF1F+1WCwCCJKTgpz9/ozjMg+ftVQQ/PtrB508f1OAcau8ADW5xfLRTOzgAZMPxTNy+YpDj6vaPGtxPgvpL7QwAtKXts8GqBveT8P1p5YF5x8nlo+n1p6bXn5ov3x9M+fZmjDGRXBXWH5X/Lv4FdqCLaLAmwX1/VKYJtIwJeYDO+dm3PSePJnO8vJbJhqN62hOUJ8QpoD1Au5kmIentr9TobAK04RyJEOazzjV9KokogVRwjvm6652kniYRJUBrTkft5bUEAGyuddzz7noHALBYls5O09skaE+4HdAYruobUz1FVI6qcy7xRFW95A915pzjiTp6zj7za6fB1lay1/Ssfa8/jRiLw/n1k9tizl7TS/aZ3xDakdqUByR/gDcF0qJV8QAXHACy+7v9wGA4ngWLVskDo8kcg4Ot8FpGa8PV0I7MyeWjq53f7Zrer3nyOLYJpJJowgN+g9IExNNQ4vLFskwyJtVrd8JoB7g3b4rz66dIpv7UHqg611xw/0om8QT7XXBx84zheCbKGui2U9n3p/YAlSVyqRqc+kt+mCyWJTSeoMGjOQciOQDXA6kjVTsL6JhpYHtA+wihPaGOWgLqnVACPQua4j8NK7bPLP4+qQAAAABJRU5ErkJggg==" width="32" height="32">


问:
How to load sentences into Python gensim?
I am trying to use the word2vec module from gensim natural language processing library in Python.

The docs say to initialize the model:

from gensim.models import word2vec
model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)
```

<p>What format does <code>gensim</code> expect for the input sentences?  I have raw text</p>

```"the quick brown fox jumps over the lazy dogs"
"Then a cop quizzed Mick Jagger's ex-wives briefly."
etc.
```

<p>What additional processing do I need to post into <code>word2fec</code>?</p>

<hr>

<p><strong>UPDATE:</strong> Here is what I have tried.  When it loads the sentences, I get nothing.</p>

```>>> sentences = ['the quick brown fox jumps over the lazy dogs',
             "Then a cop quizzed Mick Jagger's ex-wives briefly."]
>>> x = word2vec.Word2Vec()
>>> x.build_vocab([s.encode('utf-8').split( ) for s in sentences])
>>> x.vocab
{}
```

答:
Like alKid pointed out, make it utf-8.

Talking about two additional things you might have to worry about.

Input is too large and you're loading it from a file.

Removing stop words from the sentences.

Instead of loading a big list into the memory, you can do something like:

```<code>import nltk, gensim
class FileToSent(object):
    def __init__(self, filename):
        self.filename = filename
        self.stop = set(nltk.corpus.stopwords.words('english'))

    def __iter__(self):
        for line in open(self.filename, 'r'):
           ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
           yield ll
</code>```

And then,

```<code>sentences = FileToSent('sentence_file.txt')
model = gensim.models.Word2Vec(sentences=sentences, window=5, min_count=5, workers=4, hs=1)
</code>```

Body:
I am trying to use the word2vec module from gensim natural language processing library in Python.

The docs say to initialize the model:

from gensim.models import word2vec
model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)

What format does gensim expect for the input sentences?  I have raw text

"the quick brown fox jumps over the lazy dogs"
"Then a cop quizzed Mick Jagger's ex-wives briefly."
etc.

What additional processing do I need to post into word2fec?

UPDATE: Here is what I have tried.  When it loads the sentences, I get nothing.

>>> sentences = ['the quick brown fox jumps over the lazy dogs',
             "Then a cop quizzed Mick Jagger's ex-wives briefly."]
>>> x = word2vec.Word2Vec()
>>> x.build_vocab([s.encode('utf-8').split( ) for s in sentences])
>>> x.vocab
{}

Body:
Like alKid pointed out, make it utf-8.

Talking about two additional things you might have to worry about.

Input is too large and you're loading it from a file.

Removing stop words from the sentences.

Instead of loading a big list into the memory, you can do something like:

import nltk, gensim
class FileToSent(object):
    def __init__(self, filename):
        self.filename = filename
        self.stop = set(nltk.corpus.stopwords.words('english'))

    def __iter__(self):
        for line in open(self.filename, 'r'):
           ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
           yield ll

And then,

sentences = FileToSent('sentence_file.txt')
model = gensim.models.Word2Vec(sentences=sentences, window=5, min_count=5, workers=4, hs=1)

ContentLicense: CC BY-SA 4.0


问:
What is the reason I am getting: Socket operation on non-socket
I am writing c sockets the send a file from client to server.  client() is called in main client program while the server() is called in the server program. send_file() is a helper function for client().  I want the server to wait for another client connection after it finishes getting data from the current client.

The first iteration is fine but I am getting error from accept in the SECOND iteration in the server: server: accept: Socket operation on non-socket

What causes the problem?

```<code>int send_file(int socket, char *path) {
    int len;
    char buf[BUF_SIZE];
    char size[BUF_SIZE];
    struct stat stbuf;

    int fd = open(path, O_RDONLY);
    fstat(fd, &stbuf);
    sprintf(size, "%d", (int)stbuf.st_size);

    write(socket, size, BUF_SIZE);
    while((len = read(fd, buf, BUF_SIZE)) > 0) {
        write(socket, buf, len);
    }

    close(fd);
    return 1;
}

int client(char *src_path, char *dest_path, char *host_ip, int port) {

    int sock_fd;
    // Create the sock fd
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("client: socket");
        exit(1);
    }

    // Set the IP and port of the server to connect to.
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    if (inet_pton(AF_INET, host_ip, &server.sin_addr) < 1) {
        perror("client: inet_pton");
        close(sock_fd);
        exit(1);
    }

    // Connect to the server
    if (connect(sock_fd, (struct sockaddr *)&server, sizeof(server)) == -1) {
        perror("client: connect");
        close(sock_fd);
        exit(1);
    }

    send_file(sock_fd, src_path);

    return 0;
}

int server(int port) {
    printf("PORT: %d\n", port);

    char buf[BUF_SIZE];
    int sock_fd, client_fd;
    int len;

    // Create the socket FD.
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("server: socket");
        exit(1);
    }

    // Set information about the port (and IP) we want to be connected to.
    struct sockaddr_in server, client;
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = INADDR_ANY;
    memset(&server.sin_zero, 0, 8);

    // Bind the selected port to the socket
    if (bind(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
        perror("server: bind");
        close(sock_fd);
        exit(1);
    }

    // Announce willingness to accept connections on this socket
    if (listen(sock_fd, MAX_BACKLOG) < 0) {
        perror("server: listen");
        close(sock_fd);
        exit(1);
    }

    while(1) {
        socklen_t client_size = sizeof(client);
        if ((client_fd = accept(sock_fd, (struct sockaddr *)&client, &client_size)) < 0) {
            perror("server: accept");
            close(sock_fd);
            exit(1);
        }

        read(client_fd, buf, BUF_SIZE);
        int size = atoi(buf);
        printf("Size: %d\n", size);

        while ((size > 0) && ((len = read(client_fd, buf, BUF_SIZE)) > 0)) {
            size -= len;
            buf[len] = '\0';
            printf("%s", buf);
        }

       close(client_fd);
    }

    close(sock_fd);

    exit(1);
}
</code>```

答:
You have a buffer overflow in your read code on the server.

```<code>    while ((size > 0) && ((len = read(client_fd, buf, BUF_SIZE)) > 0)) {
        size -= len;
        buf[len] = '\0';
        //  ^^^ Boom!!!
        printf("%s", buf);
    }
</code>```

If you read BUF_SIZE bytes from the socket, len is BUF_SIZE and then you set the byte at buf[BUF_SIZE] to \0. This must be clobbering the socket file descriptor which is declared straight after the buffer.

I should add, the best way to fix it is probably to declare the buffer with size BUF_SIZE + 1 rather than read BUF_SIZE - 1 bytes because the IO will be a bit more efficient (you are writing in BUF_SIZE chunks).

Body:
I am writing c sockets the send a file from client to server.  client() is called in main client program while the server() is called in the server program. send_file() is a helper function for client().  I want the server to wait for another client connection after it finishes getting data from the current client.

The first iteration is fine but I am getting error from accept in the SECOND iteration in the server: server: accept: Socket operation on non-socket

What causes the problem?

int send_file(int socket, char *path) {
    int len;
    char buf[BUF_SIZE];
    char size[BUF_SIZE];
    struct stat stbuf;

    int fd = open(path, O_RDONLY);
    fstat(fd, &stbuf);
    sprintf(size, "%d", (int)stbuf.st_size);

    write(socket, size, BUF_SIZE);
    while((len = read(fd, buf, BUF_SIZE)) > 0) {
        write(socket, buf, len);
    }

    close(fd);
    return 1;
}

int client(char *src_path, char *dest_path, char *host_ip, int port) {

    int sock_fd;
    // Create the sock fd
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("client: socket");
        exit(1);
    }

    // Set the IP and port of the server to connect to.
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    if (inet_pton(AF_INET, host_ip, &server.sin_addr) < 1) {
        perror("client: inet_pton");
        close(sock_fd);
        exit(1);
    }

    // Connect to the server
    if (connect(sock_fd, (struct sockaddr *)&server, sizeof(server)) == -1) {
        perror("client: connect");
        close(sock_fd);
        exit(1);
    }

    send_file(sock_fd, src_path);

    return 0;
}

int server(int port) {
    printf("PORT: %d\n", port);

    char buf[BUF_SIZE];
    int sock_fd, client_fd;
    int len;

    // Create the socket FD.
    sock_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (sock_fd < 0) {
        perror("server: socket");
        exit(1);
    }

    // Set information about the port (and IP) we want to be connected to.
    struct sockaddr_in server, client;
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = INADDR_ANY;
    memset(&server.sin_zero, 0, 8);

    // Bind the selected port to the socket
    if (bind(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0) {
        perror("server: bind");
        close(sock_fd);
        exit(1);
    }

    // Announce willingness to accept connections on this socket
    if (listen(sock_fd, MAX_BACKLOG) < 0) {
        perror("server: listen");
        close(sock_fd);
        exit(1);
    }

    while(1) {
        socklen_t client_size = sizeof(client);
        if ((client_fd = accept(sock_fd, (struct sockaddr *)&client, &client_size)) < 0) {
            perror("server: accept");
            close(sock_fd);
            exit(1);
        }

        read(client_fd, buf, BUF_SIZE);
        int size = atoi(buf);
        printf("Size: %d\n", size);

        while ((size > 0) && ((len = read(client_fd, buf, BUF_SIZE)) > 0)) {
            size -= len;
            buf[len] = '\0';
            printf("%s", buf);
        }

       close(client_fd);
    }

    close(sock_fd);

    exit(1);
}

Body:
You have a buffer overflow in your read code on the server.

    while ((size > 0) && ((len = read(client_fd, buf, BUF_SIZE)) > 0)) {
        size -= len;
        buf[len] = '\0';
        //  ^^^ Boom!!!
        printf("%s", buf);
    }

If you read BUF_SIZE bytes from the socket, len is BUF_SIZE and then you set the byte at buf[BUF_SIZE] to \0. This must be clobbering the socket file descriptor which is declared straight after the buffer.

I should add, the best way to fix it is probably to declare the buffer with size BUF_SIZE + 1 rather than read BUF_SIZE - 1 bytes because the IO will be a bit more efficient (you are writing in BUF_SIZE chunks).


问:
Abstract type in Julia and member variables
I am very confused as to whether abstract types in Julia can have member variables (like virtual classes in C++). I am sure the docs mention it but I cannot find it!

I tried something like:

```<code>abstract AbstractR
  source
end
</code>```

And now I have a concrete implementation as:

```<code>type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end
</code>```

However, when I try to load the module, I have:

ERROR: LoadError: LoadError: LoadError: UndefVarError: source not
  defined

So is it that abstract type is just a type name and nothing else? Also, why did the language designers decide to not support member variables (if that is indeed the case). Also, I do not then really see the point of having an abstract type anyway...

EDIT

Module file

```<code>module TestProj
export AbstractR
export RR
include("generic.jl")
include("rr.jl")
end
</code>```

generic.jl

```<code>abstract AbstractR
  source
end
</code>```

rr.jl

```<code>type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end
</code>```

答:
At least the way I understand it is that abstract types are intended to serve as "nodes" and as such are not themselves instantiateable (sp?). As such they allow you organise concrete types into hierarchies & provide an easy way for methods to dispatch on any of a group of concrete types.

I think the docs explain this here.

(With this the error msg should make sense as well?)

Body:
I am very confused as to whether abstract types in Julia can have member variables (like virtual classes in C++). I am sure the docs mention it but I cannot find it!

I tried something like:

abstract AbstractR
  source
end

And now I have a concrete implementation as:

type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end

However, when I try to load the module, I have:

ERROR: LoadError: LoadError: LoadError: UndefVarError: source not
  defined

So is it that abstract type is just a type name and nothing else? Also, why did the language designers decide to not support member variables (if that is indeed the case). Also, I do not then really see the point of having an abstract type anyway...

EDIT

Module file

module TestProj
export AbstractR
export RR
include("generic.jl")
include("rr.jl")
end

generic.jl

abstract AbstractR
  source
end

rr.jl

type RR <: AbstractR
end

function loadSource(reg::RR, x::AbstractString)
  println("Hello")
end


问:
javascript | Object grouping
I have an object. It looks like below:

```<code>[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]
</code>```

I would like to group this data by group field and get this object:

```<code>var obj = {
    0 = [
    {
       'group'   = 'Technical detals',
       'name'    = 'Display',
       'id'      = '60',
       'value'   = '4'
    },
    {
       'group'   = 'Technical detals',
       'name'    = 'OS',
       'id'      = '37',
       'value'   = 'Apple iOS'
    }],
    1   = [
    {
       'group'   = 'Manufacturer',
       'name'    = 'Manufacturer',
       'id'      = '58',
       'value'   = 'Apple'
    }]
}
</code>```

How can I group my first object?

答:
You could use a hash table for the groups and Array#forEach for iterating the array.

Then check if the hash exist and if not assign an empty array to it and push it to the result set.

Later push the actual element to the array of the hash.

function groupBy(array, group) {
    var hash = Object.create(null),
        result = [];

    array.forEach(function (a) {
        if (!hash[a[group]]) {
            hash[a[group]] = [];
            result.push(hash[a[group]]);
        }
        hash[a[group]].push(a);
    });
    return result;
}

var data = [{ name: "Display", group: "Technical detals", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical detals", id: 37, value: "Apple iOS" }];

console.log(groupBy(data, "group"));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

UPDATE 2022

You could take the possible upcoming Array#groupBy or a polyfill and take only the values of the object.

This methods need a callback for a grouping value.

```<code>({ group }) => group    // take property group and return it
</code>```

Array.prototype.groupBy ??= function(callbackfn, thisArg) {
    const
        O = Object(this),
        len = O.length >>> 0;

    if (typeof callbackfn !== 'function') {
        throw new TypeError(callbackfn + ' is not a function');
    }

    let k = 0;
    const groups = {};

    while (k < len) {
        const
            Pk = Number(k).toString(),
            kValue = O[Pk],
            propertyKey = callbackfn.call(thisArg, kValue, Number(k), O);

        (groups[propertyKey] ??= []).push(kValue);
        ++k;
    }
    return groups;
}

const
    data = [{ name: "Display", group: "Technical details", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical details", id: 37, value: "Apple iOS" }],
    result = Object.values(data.groupBy(({ group }) => group));

console.log(result);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: javascript | Object grouping

Body:
I have an object. It looks like below:

[
  {
    "name":"Display",
    "group":"Technical detals",
    "id":"60",
    "value":"4"
  },
  {
    "name":"Manufacturer",
    "group":"Manufacturer",
    "id":"58",
    "value":"Apple"
  },
  {
    "name":"OS",
    "group":"Technical detals",
    "id":"37",
    "value":"Apple iOS"
  }
]

I would like to group this data by group field and get this object:

var obj = {
    0 = [
    {
       'group'   = 'Technical detals',
       'name'    = 'Display',
       'id'      = '60',
       'value'   = '4'
    },
    {
       'group'   = 'Technical detals',
       'name'    = 'OS',
       'id'      = '37',
       'value'   = 'Apple iOS'
    }],
    1   = [
    {
       'group'   = 'Manufacturer',
       'name'    = 'Manufacturer',
       'id'      = '58',
       'value'   = 'Apple'
    }]
}

How can I group my first object?

Body:
You could use a hash table for the groups and Array#forEach for iterating the array.

Then check if the hash exist and if not assign an empty array to it and push it to the result set.

Later push the actual element to the array of the hash.

function groupBy(array, group) {
    var hash = Object.create(null),
        result = [];

    array.forEach(function (a) {
        if (!hash[a[group]]) {
            hash[a[group]] = [];
            result.push(hash[a[group]]);
        }
        hash[a[group]].push(a);
    });
    return result;
}

var data = [{ name: "Display", group: "Technical detals", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical detals", id: 37, value: "Apple iOS" }];

console.log(groupBy(data, "group"));

.as-console-wrapper { max-height: 100% !important; top: 0; }

UPDATE 2022

You could take the possible upcoming Array#groupBy or a polyfill and take only the values of the object.

This methods need a callback for a grouping value.

({ group }) => group    // take property group and return it

Array.prototype.groupBy ??= function(callbackfn, thisArg) {
    const
        O = Object(this),
        len = O.length >>> 0;

    if (typeof callbackfn !== 'function') {
        throw new TypeError(callbackfn + ' is not a function');
    }

    let k = 0;
    const groups = {};

    while (k < len) {
        const
            Pk = Number(k).toString(),
            kValue = O[Pk],
            propertyKey = callbackfn.call(thisArg, kValue, Number(k), O);

        (groups[propertyKey] ??= []).push(kValue);
        ++k;
    }
    return groups;
}

const
    data = [{ name: "Display", group: "Technical details", id: 60, value: 4 }, { name: "Manufacturer", group: "Manufacturer", id: 58, value: "Apple" }, { name: "OS", group: "Technical details", id: 37, value: "Apple iOS" }],
    result = Object.values(data.groupBy(({ group }) => group));

console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
(De)Normalization of two relations
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

```<code>r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35
</code>```

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.

答:
I think the pair of relations violates fifth normal form.

R2 is a projection of R1.  Some argue that SUM is outside the scope of the relational model.  In this case, SUM is a trivial extension of COUNT, which is within the scope of the relational model.

Title: (De)Normalization of two relations

Body:
People who read C.J.Date's Introduction to Database System or books of similar level should not have problems with definition of normalization and denormalization.

However, memory is not what it used to be and I find myself often looking at some design and saying that it is not normalized even though I can not find which of the normal forms it is breaking.

The actual example that illustrate it is:

If we have relations

r1 (A, B, C) and r2 (A, D)

with FDs: AB->C and A->D

and r1 represent detailed data, while r2 is summary of that data (in another words each instance of D is a function of values in r1. in this example let it be subtotal of values C according to A from r1).

Example instance

r1 =
A  B  C
1  1  10
1  2  20
2  1  10
2  2  25

r2 =
A  D
1  30
2  35

So, even though I can not say that it breaks for example 2NF or 3NF, I seem to be stuck on the idea that the design is still denormalised in the following sense (from Codd, E.F. "Further Normalization of the Data Base Relational Model", p. 34, commenting on the reasons to normalize beyond 1NF):

To free the collection of relations from undesirable insertion,
  update and deletion dependencies;

To reduce the need for restructuring the collection of
  relations as new types of data are
  introduced, and thus increase the life
  span of application programs;

To make the relational model more informative to users;

To make the collection of relations neutral to the query
  statistics, where these statistics are
  liable to change as time goes by.

As I can say, that if we define D as a sum of all Cs from r1 where A from r1 is equal to A from r2 then, if we update C in r1 and we don't update D in r2, we can end up with undesirable update dependency and the data ends up in inconsistent state I find this reason to call r1 and r2 denormalized and to think of them as denormalized. (In fact whole r2 is a function of r1 and bring zero new facts into the model; r2 = f(r1))

So the questions are

can we call r1 and r2 denormalized?

if yes, why? if not, why? (according to which rule? or according to which definition?)

NOTE:

To those who find the question(s) interesting enough to put in an answer, I kindly ask to provide either something quotable or to put it in a form of specific assumptions and conclusions (or in another words, if you are going to put in your opinion, please follow it with some reasoning).

EDIT
I accepted dportas answer. I'll try to add a bit to it here:
C.J.Date can makes a clear and strict distinction:

Much of design theory has to do with
  reducing redundancy; normalization
  reduces redundancy within relvars,
  orthogonality reduces it across
  relvars.

quoted from Database in depth: relational theory for practitioners

and on the next page

just as a failure to normalize all the
  way implies redundancy and can lead to
  certain anomalies, so too can a
  failure to adhere to orthogonality.


问:
Semaphore signalling vs mutex
I was looking over some topics that describes the difference between mutex and binary semaphore. In many topics it is stated that semaphore act as a signalling mechanism i.e if a thread has locked a semaphore then another thread can unlock(release) the semaphore(acting as signal).
But in case of mutex only the thread that locks the mutex can unlock it .It can't be unlocked by any other thread and if other thread tries to unlock it this will return error.

I have tried writing a code that uses mutex for synchronization. In the code I am locking the mutex in one thread and successfully unlocking the mutex in other thread.
Can someone please explain how this can happen.According to the answers everywhere  the other thread should not be able to unlock mutex.

Any suggestions are most welcome.

答:
Typical POSIX thread implementations do not perform any checks or validations that the thread unlocking a mutex is the same as the one that locked that (or likely even that the mutex was locked in the first place). This is not how mutexes are supposed to be used. The word "mutex" means mutual exclusion; the purpose of the concept is to provide a mechanism for multiple threads to safely access or modify a resource (e.g. data structure) without other threads interfering, and when done a modification have the resource in consistent state before unlocking the mutex.

It could be nice to catch such programming errors in run time (just like catching out of bounds writes to arrays), but by default providing such book-keeping and guards are too expensive in terms of performance; mutex locking and unlocking operations are supposed to give you minimal overhead for them to be usable. This is the reason you are succeeding in unlocking your mutexes from a wrong thread. In standard Linux pthread implementation you could use "error checking" mutexes, which would give you error when you try to unlock a mutex from a wrong thread, but again this check exists only to catch programming errors.

I am not able to advice you in compact form about what to use for and how to implement your signaling without better understanding of the nature of your signaling need.

Title: Semaphore signalling vs mutex


问:
Why JavaScript function declaration behave differently in chrome and safari?

    foo();

    if (true) {
      function foo() {
        console.log(1);
      }
    } else {
      function foo() {
        console.log(2)
      }
    }```

In chrome it shows Uncaught TypeError,but In safari it shows 2.

答:
This behaviour has some history. In the beginning (let's say ECMA-262 ed 3, which was the first real version of the spec) function declarations weren't permitted inside blocks (see Kangax, Function statements).

However, IE just treated them as function declarations and "hoisted" them, while Mozilla browsers (maybe Netscape Navigator) conditionally evaluated them as function statements, an allowed extension to the specification. Some other browsers threw an error, which is probably what they should have done.

That range of behaviours was pretty intolerable so with ECMA-262 ed 5 aka ES5, function statements were formalised in an appendix (they were better explained in the next version, ECMAScript 2015 Appendix B.3.3 Block-Level Function Declarations Web Legacy Compatibility Semantics). This was probably part of the push to document what various implementations do rather than trying to rigidly enforce particular behaviour that was contrary to intent but not the letter of the spec.

To fix things, function statements were prohibited in strict mode, which was also introduced with ECMAScript ed 5.

For additional reading, see May function declarations appear inside statements in JavaScript? for a good Q&A from about the time of Ed 5.

The bottom line is that if you want to conditionally "declare" a function, use function expressions, which avoid all issues with function statements as they are consistently treated by all implementations:

```<code>var someFn;

if (something) {
  someFn = function(...params1) {/*statement list 1*/};

} else {
  someFn = function(...params2) {/*statement list 2*/};
}
</code>```

There is a discussion on this topic on comp.lang.javascript: FAQ Topic - What is a function statement? from May 2010. Mostly read the exchanges between  Juriy "kangax" Zaytsev and Richard Cornford, e.g.

Kangax:

… You mean -- it doesn't matter -- whether it is
  a function declaration (which is created on entering the
  context) or a function statement (which the same as function
  expression and created by the Function constructor is created
  at code execution), i.e. both of them can be treated as just
  an allowed extension?

Cornford:

Yes, ECMA syntax doesn't allow for either so if they are there they
  must be extensions. Extensions are allowed so neither can be
  considered wrong (on the surface, even if IE's treating named function
  expressions as 'out of context' function declarations, and so
  potentially producing two function objects, is so unhelpfully odd that
  it would be better considered a bug than an extension). There has
  never been any reason for expecting two different ECMAScript
  implementations to have the same extensions, so there is no reason for
  expecting the same non-(ECMA)standard syntax to result in the same
  behaviour in two different environments. (Of course if an environment
  claims to be JavaScript(tm) compatible in addition to being ECMAScript
  compatible then it should be reproducing the extensions found in
  JavaScript(tm)).

Which pretty much answers the question and notes why function statements should be avoided.

Body:
    foo();

    if (true) {
      function foo() {
        console.log(1);
      }
    } else {
      function foo() {
        console.log(2)
      }
    }

In chrome it shows Uncaught TypeError,but In safari it shows 2.

Body:
This behaviour has some history. In the beginning (let's say ECMA-262 ed 3, which was the first real version of the spec) function declarations weren't permitted inside blocks (see Kangax, Function statements).

However, IE just treated them as function declarations and "hoisted" them, while Mozilla browsers (maybe Netscape Navigator) conditionally evaluated them as function statements, an allowed extension to the specification. Some other browsers threw an error, which is probably what they should have done.

That range of behaviours was pretty intolerable so with ECMA-262 ed 5 aka ES5, function statements were formalised in an appendix (they were better explained in the next version, ECMAScript 2015 Appendix B.3.3 Block-Level Function Declarations Web Legacy Compatibility Semantics). This was probably part of the push to document what various implementations do rather than trying to rigidly enforce particular behaviour that was contrary to intent but not the letter of the spec.

To fix things, function statements were prohibited in strict mode, which was also introduced with ECMAScript ed 5.

For additional reading, see May function declarations appear inside statements in JavaScript? for a good Q&A from about the time of Ed 5.

The bottom line is that if you want to conditionally "declare" a function, use function expressions, which avoid all issues with function statements as they are consistently treated by all implementations:

var someFn;

if (something) {
  someFn = function(...params1) {/*statement list 1*/};

} else {
  someFn = function(...params2) {/*statement list 2*/};
}

There is a discussion on this topic on comp.lang.javascript: FAQ Topic - What is a function statement? from May 2010. Mostly read the exchanges between  Juriy "kangax" Zaytsev and Richard Cornford, e.g.

Kangax:

… You mean -- it doesn't matter -- whether it is
  a function declaration (which is created on entering the
  context) or a function statement (which the same as function
  expression and created by the Function constructor is created
  at code execution), i.e. both of them can be treated as just
  an allowed extension?

Cornford:

Yes, ECMA syntax doesn't allow for either so if they are there they
  must be extensions. Extensions are allowed so neither can be
  considered wrong (on the surface, even if IE's treating named function
  expressions as 'out of context' function declarations, and so
  potentially producing two function objects, is so unhelpfully odd that
  it would be better considered a bug than an extension). There has
  never been any reason for expecting two different ECMAScript
  implementations to have the same extensions, so there is no reason for
  expecting the same non-(ECMA)standard syntax to result in the same
  behaviour in two different environments. (Of course if an environment
  claims to be JavaScript(tm) compatible in addition to being ECMAScript
  compatible then it should be reproducing the extensions found in
  JavaScript(tm)).

Which pretty much answers the question and notes why function statements should be avoided.


问:
How can I add and manipulate existing GET variables of the current url in php?
Hi I have URLs like this...

```<code>www.example.com/list.php?type=vehicles&stype=Cars
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana
</code>```

Now i want to sort all my results on basis of price, model and visits. SO i use

```<code>$sort="id";
    if(isset($_GET['sort'])){
        if($_GET['sort']=='P-ASC'){ $sort = "price ASC"; }
        elseif($_GET['sort']=='P-DESC'){ $sort = "price DESC"; }
        elseif($_GET['sort']=='R-ASC'){ $sort = "model ASC"; }
        elseif($_GET['sort']=='R-DESC'){ $sort = "model DESC"; }
        elseif($_GET['sort']=='V-ASC'){ $sort = "visits ASC"; }
        elseif($_GET['sort']=='V-DESC'){ $sort = "visits DESC"; }
    }
</code>```

Now i want to add sort variable at the end of url to sort results. e.g.

```<code>www.example.com/list.php?type=vehicles&stype=Cars&sort='**ANYVALUE**'
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana&sort='**ANYVALUE**'
</code>```

And on href i am using which is working absolutely fine for me so far...

```<code><a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='**Anyvalue**'"
</code>```

Problem exists when i try to manipulate sort value e.g. I have two href

```<code><a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-ASC'"
<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-DESC'"
</code>```

When i go to first url it works fine and when i go to second url after using first one then the URL add another sort variable in URL result in TWO sort variables in URL. What i want is

To check if any of these GET variable exists or not ?

If it exists then manipulate value of those variables ?

And if doesn't exist then add new get variable to URL.

答:
http_build_query($_GET + ['sort' => 'anyvalue'])

should work

EDIT

plus sign for arrays do this

```<code>$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['a' => 4, 'd' => 5];
$res = $a + $b;
</code>```

It adds keys to array $a from $b that are not present in $a

This is $res variable:

```<code>array(4) {
  'a' =>
  int(1)
  'b' =>
  int(2)
  'c' =>
  int(3)
  'd' =>
  int(5)
}
</code>```

And http_build_query function builds a query string from array.
so http_build_query($res) will be:

```<code>a=1&b=2&c=3&d=5
</code>```

In your case you can use it like this:

```<code><a href="?<?php echo http_build_query($_GET + ['sort' => '**AnyValue**']); ?>">link</a>
</code>```

Body:
Hi I have URLs like this...

www.example.com/list.php?type=vehicles&stype=Cars
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana

Now i want to sort all my results on basis of price, model and visits. SO i use

$sort="id";
    if(isset($_GET['sort'])){
        if($_GET['sort']=='P-ASC'){ $sort = "price ASC"; }
        elseif($_GET['sort']=='P-DESC'){ $sort = "price DESC"; }
        elseif($_GET['sort']=='R-ASC'){ $sort = "model ASC"; }
        elseif($_GET['sort']=='R-DESC'){ $sort = "model DESC"; }
        elseif($_GET['sort']=='V-ASC'){ $sort = "visits ASC"; }
        elseif($_GET['sort']=='V-DESC'){ $sort = "visits DESC"; }
    }

Now i want to add sort variable at the end of url to sort results. e.g.

www.example.com/list.php?type=vehicles&stype=Cars&sort='**ANYVALUE**'
www.example.com/list.php?type=vehicles&stype=Cars&loc=Ludhiana&sort='**ANYVALUE**'

And on href i am using which is working absolutely fine for me so far...

<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='**Anyvalue**'"

Problem exists when i try to manipulate sort value e.g. I have two href

<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-ASC'"
<a href="?<?php echo $_SERVER['QUERY_STRING']; ?>&sort='P-DESC'"

When i go to first url it works fine and when i go to second url after using first one then the URL add another sort variable in URL result in TWO sort variables in URL. What i want is

To check if any of these GET variable exists or not ?

If it exists then manipulate value of those variables ?

And if doesn't exist then add new get variable to URL.

Body:
http_build_query($_GET + ['sort' => 'anyvalue'])

should work

EDIT

plus sign for arrays do this

$a = ['a' => 1, 'b' => 2, 'c' => 3];
$b = ['a' => 4, 'd' => 5];
$res = $a + $b;

It adds keys to array $a from $b that are not present in $a

This is $res variable:

array(4) {
  'a' =>
  int(1)
  'b' =>
  int(2)
  'c' =>
  int(3)
  'd' =>
  int(5)
}

And http_build_query function builds a query string from array.
so http_build_query($res) will be:

a=1&b=2&c=3&d=5

In your case you can use it like this:

<a href="?<?php echo http_build_query($_GET + ['sort' => '**AnyValue**']); ?>">link</a>