问:
SVG rect animation direction bottom to top
I have the following SVG animation:

Demo: https://codepen.io/anon/pen/xNJYGe

HTML:

```<code><div class='batteryIcon'>
  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>
</div>
</code>```

CSS:

```<code>.batteryIcon {
  svg {
    width: 50px;
    display: block;
    .st0 {
      fill: none;
      stroke: #adadad;
      stroke-width: 20;
      stroke-miterlimit: 5;
    }
    .power {
      fill: #06B67A;
    }
  }
}
</code>```

My problem is that the animation goes from _top to bottom instead of bottom to top.
I tried to transform my rect by CSS and inline attribute, added rotate and direction attributes and also keyPoints. Nothing worked so far.

答:
Instead of using a rect and animating the height you can use a polygon and animate the points attribute.

.batteryIcon svg {
  width: 50px;
  display: block;
}
.batteryIcon svg .st0 {
  fill: none;
  stroke: #adadad;
  stroke-width: 20;
  stroke-miterlimit: 5;
}
.batteryIcon svg .power {
  fill: #06B67A;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='batteryIcon'>
      <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
       <!--<rect class="power" x="100" y="150" width="470" height="880">
          <animate attributeName="height" values="0 ; 880" dur="2.5s" />
        </rect>-->

        <polygon points="100,1030 570,1030 570,150 100,150">
          <animate attributeName="points" values="100,1030 570,1030 570,1030 100,1030 ; 100,1030 570,1030 570,150 100,150" dur="2.5s" />
        </polygon>
       <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
      </svg>
    </div></code>```

Body:
I have the following SVG animation:

Demo: https://codepen.io/anon/pen/xNJYGe

HTML:

  <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
    <rect class="power" x="100" y="150" width="470" height="880">
      <animate attributeName="height" values="0 ; 880" dur="2.5s" />
    </rect>
    <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
  </svg>

CSS:

.batteryIcon {
  svg {
    width: 50px;
    display: block;
    .st0 {
      fill: none;
      stroke: #adadad;
      stroke-width: 20;
      stroke-miterlimit: 5;
    }
    .power {
      fill: #06B67A;
    }
  }
}

My problem is that the animation goes from _top to bottom instead of bottom to top.
I tried to transform my rect by CSS and inline attribute, added rotate and direction attributes and also keyPoints. Nothing worked so far.

Body:
Instead of using a rect and animating the height you can use a polygon and animate the points attribute.

.batteryIcon svg {
  width: 50px;
  display: block;
}
.batteryIcon svg .st0 {
  fill: none;
  stroke: #adadad;
  stroke-width: 20;
  stroke-miterlimit: 5;
}
.batteryIcon svg .power {
  fill: #06B67A;
}

<div class='batteryIcon'>
      <svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" viewBox="0 0 668.3 1108.2">
       <!--<rect class="power" x="100" y="150" width="470" height="880">
          <animate attributeName="height" values="0 ; 880" dur="2.5s" />
        </rect>-->

        <polygon points="100,1030 570,1030 570,150 100,150">
          <animate attributeName="points" values="100,1030 570,1030 570,1030 100,1030 ; 100,1030 570,1030 570,150 100,150" dur="2.5s" />
        </polygon>
       <polygon class="st0" points="444.9,80.7 444.9,15.8 231.2,15.8 231.2,80.7 40.3,80.7 40.3,1080.8 629.3,1080.8 629.3,80.7 "/>
      </svg>
    </div>


来源: stackexchange

问:
Butterworth Lowpass Filter
I am not getting the desired output, it is cutting off the lower freq. no matter if I set it to 'low' or 'high'.

```<code>import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

def butter_filter(data, butterCutoffFreq, order=1):
    b, a = signal.butter(order, butterCutoffFreq, 'low', analog=True)
    y = signal.lfilter(b, a, data)
    return y

"""
    White noise
"""
N = 1024
dt = np.float64(1)
y = np.random.normal(loc=0.0, scale=1.0, size=N)
t = np.arange(start=0, stop=N, step=dt)
butterCutoffFreq = 0.5 * 1/dt

amps = np.fft.rfft(y)
freqs = np.fft.rfftfreq(y.size, dt)
#plt.plot(freqs, np.abs(amps), color='b')

ampsFiltered = butter_filter(y, butterCutoffFreq)
ampsFiltered = np.fft.rfft(ampsFiltered)

plt.plot(freqs, np.abs(ampsFiltered), color='g')
plt.show()
</code>```

答:
Your problem is whith the param analog=True remove it and it will work.

lfilter() can only use a digital filter. It doesn't make sense to filter a digital signal (your white noise assumed regularly sampled) with an analog filter.

ContentLicense: CC BY-SA 4.0

Title: Butterworth Lowpass Filter

Body:
I am not getting the desired output, it is cutting off the lower freq. no matter if I set it to 'low' or 'high'.

import numpy as np
from scipy import signal
import matplotlib.pyplot as plt

def butter_filter(data, butterCutoffFreq, order=1):
    b, a = signal.butter(order, butterCutoffFreq, 'low', analog=True)
    y = signal.lfilter(b, a, data)
    return y

"""
    White noise
"""
N = 1024
dt = np.float64(1)
y = np.random.normal(loc=0.0, scale=1.0, size=N)
t = np.arange(start=0, stop=N, step=dt)
butterCutoffFreq = 0.5 * 1/dt

amps = np.fft.rfft(y)
freqs = np.fft.rfftfreq(y.size, dt)
#plt.plot(freqs, np.abs(amps), color='b')

ampsFiltered = butter_filter(y, butterCutoffFreq)
ampsFiltered = np.fft.rfft(ampsFiltered)

plt.plot(freqs, np.abs(ampsFiltered), color='g')
plt.show()


问:
Most efficient way to create a zero filled JavaScript array?
What is the most efficient way to create an arbitrary length zero filled array in JavaScript?</p>

答:
To create an all new Array

```<code>new Array(arrayLength).fill(0);
</code>```

To add some values at the end of an existing Array

[...existingArray, ...new Array(numberOfElementsToAdd).fill(0)]

Example

//**To create an all new Array**

console.log(new Array(5).fill(0));

//**To add some values at the end of an existing Array**

let existingArray = [1,2,3]

console.log([...existingArray, ...new Array(5).fill(0)]);```

ContentLicense: CC BY-SA 2.5

Body:
To create an all new Array

new Array(arrayLength).fill(0);

To add some values at the end of an existing Array

[...existingArray, ...new Array(numberOfElementsToAdd).fill(0)]

Example

//**To create an all new Array**

console.log(new Array(5).fill(0));

//**To add some values at the end of an existing Array**

let existingArray = [1,2,3]

console.log([...existingArray, ...new Array(5).fill(0)]);


问:
How can I identity MVCC Aboard?
I tried to see the problem MVCC with hyperledger fabric but the problem that when I invoke transaction that modifies and reads the same variable with the same key it works.

What are the changes to make to highlight MVCC?

答:
What are the changes to make to highlight MVCC?

MVCC stands for Multi Value Concurrency Control, this is well know approach to enable optimistic update mechanism which allow to prevent concurrent modifications of the same key. In Fabric context concurrent modification would be transactions which grouped into same block and modifies same key. Therefore in order to experience MVCC failure it's not enough to modify same key several times, you also need to make sure all those transactions will be batched to the same block.

The easiest way to achieve it is to throw as much as possible tx updates to increase probability of transactions to be places into same block.

Title: How can I identity MVCC Aboard?


问:
How can you create an API Health check in azure?
What is the best way to test API endpoints within azure? I am looking to get alerted if an endpoint is not working.</p>

答:
you can write a custom Azure Function to report Telemetry to Application Insight. See:
https://github.com/rbickel/Azure.Function.AppInsightAvailabilityTest</p>

ContentLicense: CC BY-SA 3.0


问:
Does X590Certificate.Build use OCSP if ChainPolicy RevocationMode Online is used?
If you have code like the following: is OCSP used for the 'online' revocation check?

```<code>X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
ch.Build (certificate);
</code>```

The API documentation is not explicit about this, saying:

"A revocation check is made using an online certificate revocation
  list (CRL)."

but not giving any details of how the check is made

The X509Chain.Buld methods checks if the property szOID_AUTHORITY_INFO_ACCESS has a value - I know this is where OCSP URLs are stored so again this would suggest that OCSP is being used

Build then calls BuildChain and there is a call is made to CertGeCertificateChain, passing a revocation flags unsigned int.

The documentation for GetCertificateChain gives the possible flags that can be passed in, including CERT_CHAIN_REVOCATION_CHECK_OCSP_CERT:

"This flag is used internally during chain building for an online
  certificate status protocol (OCSP) signer certificate to prevent
  cyclic revocation checks. During chain building, if the OCSP response
  is signed by an independent OCSP signer, then, in addition to the
  original chain build, there is a second chain built for the OCSP
  signer certificate itself. This flag is used during this second chain
  build to inhibit a recursive independent OCSP signer certificate. If
  the signer certificate contains the szOID_PKIX_OCSP_NOCHECK extension,
  revocation checking is skipped for the leaf signer certificate. Both
  OCSP and CRL checking are allowed."

Since a flag exists to 'inhibit' OCSP checking, I am thinking that it does happen - but again it would be nice to get an explicit confirmation of this

答:
If OCSP is the only option, like Let’s Encrypt, then yes. If both OCSP and CRL are available then the system chooses whichever it wants, using the other when the first choice produces bad/expired answers.

(On .NET Core for Linux, OCSP was not utilized before version 3.0)

Body:
If you have code like the following: is OCSP used for the 'online' revocation check?

X509Chain ch = new X509Chain();
ch.ChainPolicy.RevocationMode = X509RevocationMode.Online;
ch.Build (certificate);

The API documentation is not explicit about this, saying:

"A revocation check is made using an online certificate revocation
  list (CRL)."

but not giving any details of how the check is made

The X509Chain.Buld methods checks if the property szOID_AUTHORITY_INFO_ACCESS has a value - I know this is where OCSP URLs are stored so again this would suggest that OCSP is being used

Build then calls BuildChain and there is a call is made to CertGeCertificateChain, passing a revocation flags unsigned int.

The documentation for GetCertificateChain gives the possible flags that can be passed in, including CERT_CHAIN_REVOCATION_CHECK_OCSP_CERT:

"This flag is used internally during chain building for an online
  certificate status protocol (OCSP) signer certificate to prevent
  cyclic revocation checks. During chain building, if the OCSP response
  is signed by an independent OCSP signer, then, in addition to the
  original chain build, there is a second chain built for the OCSP
  signer certificate itself. This flag is used during this second chain
  build to inhibit a recursive independent OCSP signer certificate. If
  the signer certificate contains the szOID_PKIX_OCSP_NOCHECK extension,
  revocation checking is skipped for the leaf signer certificate. Both
  OCSP and CRL checking are allowed."

Since a flag exists to 'inhibit' OCSP checking, I am thinking that it does happen - but again it would be nice to get an explicit confirmation of this


问:
Entity Framework Core - Take(1), Single(), First()... Not Working with Oracle Provider (ORA-00933: SQL command not properly ended)
I'm using ef core(2.2.4) with oracle database

oracleProvider: Oracle.EntityFrameworkCore(2.18.0-beta3)

this code:

```<code>IQueryable<KeyInfo> queryable = context
                .KeyInfos
                .Where(x => x.MobileNumber == "989191111111")
                .Take(1);
</code>```

generate this db query:

```<code>SELECT "x"."ID", "x"."Key", "x"."MobileNumber", "x"."NationalCode"
FROM "KeyInfo" "x"
WHERE "x"."MobileNumber" = N'989191111111'
FETCH FIRST 1 ROWS ONLY;
</code>```

running query give me this error:

```<code>ORA-00933: SQL command not properly ended
00933. 00000 -  "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 4 Column: 1
</code>```

is any way to fix it? the correct way is to get the first row with

AND rownum = 1

not

FETCH FIRST 1 ROWS ONLY

and .ToList() works fine with IQueryable

答:
Apparently you are targeting an older Oracle database which doesn't support the newer FETCH FIRST N ROWS ONLY SQL construct.

In order to get the older ROWNUM based SQL translation, you should utilize the optional Action<OracleDbContextOptionsBuilder> oracleOptionsAction parameter of UseOracle method and UseOracleSQLCompatibility extension method with value "11" (the only currently supported values are "11" and "12"):

```<code>.UseOracle(connection_string, options => options
    .UseOracleSQLCompatibility("11"))
</code>```

Body:
I'm using ef core(2.2.4) with oracle database

oracleProvider: Oracle.EntityFrameworkCore(2.18.0-beta3)

this code:

IQueryable<KeyInfo> queryable = context
                .KeyInfos
                .Where(x => x.MobileNumber == "989191111111")
                .Take(1);

generate this db query:

SELECT "x"."ID", "x"."Key", "x"."MobileNumber", "x"."NationalCode"
FROM "KeyInfo" "x"
WHERE "x"."MobileNumber" = N'989191111111'
FETCH FIRST 1 ROWS ONLY;

running query give me this error:

ORA-00933: SQL command not properly ended
00933. 00000 -  "SQL command not properly ended"
*Cause:
*Action:
Error at Line: 4 Column: 1

is any way to fix it? the correct way is to get the first row with

AND rownum = 1

not

FETCH FIRST 1 ROWS ONLY

and .ToList() works fine with IQueryable

Body:
Apparently you are targeting an older Oracle database which doesn't support the newer FETCH FIRST N ROWS ONLY SQL construct.

In order to get the older ROWNUM based SQL translation, you should utilize the optional Action<OracleDbContextOptionsBuilder> oracleOptionsAction parameter of UseOracle method and UseOracleSQLCompatibility extension method with value "11" (the only currently supported values are "11" and "12"):

.UseOracle(connection_string, options => options
    .UseOracleSQLCompatibility("11"))


问:
Why is my iCloud KVS Observer not working
In my app I implemented a Preferences class that looks like this.

```<code>public class Preferences: Codable {
    public static var sharedPreferences: Preferences = {
        let preferences = Preferences()

        return preferences
    }()

    public class func shared() -> Preferences {
        return sharedPreferences
    }

    private let cloud: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore.default

    public init () {
        NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                               name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                               object: nil)
        self.cloud.synchronize()
    }

    @objc func keysDidChangeOnCloud(notification: Notification) {
        print("CLOUD CHANGED")
    }
}
</code>```

I observe a change in the Key Value storage. That print() is never executed though. Any idea why?

答:
I believe you need to observe the NSUbiquitousKeyValueStore.default object like so:</p>

```<code>NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                           name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                           object: NSUbiquitousKeyValueStore.default)
</code>```

Body:
In my app I implemented a Preferences class that looks like this.

public class Preferences: Codable {
    public static var sharedPreferences: Preferences = {
        let preferences = Preferences()

        return preferences
    }()

    public class func shared() -> Preferences {
        return sharedPreferences
    }

    private let cloud: NSUbiquitousKeyValueStore = NSUbiquitousKeyValueStore.default

    public init () {
        NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                               name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                               object: nil)
        self.cloud.synchronize()
    }

    @objc func keysDidChangeOnCloud(notification: Notification) {
        print("CLOUD CHANGED")
    }
}

I observe a change in the Key Value storage. That print() is never executed though. Any idea why?

Body:
I believe you need to observe the NSUbiquitousKeyValueStore.default object like so:

NotificationCenter.default.addObserver(self, selector: #selector(keysDidChangeOnCloud(notification:)),
                                           name: NSUbiquitousKeyValueStore.didChangeExternallyNotification,
                                           object: NSUbiquitousKeyValueStore.default)


问:
Where i can check the main standards for making android user interfaces?
i need a link where i can read and understand the main standards to follow where making android user interfaces

i can't find it on google

thanks

答:
Have you checked out the developer guide?

You can find it over here: Google Android Dev Guide


问:
NSwag adding three parameters to some of my methods
Swagger is adding three extra parameters in the UI. It only does it with two methods.  The other three are fine.  All are defined pretty much the same way.  The only difference I can see is the order of parameters ([FromBody] is first on the offending methods).

I have been researching on Google and cannot find anyone having the same issue.  The only thing I could think to try was rearranging the order of the parameters.

```<code>// Does not have the parameters
[HttpPost]
[Route ( "api/Processor/GetHtmlWithByteArrays" )]
public JsonResult GetHtmlWithByteArrays ( [FromQuery] List<string> roles, [FromBody] List<byte[ ]> files ) => new JsonResult ( Processor.GetHtml ( roles, files ) );

// Has the extra parameters
[HttpPost]
[Route ( "api/Processor/GetDocFromHtmlString" )]
public JsonResult GetDocFromHtmlString ( [FromBody] string htmlString, [FromQuery] DocType docType, [FromQuery] bool includeToc = true,
bool includeFooter = false ) => new JsonResult ( Processor.GetDocFromHtmlString ( htmlString, docType, includeToc, includeFooter ) );
</code>```

I would expect the SwaggerUI to just show the parameters I have defined.  However, for two of my methods, the following parameters are being added:

```<code>Provider.SupportedExtensions
Provider.CanImport
Provider.CanExport
</code>```

答:
I finally figured out that this was caused because I am referencing an abstract class (DocType).  I resolved it by referencing Newtonsoft.Json and setting up the class with the necessary decorations to let Json know how to resolve it.  The known types are the objects that inherit the abstract class.  I hope this helps anyone having a similar issue.</p>

```<code>[ JsonConverter ( typeof ( JsonInheritanceConverter ), "discriminator" ) ]
[ KnownType ( typeof ( Docx ) ) ]
[ KnownType ( typeof ( Html ) ) ]
[ KnownType ( typeof ( Pdf ) ) ]
[ KnownType ( typeof ( Rtf ) ) ]
[ KnownType ( typeof ( Txt ) ) ]
</code>```

Body:
Swagger is adding three extra parameters in the UI. It only does it with two methods.  The other three are fine.  All are defined pretty much the same way.  The only difference I can see is the order of parameters ([FromBody] is first on the offending methods).

I have been researching on Google and cannot find anyone having the same issue.  The only thing I could think to try was rearranging the order of the parameters.

// Does not have the parameters
[HttpPost]
[Route ( "api/Processor/GetHtmlWithByteArrays" )]
public JsonResult GetHtmlWithByteArrays ( [FromQuery] List<string> roles, [FromBody] List<byte[ ]> files ) => new JsonResult ( Processor.GetHtml ( roles, files ) );

// Has the extra parameters
[HttpPost]
[Route ( "api/Processor/GetDocFromHtmlString" )]
public JsonResult GetDocFromHtmlString ( [FromBody] string htmlString, [FromQuery] DocType docType, [FromQuery] bool includeToc = true,
bool includeFooter = false ) => new JsonResult ( Processor.GetDocFromHtmlString ( htmlString, docType, includeToc, includeFooter ) );

I would expect the SwaggerUI to just show the parameters I have defined.  However, for two of my methods, the following parameters are being added:

Provider.SupportedExtensions
Provider.CanImport
Provider.CanExport

Body:
I finally figured out that this was caused because I am referencing an abstract class (DocType).  I resolved it by referencing Newtonsoft.Json and setting up the class with the necessary decorations to let Json know how to resolve it.  The known types are the objects that inherit the abstract class.  I hope this helps anyone having a similar issue.

[ JsonConverter ( typeof ( JsonInheritanceConverter ), "discriminator" ) ]
[ KnownType ( typeof ( Docx ) ) ]
[ KnownType ( typeof ( Html ) ) ]
[ KnownType ( typeof ( Pdf ) ) ]
[ KnownType ( typeof ( Rtf ) ) ]
[ KnownType ( typeof ( Txt ) ) ]


问:
Data transformation in logstash
I have a data source, a read-only SQL server, and by combining tables from this server, I am making a log, that I need to upload it Elastic Search.

To do this, I have an API call to the data source, and then have the data transformation happen in Logstash, and then upload it to ES.

I have done the data transformation several times before, in SQL. In SQL I would JOIN several tables and INSERT the query results into a log table, but I don't have SQL option in this setup, I need to do the transformation in logstash.

What I am asking for is best-practice suggestions for logstash.

答:
```<code>input {
  jdbc {
    jdbc_driver_library => "mysql-connector-java-5.1.38-bin.jar"
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    jdbc_connection_string => "jdbc:mysql://localhost/student?user=root&password="
    jdbc_user => "Croos"
    parameters => {
    }

    schedule => "* * * * *"
    statement => "SELECT * from subject WHERE id > :sql_last_value"
    use_column_value => true
    tracking_column => id
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}
</code>```

This link may help full to you.

Title: Data transformation in logstash

Body:
input {
  jdbc {
    jdbc_driver_library => "mysql-connector-java-5.1.38-bin.jar"
    jdbc_driver_class => "com.mysql.jdbc.Driver"
    jdbc_connection_string => "jdbc:mysql://localhost/student?user=root&password="
    jdbc_user => "Croos"
    parameters => {
    }

    schedule => "* * * * *"
    statement => "SELECT * from subject WHERE id > :sql_last_value"
    use_column_value => true
    tracking_column => id
  }
}

output {
  elasticsearch {
    hosts => ["localhost:9200"]
  }
}

This link may help full to you.


问:
Add action to scaffold generated controller
I have created model, view and controller:

```<code>$ rails generate scaffold Post name:string title:string content:text
</code>```

Then I have added the method on Post controller:

```<code>def fill_default_data
  Post.fill_default_data
end
</code>```

But when I have open http://localhost:3000/posts/fill_default_data in browser I get the error:

ActiveRecord::RecordNotFound in
  PostsController#show

Couldn't find Post with
  ID=fill_default_data

It looks like Rails don't see fill_default_data action and use show method.  How can I add new method to scaffold generated controller?

答:
You should add the relevant route to your config/routes.rb file. If you currently have:

```<code>resources :posts
</code>```

You should change that to:

```<code>resources :posts do
  collection do
    get :fill_default_data
  end
end
</code>```

That will generate a route that you can access through /posts/fill_default_data. Now your app is actually accessing the show action and filling in "fill_default_data" as the ID.

Body:
I have created model, view and controller:

$ rails generate scaffold Post name:string title:string content:text

Then I have added the method on Post controller:

def fill_default_data
  Post.fill_default_data
end

But when I have open http://localhost:3000/posts/fill_default_data in browser I get the error:

ActiveRecord::RecordNotFound in
  PostsController#show

Couldn't find Post with
  ID=fill_default_data

It looks like Rails don't see fill_default_data action and use show method.  How can I add new method to scaffold generated controller?

Body:
You should add the relevant route to your config/routes.rb file. If you currently have:

resources :posts

You should change that to:

resources :posts do
  collection do
    get :fill_default_data
  end
end

That will generate a route that you can access through /posts/fill_default_data. Now your app is actually accessing the show action and filling in "fill_default_data" as the ID.


问:
angularjs - ngTable - issue with dynamic filter in controller
I want to create a filter for my ngTable.

In the controller at the root (not in a function) I do :

```<code>$scope.filters = {
   nomSociete: 'test'
}
</code>```

then

```<code>$scope.tableParamsContacts.reload();
$scope.tableParamsContacts = new ngTableParams({
           page: 1,            // show first page
           count: 10,
           filter : $scope.filters,
           sorting: {
               nom:'asc',
               prenom:'asc'
           }
       }, {
           total: dataContact.length, // length of data
           getData: function($defer, params) {
               // use build-in angular filter
               var filteredData = params.filter() ?
                   $filter('filter')(dataContact, params.filter()) :
                   data;
               var orderedData = params.sorting() ?
                   $filter('orderBy')(filteredData, params.orderBy()) :
                   dataContact;

               params.total(orderedData.length); // set total for recalc pagination
               if(params.total() < (params.page() -1) * params.count()){
                   params.page(1);
               }
               $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
           }
       });
</code>```

It works

But if I place

```<code>$scope.filters = {
   nomSociete: 'test'
}
</code>```

in a function in my controller:

```<code>vm.onClientSelect = function(affaire){
   $scope.filters = {
      nomSociete: 'test'
   }
   $scope.tableParamsContacts.reload();
}
</code>```

It doesn't work, the value of the filter doesn't appear in the ng table, and the ng table gets empty.

I don't understand why.

答:
Change the filter directly from within your ngTableParams like this:

```<code> $scope.filters = {
   nomSociete: 'test'
 }
 $scope.tableParamsContacts.filter($scope.filters);
 $scope.tableParamsContacts.reload();
</code>```

Body:
I want to create a filter for my ngTable.

In the controller at the root (not in a function) I do :

$scope.filters = {
   nomSociete: 'test'
}

then

$scope.tableParamsContacts.reload();
$scope.tableParamsContacts = new ngTableParams({
           page: 1,            // show first page
           count: 10,
           filter : $scope.filters,
           sorting: {
               nom:'asc',
               prenom:'asc'
           }
       }, {
           total: dataContact.length, // length of data
           getData: function($defer, params) {
               // use build-in angular filter
               var filteredData = params.filter() ?
                   $filter('filter')(dataContact, params.filter()) :
                   data;
               var orderedData = params.sorting() ?
                   $filter('orderBy')(filteredData, params.orderBy()) :
                   dataContact;

               params.total(orderedData.length); // set total for recalc pagination
               if(params.total() < (params.page() -1) * params.count()){
                   params.page(1);
               }
               $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
           }
       });

It works

But if I place

$scope.filters = {
   nomSociete: 'test'
}

in a function in my controller:

vm.onClientSelect = function(affaire){
   $scope.filters = {
      nomSociete: 'test'
   }
   $scope.tableParamsContacts.reload();
}

It doesn't work, the value of the filter doesn't appear in the ng table, and the ng table gets empty.

I don't understand why.

Body:
Change the filter directly from within your ngTableParams like this:

 $scope.filters = {
   nomSociete: 'test'
 }
 $scope.tableParamsContacts.filter($scope.filters);
 $scope.tableParamsContacts.reload();


问:
Covariant wrapper for std::vector
I want a covariant wrapper for std::vector.  My idea was to do something like this:

Create an abstract base class BaseVector whose begin and end methods just forward to pure virtual functions.

Create a concrete derived class DerivedVector that wraps a std::vector<D>.  Its begin and end methods would shadow the base class's, and it would implement the virtual methods that the base class forwards to.

In this way, if you have a pointer to a BaseVector you can iterate over base class instances, and if you have a DerivedVector pointer you can iterate over derived class instances.

(EDIT: Obviously the BaseVector will necessarily not support insertion, since it can't know the type of the objects it contains.  Perhaps this means "Vector" isn't the best name for it; I'm open to suggestions.  Thanks @CygnusX1.)

For the DerivedVector class the begin and end methods could just forward to std::vector's.

Question: How could I implement the methods the BaseVector begin and end forward to?  Do I have to write my own iterator class that wraps the std::vector iterators?

Alternatively: Is there a better or easier way to do this?

A DerivedVector instance needs to be usable through a BaseVector pointer in code that knows about B but not D, and it needs to have equivalent performance to just holding a derived class vector (if the calling code knew about the derived class)

Sample use case:

A library provides a BaseWidget class and a BaseWidgetPool class, which the user derives from.  Due to the nature of the library, in any given program there will be exactly one DerivedWidget class, but this class will differ for every program using the library.

The BaseWidgetPool class includes methods that iterate over all the widgets in the pool and make use of their BaseWidget functionality.  But each program's DerivedWidgetPool is likely to want to use the DerivedWidget functionality of its contents.

(I know I could also handle this by making a generic WidgetPool<T> class, but I'd rather encapsulate T to the part of the code which actually uses it.)

答:
With ranges, this become a non issue. It has all the api you need for polymorphic ranges:

```<code>#include <range/v3/all.hpp>

namespace rv = ranges::view;

int main() {
    std::vector<Derived> derived_container;

    // ... fill it

    ranges::any_view<Base*> base_view =
        rv::all(derived_container) | rv::transform([](auto& e) -> Base* { return &e; });

    // do stuff with `base_view`
}
</code>```

Then you can use base_view as long as derived_container lives.

I used any_view so that the range is type erased. You can pass it around without needing to templatize function and you can pass it in virtual functions.

If you cannot use std ranges nor range v3, I'd create a simialar wrapper. So instead of a exposing a class herarchy, you hide it in the utility class.

Live example

Of course, the any_view is there only to avoid templating function over the range type when passing it around. You can instead directly materialize the range into a vector:

```<code>auto base_view =
    rv::all(derived_container) | rv::transform([](auto& e) -> Base* { return &e; });

std::vector<Base*> base_container = ranges::to<std::vector>(base_view);
</code>```

This will avoid overhead during iteration but require a memory allocation for the new vector.

Title: Covariant wrapper for std::vector

Body:
With ranges, this become a non issue. It has all the api you need for polymorphic ranges:

#include <range/v3/all.hpp>

namespace rv = ranges::view;

int main() {
    std::vector<Derived> derived_container;

    // ... fill it

    ranges::any_view<Base*> base_view =
        rv::all(derived_container) | rv::transform([](auto& e) -> Base* { return &e; });

    // do stuff with `base_view`
}

Then you can use base_view as long as derived_container lives.

I used any_view so that the range is type erased. You can pass it around without needing to templatize function and you can pass it in virtual functions.

If you cannot use std ranges nor range v3, I'd create a simialar wrapper. So instead of a exposing a class herarchy, you hide it in the utility class.

Live example

Of course, the any_view is there only to avoid templating function over the range type when passing it around. You can instead directly materialize the range into a vector:

auto base_view =
    rv::all(derived_container) | rv::transform([](auto& e) -> Base* { return &e; });

std::vector<Base*> base_container = ranges::to<std::vector>(base_view);

This will avoid overhead during iteration but require a memory allocation for the new vector.


问:
How to identify if certain keys are present in dictonary?
I have dictonary named as Entity which look like this:

```<code>Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}
</code>```

Now I have to create other dictionary which will contain below value according to condition.

```<code>Class = {'Signal':'<Condition>'}
</code>```

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

```<code>Class = {'Signal' : 'Medium'}
</code>```

答:
To check if dictionary contains specific key use:
'ORG' in Entity statement which returns True if given key is present in the dictionary and False otherwise.

Body:
I have dictonary named as Entity which look like this:

Entity = {'ORG': 'ABC','PERSON': 'Ankit','ORDINAL': '150th','DATE': 'quarterly', 'MONEY': 'dollars'}

Now I have to create other dictionary which will contain below value according to condition.

Class = {'Signal':'<Condition>'}

The condition is:

If Entity key consists of ORG and PERSON then in Class dictionary value "Medium" should be updated.

If Entity key consists of ORG, PERSON, and MONEY then in Class dictionary value "Strong" should be updated.

If Entity key doesn't consist of above keys then in Class dictionary value "Weak" should be updated.

How should I make the condition for the above problem?

I want an output in Class dictionary like below,

If in Entity dictionary there are ORG and PERSIN keys then Class dictionary should be like,

Class = {'Signal' : 'Medium'}


问:
Need to extract all links from script tag HTML Python
Basically i need to parse all src="" links from all

Unfortunately, bs4 cannot do that. Any ideas how can i achieve this?

答:
```<code>import requests
import bs4
text = requests.get('http://example.com').text
soup = bs4.BeautifulSoup(text, features='html.parser')
scripts = soup.find_all('script')
srcs = [link['src'] for link in scripts if 'src' in link.attrs]
print(srcs)
</code>```


问:
How Share an instance of Ignite between webapps?
I am trying to do a demo application, that reads some data and caches it to Ignite. This is a tomcat web application. I would like to start another tomcat web app on another machine, and would like to read data from the first webapp's ignite. Whatever config i use, looks like the second application is not able to find the first ignite instance?

I've tried using TcpDiscoveryMulticastIpFinder and also TcpDiscoveryVmIpFinder

Below is one of the config I tried

```<code>   <property name="discoverySpi">
        <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
            <property name="ipFinder">
                <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                    <property name="multicastGroup" value="228.111.111.222"/>
                </bean>
            </property>
        </bean>
    </property>
</code>```

Also tried below config

```<code>      <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
      <property name="addresses">
        <list>
            <!--local node -->
          <value>165.80.121.125</value>

            <!--Remote node -->
          <value>165.80.113.121</value>
        </list>
      </property>
    </bean>
</code>```

In both cases, i do not see the 2nd node connecting to the first node.
I also tried to start the first node as server, and the second as client, but still with no success. Can anyone suggest where am i going wrong?

Should i start a stand alone ignite client, and start ignite in client mode in both apps? Would that work?

答: It seems that you should organize your application architecture to have separate server node(s) and Ignite clients. Client nodes could be embedded into your web application instances. In general client nodes doesn't store data, their purpose is to serve as a "facade" to server nodes. </p>

Body:
I am trying to do a demo application, that reads some data and caches it to Ignite. This is a tomcat web application. I would like to start another tomcat web app on another machine, and would like to read data from the first webapp's ignite. Whatever config i use, looks like the second application is not able to find the first ignite instance?

I've tried using TcpDiscoveryMulticastIpFinder and also TcpDiscoveryVmIpFinder

Below is one of the config I tried

   <property name="discoverySpi">
        <bean class="org.apache.ignite.spi.discovery.tcp.TcpDiscoverySpi">
            <property name="ipFinder">
                <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.multicast.TcpDiscoveryMulticastIpFinder">
                    <property name="multicastGroup" value="228.111.111.222"/>
                </bean>
            </property>
        </bean>
    </property>

Also tried below config

      <bean class="org.apache.ignite.spi.discovery.tcp.ipfinder.vm.TcpDiscoveryVmIpFinder">
      <property name="addresses">
        <list>

          <value>165.80.121.125</value>

          <value>165.80.113.121</value>
        </list>
      </property>
    </bean>

In both cases, i do not see the 2nd node connecting to the first node.
I also tried to start the first node as server, and the second as client, but still with no success. Can anyone suggest where am i going wrong?

Should i start a stand alone ignite client, and start ignite in client mode in both apps? Would that work?


答: Are you looking for the Android UI guidelines?</p>

Title: Where i can check the main standards for making android user interfaces?

Body:
i need a link where i can read and understand the main standards to follow where making android user interfaces

i can't find it on google

thanks


问:
How To Change The Bottom Line EditText Color?
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

```<code>AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();
</code>```

For some weird reason that is not working, setHightlightColor should be it.

答:
You need to set the Background Tint for that use :</p>

```<code>inputET.setBackgroundTintList(ColorStateList.valueOf(intColorCode));
</code>```

Body:
I have an EditText in an AlertDialog and the bottom line color is not what I want, and I can't figure out how to change it.

Here is what I have so far.

AlertDialog.Builder adb = new AlertDialog.Builder(new ContextThemeWrapper(MainActivity.this, R.style.EditTextAlertDialog));
    adb.setTitle("Title");
    inputET = new EditText(this);
    inputET.setInputType(InputType.TYPE_CLASS_TEXT);
    inputET.setTextColor(getResources().getColor(android.R.color.white));
   inputET.setHighlightColor(getResources().getColor(android.R.color.white)); //This should change it, but it's not.
    adb.setView(inputET);

    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();

For some weird reason that is not working, setHightlightColor should be it.

Body:
You need to set the Background Tint for that use :

inputET.setBackgroundTintList(ColorStateList.valueOf(intColorCode));


问:
Deleting a string between two carriage returns tsql
Very new to SQL so I appreciate your patience in advance.
I have a column in a table that stores a particular set of instructions; each instruction is encapsulated by a carriage return.

eg: char(13)+ @instruction1 + char(13)...

@Instruction1 is a string  of variable length but I do know a certain part of the string eg: @instruction1 = some string + @knownstring + some string.

So we have char(13) + (some string + @knownstring + some string) +char(13).

I want to replace this entire line with ''.

Identifying it just using the @knownstring.

Is this possible?

Thanking you all again, I really appreciate your assistance

```<code>select replace(replace(column,@knownsting,''),char(13),'')
from table
where key=1235
</code>```

Replaces only the @knownstring but I also need to replace the surrounding text between the two char(13)

答:
You might try something along this:

```<code>DECLARE @KnownString VARCHAR(50)='Keep This'
DECLARE @YourString VARCHAR(MAX)='blah' + CHAR(13) + 'dummy keep this dummy more' + CHAR(13) + 'Something without the known part' + CHAR(13) + 'Again with Keep THIS';

SELECT STUFF(
(
    SELECT CHAR(13) + CASE WHEN CHARINDEX(@KnownString,LineText)>0 THEN @KnownString ELSE LineText END
    FROM (SELECT CAST('<x>' + REPLACE(@YourString,CHAR(13),'</x><x>') + '</x>' AS XML)) A(Casted)
    CROSS APPLY Casted.nodes('/x') B(fragment)
    OUTER APPLY (SELECT fragment.value('text()[1]','nvarchar(max)')) C(LineText)
    FOR XML PATH(''),TYPE
).value('.','nvarchar(max)'),1,1,'');
</code>```

The result

```<code>blah
Keep This
Something without the known part
Keep This
</code>```

The idea

The string is transformed to XML by replacing the line breaks with XML tags. Now we can query all text lines separately, check them for the known string, do the needed manipulation, and finally reconcatenate all fragments using the XML-trick (together with STUFF to get rid of the leading CHAR(13)).

Remarks

Using v2016 I'd use the split-string approach with OPENJSON and starting with v2017 there is STRING_AGG() to make the reconcatenation easier.

Body:
Very new to SQL so I appreciate your patience in advance.
I have a column in a table that stores a particular set of instructions; each instruction is encapsulated by a carriage return.

eg: char(13)+ @instruction1 + char(13)...

@Instruction1 is a string  of variable length but I do know a certain part of the string eg: @instruction1 = some string + @knownstring + some string.

So we have char(13) + (some string + @knownstring + some string) +char(13).

I want to replace this entire line with ''.

Identifying it just using the @knownstring.

Is this possible?

Thanking you all again, I really appreciate your assistance

select replace(replace(column,@knownsting,''),char(13),'')
from table
where key=1235

Replaces only the @knownstring but I also need to replace the surrounding text between the two char(13)

Body:
You might try something along this:

DECLARE @KnownString VARCHAR(50)='Keep This'
DECLARE @YourString VARCHAR(MAX)='blah' + CHAR(13) + 'dummy keep this dummy more' + CHAR(13) + 'Something without the known part' + CHAR(13) + 'Again with Keep THIS';

SELECT STUFF(
(
    SELECT CHAR(13) + CASE WHEN CHARINDEX(@KnownString,LineText)>0 THEN @KnownString ELSE LineText END
    FROM (SELECT CAST('<x>' + REPLACE(@YourString,CHAR(13),'</x><x>') + '</x>' AS XML)) A(Casted)
    CROSS APPLY Casted.nodes('/x') B(fragment)
    OUTER APPLY (SELECT fragment.value('text()[1]','nvarchar(max)')) C(LineText)
    FOR XML PATH(''),TYPE
).value('.','nvarchar(max)'),1,1,'');

The result

blah
Keep This
Something without the known part
Keep This

The idea

The string is transformed to XML by replacing the line breaks with XML tags. Now we can query all text lines separately, check them for the known string, do the needed manipulation, and finally reconcatenate all fragments using the XML-trick (together with STUFF to get rid of the leading CHAR(13)).

Remarks

Using v2016 I'd use the split-string approach with OPENJSON and starting with v2017 there is STRING_AGG() to make the reconcatenation easier.


答:
You should Google for User Interface Guidelines or smth..
Check this out

http://developer.android.com/guide/practices/ui_guidelines/index.html


问:
Sentry.io doesn't capture errors when Spring Boot running in production?
There is Spring Boot application that runs on the server without exposing to external world. I connected Sentry to monitor it but never got any errors, even I have tons of them in the logs.

By without exposing to external world I mean that there is no open url that everyone can use for API connection.

How should I configure Sentry in order to get errors? Should I fall down to other scenarios, not default Spring Boot app configuration?

答:
Sentry doesn't need to connect to your application. When you add Sentry's SDK to your app and configure it with the correct DSN, your app will connect to Sentry to send errors as they occur.

For that you need to make sure the DSN you used goes to the project your expect to see the events in Sentry. That could be a reason why you don't see the events.

Perhaps your server has not access to the Internet? Or if it does, it requires use of an internal proxy server which was not configured in your server/application/sdk.


问:
Pagination in Cosmos DB using Page Size and Page Number
I am trying to return items from cosmosDB using PageSize and PageNumber. I know we can set the page size in MaxItemCount, but how do we put the page number in this function?

Here's what I got so far:

```<code>  public async Task<IEnumerable<T>> RunSQLQueryAsync(string queryString, int pageSize, int pageNumber)
        {
            var feedOptions = new FeedOptions { MaxItemCount = pageSize, EnableCrossPartitionQuery = true };
            IQueryable<T> filter = _client.CreateDocumentQuery<T>(_collectionUri, queryString, feedOptions);
            IDocumentQuery<T> query = filter.AsDocumentQuery();
            var currentPageNumber = 0;
            var documentNumber = 0;
            List<T> results = new List<T>();
            while (query.HasMoreResults)
            {
                foreach (T t in await query.ExecuteNextAsync())
                {
                    results.Add(t);
                    documentNumber++;
                }
                currentPageNumber++;
                return results;

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

答:
There is a workaround, but it is not optimal:</p>

```<code>...
int pageNumber = 1;
int pageSize = 10;
...
    var query = Client.CreateDocumentQuery<T>(
                    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                    new FeedOptions { MaxItemCount = pageNumber * pageSize }) // Limit count or returned items
                    .Where(predicate)
                    .AsDocumentQuery();

                var results = new List<T>();
                int resultsToSkip = (pageNumber - 1) * pageSize;

                while (query.HasMoreResults)
                {
                    var result = await query.ExecuteNextAsync<T>();

                    // Skip pages, not optimal way, the best solution is to use RequestContinuation token.
                    if (resultsToSkip > 0)
                    {
                        resultsToSkip--;
                        continue;
                    }

                    results.AddRange(result);
                }

                return results;
    ...
</code>```

Body:
I am trying to return items from cosmosDB using PageSize and PageNumber. I know we can set the page size in MaxItemCount, but how do we put the page number in this function?

Here's what I got so far:

  public async Task<IEnumerable<T>> RunSQLQueryAsync(string queryString, int pageSize, int pageNumber)
        {
            var feedOptions = new FeedOptions { MaxItemCount = pageSize, EnableCrossPartitionQuery = true };
            IQueryable<T> filter = _client.CreateDocumentQuery<T>(_collectionUri, queryString, feedOptions);
            IDocumentQuery<T> query = filter.AsDocumentQuery();
            var currentPageNumber = 0;
            var documentNumber = 0;
            List<T> results = new List<T>();
            while (query.HasMoreResults)
            {
                foreach (T t in await query.ExecuteNextAsync())
                {
                    results.Add(t);
                    documentNumber++;
                }
                currentPageNumber++;
                return results;

            }
            return null;
        }

Body:
There is a workaround, but it is not optimal:

...
int pageNumber = 1;
int pageSize = 10;
...
    var query = Client.CreateDocumentQuery<T>(
                    UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),
                    new FeedOptions { MaxItemCount = pageNumber * pageSize }) // Limit count or returned items
                    .Where(predicate)
                    .AsDocumentQuery();

                var results = new List<T>();
                int resultsToSkip = (pageNumber - 1) * pageSize;

                while (query.HasMoreResults)
                {
                    var result = await query.ExecuteNextAsync<T>();

                    // Skip pages, not optimal way, the best solution is to use RequestContinuation token.
                    if (resultsToSkip > 0)
                    {
                        resultsToSkip--;
                        continue;
                    }

                    results.AddRange(result);
                }

                return results;
    ...


问:
How to preform JOIN with JPA JAVA

I want to be short and clear for my problem.. I am trying to retrieve datas from the database performing join to get the result I want..

So i have 3 tables ,

```<code>EMPLOYEE:
emp_id -- PK
name..
surname..
dob.. etc
</code>```

USER:

```<code>UserID PK
Username
Pass
emp_id fk
role_id fk
</code>```

Role

```<code>RoleID pk
Description
</code>```

I want to perform a  query to get a list of employees who are users ,and have roleid =2;
How can I do that on JPA

I tried this

```<code>Select e from Employee e JOIN User u Join Role r where r.roleId = 2
</code>```

But it doesn't work still gets all employees without filtering those who have ID=2

Thanks y'all

答:
You have to set associations between your entities i.e. define how your two entities are linked to each other. This way spring will be able to convert jpql into sql and get data.

You will have to write your User and Employee entity like

```<code>public class User {
...
@OneToOne
@JoinColumn //using which column name it should join
private Employee employee;

@ManyToOne
@JoinColumn
private Role role;
...
</code>```

```<code>public class Employee {
...
@OneToOne(mapedBy="employee")
private User user;
...
</code>```

then you can write your query like

```<code>@Query("select e from Employee e LEFT JOIN e.user u LEFT JOIN u.role r where r.id = :roleId")
List<Employee> getEmployeeListByRoleId(@Param("roleId") Long roleId);
</code>```

Title: How to preform JOIN with JPA JAVA

Body:
I want to be short and clear for my problem.. I am trying to retrieve datas from the database performing join to get the result I want..

So i have 3 tables ,

EMPLOYEE:
emp_id -- PK
name..
surname..
dob.. etc

USER:

UserID PK
Username
Pass
emp_id fk
role_id fk

Role

RoleID pk
Description

I want to perform a  query to get a list of employees who are users ,and have roleid =2;
How can I do that on JPA

I tried this

Select e from Employee e JOIN User u Join Role r where r.roleId = 2

But it doesn't work still gets all employees without filtering those who have ID=2

Thanks y'all

Body:
You have to set associations between your entities i.e. define how your two entities are linked to each other. This way spring will be able to convert jpql into sql and get data.

You will have to write your User and Employee entity like

public class User {
...
@OneToOne
@JoinColumn //using which column name it should join
private Employee employee;

@ManyToOne
@JoinColumn
private Role role;
...

public class Employee {
...
@OneToOne(mapedBy="employee")
private User user;
...

then you can write your query like

@Query("select e from Employee e LEFT JOIN e.user u LEFT JOIN u.role r where r.id = :roleId")
List<Employee> getEmployeeListByRoleId(@Param("roleId") Long roleId);


问:
Understand python multithreading by simple math computational problem, How Make it faster codes in python
I am trying to understand multithreading in python, but every examples I read are very simple and similar to each other and don't serve my purpose.

I am performing high mathematics computation tasks so I need to use python mulithreading. I need to use multithreading NOT multiprocessing to avoid memory issues.

Below you will find a simple math problem that I wanna perform multithreading (Not an actual one, but let me understand threading). So i need to run task#1 (square) and task#2 (inve) in-parallel at the same time at two different threads (wait the results from the two), and then use the results from the two to obtain final result back in the main thread.

Please use any threading options in python (Thread, ThreadPool, ThreadPoolExecutor) anything you prefer, and really save time and cost comparing to serial code

If any one has better idea to make this code run faster, please share it

```<code>import scipy
import numpy

def square(A):
    # take the square root of a matix
    y = scipy.linalg.sqrtm(A)
    return y

def inve(A):
    # take the inverse of a matrix
    y = numpy.linalg.inv(A)

def main(A):
    # A is a matrix
    # a is the square root of a matrix
    # b is the inverse of a matix

    # Run the first task on one thread
    a = square(A)
    # Run the second task in-parallel in another thread
    b = inve(A)

    # and then run final result in main thread
    result = a * b

    return result

A=[[1,2],[3,4]]
result = main(A)
</code>```

答:
Here is how you can perform multithreading:</p>

```<code>import threading
from scipy import linalg
import numpy

x=1
y=1
def square(A):
    global x
    # take the square root of a matix
    x = linalg.sqrtm(A)

def inve(A):
    global y
    y = numpy.linalg.inv(A)

def main(A):
    # creating thread
    t1 = threading.Thread(target=square, args=(A,))
    t2 = threading.Thread(target=inve, args=(A,))

    # starting thread 1
    t1.start()
    # starting thread 2
    t2.start()

    # wait until thread 1 is completely executed
    t1.join()
    # wait until thread 2 is completely executed
    t2.join()

if __name__ == "__main__":
    A = [[1,2],[3,4]]
    main(A)
    result = x*y
    print(result)
</code>```

Body:
I am trying to understand multithreading in python, but every examples I read are very simple and similar to each other and don't serve my purpose.

I am performing high mathematics computation tasks so I need to use python mulithreading. I need to use multithreading NOT multiprocessing to avoid memory issues.

Below you will find a simple math problem that I wanna perform multithreading (Not an actual one, but let me understand threading). So i need to run task#1 (square) and task#2 (inve) in-parallel at the same time at two different threads (wait the results from the two), and then use the results from the two to obtain final result back in the main thread.

Please use any threading options in python (Thread, ThreadPool, ThreadPoolExecutor) anything you prefer, and really save time and cost comparing to serial code

If any one has better idea to make this code run faster, please share it

import scipy
import numpy

def square(A):
    # take the square root of a matix
    y = scipy.linalg.sqrtm(A)
    return y

def inve(A):
    # take the inverse of a matrix
    y = numpy.linalg.inv(A)

def main(A):
    # A is a matrix
    # a is the square root of a matrix
    # b is the inverse of a matix

    # Run the first task on one thread
    a = square(A)
    # Run the second task in-parallel in another thread
    b = inve(A)

    # and then run final result in main thread
    result = a * b

    return result

A=[[1,2],[3,4]]
result = main(A)

Body:
Here is how you can perform multithreading:

import threading
from scipy import linalg
import numpy

x=1
y=1
def square(A):
    global x
    # take the square root of a matix
    x = linalg.sqrtm(A)

def inve(A):
    global y
    y = numpy.linalg.inv(A)

def main(A):
    # creating thread
    t1 = threading.Thread(target=square, args=(A,))
    t2 = threading.Thread(target=inve, args=(A,))

    # starting thread 1
    t1.start()
    # starting thread 2
    t2.start()

    # wait until thread 1 is completely executed
    t1.join()
    # wait until thread 2 is completely executed
    t2.join()

if __name__ == "__main__":
    A = [[1,2],[3,4]]
    main(A)
    result = x*y
    print(result)


问:
Sweet Alert 2 and Socket.io use result of an emit in preConfirm
I'm using SWAL2 preConfirm() function in a sweet alert to test if an ID is ok server side... using socket.emit() with acknowledgements

I would like to be able to use Swal.showValidationMessage("Some error") depending on the server's error returned ...

But the preConfirm function only works with promises functions, meaning using .then().catch()...

The only workaround I found is an ugly one :

```<code> Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      socket.emit('isID', id, this.props.name, (r) => {

        // Here I have the answer from the server so I can test the returned
        // value and eventualy set an error which I couldn't if I didn't put the "TRICK" part ( see below )
        if(r === 'ok'){
          Swal.fire({
            title: `ok !!`,
            type: 'success'
          });
        } else {
           Swal.showValidationMessage("Server error !");
        }
      });

      Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'

    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
});
</code>```

Let me explain : using Swal.showValidationMessage("") keeps the sweet alert open in order to later fulfill it with the server error ...

The problem is if there's a low connection the empty message can be seen even if the server's answer gonna be correct

Any advices on how to improve this ?

( In the code snippet below I use a promise with a timeout to mimics a long server answer )

Swal.fire({
      title: 'ID ?',
      input: 'text',
      showCancelButton: true,
      confirmButtonText:'Go',
      cancelButtonText: "Cancel",
      showLoaderOnConfirm: true,
      preConfirm: (id) => {
        if(id.trim().length === 3){
          let r = new Promise(function(resolve, reject) {
            setTimeout(function() {
              Swal.fire({
                title: `Server answered OK no need to error message !`,
                type: 'success'
              });
            }, 2000);
          });

          Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'

        } else {
          Swal.showValidationMessage(" it's 3 letters for an id mate ;)");
        }
      },
    });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.0.7/dist/sweetalert2.all.min.js"></script></code>```

EDIT Bump

答:
With @Mike85's help, here is what works :

const gonnaWork = false;
const promiseWrapper = (id) => {
   return new Promise((resolve, reject) => {
       //this.socket.emit(id, data, data2, (response) => {
       //   resolve(response);
       //});
       setTimeout(function() {
          resolve(gonnaWork ? 'ok' : 'ko');
       }, 2000);
   });
}

Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      return promiseWrapper(id)
      .then((r) => {
        if(r === 'ok'){
          return r;
        } else {
           Swal.showValidationMessage("Server error !");
        }
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
        title: `ok !!`,
        type: 'success'
      });
  }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.0.7/dist/sweetalert2.all.min.js"></script></code>```

Body:
I'm using SWAL2 preConfirm() function in a sweet alert to test if an ID is ok server side... using socket.emit() with acknowledgements

I would like to be able to use Swal.showValidationMessage("Some error") depending on the server's error returned ...

But the preConfirm function only works with promises functions, meaning using .then().catch()...

The only workaround I found is an ugly one :

 Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      socket.emit('isID', id, this.props.name, (r) => {

        // Here I have the answer from the server so I can test the returned
        // value and eventualy set an error which I couldn't if I didn't put the "TRICK" part ( see below )
        if(r === 'ok'){
          Swal.fire({
            title: `ok !!`,
            type: 'success'
          });
        } else {
           Swal.showValidationMessage("Server error !");
        }
      });

      Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'

    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
});

Let me explain : using Swal.showValidationMessage("") keeps the sweet alert open in order to later fulfill it with the server error ...

The problem is if there's a low connection the empty message can be seen even if the server's answer gonna be correct

Any advices on how to improve this ?

( In the code snippet below I use a promise with a timeout to mimics a long server answer )

Swal.fire({
      title: 'ID ?',
      input: 'text',
      showCancelButton: true,
      confirmButtonText:'Go',
      cancelButtonText: "Cancel",
      showLoaderOnConfirm: true,
      preConfirm: (id) => {
        if(id.trim().length === 3){
          let r = new Promise(function(resolve, reject) {
            setTimeout(function() {
              Swal.fire({
                title: `Server answered OK no need to error message !`,
                type: 'success'
              });
            }, 2000);
          });

          Swal.showValidationMessage(""); // --> HERE IS THE 'TRICK'

        } else {
          Swal.showValidationMessage(" it's 3 letters for an id mate ;)");
        }
      },
    });

EDIT Bump

Body:
With @Mike85's help, here is what works :

const gonnaWork = false;
const promiseWrapper = (id) => {
   return new Promise((resolve, reject) => {
       //this.socket.emit(id, data, data2, (response) => {
       //   resolve(response);
       //});
       setTimeout(function() {
          resolve(gonnaWork ? 'ok' : 'ko');
       }, 2000);
   });
}

Swal.fire({
  title: 'ID ?',
  input: 'text',
  showCancelButton: true,
  confirmButtonText:'Go',
  cancelButtonText: "Cancel",
  showLoaderOnConfirm: true,
  preConfirm: (id) => {
    if(id.trim().length === 3){
      return promiseWrapper(id)
      .then((r) => {
        if(r === 'ok'){
          return r;
        } else {
           Swal.showValidationMessage("Server error !");
        }
      })
      .catch(error => {
        Swal.showValidationMessage(
          `Request failed: ${error}`
        )
      })
    } else {
      Swal.showValidationMessage(" it's 3 letters for an id mate !");
    }
  },
  allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
  if (result.value) {
    Swal.fire({
        title: `ok !!`,
        type: 'success'
      });
  }
})

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@8.0.7/dist/sweetalert2.all.min.js"></script>


问:
Terraform 0.9.6 remote config outdated
I have been trying to update some of the terraform scripts from version 0.6.13 to 0.9.6. In my scripts I had before

```<code>     terraform remote config -backend=s3 \
      -backend-config="bucket=my_bucker" \
      -backend-config="access_key=my_access_key" \
      -backend-config="secret_key=my_secret" \
      -backend-config="region=my_region" \
      -backend-config="key=my_state_key"
</code>```

and then

```<code>     terraform/terraform remote pull
</code>```

Which was pulling the remote state from aws. Upon running terraform apply it will give me the exact resources that needed to be updated/ created based on the remote tfstate that is stored in an s3 bucket.

Now the issue I'm facing is that remote pull and remote config commands are outdated and don't work anymore.

I tried to follow the instructions on https://www.terraform.io/docs/backends/types/remote.html
    however it was not much helpful.

From what I understand I would have to do an init first with a partial configuration which presumably would automatically pull the remote state as following:

```<code>`terraform init -var-file="terraform.tfvars"\
 -backend=true \
 -backend-config="bucket=my_bucker" \
  -backend-config="access_key=my_access_key" \
  -backend-config="secret_key=my_secret" \
  -backend-config="region=my_region" \
  -backend-config="key=my_state_key"`
</code>```

However it doesn't really pull the remote state as it was doing before.

Would anyone be able to guide me into the right direction?

答:
Apparently I had to add a minimal backend configuration such as

```<code>terraform {
  backend "s3" {
  }
}
</code>```

in my main.tf file for it to work

Title: Terraform 0.9.6 remote config outdated

Body:
I have been trying to update some of the terraform scripts from version 0.6.13 to 0.9.6. In my scripts I had before

     terraform remote config -backend=s3 \
      -backend-config="bucket=my_bucker" \
      -backend-config="access_key=my_access_key" \
      -backend-config="secret_key=my_secret" \
      -backend-config="region=my_region" \
      -backend-config="key=my_state_key"

and then

     terraform/terraform remote pull

Which was pulling the remote state from aws. Upon running terraform apply it will give me the exact resources that needed to be updated/ created based on the remote tfstate that is stored in an s3 bucket.

Now the issue I'm facing is that remote pull and remote config commands are outdated and don't work anymore.

I tried to follow the instructions on https://www.terraform.io/docs/backends/types/remote.html
    however it was not much helpful.

From what I understand I would have to do an init first with a partial configuration which presumably would automatically pull the remote state as following:

`terraform init -var-file="terraform.tfvars"\
 -backend=true \
 -backend-config="bucket=my_bucker" \
  -backend-config="access_key=my_access_key" \
  -backend-config="secret_key=my_secret" \
  -backend-config="region=my_region" \
  -backend-config="key=my_state_key"`

However it doesn't really pull the remote state as it was doing before.

Would anyone be able to guide me into the right direction?

Body:
Apparently I had to add a minimal backend configuration such as

terraform {
  backend "s3" {
  }
}

in my main.tf file for it to work


问:
Sum of all odd fibonacci numbers upto n
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));```

Expected output 10, but getting 99

答:
```<code>function sumFibs(num) {
  var fib=[1,1];
  for(var i=2; i<num; i++){
  var next=fib[i-1]+fib[i-2];
  var fibi=fib.push(next);
}
return fib.filter(function(a){
  return(a%2!=0 && a<=num);
})
.reduce(function(a,z){
 return a+z;
})
}
console.log(sumFibs(10));
</code>```

Title: Sum of all odd fibonacci numbers upto n

Body:
I am stuck in summing up to number 10. Can't get it right.
What i am getting is the total sum from 10 digits (after filtering odd only 7). Where should i make <= num ?

function sumFibs(num) {
  var fib = [1, 1];
  for (var i = 2; i < num; i++) {
    var next = fib[i - 1] + fib[i - 2];
    var fibi = fib.push(next);
  }

  return fib.filter(function(a) {
      return (a % 2 != 0);
    })
    .reduce(function(a, z) {
      return a + z;
    })
}
console.log(sumFibs(10));

Expected output 10, but getting 99


问:
Calculating the length of a Japanese multibyte string with half-width kana in PHP
So I have a UTF-8 encoded string which can contain full-width kanji, full-width kana, half-width kana, romaji, numbers or kawaii japanese symbols like ★ or  ♥.

If I want the length I use mb_strlen() and it counts each of these as 1 in length. Which is fine for most purposes.

But, I've been asked (by a Japanese client) to only count half-width kana as 0.5 (for the purpose of maxlength of a text field) because apparently thats how Japanese websites do it. I do this using mb_strwidth() which counts full-width as 2, and half-width as 1, then i just divide by 2.

However this method also counts romaji characters as 1 so something like Chocｱｲｽ would count as 7 .. then i'd divide by 2 to account for kanji and I'd get 3.5. but I actually want 5.5 (4 for the Romaji + 1.5 for the 3 half-width kana).

// EDIT:
some more info: any character (even non-kana) which has both a full and a half should be 1 for the full-width and 0.5 for the half-width. for example, characters like ￥、３＠（ should all be 1, but characters like ¥,3@( should all be 0.5

// EXTRA EDIT: symbols like ☆ and ♥ should be 1, but the mb_strwidth/2 method return them as 0.5

Is there a standard way that Japanese systems count string length?
Or does everyone just loop thru their strings and count the characters which don't match the standard width rules?

答:
One way is to convert the half-width katakana to full-width and subtract the difference in width from the original length:

```<code>$raw = 'Chocｱｲｽ';
$full = mb_convert_kana($raw, 'K');
$len = mb_strlen($raw) - (mb_strwidth($full) - mb_strwidth($raw))/2;
assert($len === 5.5);
</code>```

However, are you sure that you should be considering basic latin characters as full-width? There do exist full-width varieties of basic latin characters too---that is, should Choc be considered the same as Ｃｈｏｃ?

Usually, characters like "A" and "ｱ" would have a width of 1, but "Ａ" and "ア" would have a width of 2 (which is what mb_strwidth does). I'd be cautious about having to hack around that.

Given your edit, mb_strwidth (or mb_strwidth/2) does exactly what you want.

Body:
One way is to convert the half-width katakana to full-width and subtract the difference in width from the original length:

$raw = 'Chocｱｲｽ';
$full = mb_convert_kana($raw, 'K');
$len = mb_strlen($raw) - (mb_strwidth($full) - mb_strwidth($raw))/2;
assert($len === 5.5);

However, are you sure that you should be considering basic latin characters as full-width? There do exist full-width varieties of basic latin characters too---that is, should Choc be considered the same as Ｃｈｏｃ?

Usually, characters like "A" and "ｱ" would have a width of 1, but "Ａ" and "ア" would have a width of 2 (which is what mb_strwidth does). I'd be cautious about having to hack around that.

Given your edit, mb_strwidth (or mb_strwidth/2) does exactly what you want.


问:
Encrypt root volume of EC2 while creating stack using cloud formation
Working on cloud formation script which will create simple ec2 instance. here i want to encrypt a root volume at the time of launch. its possible to create a separate EBS, encrypt it and attach it as boot volume. but i couldn't find a way to encrypt it while launching. any way to do this?

Thanks In Advance

答:
It looks like AWS has recently released a feature to launch an instance with encrypted volume based on non-encrypted AMI.
Launch encrypted EBS backed EC2 instances from unencrypted AMIs in a single step

From the CloudFormation perspective, you need to overwrite AMI block device configuration. So for example, you can write like this:

```<code>  BlockDeviceMappings:
  - DeviceName: "/dev/xvda"
    Ebs:
      VolumeSize: '8'
      Encrypted: 'true'
</code>```

This will start an instance with encrypted root EBS from non-encrypted AMI with a default KMS key

Body:
It looks like AWS has recently released a feature to launch an instance with encrypted volume based on non-encrypted AMI.
Launch encrypted EBS backed EC2 instances from unencrypted AMIs in a single step

From the CloudFormation perspective, you need to overwrite AMI block device configuration. So for example, you can write like this:

  BlockDeviceMappings:
  - DeviceName: "/dev/xvda"
    Ebs:
      VolumeSize: '8'
      Encrypted: 'true'

This will start an instance with encrypted root EBS from non-encrypted AMI with a default KMS key


问:
How can I make a switch in navigation drawer have functionality?
I'm trying to make a navigation drawer switch which switches between a normal theme and a dark theme of an app, however I can't get the switch to work.

I already have a working switch on mainactivity but I can't get it to work in the navigation drawer.

This is the code to switch between light/dark mode.

```<code>    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if(AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_YES) {
            setTheme(R.style.HROTheme);
        }
        else setTheme(R.style.AppTheme);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        modeswitch=(Switch)findViewById(R.id.switch2);
        if (AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_YES) {
            modeswitch.setChecked(true);
        }
        modeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    recreate();
                }
                else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    recreate();
                }
            }
        });
</code>```

答:
You can try to add an item in values/attrs like this: <attr name="bottomback" format="color" />

Then define "bottomback" in styles for your both dark and light styles like this:

<item name="bottomback">#000</item>

That must be different in both styles.
 now you can set the backgroundTint of drawer as this: android:backgroundTint="?attr/bottomback"

Body:
I'm trying to make a navigation drawer switch which switches between a normal theme and a dark theme of an app, however I can't get the switch to work.

I already have a working switch on mainactivity but I can't get it to work in the navigation drawer.

This is the code to switch between light/dark mode.

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        if(AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_YES) {
            setTheme(R.style.HROTheme);
        }
        else setTheme(R.style.AppTheme);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        modeswitch=(Switch)findViewById(R.id.switch2);
        if (AppCompatDelegate.getDefaultNightMode()==AppCompatDelegate.MODE_NIGHT_YES) {
            modeswitch.setChecked(true);
        }
        modeswitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
                    recreate();
                }
                else {
                    AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
                    recreate();
                }
            }
        });


问:
Android EditText: How to disable cursor move on touch?
I have EditText which displays something like ###-###. I want the user to be able to change this text only from the 1st position onward. That is user should not be able to touch a # in the middle and change it. How can I do this? Thanks a lot.

Sorry, I was not precise in my question. I want to disable even tapping in the middle of the text.

答:
this solution also prevents a touch and drag, apart from click</p>

```<code>       //don't allow user to move cursor
       editText.setOnTouchListener { view, motionEvent ->
            if (motionEvent.action == MotionEvent.ACTION_UP) {
                editText.setSelection(editText.text.length)
            }
            return@setOnTouchListener true
        }
</code>```

Body:
this solution also prevents a touch and drag, apart from click

       //don't allow user to move cursor
       editText.setOnTouchListener { view, motionEvent ->
            if (motionEvent.action == MotionEvent.ACTION_UP) {
                editText.setSelection(editText.text.length)
            }
            return@setOnTouchListener true
        }


问:
Weird scrolling effect caused by overflow: hidden on body, html
If I disable overflow: hidden; on my body, html adds some sort of crop at the bottom of the screen. If I have it enabled I also can't get the scroll-to-top button to work.

Is there any way I can fix this or maybe have the grid scroll affect the button reveal? Also the arrow key scrolling doesn't seem to work as well on the grid div. Hope you guys can help!

body, html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}
```

<p>Full code:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("backTop").style.opacity = "1";
  } else {
    document.getElementById("backTop").style.opacity = "0";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}</code>```

body,
html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

.container {
  background-color: white;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.left-div {
  background-color: yellow;
  height: 100vh;
  width: 100px;
}

.mid-div {
  background-color: pink;
  height: 100vh;
  width: 100%;
  overflow: scroll;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  grid-gap: 10px;
  grid-auto-rows: minmax(90px, auto);
  grid-auto-flow: dense;
  padding: 10px;
}

  .grid-item {
    position: relative;
    grid-row-end: span 1;
    grid-column-end: span 2;
    background-color: red;
  }

    .span-wide {
        grid-column-end: span 2;
        grid-row-end: span 2;
    }

    .span-long {
        grid-column-end: span 1;
        grid-row-end: span 4;
    }

.right-div {
  background-color: blue;
  height: 100vh;
  width: 100px;
}

  #backTop {
    opacity: 0;
    transition: 1s opacity;
    width: 40px;
    height: 40px;
    border-radius: 2em;
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: green;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="left-div"></div>

  <div class="mid-div">
    <div class="grid-item"></div>
    <div class="grid-item span-wide"></div>
    <div class="grid-item"></div>
    <div class="grid-item span-long"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
    <div class="grid-item span-long"></div>
    <div class="grid-item"></div>
    <div class="grid-item"></div>
  </div>

  <div class="right-div">
    <button onclick="topFunction()" id="backTop" title="Back to Top">Top</button>
  </div>
</div></code>```

答:
Add id to your mid-div

```<code>  <div id="midDiv" class="mid-div">
<div class="grid-item"></div>
<div class="grid-item span-wide"></div>
<div class="grid-item"></div>
<div class="grid-item span-long"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item span-long"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
</code>```

And then modify scrollFunction()

```<code>    document.getElementById("midDiv").onscroll = function() {scrollFunction()};

    function scrollFunction() {
      if (document.getElementById("midDiv").scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("backTop").style.opacity = "1";
      } else {
        document.getElementById("backTop").style.opacity = "0";
      }

}
</code>```

Body:
If I disable overflow: hidden; on my body, html adds some sort of crop at the bottom of the screen. If I have it enabled I also can't get the scroll-to-top button to work.

Is there any way I can fix this or maybe have the grid scroll affect the button reveal? Also the arrow key scrolling doesn't seem to work as well on the grid div. Hope you guys can help!

body, html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

Full code:

window.onscroll = function() {scrollFunction()};

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("backTop").style.opacity = "1";
  } else {
    document.getElementById("backTop").style.opacity = "0";
  }
}

function topFunction() {
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}

body,
html {
  overflow: hidden; /*scrolling problem*/
  height: 100%;
}

.container {
  background-color: white;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: space-between;
}

.left-div {
  background-color: yellow;
  height: 100vh;
  width: 100px;
}

.mid-div {
  background-color: pink;
  height: 100vh;
  width: 100%;
  overflow: scroll;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
  grid-gap: 10px;
  grid-auto-rows: minmax(90px, auto);
  grid-auto-flow: dense;
  padding: 10px;
}

  .grid-item {
    position: relative;
    grid-row-end: span 1;
    grid-column-end: span 2;
    background-color: red;
  }

    .span-wide {
        grid-column-end: span 2;
        grid-row-end: span 2;
    }

    .span-long {
        grid-column-end: span 1;
        grid-row-end: span 4;
    }

.right-div {
  background-color: blue;
  height: 100vh;
  width: 100px;
}

  #backTop {
    opacity: 0;
    transition: 1s opacity;
    width: 40px;
    height: 40px;
    border-radius: 2em;
    position: absolute;
    bottom: 20px;
    right: 20px;
    background-color: green;
  }

    <button onclick="topFunction()" id="backTop" title="Back to Top">Top</button>

Body:
Add id to your mid-div

  <div id="midDiv" class="mid-div">
<div class="grid-item"></div>
<div class="grid-item span-wide"></div>
<div class="grid-item"></div>
<div class="grid-item span-long"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>
<div class="grid-item span-long"></div>
<div class="grid-item"></div>
<div class="grid-item"></div>

And then modify scrollFunction()

    document.getElementById("midDiv").onscroll = function() {scrollFunction()};

    function scrollFunction() {
      if (document.getElementById("midDiv").scrollTop > 20 || document.documentElement.scrollTop > 20) {
        document.getElementById("backTop").style.opacity = "1";
      } else {
        document.getElementById("backTop").style.opacity = "0";
      }

}


问:
Problem with rotating object
I've been having this problem for a while, and it would be great if someone can help. :)

http://img31.imageshack.us/i/problemsc.jpg/
(illustration of the problem)

So, I have this object with registration point at middle bottom. I want this object to follow the mouse, but to remain on the center of the screen while rotating. Here is what I used :

```<code>dx = mouseX - this.x ;
dy = mouseY - this.y ;

radians = Math.atan2(dy, dx);
angle= radians * 180/Math.PI;

this.rotation = angle + 90;
this.y = mouseY + this.height;
</code>```

The problem with this code is that when you move the mouse away from the center,e.g. the angle is not 90 degrees, there is an offset between the mouse cursor and the object. By tracing, I found out that it follows the y position of the mouse as it should, but by rotating the object, it's height and width is changing, so the object is not pointing right on the cursor.

Is there a way to compensate for this offset? Or maybe another approach?
Thanks in advance.

UPDATE: Ok, it seems that I didn't explain the problem right, sorry, English is not my native language. I need the object to follow the cursor, but the front end of the object to be on the same position as the cursor and the back end of the object to be in the middle of the screen, just on the center x axis. So when you move the mouse, front end of the object will always pointing at and will be on the mouse position. Back end should stay on same position, but rotated.

答:
The following works for me (it's pretty much identical to yours)

```<code>import flash.events.MouseEvent;

const RAD_TO_DEG:Number = 180/Math.PI;
const OFFSET:Number = 90;

var angle:Number;
var radians:Number;

stage.addEventListener(MouseEvent.MOUSE_MOVE, moveIt, false, 0, true);

function moveIt(e:MouseEvent):void {
    radians = Math.atan2(mouseY - mc.y, mouseX - mc.x);
    angle = radians * RAD_TO_DEG;

    mc.rotation = angle + OFFSET;
}
</code>```

Just ensure you have the registration point set correctly (see image)

I have also uploaded a SWF

http://megaswf.com/serve/1054550

Title: Problem with rotating object

Body:
I've been having this problem for a while, and it would be great if someone can help. :)

http://img31.imageshack.us/i/problemsc.jpg/
(illustration of the problem)

So, I have this object with registration point at middle bottom. I want this object to follow the mouse, but to remain on the center of the screen while rotating. Here is what I used :

dx = mouseX - this.x ;
dy = mouseY - this.y ;

radians = Math.atan2(dy, dx);
angle= radians * 180/Math.PI;

this.rotation = angle + 90;
this.y = mouseY + this.height;

The problem with this code is that when you move the mouse away from the center,e.g. the angle is not 90 degrees, there is an offset between the mouse cursor and the object. By tracing, I found out that it follows the y position of the mouse as it should, but by rotating the object, it's height and width is changing, so the object is not pointing right on the cursor.

Is there a way to compensate for this offset? Or maybe another approach?
Thanks in advance.

UPDATE: Ok, it seems that I didn't explain the problem right, sorry, English is not my native language. I need the object to follow the cursor, but the front end of the object to be on the same position as the cursor and the back end of the object to be in the middle of the screen, just on the center x axis. So when you move the mouse, front end of the object will always pointing at and will be on the mouse position. Back end should stay on same position, but rotated.

Body:
The following works for me (it's pretty much identical to yours)

import flash.events.MouseEvent;

const RAD_TO_DEG:Number = 180/Math.PI;
const OFFSET:Number = 90;

var angle:Number;
var radians:Number;

stage.addEventListener(MouseEvent.MOUSE_MOVE, moveIt, false, 0, true);

function moveIt(e:MouseEvent):void {
    radians = Math.atan2(mouseY - mc.y, mouseX - mc.x);
    angle = radians * RAD_TO_DEG;

    mc.rotation = angle + OFFSET;
}

Just ensure you have the registration point set correctly (see image)

I have also uploaded a SWF

http://megaswf.com/serve/1054550


问:
Pandas still converts ints to float when I make a dictionary
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

```<code>test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)
</code>```

Expected :

```<code>[{0: 1}, {1: 1.3}]
</code>```

Actual :

```<code>[{0: 1.0}, {1: 1.3}]
</code>```

答:
Try using the modulo operator % and an if-else statement within your dict comprehension:

```<code>result = [{i: int(x)} if x % 1 == 0 else {i: x} for i, x in test_series.iteritems()]
</code>```

[out]

```<code>[{0: 1}, {1: 1.3}]
</code>```

Body:
Pandas still makes ints into floats when I try to make a mixed-type series into a dictionary.

The suggested workarounds don't work for me. I've tried casting to object and using iteritems, and both together. I'm using pandas version 0.24.2

test_series = pd.Series([1,1.3])
result = [{index:value} for index,value in test_series.astype(object).iteritems()]
print (results)

Expected :

[{0: 1}, {1: 1.3}]

Actual :

[{0: 1.0}, {1: 1.3}]

Body:
Try using the modulo operator % and an if-else statement within your dict comprehension:

result = [{i: int(x)} if x % 1 == 0 else {i: x} for i, x in test_series.iteritems()]

[out]

[{0: 1}, {1: 1.3}]


问:
php artisan migrate throwing [PDO Exception] Could not find driver - Using Laravel
I have a bad experience while installing laravel. However, I was able to do so and move to the next level. I used generators and created my migrations.
But when I type the last command

```<code>php artisan migrate
</code>```

It's throwing a PDOException - could not find driver.

```<code>       'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'unix_socket'   => '/Applications/MAMP/tmp/mysql/mysql.sock',
            'database'  => 'database',
            'username'  => 'root',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),
</code>```

That's my configuration in config/database.php.

I tried searching on stackoverflow and laravel forums and people suggest that it's PDO problem and not artisan's or php's - I followed those suggestions like adding

```<code>extension=pgsql.so
extension=pdo_pgsql.so
</code>```

in php.ini

No positive result. It always says [PDOException]could not find driver.

Can someone please help resolving this.

Environment that I am using: Mac, laravel 4, MAMP PRO with php 5.4.4

答:
first check your php version  like this :

```<code>php -v
</code>```

after you get  version number for example i get 7.1 then install like that

```<code>sudo apt-get install  php7.1-sqlite     //for laravel testing with sqlite
sudo apt-get install  php-mysql         //for default mysql
sudo apt-get install  php7.1-mysql      //for version based mysql
sudo apt-get install  php7.1-common     //for other necessary package for php
</code>```

and need to restart apache2

```<code>sudo service apache2 restart
</code>```

Body:
I have a bad experience while installing laravel. However, I was able to do so and move to the next level. I used generators and created my migrations.
But when I type the last command

php artisan migrate

It's throwing a PDOException - could not find driver.

       'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'unix_socket'   => '/Applications/MAMP/tmp/mysql/mysql.sock',
            'database'  => 'database',
            'username'  => 'root',
            'password'  => '',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ),

That's my configuration in config/database.php.

I tried searching on stackoverflow and laravel forums and people suggest that it's PDO problem and not artisan's or php's - I followed those suggestions like adding

extension=pgsql.so
extension=pdo_pgsql.so

in php.ini

No positive result. It always says [PDOException]could not find driver.

Can someone please help resolving this.

Environment that I am using: Mac, laravel 4, MAMP PRO with php 5.4.4

Body:
first check your php version  like this :

php -v

after you get  version number for example i get 7.1 then install like that

sudo apt-get install  php7.1-sqlite     //for laravel testing with sqlite
sudo apt-get install  php-mysql         //for default mysql
sudo apt-get install  php7.1-mysql      //for version based mysql
sudo apt-get install  php7.1-common     //for other necessary package for php

and need to restart apache2

sudo service apache2 restart