问:
Share extension registeredTypeIdentifiers
My share extension is supposed to handle Image, Video, File the same way, namely, just write it to shared container app group, but currently, i just do something like this:

```<code>   if let item = extensionContext?.inputItems.first as? NSExtensionItem {
  if let itemProvider = item.attachments?.first as? NSItemProvider {
    if itemProvider.hasItemConformingToTypeIdentifier(contentTypeImage) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeImage, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let image = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: image, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypePDF) {
      itemProvider.loadItem(forTypeIdentifier: contentTypePDF, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let pdf = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: pdf, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeMovie) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeMovie, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let pdf = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: pdf, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeURL, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else {
      extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
    }
  }
}
</code>```

Which handles types separately, thus very lengthy, so i dont know if any way i can check and handle forTypeIdentifier of Image, pdf, photo in just 1 if statement like this:

```<code>if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {
</code>```

}

Thanks,
Tuyen

答:
You should have 3 condition since there is no property or method to get item provider type. But you can simplify the code by moving the common code into the separate method.

```<code>func loadItem(itemProvider: NSItemProvider, contentType: NSString) {
  itemProvider.loadItem(forTypeIdentifier: contentType, options: nil, completionHandler: { (url, error) -> Void in
    if let shareURL = url as? URL {
      if (type == contentTypeURL) {
        //URL operation goes here
      } else {
        if let data = NSData(contentsOf: shareURL) {
          self.writeSharedData(data: data, to: shareURL.lastPathComponent)
        }
      }
    }
    self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
  })
}
</code>```

The call the method like following

```<code>if itemProvider.hasItemConformingToTypeIdentifier(contentTypeImage) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeImage)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypePDF) {
  loadItem(itemProvider: itemProvider, contentType: contentTypePDF)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeMovie) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeMovie)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeURL)

} else {
  self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
}
</code>```

Body:
My share extension is supposed to handle Image, Video, File the same way, namely, just write it to shared container app group, but currently, i just do something like this:

   if let item = extensionContext?.inputItems.first as? NSExtensionItem {
  if let itemProvider = item.attachments?.first as? NSItemProvider {
    if itemProvider.hasItemConformingToTypeIdentifier(contentTypeImage) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeImage, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let image = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: image, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypePDF) {
      itemProvider.loadItem(forTypeIdentifier: contentTypePDF, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let pdf = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: pdf, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeMovie) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeMovie, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          if let pdf = NSData(contentsOf: shareURL) {
            _ = self.writeSharedData(data: pdf, to: shareURL.lastPathComponent)
          }
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {
      itemProvider.loadItem(forTypeIdentifier: contentTypeURL, options: nil, completionHandler: { (url, error) -> Void in
        if let shareURL = url as? URL {
          _ = self.openURL(URL(string: "cpc:/
          self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
        }
      })
    } else {
      extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
    }
  }
}

Which handles types separately, thus very lengthy, so i dont know if any way i can check and handle forTypeIdentifier of Image, pdf, photo in just 1 if statement like this:

if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {

}

Thanks,
Tuyen

Body:
You should have 3 condition since there is no property or method to get item provider type. But you can simplify the code by moving the common code into the separate method.

func loadItem(itemProvider: NSItemProvider, contentType: NSString) {
  itemProvider.loadItem(forTypeIdentifier: contentType, options: nil, completionHandler: { (url, error) -> Void in
    if let shareURL = url as? URL {
      if (type == contentTypeURL) {
        //URL operation goes here
      } else {
        if let data = NSData(contentsOf: shareURL) {
          self.writeSharedData(data: data, to: shareURL.lastPathComponent)
        }
      }
    }
    self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
  })
}

The call the method like following

if itemProvider.hasItemConformingToTypeIdentifier(contentTypeImage) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeImage)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypePDF) {
  loadItem(itemProvider: itemProvider, contentType: contentTypePDF)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeMovie) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeMovie)

} else if itemProvider.hasItemConformingToTypeIdentifier(contentTypeURL) {
  loadItem(itemProvider: itemProvider, contentType: contentTypeURL)

} else {
  self.extensionContext?.completeRequest(returningItems: [], completionHandler:nil)
}


来源: stackexchange

问:
SQL Server - Convert scalar function into table valued function
I have below scalar function:

```<code>CREATE FUNCTION [dbo].[GetStringIds]
(
   @IdsTbl ids READONLY
)
RETURNS nvarchar(800)
AS
BEGIN
    DECLARE @IdsLst nvarchar(800);

    SELECT
           @IdsLst = COALESCE(@IdsLst + ', ', '') + '(' + CAST(ID1 AS NVARCHAR) + ' : ' + CAST(ID2 AS NVARCHAR) + ')'
      FROM
           @IdsTbl

    Return @IdsLst
END
</code>```

A table type is passed to this scalar function which contains two fields ID1 and ID2, both int type. This function builds an strings like below:

(12 : 2), (23 : 4), (4 : 34)

NOTE:
ID1 can be repeated but not ID2, ID1+ID2 are primary keys. For example:

```<code>ID1  | ID2
 1     100
 1     200
 1     110
 2     500
 3     200
 3     600
</code>```

Now, I am wondering if it is better to convert it to a table valued function in order to increase database performance in terms of execution time.

So in this case, if I convert it to a table valued function, will it increase performance? Is its execution time be reduced? If so how can convert it to a table valued function? I have problems to convert it as I need to declare a variable in which concatenate.

答:
You can do something like this,

```<code>CREATE FUNCTION [dbo].[GetStringIds] (@IdsTbl ids READONLY)
Returns Table
Return (
     SELECT
       @IdsLst = COALESCE(@IdsLst + ', ', '') + '(' + CAST(ID1 AS NVARCHAR) + ' : ' + CAST(ID2 AS NVARCHAR) + ')'
  FROM
       @IdsTbl
)
</code>```

This may work as my requirement was different I tried to edit in that. Hope for the best.

ContentLicense: CC BY-SA 3.0

Body:
I have below scalar function:

CREATE FUNCTION [dbo].[GetStringIds]
(
   @IdsTbl ids READONLY
)
RETURNS nvarchar(800)
AS
BEGIN
    DECLARE @IdsLst nvarchar(800);

    SELECT
           @IdsLst = COALESCE(@IdsLst + ', ', '') + '(' + CAST(ID1 AS NVARCHAR) + ' : ' + CAST(ID2 AS NVARCHAR) + ')'
      FROM
           @IdsTbl

    Return @IdsLst
END

A table type is passed to this scalar function which contains two fields ID1 and ID2, both int type. This function builds an strings like below:

(12 : 2), (23 : 4), (4 : 34)

NOTE:
ID1 can be repeated but not ID2, ID1+ID2 are primary keys. For example:

ID1  | ID2
 1     100
 1     200
 1     110
 2     500
 3     200
 3     600

Now, I am wondering if it is better to convert it to a table valued function in order to increase database performance in terms of execution time.

So in this case, if I convert it to a table valued function, will it increase performance? Is its execution time be reduced? If so how can convert it to a table valued function? I have problems to convert it as I need to declare a variable in which concatenate.

Body:
You can do something like this,

CREATE FUNCTION [dbo].[GetStringIds] (@IdsTbl ids READONLY)
Returns Table
Return (
     SELECT
       @IdsLst = COALESCE(@IdsLst + ', ', '') + '(' + CAST(ID1 AS NVARCHAR) + ' : ' + CAST(ID2 AS NVARCHAR) + ')'
  FROM
       @IdsTbl
)

This may work as my requirement was different I tried to edit in that. Hope for the best.


问:
how to custom error page from response 403 from .htaccess
I protect .env file using .htaccess file, with this script :

```<code><Files .env>
    Order allow,deny
    Deny from all
</Files>
</code>```

if I access this file with url

```<code>https://myapp.mydomain.com/.env
</code>```

I get this page error :
Forbidden

```<code>You don't have permission to access /.env on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.
</code>```

how to custom this page error ?

I try to override App\Exceptions\Handler.php like this :

```<code>public function render($request, Exception $exception)
    {
        if($e instanceof HttpException && $e->getStatusCode() == 403){
        return abort(403,'Access Denied');
        }
        return parent::render($request, $exception);
    }
</code>```

but no results

答:
You can set custom error pages in Laravel by adding the appropriately named blade to the folder resources/views/errors/ so for a custom 403 add the file 403.blade.php to the above mentioned folder. Inside the blade you can use (from documentation) $exception, dd($exception) to get the handle of the message (more than likley ->getMessage())

Documentation

Body:
I protect .env file using .htaccess file, with this script :

<Files .env>
    Order allow,deny
    Deny from all
</Files>

if I access this file with url

https://myapp.mydomain.com/.env

I get this page error :
Forbidden

You don't have permission to access /.env on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

how to custom this page error ?

I try to override App\Exceptions\Handler.php like this :

public function render($request, Exception $exception)
    {
        if($e instanceof HttpException && $e->getStatusCode() == 403){
        return abort(403,'Access Denied');
        }
        return parent::render($request, $exception);
    }

but no results


问:
codeigniter will not show info from database
Hello all i have a problem that my information is not being sendt to my view file.

it says: Message: Undefined variable: queryWall

my controller is this

```<code>function wallShow()
 {
  $this->load->model('profil_model');
  $data['queryWall'] = $this->profil_model->wallGet($this->uri->segment(3));

  $data['content'] = 'profil_view';
  $this->load->view('includes/template', $data);
 }
</code>```

my model:

```<code>function wallGet($name)
 {
  $this->db->select('profileName', 'wallComment');
  $this->db->where('profileName', $name);
  $queryWall = $this->db->get('profileWall');

  if($queryWall->num_rows() > 0)
  {
   return $queryWall->result();
  } else {
   return false;
  }
 }
</code>```

and my view file

```<code> <?php
 if(!isset($queryWall)):
  foreach ($queryWall as $wall):
   echo $wall->wallComment;
  endforeach;
 endif;
 ?>
</code>```

答:
You are not using the correct syntax for

```<code>$this->db->select('profileName', 'wallComment');
</code>```

Adjust it to this:

```<code>$this->db->select('profileName,wallComment');
</code>```

then also enable the out profiler to verify your query is being written correctly by the database class.  In your controller, enable the profiler:

```<code>$this->output->enable_profiler(true);
</code>```

This can be inserted anywhere in the controller function.

I agree with ifaour about making sure your if statement is what you meant it to be.

ContentLicense: CC BY-SA 2.5

Body:
Hello all i have a problem that my information is not being sendt to my view file.

it says: Message: Undefined variable: queryWall

my controller is this

function wallShow()
 {
  $this->load->model('profil_model');
  $data['queryWall'] = $this->profil_model->wallGet($this->uri->segment(3));

  $data['content'] = 'profil_view';
  $this->load->view('includes/template', $data);
 }

my model:

function wallGet($name)
 {
  $this->db->select('profileName', 'wallComment');
  $this->db->where('profileName', $name);
  $queryWall = $this->db->get('profileWall');

  if($queryWall->num_rows() > 0)
  {
   return $queryWall->result();
  } else {
   return false;
  }
 }

and my view file

 <?php
 if(!isset($queryWall)):
  foreach ($queryWall as $wall):
   echo $wall->wallComment;
  endforeach;
 endif;
 ?>

Body:
You are not using the correct syntax for

$this->db->select('profileName', 'wallComment');

Adjust it to this:

$this->db->select('profileName,wallComment');

then also enable the out profiler to verify your query is being written correctly by the database class.  In your controller, enable the profiler:

$this->output->enable_profiler(true);

This can be inserted anywhere in the controller function.

I agree with ifaour about making sure your if statement is what you meant it to be.


问:
JavaFx TableView cellFactory memory overhead
My question is related to TableView from JavaFx.
JavaFx recommends using Properties for storing values which are going to be shown in the table ( SimpleSttringProperty, etc. ) like in the example below.

Isn't this an memory overhead for Java ( creating another object for each cell ) ?
I am going to use the TableView to show more then 10.000 rows from the database.
Isn't there a way to avoid this, and simply work as Swing did earlier ?
Can't TableView get only the value to represent ?
For all solutions I found an ObservableValue is required for each cell, which may require a lot of memory.

```<code>TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>("First Name");
firstNameCol.setCellValueFactory( element -> element.getValue().firstName );
or
firstNameCol.setCellValueFactory( new PropertyValueFactory<Person, String>("firstName"));
public static class Person {

    public final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private final SimpleStringProperty email;

    private Person(String fName, String lName, String email) {
        this.firstName = new SimpleStringProperty(fName);
        this.lastName = new SimpleStringProperty(lName);
        this.email = new SimpleStringProperty(email);
    }
</code>```

答:
You are not required to use property in your model. Here is an example

```<code>public class Person {

    private String firstName;
    private String lastName;
    private String email;

    public Person() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}
</code>```

just create the property when you need it.

```<code>firstNameCol.setCellValueFactory(cdf -> new SimpleStringProperty(cdf.getValue().getFirstName()));
</code>```

Body:
My question is related to TableView from JavaFx.
JavaFx recommends using Properties for storing values which are going to be shown in the table ( SimpleSttringProperty, etc. ) like in the example below.

Isn't this an memory overhead for Java ( creating another object for each cell ) ?
I am going to use the TableView to show more then 10.000 rows from the database.
Isn't there a way to avoid this, and simply work as Swing did earlier ?
Can't TableView get only the value to represent ?
For all solutions I found an ObservableValue is required for each cell, which may require a lot of memory.

TableColumn<Person,String> firstNameCol = new TableColumn<Person,String>("First Name");
firstNameCol.setCellValueFactory( element -> element.getValue().firstName );
or
firstNameCol.setCellValueFactory( new PropertyValueFactory<Person, String>("firstName"));
public static class Person {

    public final SimpleStringProperty firstName;
    private final SimpleStringProperty lastName;
    private final SimpleStringProperty email;

    private Person(String fName, String lName, String email) {
        this.firstName = new SimpleStringProperty(fName);
        this.lastName = new SimpleStringProperty(lName);
        this.email = new SimpleStringProperty(email);
    }

Body:
You are not required to use property in your model. Here is an example

public class Person {

    private String firstName;
    private String lastName;
    private String email;

    public Person() {
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

just create the property when you need it.

firstNameCol.setCellValueFactory(cdf -> new SimpleStringProperty(cdf.getValue().getFirstName()));


问:
How to animate triangle vertices in a-frame
I am trying to animate an individual vertex of a triangle primitive in a-frame using the animation tag and am having some strange results

In one case, If I try to animate as I would expect to, changing the x,y,z values like so...

```<code><a-triangle
        vertex-a="-1 1 -5"
        vertex-b="-1 1 -10"
        vertex-c="4 1 -10"
        color="blue"
        material="side: double">
            <a-animation
                attribute="vertex-b"
                from="-1 1 -10"
                to="-1 5 -10"
                dur="4000"
                >
            </a-animation>
    </a-triangle>
</code>```

Fiddle https://jsfiddle.net/k7fbmo9k/

...I get the following error

'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is
  NaN. The "position" attribute is likely to have NaN values.'

However, If I only offer a single value like so..

```<code>   <a-triangle
        vertex-a="-1 1 -5"
        vertex-b="-1 1 -10"
        vertex-c="4 1 -10"
        color="blue"
        material="side: double">
            <a-animation
                attribute="vertex-b"
                from="1"
                to="5"
                dur="4000"
                >
            </a-animation>
    </a-triangle>
</code>```

Fiddle https://jsfiddle.net/k7fbmo9k/1/

..it seems to 'work' as in no errors and there is animation but I have no control over it.

Am I doing something wrong?

Thanks for any advice as ever

答:
Try attribute="geometry.vertexB". It might not work to animate the primitive attributes, so we animate the geometry component directly.

Otherwise, if you are comfortable enough, it is better to animate vertices at a more advanced level for performance. You can use a vertex shader.

Or you can manipulate the vertices manually:

```<code>var geometry = triangleEl.getObject3D('mesh').geometry;
geometry.attributes.position[0] += 0.1;
geometry.attributes.position[1] += 0.1;
geometry.attributes.position[2] += 0.1;
geometry.attributes.position.needsUpdate = true;
</code>```

And to animate, do it in a tick handler:

```<code>AFRAME.registerComponent('animate-vertex', {
  tick: function (t) {
    // Animate vertex position until desired position using `t` to interpolate time.
  }
});
</code>```

Body:
I am trying to animate an individual vertex of a triangle primitive in a-frame using the animation tag and am having some strange results

In one case, If I try to animate as I would expect to, changing the x,y,z values like so...

Fiddle https://jsfiddle.net/k7fbmo9k/

...I get the following error

'THREE.BufferGeometry.computeBoundingSphere(): Computed radius is
  NaN. The "position" attribute is likely to have NaN values.'

However, If I only offer a single value like so..

Fiddle https://jsfiddle.net/k7fbmo9k/1/

..it seems to 'work' as in no errors and there is animation but I have no control over it.

Am I doing something wrong?

Thanks for any advice as ever

Body:
Try attribute="geometry.vertexB". It might not work to animate the primitive attributes, so we animate the geometry component directly.

Otherwise, if you are comfortable enough, it is better to animate vertices at a more advanced level for performance. You can use a vertex shader.

Or you can manipulate the vertices manually:

var geometry = triangleEl.getObject3D('mesh').geometry;
geometry.attributes.position[0] += 0.1;
geometry.attributes.position[1] += 0.1;
geometry.attributes.position[2] += 0.1;
geometry.attributes.position.needsUpdate = true;

And to animate, do it in a tick handler:

AFRAME.registerComponent('animate-vertex', {
  tick: function (t) {
    // Animate vertex position until desired position using `t` to interpolate time.
  }
});


问:
How to compare bit mask?
I want to create function which return me true when first number (binary) contains in second number (binary):

```<code>a = '1100'
b = '0101'
</code>```

returns false but:

```<code>a = '0100'
b = '0101'
</code>```

returns true

How to do it?

答:
You can do this by first creating the binary numbers out of the strings, and next, doing an and (&) on the numbers and checking if the output matches either of them.

```<code>In [14]: str_to_bin = lambda x: int(x, 2)
    ...:
    ...: a = '1100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...:
    ...: a = '0100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...:
False
True
</code>```

If you want to exclusively check for a being present in b, use the condition

```<code>print a & b == a
</code>```

Title: How to compare bit mask?

Body:
I want to create function which return me true when first number (binary) contains in second number (binary):

a = '1100'
b = '0101'

returns false but:

a = '0100'
b = '0101'

returns true

How to do it?

Body:
You can do this by first creating the binary numbers out of the strings, and next, doing an and (&) on the numbers and checking if the output matches either of them.

In [14]: str_to_bin = lambda x: int(x, 2)
    ...:
    ...: a = '1100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...:
    ...: a = '0100'
    ...: b = '0101'
    ...: a = str_to_bin(a)
    ...: b = str_to_bin(b)
    ...: print a & b in (a, b)
    ...:
False
True

If you want to exclusively check for a being present in b, use the condition

print a & b == a


问:
Java passing generic objects
I have different objects(Object A and object B). But some of the objects' fields are same. I can't change the object classes( i mean i cant write a implement/extends condition for them). I want to pass the objects to a method which uses the objects' fields They have same fields. I don't want to overloading. Which design is the most suitable for this?.

```<code>A obj1 = new A();
B obj2 = new B();

update(obj1);
update(obj2);

// my function
public <T extends myInterface> void update(T obj)
{
    obj.field+=1;
}
</code>```

```<code>public interface myInterface{
   int field=0;
}

--------------
public class A{
   int field;
   .... // smt else
}
--------------
public class B{
   int field;
   .... // smt else
}
</code>```

答:
instanceof can be used indentify class of object. Like this:

```<code>public <T extends myInterface> void update(Object obj)
    {
        if ( obj instanceof A )
        {
            A a = (A)obj;
            a.field+=1;
        }
        if( obj instanceof B )
        {
            B b = (B)obj;
            b.field+=1;
        }
    }
</code>```

Title: Java passing generic objects

Body:
I have different objects(Object A and object B). But some of the objects' fields are same. I can't change the object classes( i mean i cant write a implement/extends condition for them). I want to pass the objects to a method which uses the objects' fields They have same fields. I don't want to overloading. Which design is the most suitable for this?.

A obj1 = new A();
B obj2 = new B();

update(obj1);
update(obj2);

// my function
public <T extends myInterface> void update(T obj)
{
    obj.field+=1;
}

public interface myInterface{
   int field=0;
}

--------------
public class A{
   int field;
   .... // smt else
}
--------------
public class B{
   int field;
   .... // smt else
}

Body:
instanceof can be used indentify class of object. Like this:

public <T extends myInterface> void update(Object obj)
    {
        if ( obj instanceof A )
        {
            A a = (A)obj;
            a.field+=1;
        }
        if( obj instanceof B )
        {
            B b = (B)obj;
            b.field+=1;
        }
    }


问:
jQuery Spell Checker plugin for TinyMCE in .NET
We have an app written in .NET/MVC (C#) and it uses TinyMCE as the WYSIWYG editor. Works fine except no spell checking natively. The current options are pretty limited (iespell for IE but requires ActiveX, or spellchecker for PHP).

I stumbled on this site and it looked promising until I read the documentation and saw that it also requires PHP on the backend.

So I'm looking for an alternative - jQuery plug-in that will work with a .NET backend or possibly replacing TinyMCE and using CKEditor which supports SCAYT.

Anyone have any idea if there is a good jQuery plugin to use or am I possibly stuck with ripping out TinyMCE and replacing it with CKEditor?

答:
To anyone coming on this post later:

TinyMCE can now use the browser's built in spell checking functionality, just turn on the option as follows:

```<code>tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  browser_spellcheck: true
});
</code>```

More details in the relevant section of the official documentation.

You should then get the red squigglies in the browser:

Body:
To anyone coming on this post later:

TinyMCE can now use the browser's built in spell checking functionality, just turn on the option as follows:

tinymce.init({
  selector: 'textarea',  // change this value according to your HTML
  browser_spellcheck: true
});

More details in the relevant section of the official documentation.

You should then get the red squigglies in the browser:


问:
ssas calculated member with CASE, DIVIDE and .All members
I have some troubles with finilizing one calculation:

```<code>CASE
WHEN ISEMPTY( [Measures].[Base])
THEN NULL
ELSE
DIVIDE
(([Status].[Status].CurrentMember,
[Measures].[Base]),
([Status].[Status].[All],
[Measures].[Base]))
End
</code>```

When I intersect the result with Status - values are correct. When I use the Type filter - values are mostly correct. For "Blank" Type my values are going crazy:
Values in %

The should always add up to 100% - and they are but not for this Blank

Does anyone have any suggestions, Should I include sth more in my Calculation?

答: Solved - the problem was with the new data in the datawarehouse</p>

Body:
I have some troubles with finilizing one calculation:

CASE
WHEN ISEMPTY( [Measures].[Base])
THEN NULL
ELSE
DIVIDE
(([Status].[Status].CurrentMember,
[Measures].[Base]),
([Status].[Status].[All],
[Measures].[Base]))
End

When I intersect the result with Status - values are correct. When I use the Type filter - values are mostly correct. For "Blank" Type my values are going crazy:
Values in %

The should always add up to 100% - and they are but not for this Blank

Does anyone have any suggestions, Should I include sth more in my Calculation?


问:
Search ArrayList for certain character in string
What is the correct syntax for searching an ArrayList of strings for a single character?  I want to check each string in the array for a single character.
Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string.
I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists.  None of them do quite what I need.
P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.

--- Edit ---

As per MightyPork's recommendations arraylist revised to use simple string type.  This also made it compatible with hoosssein's solution which is included.

```<code>public void ArrayInput() {
    String FileName;                            // set file variable
    FileName = fileName.getText();              // get file name

    ArrayList<String> fileContents = new ArrayList<String>();       // create arraylist

    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
        String line = null;

        while ((line = reader.readLine()) != null) {
            if(line.length() > 0) {                         // don't include blank lines
                line = line.trim();                         // remove whitespaces
                fileContents.add(line);                     // add to array
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }

        String oldstr;
        String newstr;

        oldstr = "}";
        newstr = "!!!!!";

        for(int i = 0; i < fileContents.size(); i++) {
            if(fileContents.contains(oldstr)) {
                fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }
                                // close file
    }

    catch (IOException ex) {    // E.H. for try
        JOptionPane.showMessageDialog(null, "File not found.  Check name and directory.");
    }
}
</code>```

答:
You don't need to iterate over lines twice to do what you need. You can make replacement when iterating over file.

Java 8 solution

```<code> try (BufferedReader reader = Files.newBufferedReader(Paths.get("pom.xml"))) {
        reader
            .lines()
            .filter(x -> x.length() > 0)
            .map(x -> x.trim())
            .map(x -> x.replace("a", "b"))
            .forEach(System.out::println);
    } catch (IOException e){
        //handle exception
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
What is the correct syntax for searching an ArrayList of strings for a single character?  I want to check each string in the array for a single character.
Ultimately I want to perform multiple search and replaces on all strings in an array based on the presence of a single character in the string.
I have reviewed java-examples.com and java docs as well as several methods of searching ArrayLists.  None of them do quite what I need.
P.S. Any pointers on using some sort of file library to perform multiple search and replaces would be great.

--- Edit ---

As per MightyPork's recommendations arraylist revised to use simple string type.  This also made it compatible with hoosssein's solution which is included.

public void ArrayInput() {
    String FileName;                            // set file variable
    FileName = fileName.getText();              // get file name

    ArrayList<String> fileContents = new ArrayList<String>();       // create arraylist

    try {
        BufferedReader reader = new BufferedReader(new FileReader(FileName)); // create reader
        String line = null;

        while ((line = reader.readLine()) != null) {
            if(line.length() > 0) {                         // don't include blank lines
                line = line.trim();                         // remove whitespaces
                fileContents.add(line);                     // add to array
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }

        String oldstr;
        String newstr;

        oldstr = "}";
        newstr = "!!!!!";

        for(int i = 0; i < fileContents.size(); i++) {
            if(fileContents.contains(oldstr)) {
                fileContents.set(i, fileContents.get(i).replace(oldstr, newstr));
            }
        }

        for (String row : fileContents) {
            System.out.println(row);        // print array to cmd
        }
                                // close file
    }

    catch (IOException ex) {    // E.H. for try
        JOptionPane.showMessageDialog(null, "File not found.  Check name and directory.");
    }
}

Body:
You don't need to iterate over lines twice to do what you need. You can make replacement when iterating over file.

Java 8 solution

 try (BufferedReader reader = Files.newBufferedReader(Paths.get("pom.xml"))) {
        reader
            .lines()
            .filter(x -> x.length() > 0)
            .map(x -> x.trim())
            .map(x -> x.replace("a", "b"))
            .forEach(System.out::println);
    } catch (IOException e){
        //handle exception
    }


问:
Monitoring CPU usage of IIS7 worker processes
What is the best way to monitor IIS7 worker processes and store informations about websites which are using CPU/memory too much?

Thanks

答:
There are some commercial options that will monitor a process's CPU and memory utilization.

But there is also a solution on Code Project that will let you tap into the values to monitor them from a winform application.

OwnerDisplayName: GrZeCh

OwnerDisplayName: David Thomas Garcia


问:
api-platform : how secure custom operation
I want to know how to secure custom itemsOperation with api-platform, I found this code on documentation:

```<code>/**
 * Secured resource.
 *
 * @ApiResource(
 *     attributes={"access_control"="is_granted('ROLE_USER')"},
 *     collectionOperations={
 *         "get"={"method"="GET"},
 *         "post"={"method"="POST", "access_control"="is_granted('ROLE_ADMIN')"}
 *     },
 *     itemOperations={
 *         "get"{"method"="GET","access_control"="is_granted('ROLE_USER') and object.owner == user"}
 *     }
 * )
 * @ORM\Entity
 */
</code>```

But I want to do something like:

```<code>/**
 * @ApiResource(itemOperations={
 *     "get"={"method"="GET"} //Public route,
 *     "special"={"route_name"="special", "access_control"="is_granted('ROLE_ADMIN') or object.owner == user"}},
 *     "special2"={"route_name"="special2",  "access_control"="is_granted('ROLE_USER')"}
 * })
 */
</code>```

Does it work? Or I have to check user roles in special Action file?

What is the best practice in this case?

答:
You should consider create a custom symfony voter

Please try this code, I'm here if you don't understand something with voters

```<code><?php
namespace yournamespace;

use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class YourObjectVoter extends Voter
{
    const YOUR_CUSTOM_ACTION = 'custom_action';

    protected function supports($attribute, $subject)
    {
        if (!$subject instanceof YourObject) {
            return false;
        }

        if (!in_array($attribute, array(self::YOUR_CUSTOM_ACTION))) {
            return false;
        }

        return true;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        if($this->isGranted('ROLE_ADMIN')) {
            return true;
        }

        $user = $token->getUser();
        if(!$user instanceOf User) {
            return false;
        }

        if($subject->getOwner() === $user) {
            return true;
        }

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

Then you need to define your voter as a service with the tag security.voter

```<code>class:  Yournamespace\Security\YourObjectVoter
        public: false
        tags:
            - { name: security.voter }
</code>```

custom_action is the same string that the one defined in the voter class

With this code you can just secure your action with :

```<code>itemOperations={
 *         "get"{"method"="GET","access_control"="is_granted('custom_action', object)"}
 *     }
</code>```

Let me know if It doesn't work. I hope it's help !

Body:
I want to know how to secure custom itemsOperation with api-platform, I found this code on documentation:

/**
 * Secured resource.
 *
 * @ApiResource(
 *     attributes={"access_control"="is_granted('ROLE_USER')"},
 *     collectionOperations={
 *         "get"={"method"="GET"},
 *         "post"={"method"="POST", "access_control"="is_granted('ROLE_ADMIN')"}
 *     },
 *     itemOperations={
 *         "get"{"method"="GET","access_control"="is_granted('ROLE_USER') and object.owner == user"}
 *     }
 * )
 * @ORM\Entity
 */

But I want to do something like:

/**
 * @ApiResource(itemOperations={
 *     "get"={"method"="GET"} //Public route,
 *     "special"={"route_name"="special", "access_control"="is_granted('ROLE_ADMIN') or object.owner == user"}},
 *     "special2"={"route_name"="special2",  "access_control"="is_granted('ROLE_USER')"}
 * })
 */

Does it work? Or I have to check user roles in special Action file?

What is the best practice in this case?

Body:
You should consider create a custom symfony voter

Please try this code, I'm here if you don't understand something with voters

<?php
namespace yournamespace;

use App\Entity\User;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\Voter;

class YourObjectVoter extends Voter
{
    const YOUR_CUSTOM_ACTION = 'custom_action';

    protected function supports($attribute, $subject)
    {
        if (!$subject instanceof YourObject) {
            return false;
        }

        if (!in_array($attribute, array(self::YOUR_CUSTOM_ACTION))) {
            return false;
        }

        return true;
    }

    protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
    {
        if($this->isGranted('ROLE_ADMIN')) {
            return true;
        }

        $user = $token->getUser();
        if(!$user instanceOf User) {
            return false;
        }

        if($subject->getOwner() === $user) {
            return true;
        }

        return false;
    }
}

Then you need to define your voter as a service with the tag security.voter

class:  Yournamespace\Security\YourObjectVoter
        public: false
        tags:
            - { name: security.voter }

custom_action is the same string that the one defined in the voter class

With this code you can just secure your action with :

itemOperations={
 *         "get"{"method"="GET","access_control"="is_granted('custom_action', object)"}
 *     }

Let me know if It doesn't work. I hope it's help !


问:
Right align button in form
I'm having some trouble using float: right; on a button.

Whatever I do, the button just doesn't wanna go to the right.
It's the second button, the one with the "advanced-search-button" class.

I'm using Bootstrap 4.

HTML

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Opgaver

        <form action="" class="form-inline">

                <input type="text" class="form-control" placeholder="Rekvirent">

                <input type="text" class="form-control" placeholder="Tildelt til">

                <select name="select_Afsluttet" id="select_Afsluttet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Afsluttet</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <select name="select_Godkendt" id="select_Godkendt" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Godkendt</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <button type="button" class="btn btn-success btn-sm" style="margin-right: 15px;">Søg</button>
                <button type="button" class="btn btn-primary btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>

        </form>
        <form action="" class="form-inline form-custom advanced-search">

                <select name="select_Prioritet" id="select_Prioritet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Prioritet</option>
                    <option value="">Lav</option>
                    <option value="">Middel</option>
                    <option value="">Høj</option>
                    <option value="">Straks</option>
                    <option value="">Driftfejl</option>
                </select>

                <select name="select_Opgavestatus" id="select_Opgavestatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavestatus</option>
                    <option value="">Arkiveret</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Opgavetype" id="select_Opgavetype" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavetype</option>
                    <option value="">Andet</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Underkategori" id="select_Underkategori" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Underkategori</option>
                    <option value="">Via telefon</option>
                    <option value="">Via email</option>
                    <option value="">Internet</option>
                    <option value="">Intranet</option>
                    <option value="">VMS</option>
                </select>

                <input type="text" class="form-control" placeholder="Søg efter">

        </form>

                    Dato
                    ID
                    Rekv
                    Tildelt
                    Beskrivelse
                    Type
                    Seneste log besked
                    Deadline

                    22-11-2017
                    70935
                    HJR
                    LUC
                    Docking Station...
                    Bestilling - Via Telefon
                    8 dage
                    22-11-2017

                    28-11-2017
                    71049
                    LLJ
                    LUC
                    Kan ikke scanne fra sin printe....
                    IT-Drift - Via Telefon
                    3 dage
                    28-11-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

```

I hope you can help me :)

I don't have any custom CSS for this part, I only use the classes for JS.

答:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<form action="" class="">

        <button type="button" class="btn btn-success float-left  btn-sm" style="margin-right: 15px;">Søg</button>
        <button type="button" class="btn btn-primary float-right  btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>

</form>

```

Removed the class form-inline form and added w-100 for the first div within form.

Title: Right align button in form

Body:
I'm having some trouble using float: right; on a button.

Whatever I do, the button just doesn't wanna go to the right.
It's the second button, the one with the "advanced-search-button" class.

I'm using Bootstrap 4.

HTML

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>

Opgaver

        <form action="" class="form-inline">

                <input type="text" class="form-control" placeholder="Rekvirent">

                <input type="text" class="form-control" placeholder="Tildelt til">

                <select name="select_Afsluttet" id="select_Afsluttet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Afsluttet</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <select name="select_Godkendt" id="select_Godkendt" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Godkendt</option>
                    <option value="">Ja</option>
                    <option value="">Nej</option>
                    <option value="">Alle</option>
                </select>

                <button type="button" class="btn btn-success btn-sm" style="margin-right: 15px;">Søg</button>
                <button type="button" class="btn btn-primary btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>

        </form>
        <form action="" class="form-inline form-custom advanced-search">

                <select name="select_Prioritet" id="select_Prioritet" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Prioritet</option>
                    <option value="">Lav</option>
                    <option value="">Middel</option>
                    <option value="">Høj</option>
                    <option value="">Straks</option>
                    <option value="">Driftfejl</option>
                </select>

                <select name="select_Opgavestatus" id="select_Opgavestatus" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavestatus</option>
                    <option value="">Arkiveret</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Opgavetype" id="select_Opgavetype" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Opgavetype</option>
                    <option value="">Andet</option>
                    <option value="">Sendt til DUC</option>
                    <option value="">Venter på bruger</option>
                    <option value="">Venter på kunde</option>
                    <option value="">Venter på AO</option>
                </select>

                <select name="select_Underkategori" id="select_Underkategori" class="custom-select mb-2 mr-sm-2 mb-sm-0">
                    <option selected hidden value="">Underkategori</option>
                    <option value="">Via telefon</option>
                    <option value="">Via email</option>
                    <option value="">Internet</option>
                    <option value="">Intranet</option>
                    <option value="">VMS</option>
                </select>

                <input type="text" class="form-control" placeholder="Søg efter">

        </form>

                    Dato
                    ID
                    Rekv
                    Tildelt
                    Beskrivelse
                    Type
                    Seneste log besked
                    Deadline

                    22-11-2017
                    70935
                    HJR
                    LUC
                    Docking Station...
                    Bestilling - Via Telefon
                    8 dage
                    22-11-2017

                    28-11-2017
                    71049
                    LLJ
                    LUC
                    Kan ikke scanne fra sin printe....
                    IT-Drift - Via Telefon
                    3 dage
                    28-11-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

                    05-12-2017
                    71244
                    LYL
                    LUC
                    Printer med gul baggrund på hy....
                    IT-support - Via Telefon
                    1 dage
                    05-12-2017

I hope you can help me :)

I don't have any custom CSS for this part, I only use the classes for JS.

Body:
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" integrity="sha384-PsH8R72JQ3SOdhVi3uxftmaW6Vc51MKb0q5P2rRUpPvrszuE4W1povHYgTpBfshb" crossorigin="anonymous">

<div class="box-form w-100">
<form action="" class="">
    <div class="form-group col-sm-9 d-inline-block form-group-custom float-left">
        <button type="button" class="btn btn-success float-left  btn-sm" style="margin-right: 15px;">Søg</button>
        <button type="button" class="btn btn-primary float-right  btn-sm advanced-search-button" onclick="advancedSearch(this)">Avanceret søgning</button>
    </div>
</form>
</div>

Removed the class form-inline form and added w-100 for the first div within form.


问:
What is the right way to fix error NU1605: Detected package downgrade - log4net
You do as follows:

```<code>dotnet new console
dotnet add-package log4net --version 2.0.8
dotnet publish -r win10-x64
</code>```

And then you get:

```<code>error NU1605: Detected package downgrade: System.Runtime.InteropServices from 4.3.0 to 4.1.0.
</code>```

You can fix it adding the following to your csproj under PropertyGroup

```<code><NoWarn>$(NoWarn);NU1605</NoWarn>
</code>```

But I'd like to understand the right way to get this fixed.

答: Unfortunately, there's no other option than the package owner to upgrade their references or you adding the  clausule in the csproj. Please see this GitHub issue for more information: https://github.com/dotnet/core/issues/907</p>

Body:
You do as follows:

dotnet new console
dotnet add-package log4net --version 2.0.8
dotnet publish -r win10-x64

And then you get:

error NU1605: Detected package downgrade: System.Runtime.InteropServices from 4.3.0 to 4.1.0.

You can fix it adding the following to your csproj under PropertyGroup

<NoWarn>$(NoWarn);NU1605</NoWarn>

But I'd like to understand the right way to get this fixed.


问:
Making an input and two buttons aligned using SCSS
I want my two buttons, that are actually  tags, stick with my input, and be the same size as input. Image perfectly describes what I want to achieve.

Note that I am just starting to learn SASS and CSS. I have tried with this but no luck

NumberInput.js

```<code><div
 className="NumberInput"
 data-key={dataKey}>
    <div className="numberInputField">
        <input
          data-key={dataKey}
          type="text"
          name="number"
          value={getValue(datakey)}
          onChange={onChange(datakey)}/>
     </div>
     <div className="buttonsField">
        <div className="row">
          <ValueChangeButton/>
        </div>
        <div className="row">
          <ValueChangeButton/>
        </div>
     </div>
</div>
</code>```

NumberInput.scss

```<code>$inputMaxWidth: 450px;
$maxHeight: 80px;
$btnFieldMaxWidth: 150px;

.NumberInput{
   max-width: $inputMaxWidth;
   max-height: $maxHeight;

   .numberInputField{
       display: inline-block;
       text-align: center;
       max-width: inherit;
       max-height: inherit;
    }

    .buttonsField{
        display: inline-block;
        max-width: $btnFieldMaxWidth;
        max-height: $maxHeight;
        .button{
          width: auto;
          height: auto;
        }
     }
 }
</code>```

The result I get is, buttons are contained in their respective rows, but are not the same size as input, and they are flying all around the page. Also, if I change the className of my input, and set the className of its
 to "numberInputField", it doesn't change its width and height.

答:
Flexbox is perfect for this:

body {
  margin: 1em;
}

.NumberInput {
  display: flex;
  max-width:450px;
  margin:auto;
}

.numberInputField {
  flex: 3; /* say 3/4 of width */
  display: flex;
  flex-direction: column;
}

input {
  padding: 1em 4em;
  flex: 1;
}

.buttonsField {
  flex: 1; /* say 1/4 of width */
  display: flex;
  flex-direction: column;
}

.row {
  flex: 1; /* share width equally */
}

a {
  width: 100%;
  display: block;
  background: rebeccapurple;
  text-align:center;
  text-decoration: none;
  font-size: 1.5em;
  color: white;
  border:1px solid grey;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="NumberInput">
  <div class="numberInputField">
    <input type="submit" />
  </div>
  <div class="buttonsField">
    <div class="row">
      ↑
    </div>
    <div class="row">
      ↓
    </div>
  </div>
</div></code>```

Body:
I want my two buttons, that are actually  tags, stick with my input, and be the same size as input. Image perfectly describes what I want to achieve.

Note that I am just starting to learn SASS and CSS. I have tried with this but no luck

NumberInput.js

        <input
          data-key={dataKey}
          type="text"
          name="number"
          value={getValue(datakey)}
          onChange={onChange(datakey)}/>

          <ValueChangeButton/>

          <ValueChangeButton/>

NumberInput.scss

$inputMaxWidth: 450px;
$maxHeight: 80px;
$btnFieldMaxWidth: 150px;

.NumberInput{
   max-width: $inputMaxWidth;
   max-height: $maxHeight;

   .numberInputField{
       display: inline-block;
       text-align: center;
       max-width: inherit;
       max-height: inherit;
    }

    .buttonsField{
        display: inline-block;
        max-width: $btnFieldMaxWidth;
        max-height: $maxHeight;
        .button{
          width: auto;
          height: auto;
        }
     }
 }

The result I get is, buttons are contained in their respective rows, but are not the same size as input, and they are flying all around the page. Also, if I change the className of my input, and set the className of its
 to "numberInputField", it doesn't change its width and height.

Body:
Flexbox is perfect for this:

body {
  margin: 1em;
}

.NumberInput {
  display: flex;
  max-width:450px;
  margin:auto;
}

.numberInputField {
  flex: 3; /* say 3/4 of width */
  display: flex;
  flex-direction: column;
}

input {
  padding: 1em 4em;
  flex: 1;
}

.buttonsField {
  flex: 1; /* say 1/4 of width */
  display: flex;
  flex-direction: column;
}

.row {
  flex: 1; /* share width equally */
}

a {
  width: 100%;
  display: block;
  background: rebeccapurple;
  text-align:center;
  text-decoration: none;
  font-size: 1.5em;
  color: white;
  border:1px solid grey;
}

<div class="NumberInput">
  <div class="numberInputField">
    <input type="submit" />
  </div>
  <div class="buttonsField">
    <div class="row">
      <a href="#2">&uarr;</a>
    </div>
    <div class="row">
      <a href="#3">&darr;</a>
    </div>
  </div>
</div>


问:
How do I request the AdWords API without client authentication in Google Apps Script?
I have a Google Apps Script bound to a spreadsheet that needs to read AdWords data. I'm avoiding the user permission OAuth2 procedures because it's an entirely server-to-server script that automatically updates daily data to the sheet.

After much swimming through documentation, I've created a service account and given it the necessary permissions as per this guide:
https://developers.google.com/adwords/api/docs/guides/authentication#oauth2_service_accounts

I haven't fully understood the next step, which is how to actually make the request, specifically in Apps Script. What would be the code for this?

Also accepting better suggestions on the most elegant way to request the AdWords API on Apps Script without client permissions. I'd managed to get a refresh token which seemed to be the right track, but couldn't generate an OAuth2 token with it.

答:
I've found that a service account is not required, and the best way is to follow the installed app flow.

Here's the simplest way to request the AdWords API on Google Apps Script:

Create a client ID and client secret as described here.

Follow the OAuth2 Playground process to get a refresh token as described here.

Get your developer token by following this process. Note: You'll have to create/use a separate manager account, apply for a token, and wait for its approval. You could alternatively use a test account.

Find your client customer ID here - after logging in it'll be on the top right in the form XXX-XXX-XXXX.

Create your AWQL query (not sure if this guide works the same for XML).

function getGoogleAccessToken() {

    // This is also a general method to fetch an access token using a refresh token in GAS.

    var params = {
        client_id: YOUR_CLIENT_ID,
        client_secret: YOUR_CLIENT_SECRET,
        refresh_token: YOUR_REFRESH_TOKEN,
        grant_type: 'refresh_token'
    }

    const options = {
        contentType: 'application/x-www-form-urlencoded',
        method: 'post',
        muteHttpExceptions: true, // To see the whole response in case of errors
        payload: params
    }

    var url = "https://www.googleapis.com/oauth2/v4/token";

    var data = UrlFetchApp.fetch(url, options);
    return (JSON.parse(data).access_token);
}

function getAdwordsData() {

    var adwordsParams = {
        "__fmt": "CSV",
        "__rdquery": YOUR_VALID_AWQL_QUERY
    }

    var adwordsOptions = {
        contentType: "application/x-www-form-urlencoded",
        method: 'post',
        muteHttpExceptions: true,
        payload: adwordsParams
    };

    adwordsOptions.headers = {
        "Authorization": "Bearer " + getGoogleAccessToken(),
        "developerToken": YOUR_DEVELOPER_TOKEN,
        "clientCustomerId": YOUR_CLIENT_CUSTOMER_ID",
        "includeZeroImpressions": true,
        "Expect": "100-continue",
        "User-Agent": "curl, gzip",
        "Accept": "*/*",
        "Accept-Encoding": "gzip"
    };

    var url = 'https://adwords.google.com/api/adwords/reportdownload/v201710';
    var res = UrlFetchApp.fetch(url, options);
    Logger.log(res);
}```


答:
If you have two classes which do not implement a common interface or share a common base class, you can't really pass them to your function.

The fact that they have a common field doesn't matter.

You have 3 workarounds, none of which is really good:

Have your function accept Object type, and check its type (A or B) inside using instanceof.  This is ugly and not recommended as any class can be passed inside, and also your code has to check it's type all the time.

Have your function accept Object type, Use reflection to access field with specific name, in this way:

Field field = obj.getClass().getDeclaredField('myfeild');
Object value = field.get(obj);

This is better in that your code doesn't have to check types, but more unsafe. Any class can be passed to your function, and there's some dark magic which relies on static field names. If field name changes, your code breaks.

Perhaps the best - Implement a wrapper for your objects. It will have two constructors, one for class A and one for class B. The wrapper will remember which kind of object resides inside. In its getField function if will have a single if statement. Have your function accept the wrapper type as the argument.

Title: Java passing generic objects


问:
How to check if a table exists in a MySQL database using shell script?
i am trying to check whether a table is empty or not using shell script
the code that i have is

```<code>#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi
</code>```

but when i run this it always displays "table not empty" even if the output of the query is 0.

```<code>user@server$ ./table_check.sh
table not empty
</code>```

what is wrong here?

答:
This should work</p>

```<code>if [ $(mysql -u root -p -e \
  "select count(*) from information_schema.tables where \
     table_schema='db_name' and table_name='table_name';") -eq 1 ]; then
echo "table exist"
   exit 1
else
   echo "table doesn't exist"
   exit 1
fi
</code>```

Body:
i am trying to check whether a table is empty or not using shell script
the code that i have is

#!/bin/bash

if [ "mysql -u user -ppassword -hserver dbname -e 'select count(*) from test_dec;'" != 0 ];
then
        echo "table not empty"
else
        echo "table empty"
fi

but when i run this it always displays "table not empty" even if the output of the query is 0.

user@server$ ./table_check.sh
table not empty

what is wrong here?

Body:
This should work

if [ $(mysql -u root -p -e \
  "select count(*) from information_schema.tables where \
     table_schema='db_name' and table_name='table_name';") -eq 1 ]; then
echo "table exist"
   exit 1
else
   echo "table doesn't exist"
   exit 1
fi


问:
How to check whether a generic type implements a generic trait?
I want to check whether a type implements a trait without creating an object. But it doesn't compile. See the comments in code . So what should I do to get my goal?</p>

```<code>#![feature(specialization)]

struct T1;
struct T2;

trait A {}

impl A for T1 {}

trait Get_Static<TraitType> {
    fn has_trait() -> bool ;
}
default impl<TraitType, T> Get_Static<TraitType> for T
{
    fn has_trait() -> bool { false }
}
impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}//Compiler complains TraitType is not a trait but type parameter

fn main() {
    if <T1 as Get_Static>::<A>::has_trait() {println!("{}", true)} else {println!("{}", false)}
    if <T2 as Get_Static>::<A>::has_trait() {println!("{}", true)} else {println!("{}", false)}
//This is surely wrong syntax but I don't know the right syntax
}
</code>```

答:
Warning: this solution no longer works with recent nightly (2022-01), and it is unknown when it stopped working.

Thanks to Stefan who smoothed out the last wrinkle.

```<code><T2 as Get_Static>::<A>::has_trait()
</code>```

```<code>  //This is surely wrong syntax but I don't know the right syntax
</code>```

This attempts to call:

a trait associated function,

implemented for a particular type.

The syntax is <Type as Trait>::associated_function(). In this case, Type is T1, Trait is Get_Static so this should be:

```<code><T2 as Get_Static<A>>::has_trait()
</code>```

```<code>impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}
//Compiler complains TraitType is not a trait but type parameter
</code>```

It is not possible, directly, to indicate that TraitType should be a trait, however the Unsize marker can be used to check if T: Unsize<TraitType> which is sufficient for our purpose.

This requires 3 changes:

enabling the nightly feature #![feature(unsize)] as the Unsize marker is unstable,

allowing the Get_Static generic parameter to be ?Sized, because traits are unsized,

using T: Unsize<TraitType> as constraint in the implementation.

All told, this means:

```<code>#![feature(specialization)]
#![feature(unsize)]

trait GetStatic<TraitType: ?Sized> {
    fn has_trait() -> bool ;
}

default impl<TraitType: ?Sized, T> GetStatic<TraitType> for T {
    fn has_trait() -> bool { false }
}

impl<TraitType: ?Sized, T> GetStatic<TraitType> for T
    where
        T: std::marker::Unsize<TraitType>
{
    fn has_trait() -> bool { true }
}
</code>```

Which is then used as:

```<code>struct T1;
struct T2;

trait A {}

impl A for T1 {}

fn main() {
    println!("{}", <T1 as GetStatic<A>>::has_trait());
    println!("{}", <T2 as GetStatic<A>>::has_trait());
}
</code>```

See it in action on the playground

Body:
I want to check whether a type implements a trait without creating an object. But it doesn't compile. See the comments in code . So what should I do to get my goal?

#![feature(specialization)]

struct T1;
struct T2;

trait A {}

impl A for T1 {}

trait Get_Static<TraitType> {
    fn has_trait() -> bool ;
}
default impl<TraitType, T> Get_Static<TraitType> for T
{
    fn has_trait() -> bool { false }
}
impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}//Compiler complains TraitType is not a trait but type parameter

fn main() {
    if <T1 as Get_Static>::::has_trait() {println!("{}", true)} else {println!("{}", false)}
    if <T2 as Get_Static>::::has_trait() {println!("{}", true)} else {println!("{}", false)}
//This is surely wrong syntax but I don't know the right syntax
}

Body:
Warning: this solution no longer works with recent nightly (2022-01), and it is unknown when it stopped working.

Thanks to Stefan who smoothed out the last wrinkle.

<T2 as Get_Static>::<A>::has_trait()

  //This is surely wrong syntax but I don't know the right syntax

This attempts to call:

a trait associated function,

implemented for a particular type.

The syntax is <Type as Trait>::associated_function(). In this case, Type is T1, Trait is Get_Static<A> so this should be:

<T2 as Get_Static<A>>::has_trait()

impl<TraitType, T> Get_Static<TraitType> for T where T:TraitType
{
    fn has_trait() -> bool { true }
}
//Compiler complains TraitType is not a trait but type parameter

It is not possible, directly, to indicate that TraitType should be a trait, however the Unsize marker can be used to check if T: Unsize<TraitType> which is sufficient for our purpose.

This requires 3 changes:

enabling the nightly feature #![feature(unsize)] as the Unsize marker is unstable,

allowing the Get_Static generic parameter to be ?Sized, because traits are unsized,

using T: Unsize<TraitType> as constraint in the implementation.

All told, this means:

#![feature(specialization)]
#![feature(unsize)]

trait GetStatic<TraitType: ?Sized> {
    fn has_trait() -> bool ;
}

default impl<TraitType: ?Sized, T> GetStatic<TraitType> for T {
    fn has_trait() -> bool { false }
}

impl<TraitType: ?Sized, T> GetStatic<TraitType> for T
    where
        T: std::marker::Unsize<TraitType>
{
    fn has_trait() -> bool { true }
}

Which is then used as:

struct T1;
struct T2;

trait A {}

impl A for T1 {}

fn main() {
    println!("{}", <T1 as GetStatic<A>>::has_trait());
    println!("{}", <T2 as GetStatic<A>>::has_trait());
}

See it in action on the playground


问:
Fetch only 5 records of each Id which is pass in $in In MongoDb
I have a query in MongoDb where I am fetching records from some collection using $in where I am passing an array. The query is like this

```<code>db.getCollection('feed').find({"_id" : {"$in" : [3,5,8,64,23,18,78,67]}});
</code>```

As this query is working perfectly fine. It will fetch all the records of these ids but I only wants to fetch only 5 record for each Id like 5 records for Id 3, 5 records for Id 8,5 records for Id 64 and so on for every id.

I have even tried with $last but no success so far .

```<code>db.getCollection('feed').find({"_id" : {"$in" : [3,5,8,64,23,18,78,67],"$last" : 5}});
</code>```

Is there any way I can achieve this ?

Body:
I have a query in MongoDb where I am fetching records from some collection using $in where I am passing an array. The query is like this

db.getCollection('feed').find({"_id" : {"$in" : [3,5,8,64,23,18,78,67]}});

As this query is working perfectly fine. It will fetch all the records of these ids but I only wants to fetch only 5 record for each Id like 5 records for Id 3, 5 records for Id 8,5 records for Id 64 and so on for every id.

I have even tried with $last but no success so far .

db.getCollection('feed').find({"_id" : {"$in" : [3,5,8,64,23,18,78,67],"$last" : 5}});

Is there any way I can achieve this ?

Body:
One of the approach using aggregation pipeline is shown below

Let us have documents like

{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f1"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f2"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f3"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f4"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f5"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f6"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f7"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f8"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9f9"), "myId" : 5 }
{ "_id" : ObjectId("5a2a793118e947e4f4c1e9fa"), "myId" : 5 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1e9fb"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1e9fc"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1e9fd"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1e9fe"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1e9ff"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1ea00"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1ea01"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1ea02"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1ea03"), "myId" : 3 }
{ "_id" : ObjectId("5a2a794918e947e4f4c1ea04"), "myId" : 3 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea05"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea06"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea07"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea08"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea09"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea0a"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea0b"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea0c"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea0d"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795018e947e4f4c1ea0e"), "myId" : 103 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea19"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1a"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1b"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1c"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1d"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1e"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea1f"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea20"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea21"), "myId" : 45 }
{ "_id" : ObjectId("5a2a795e18e947e4f4c1ea22"), "myId" : 45 }

The above shown sample collection has four different id's 3,5,45 and 103

Let us pick 5 records from id's 3 and 5

db.getCollection('feed').aggregate([
    {
        $facet: {
            "result1": [
                {$match:{ myId:3}},
                {$limit: 5}
            ],
            "result2": [
                {$match: {"myId": 5}},
                {$limit: 5}
            ]
        }
    },
    {$project : { result: {$concatArrays:["$result1", "$result2"]}} },
    {$unwind:"$result"}
])

After execution of this query we will be getting a result as shown below

{ "result" : { "_id" : ObjectId("5a2a794918e947e4f4c1e9fb"), "myId" : 3 } }
{ "result" : { "_id" : ObjectId("5a2a794918e947e4f4c1e9fc"), "myId" : 3 } }
{ "result" : { "_id" : ObjectId("5a2a794918e947e4f4c1e9fd"), "myId" : 3 } }
{ "result" : { "_id" : ObjectId("5a2a794918e947e4f4c1e9fe"), "myId" : 3 } }
{ "result" : { "_id" : ObjectId("5a2a794918e947e4f4c1e9ff"), "myId" : 3 } }
{ "result" : { "_id" : ObjectId("5a2a793118e947e4f4c1e9f1"), "myId" : 5 } }
{ "result" : { "_id" : ObjectId("5a2a793118e947e4f4c1e9f2"), "myId" : 5 } }
{ "result" : { "_id" : ObjectId("5a2a793118e947e4f4c1e9f3"), "myId" : 5 } }
{ "result" : { "_id" : ObjectId("5a2a793118e947e4f4c1e9f4"), "myId" : 5 } }
{ "result" : { "_id" : ObjectId("5a2a793118e947e4f4c1e9f5"), "myId" : 5 } }

In this approach we have used $facet, $project and $unwind


问:
When can Javascript start calling Actionscript?
Question

Is there a non-polling way for Javascript to command Flash right when its external interface is ready?

Background

In Actionscript, I've registered a function for Javascript to call:

```<code>ExternalInterface.addCallback('doStuff", this.doStuff);
</code>```

I use SWFObject to embed the Flash into my page:

```<code>swfobject.embedSWF(
    'flash/player.swf',
    'flashPlayer',
    '100%',
    '100%',
    '9',
    'expressInstallSwfTODO.swf',
    {},
    {allowfullscreen: true},
    {},
    function(status) {
        if (!status.success) {
            alert('Failed to embed Flash player');
        } else {
            $('flashPlayer').doStuff();
        }
    }.bind(this)
);
</code>```

SWFObject lets you run code when Flash has been successfully embedded through a callback. I attempt to run $('flashPlayer').doStuff in this callback, but it claims it's undefined. It seems that Flash needs some time to boot up its external interface. So I've been using a polling hack to find out when the external interface is ready:

```<code>new PeriodicalExecutuer(
 function(poller) {
  if ($('flashPlayer').doStuff) {
   $('flashPlayer').doStuff();
   poller.stop()
  }
 },
 0.2
);
</code>```

This poller is not ideal. There's a visually perceptible delay in the execution of doStuff and it makes my overall code structure muddy.

答:
In Javascript:

```<code>function flashIsReady()
{
    $('flashPlayer').doStuff();
}
</code>```

In Actionscript:

```<code>if (ExternalInterface.available) {
    ExternalInterface.addCallback('doStuff', this.doStuff);
    ExternalInterface.call("flashIsReady");
}
</code>```

Body:
Question

Is there a non-polling way for Javascript to command Flash right when its external interface is ready?

Background

In Actionscript, I've registered a function for Javascript to call:

ExternalInterface.addCallback('doStuff", this.doStuff);

I use SWFObject to embed the Flash into my page:

swfobject.embedSWF(
    'flash/player.swf',
    'flashPlayer',
    '100%',
    '100%',
    '9',
    'expressInstallSwfTODO.swf',
    {},
    {allowfullscreen: true},
    {},
    function(status) {
        if (!status.success) {
            alert('Failed to embed Flash player');
        } else {
            $('flashPlayer').doStuff();
        }
    }.bind(this)
);

SWFObject lets you run code when Flash has been successfully embedded through a callback. I attempt to run $('flashPlayer').doStuff in this callback, but it claims it's undefined. It seems that Flash needs some time to boot up its external interface. So I've been using a polling hack to find out when the external interface is ready:

new PeriodicalExecutuer(
 function(poller) {
  if ($('flashPlayer').doStuff) {
   $('flashPlayer').doStuff();
   poller.stop()
  }
 },
 0.2
);

This poller is not ideal. There's a visually perceptible delay in the execution of doStuff and it makes my overall code structure muddy.

Body:
In Javascript:

function flashIsReady()
{
    $('flashPlayer').doStuff();
}

In Actionscript:

if (ExternalInterface.available) {
    ExternalInterface.addCallback('doStuff', this.doStuff);
    ExternalInterface.call("flashIsReady");
}


问:
How to save my app's settings?
How do I save the back ground setting in the app and when it exits back it still saves that background
As the default app I to be :

```<code><AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg2"
android:id="@+id/bgplayer">
</code>```

and click button

```<code> bgplayer.setBackgroundResource(R.drawable.bg1a);
</code>```

If you want to completely exit the app and re-enter the background it will be bga1

答:
Use shared preferences in Activity:

```<code>SharedPreferences prefs = getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);
</code>```

then save like this:

```<code>prefs.edit().putInt("your_key", R.drawable.bg1a).apply();
</code>```

and read like this:

```<code>int value = prefs.getInt("your_key", defaultIntValue);
</code>```

And set background as:

```<code>bgplayer.setBackgroundResource(value);
</code>```

Title: How to save my app's settings?

Body:
How do I save the back ground setting in the app and when it exits back it still saves that background
As the default app I to be :

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg2"
android:id="@+id/bgplayer">

and click button

 bgplayer.setBackgroundResource(R.drawable.bg1a);

If you want to completely exit the app and re-enter the background it will be bga1

Body:
Use shared preferences in Activity:

SharedPreferences prefs = getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);

then save like this:

prefs.edit().putInt("your_key", R.drawable.bg1a).apply();

and read like this:

int value = prefs.getInt("your_key", defaultIntValue);

And set background as:

bgplayer.setBackgroundResource(value);


问:
Difference in Months between two dates in JavaScript
How would I work out the difference for two Date() objects in JavaScript, while only return the number of months in the difference?

Any help would be great :)

答:
It also counts the days and convert them in months.

```<code>function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
    months -= d1.getMonth() + 1;
    months += d2.getMonth();  //calculates number of complete months between two months
    day1 = 30-d1.getDate();
    day2 = day1 + d2.getDate();
    months += parseInt(day2/30);  //calculates no of complete months lie between two dates
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
    new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
);
//return value will be 4 months
</code>```

Body:
It also counts the days and convert them in months.

function monthDiff(d1, d2) {
    var months;
    months = (d2.getFullYear() - d1.getFullYear()) * 12;   //calculates months between two years
    months -= d1.getMonth() + 1;
    months += d2.getMonth();  //calculates number of complete months between two months
    day1 = 30-d1.getDate();
    day2 = day1 + d2.getDate();
    months += parseInt(day2/30);  //calculates no of complete months lie between two dates
    return months <= 0 ? 0 : months;
}

monthDiff(
    new Date(2017, 8, 8), // Aug 8th, 2017    (d1)
    new Date(2017, 12, 12)  // Dec 12th, 2017   (d2)
);
//return value will be 4 months


问:
How to create hive ddl using python
I recently started learning hive. I have a python list which has the following values

```<code>list=['hello:struct', 'env:string', 'element:struct','AppId:string','processId:string']
</code>```

So using above values I need to create a hive DDL. Similar to this.

```<code>create table demo

{

hello :struct

<

   env:string,

    element:struct

      <

       AppId:string,

       processId:string

      >

>

formatted b\y..

location..
</code>```

答:
I would suggest you use the JSON serde. See here https://community.hortonworks.com/repos/30883/hive-json-serde.html

DDL you are after would be

```<code>CREATE TABLE demo
(
    hello struct
    <
       env:string,
        element:struct
             <
               AppId:string,
               processId:string
             >
    >
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION '/user/hive/demo';
</code>```

Title: How to create hive ddl using python

Body:
I recently started learning hive. I have a python list which has the following values

list=['hello:struct', 'env:string', 'element:struct','AppId:string','processId:string']

So using above values I need to create a hive DDL. Similar to this.

create table demo

{

hello :struct

<

   env:string,

    element:struct

      <

       AppId:string,

       processId:string

      >

>

formatted b\y..

location..

Body:
I would suggest you use the JSON serde. See here https://community.hortonworks.com/repos/30883/hive-json-serde.html

DDL you are after would be

CREATE TABLE demo
(
    hello struct
    <
       env:string,
        element:struct
             <
               AppId:string,
               processId:string
             >
    >
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION '/user/hive/demo';


问:
Comma is causing unwanted string split
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

```<code>public List getAnswerStringEdit() {
        return answer_edit;
    }
</code>```

I save it as so:

```<code>editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());
</code>```

Then retrieve it here:

```<code>String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");
</code>```

Finally, I access the array as so:

```<code>et_answer1_edit.append(array[0]);
</code>```

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

```<code>{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}
</code>```

Any help/advice that can help me to understand what is causing this, would be really appreciated.

答:
try this one</p>

```<code>JSONObject jsonObject = new JSONObject("your json response");

try
  {
      JSONObject answer= jsonObject.getJSONObject("answer");

      JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
      Log.e("=>", "" + jsonArrayAnswerEdit);
      for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
          String que= jsonArrayAnswerEdit.getString(i);
          Log.e("json", i + "=" + que);
     }
  } catch (JSONException e) {
      e.printStackTrace();
  }
</code>```

Title: Comma is causing unwanted string split

Body:
I have an array of data sent from my database - Once received, I save it in shared preferences - here is my getter:

public List getAnswerStringEdit() {
        return answer_edit;
    }

I save it as so:

editor.putString(Constants.ANSWER_EDIT,resp.getAnswer().getAnswerStringEdit().toString().trim());

Then retrieve it here:

String answerString = pref.getString(Constants.ANSWER_EDIT, "").trim();
        answerString = answerString.substring(1, answerString.length() - 1).trim();
        String[] array = answerString.split(",");

Finally, I access the array as so:

et_answer1_edit.append(array[0]);

My problem is this - Say I add a questions which has a comma in the middle of it, like -

Question 1- "Why is this broke, I don't know?"

Currently, when I retrieve my question, the string is getting split, even though there are quotation marks around the whole question/answer- So in the example above, in position 0 in the array, I should have:

"Why is this broke, I don't know?"

However, instead I am getting in position 0:

Why is this broke - then position 1 as: I don't know

I know this sounds daft because clearly, I am calling for the split to happen on the comma, but I expect that at the end of the whole string object, not in the middle of it.

The retrieved JSON is as follows:

{
    "result": "success",
    "message": "Answer Has Been Selected",
    "answer": {
        "answer_edit": ["Why is this broke, I don't know?", "What is your favorite song, because I want to know"]
    }
}

Any help/advice that can help me to understand what is causing this, would be really appreciated.

Body:
try this one

JSONObject jsonObject = new JSONObject("your json response");

try
  {
      JSONObject answer= jsonObject.getJSONObject("answer");

      JSONArray jsonArrayAnswerEdit = answer.getJSONArray("answer_edit");
      Log.e("=>", "" + jsonArrayAnswerEdit);
      for (int i = 0; i < jsonArrayAnswerEdit.length(); i++){
          String que= jsonArrayAnswerEdit.getString(i);
          Log.e("json", i + "=" + que);
     }
  } catch (JSONException e) {
      e.printStackTrace();
  }


问:
Shadows not showing when the distance increase b/w trees and Camera in unity
Trees are placed randomly every time on plane at runtime and camera moving forward continuously at z axis and static on other axis , actually the problem is that when camera position more than 10 on y axis the shadow not displaying but when the value is equal to 10 or less works fine but when move up more than 10 on y axis the shadows are not displaying.i increase the value of shadow distance in quality settings(eg.shadow distance=1000) but nothing effects.one more thing everything things work fine in unity.But not work on android device.

答: i got the solution of problem.Actually i was doing wrong that is selecting the fantastic while building my game for android.the right selection was simple because the green tick for android in that Row.After tweaking the quality settings will effect on android build.....


问:
Validation expression in asp.net
How to disallow use of double quotes " in a textbox

答:
Use the RegularExpressionValidator for your page input validation. The .NET validation controls will verify your users' input on both sides, the client-side, and the server-side which is important if the user has disabled JavaScript. This article might also help you to implement the validation of your ASP.NET server controls.

Please don't do this just with JavaScript or AJAX. Always perform a server-side input validation! Especially if you are writing the users' input back into a database (SQL Injections).

Title: Validation expression in asp.net


问:
Replace array key value
I want to replace array values (1, 2, 3 and 4) to corresponding text

```<code>1 = OK;
2 = nOK;
3 = Warning;
4 = Other
</code>```

Here is some code:

```<code>$status = $row['status'];
</code>```

(I stored $status text in mysql row 1,2,3,4,1,2,4,4,1, etc)

```<code>$myarray = array($status);
foreach($myarray as $key => $val)
{
    print_r($val);
}
</code>```

Output of this is:

```<code>Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 4 [4] => 1 [5] => 1 [6] => 3 [7] => 4 [8] => 1 [9] => 2 )
</code>```

How to do this? Thanks!

答:
```<code>$newArray= array_flip($oldArray);
</code>```

This will give your array keys the values of your "values".
If i understood correct the "text" you are referring to is the array values.

Title: Replace array key value

Body:
I want to replace array values (1, 2, 3 and 4) to corresponding text

1 = OK;
2 = nOK;
3 = Warning;
4 = Other

Here is some code:

$status = $row['status'];

(I stored $status text in mysql row 1,2,3,4,1,2,4,4,1, etc)

$myarray = array($status);
foreach($myarray as $key => $val)
{
    print_r($val);
}

Output of this is:

Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 4 [4] => 1 [5] => 1 [6] => 3 [7] => 4 [8] => 1 [9] => 2 )

How to do this? Thanks!

Body:
$newArray= array_flip($oldArray);

This will give your array keys the values of your "values".
If i understood correct the "text" you are referring to is the array values.