问:
How to renew an authorization token in background with Auth0 in Nuxt
For the platform I'm currently working on, my employer decided to outsource authentication to Auth0.

We managed to get the login and logout flows to work, by opening a hosted page on Auth0 and redirecting to our platform after succesful login / logout.

Upon a successful login with an email & password, Auth0 returns a response in the following format :

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlEwWTFRemREUlRW...",
  "expires_in": "86400",
  "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlEwWTFRemREUlRWRk9V...",
  "scope": "openid email",
  "state": "my-custom-state",
  "token_type": "Bearer"
}
```
<p>According to the official Auth0 documentation, Auth0 allows two method for renewing an existing authorization token :</p>
<ul>
<li>silent authentication requests, for tokens that have not expired yet</li>
<li>a silent token request in a hidden iframe, for tokens that have expired</li>
</ul>
<hr />
<h1>Silent authentication requests</h1>
<p>The documentation tells me I should to a get request to the following URL :</p>
```https://████████████████████/authorize
    ?response_type=id_token token&
    client_id=...&
    redirect_uri=...&
    state=...&
    scope=openid...&
    nonce=...&
    audience=...&
    response_mode=...&
    prompt=none
```
<p>When I open this URL in any tab of my browser, I am indeed correctly redirected to the <code>redirect_uri</code>, if this <code>redirect_uri</code> is listed in the Auth0 config. And a new token is added to the <code>url</code> after an <code>#</code>.</p>
<p>I am, however, unable to get this to work with XHR, either from the backend (Node.js / Nuxt) or the frontend (Vue / Nuxt). When I try doing this from the frontend, my browser complains that this resource didn't set CORS headers. When I try doing this from the backend, I can't find a way to pass my credentials to the URL.</p>
<hr />
<h1>Renewing expired tokens</h1>
<p>I can't find any code examples of demos for how to renew expired tokens without the use of the auth0.js library, which I'd rather not use if possible.</p>
<p>And when I try using their demo for the auth0.js library after installing it locally, I can't even get a simple login to work after filling in all these fields :</p>
<p><img src="https://i.stack.imgur.com/XonhW.png" alt="enter image description here" /></p>
<p>This is the error I'm getting :</p>
<pre class="lang-json prettyprint-override"><code>{
  "original": {
    "error": "request_error",
    "error_description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}"
  },
  "code": "request_error",
  "description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}",
  "error": "request_error",
  "error_description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}"
}
</code>```

Can anyone help me figure out how to properly implement a refresh in blackground, either of expired of non-expired Auth tokens?

UPDATE

I managed to get one step further, by...

porting the SilentAuthenticationHandler from Auth0.js to my project

Commenting out one line in the SilentAuthenticationHandler to prevent the browser from freaking out if the /authorize endpoint is on a different domain

Creating an instance of SilentAuthenticationHandler with an url that has response_mode web_message and a value for postMessageOrigin that corresponds with my audience

Calling the login method on SilentAuthenticationHandler, with usePostMessageset totrue, to open the /authorize` endpoint in a hidden iframe

Parsing the hash in the URL of the callback page passed as a redirect_uri and then using Window.parent.postMessage(parsedParams, '*') to send it back to the main window

After taking all of these 5 steps, I finally get my new access token & id token.

Unfortunately, I can't figure out how to update my Nuxt with these new credentials. I looked for inspiration in the @nuxtjs/auth package, but the best I could come up with, is something like this :

this.$auth.setUserToken(token);
```

I tried combining this with eg. fetchUser & a setUser, but no matter what I try, it keep ***ing up my session and trigger a 400 error upon reload.

What am I doing wrong?

答:
if you want to use authentication in nuxt app on my experience the best thing that you can use is nuxt auth module

it handels a lots of codings and it's sooo easy to use and understand also published by official nuxt site

if you use that you can logout with:

```<code>this.$auth.logout(/* .... */)
</code>```

Body:
For the platform I'm currently working on, my employer decided to outsource authentication to Auth0.

We managed to get the login and logout flows to work, by opening a hosted page on Auth0 and redirecting to our platform after succesful login / logout.

Upon a successful login with an email & password, Auth0 returns a response in the following format :

{
  "access_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlEwWTFRemREUlRW...",
  "expires_in": "86400",
  "id_token": "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IlEwWTFRemREUlRWRk9V...",
  "scope": "openid email",
  "state": "my-custom-state",
  "token_type": "Bearer"
}

According to the official Auth0 documentation, Auth0 allows two method for renewing an existing authorization token :

silent authentication requests, for tokens that have not expired yet

a silent token request in a hidden iframe, for tokens that have expired

Silent authentication requests

The documentation tells me I should to a get request to the following URL :

https://████████████████████/authorize
    ?response_type=id_token token&
    client_id=...&
    redirect_uri=...&
    state=...&
    scope=openid...&
    nonce=...&
    audience=...&
    response_mode=...&
    prompt=none

When I open this URL in any tab of my browser, I am indeed correctly redirected to the redirect_uri, if this redirect_uri is listed in the Auth0 config. And a new token is added to the url after an #.

I am, however, unable to get this to work with XHR, either from the backend (Node.js / Nuxt) or the frontend (Vue / Nuxt). When I try doing this from the frontend, my browser complains that this resource didn't set CORS headers. When I try doing this from the backend, I can't find a way to pass my credentials to the URL.

Renewing expired tokens

I can't find any code examples of demos for how to renew expired tokens without the use of the auth0.js library, which I'd rather not use if possible.

And when I try using their demo for the auth0.js library after installing it locally, I can't even get a simple login to work after filling in all these fields :

This is the error I'm getting :

{
  "original": {
    "error": "request_error",
    "error_description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}"
  },
  "code": "request_error",
  "description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}",
  "error": "request_error",
  "error_description": "{\"crossDomain\":true,\"method\":\"POST\",\"url\":\"https://████████████████████/co/authenticate\"}"
}

Can anyone help me figure out how to properly implement a refresh in blackground, either of expired of non-expired Auth tokens?

UPDATE

I managed to get one step further, by...

porting the SilentAuthenticationHandler from Auth0.js to my project

Commenting out one line in the SilentAuthenticationHandler to prevent the browser from freaking out if the /authorize endpoint is on a different domain

Creating an instance of SilentAuthenticationHandler with an url that has response_mode web_message and a value for postMessageOrigin that corresponds with my audience

Calling the login method on SilentAuthenticationHandler, with usePostMessageset totrue, to open the /authorize` endpoint in a hidden iframe

Parsing the hash in the URL of the callback page passed as a redirect_uri and then using Window.parent.postMessage(parsedParams, '*') to send it back to the main window

After taking all of these 5 steps, I finally get my new access token & id token.

Unfortunately, I can't figure out how to update my Nuxt with these new credentials. I looked for inspiration in the @nuxtjs/auth package, but the best I could come up with, is something like this :

this.$auth.setUserToken(token);

I tried combining this with eg. fetchUser & a setUser, but no matter what I try, it keep ***ing up my session and trigger a 400 error upon reload.

What am I doing wrong?

Body:
if you want to use authentication in nuxt app on my experience the best thing that you can use is nuxt auth module

it handels a lots of codings and it's sooo easy to use and understand also published by official nuxt site

if you use that you can logout with:

this.$auth.logout(/* .... */)


来源: stackexchange

问:
Error after accidentally deleting Podfile
I made a huge mistake by deleting one podFile I had in my Xcode iOS application. I thought that the error was coming from that file when Instead it was another.
Long story short, I deleted the LevelDB pod and now the application is giving me this error after trying to launch it:

```<code>duplicate symbol '_pb_field_iter_find' in:
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common 2.o
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common.o.
ld: 3 duplicate symbols for architecture x86_64
</code>```

I don't know how to move from here; Do I have to reinstall the podfile? Can I solve this problem by doing something else? thank you to whoever can help me.

答: Clear derived data. Try to run pod install then and build the app.</p>

ContentLicense: CC BY-SA 4.0

Body:
I made a huge mistake by deleting one podFile I had in my Xcode iOS application. I thought that the error was coming from that file when Instead it was another.
Long story short, I deleted the LevelDB pod and now the application is giving me this error after trying to launch it:

duplicate symbol '_pb_field_iter_find' in:
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common 2.o
/Users/andreagualandris/Library/Developer/Xcode/DerivedData/InstagramClone-agfsqctheamzqfcdwrbfiaaauqhd/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/nanopb.build/Objects-normal/x86_64/pb_common.o.
ld: 3 duplicate symbols for architecture x86_64

I don't know how to move from here; Do I have to reinstall the podfile? Can I solve this problem by doing something else? thank you to whoever can help me.


问:
Angular2: Custom material theme in each lazy loaded submodule

Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

```<code>@import './theme.scss';

</code>```

VS.

angular.json

```<code>...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

</code>```

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss

答: Try to just add ng generate module Shared which will create SharedModule at the root right next to AppModule with nothing in it.   For some reason when it recompiles it may reconnect some of your sub modules to a theme like Angular Material Themes magically.  Not sure what going on under the hood.

Body:
Problem with loading custom Angular Material 2 themes in separate submodules of Angular 7 app

I have angular wrapper module (app module) and many independent lazy-loaded sub-modules. Each sub-module behaves like a totaly separate app and needs its own angular material theme.

I've created custom theme for each sub-module and tried to reference the custom theme in each of components' .scss file with relative path.

Some of the Material components apply the custom theme (button) and some (mat-form-field) just take the theme specified in styles.scss.

One way I can avoid this is including each custom theme in 'styles' array of angular.json, but I'm afraid that, by doing this, each independent sub-module (app) will have to load every themes' compiled .css and it'll be overhead.

Is there any known issue with this or any better solution?

home-app.component.scss:

@import './theme.scss';

VS.

angular.json

...
"styles": [
    "src/styles.scss",
    "src/app/orgs/home/theme.scss" // <-- FIXED BY ADDING THIS
],
...

Expected:
Theme declared in the home-app.component.scss will be loaded and applied to every material component used in home-app.component.html

Actual:
If I don't add "src/app/orgs/home/theme.scss" to angular.json, the custom theme declared in styles.scss will be applied to some material components used in home-app.component.html, and some material components will use the imported theme specified in home-app.component.scss


问:
SELECT $b shows no intellisense as error, but throws error. what's the reason behind this scenario?
i tried to explore SQL.while doing so, got below error-

```<code>SELECT $b
</code>```

Error- Invalid pseudocolumn "$b".

What is this error? Why SSMS's Intellisense cannot handle it as error if it's error. If I write query as 'Select #', then Intellisense shows red mark under # symbol. if i do the same for $b, it is looking like no error,but after execution, throws error.

答: IntelliSense is a client side thing, columns are a server side thing. IntelliSense won't necessarily know that a particular pseudocolumn doesn't exist (like $IDENTITY does exist, but only for tables that have an IDENTITY type column) but when you run the query the server will tell you it didn't exist. IntelliSense isn't a device that constantly queries the server to make sure what you're writing isn't garbage - you can see this if you use another SSMS window to add a column to a table then reference it from the first window - i tellisene doesn't know its there unless you refresh it (Ctrl+Alt+R I think) so it will draw a red line under the new column even though the query will run fine when you submit it to the server </p>

Body:
i tried to explore SQL.while doing so, got below error-

SELECT $b

Error- Invalid pseudocolumn "$b".

What is this error? Why SSMS's Intellisense cannot handle it as error if it's error. If I write query as 'Select #', then Intellisense shows red mark under # symbol. if i do the same for $b, it is looking like no error,but after execution, throws error.


问:
When i run command npm install it is give error npm ERR cb() never called
this type of error

npm ERR! CB() never called!

I have already cleared clear npm cache
I have already run this command

```<code>rm -rf node_modules
rm package.lock.json yarn.lock
npm cache clear --force
npm install
</code>```

npm, WARN deprecated popper.js@1.16.1: You can find the new Popper v2
  at @popperjs/core, this package is dedicated to the legacy v1 npm ERR!
  CB() never called!

Valid answer give for this error
and this command I run on my ubuntu server machine
node v6.17.1
npm  v3.10.10
already installed

```<code>npm run development
</code>```

npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run"
  "developement" npm ERR! node v6.17.1 npm ERR! npm  v3.10.10

npm ERR! missing script: development npm ERR! npm ERR! If you need
  help, you may report this error at: npm ERR!

  https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
  npm ERR!     /home/project_name/public_html/npm-debug.log

答:
The part that says "cb() never called" looks like it's just a warning and probably isn't a big issue right now.

The error you are gettin below that seems to indicate that you have no "development" script defined under "scripts" in package.json. You probably want something that looks like this in package.json:

```<code>  6   "scripts": {
  7     "development": "node server.js",
  8   }
</code>```

Although the script itself may vary based on how you have your development server setup

Body:
this type of error

npm ERR! CB() never called!

I have already cleared clear npm cache
I have already run this command

rm -rf node_modules
rm package.lock.json yarn.lock
npm cache clear --force
npm install

npm, WARN deprecated popper.js@1.16.1: You can find the new Popper v2
  at @popperjs/core, this package is dedicated to the legacy v1 npm ERR!
  CB() never called!

Valid answer give for this error
and this command I run on my ubuntu server machine
node v6.17.1
npm  v3.10.10
already installed

npm run development

npm ERR! argv "/usr/local/bin/node" "/usr/local/bin/npm" "run"
  "developement" npm ERR! node v6.17.1 npm ERR! npm  v3.10.10

npm ERR! missing script: development npm ERR! npm ERR! If you need
  help, you may report this error at: npm ERR!

  https://github.com/npm/npm/issues

npm ERR! Please include the following file with any support request:
  npm ERR!     /home/project_name/public_html/npm-debug.log

Body:
The part that says "cb() never called" looks like it's just a warning and probably isn't a big issue right now.

The error you are gettin below that seems to indicate that you have no "development" script defined under "scripts" in package.json. You probably want something that looks like this in package.json:

  6   "scripts": {
  7     "development": "node server.js",
  8   }

Although the script itself may vary based on how you have your development server setup


问:
Why do we use matrices?
Why we use matrices instead of just arrays?

If I create an array of vertices of a 3d model and I want to move each vertex left well

```<code>   ArrayList<Vertex> vertex = fillVertecis();
   for(Vertex vertex: vertices){
      vertex.x += 2;
   }

   //or avoiding creating all those objects

   float[] vertices = fillVertecis();

   //asumming we arrange the array like so [x1,y1,z1,x2,y2,z2....]
   int x = 0;
   int y = 1;
   int z = 2;

   for(int i = 0; i < vertices.lenght/3; i+= 3){
      vertices[i+x] += 1;
   }

</code>```

sure  I'm looping through all vertex but don't we have to do the same using matrices?

What advantages do we have using matrices instead of arrays?

答:
What advantages do we have using matrices instead of arrays?

Clarity of purpose.

Ease of manipulation.

Abstraction of implementation.

...

Title: Why do we use matrices?

Body:
Why we use matrices instead of just arrays?

If I create an array of vertices of a 3d model and I want to move each vertex left well

   ArrayList<Vertex> vertex = fillVertecis();
   for(Vertex vertex: vertices){
      vertex.x += 2;
   }

   //or avoiding creating all those objects

   float[] vertices = fillVertecis();

   //asumming we arrange the array like so [x1,y1,z1,x2,y2,z2....]
   int x = 0;
   int y = 1;
   int z = 2;

   for(int i = 0; i < vertices.lenght/3; i+= 3){
      vertices[i+x] += 1;
   }

sure  I'm looping through all vertex but don't we have to do the same using matrices?

What advantages do we have using matrices instead of arrays?


问:
rails - confused about routing and params
I have a two models, Group and User

User belongs_to Group and
Group has_many Users

In my groups/show.html.erb I have the user sign-up form

```<code><h1>Create user</h1>

<%= form_for @user do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>
  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :email %><br />
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password %><br />
    <%= f.password_field :password %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation, "Confirmation" %><br />
    <%= f.password_field :password_confirmation %>
  </div>
  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>
</code>```

To get a relation between the Group and the User I have a create method in my Users controller as follows

```<code>def create
    @group = Group.find(params[:group][:id])
    @user = @group.users.build(params[:user])
    if @user.save
      flash[:success] = "You have created a new user"
      redirect_to group_path
    else
      @title = "Create user"
      render 'new'
    end
end
</code>```

I have also tried:
 @group = Group.find(params[:id])

and

@group = Group.find(params[:group_id])

But I still get an error

Essentially I want to create new users in the group/show.html.erb and associate that user with the group where the user was created. If the user is created in groups/3 for example, how do I set my create method in the Users controller to make sure this relation holds?

In general I've been following the Hartl Rails tutorial book at http://ruby.railstutorial.org/chapters/user-microposts#sec:creating_microposts and following the approach for forms and create methods. However I am not sure how to get the params for groups/3 into the find method like @group = Group.find(?????)

Can someone please enlighten me, this issue has been bothering me for a few days now.

Thanks in advance

答:
After the form is submitted, it takes you to the users#create. This route doesn't have a group_id segment.

To pass group_id there, you need to store it in a hidden field in your form.

ContentLicense: CC BY-SA 3.0

Body:
I have a two models, Group and User

User belongs_to Group and
Group has_many Users

In my groups/show.html.erb I have the user sign-up form

Create user

<%= form_for @user do |f| %>
  <%= render 'shared/error_messages', :object => f.object %>

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :email %>

    <%= f.text_field :email %>

    <%= f.label :password %>

    <%= f.password_field :password %>

    <%= f.label :password_confirmation, "Confirmation" %>

    <%= f.password_field :password_confirmation %>

    <%= f.submit "Sign up" %>

<% end %>

To get a relation between the Group and the User I have a create method in my Users controller as follows

def create
    @group = Group.find(params[:group][:id])
    @user = @group.users.build(params[:user])
    if @user.save
      flash[:success] = "You have created a new user"
      redirect_to group_path
    else
      @title = "Create user"
      render 'new'
    end
end

I have also tried:
 @group = Group.find(params[:id])

and

@group = Group.find(params[:group_id])

But I still get an error

Essentially I want to create new users in the group/show.html.erb and associate that user with the group where the user was created. If the user is created in groups/3 for example, how do I set my create method in the Users controller to make sure this relation holds?

In general I've been following the Hartl Rails tutorial book at http://ruby.railstutorial.org/chapters/user-microposts#sec:creating_microposts and following the approach for forms and create methods. However I am not sure how to get the params for groups/3 into the find method like @group = Group.find(?????)

Can someone please enlighten me, this issue has been bothering me for a few days now.

Thanks in advance


问:
Difference between "spark.yarn.executor.memoryOverhead" and "spark.memory.offHeap.size"
I am running spark on yarn. I don't understand what is the difference between the following settings spark.yarn.executor.memoryOverhead and spark.memory.offHeap.size. Both seem to be settings for allocating off-heap memory to spark executor. Which one should I use? Also what is the recommended setting for executor offheap memory?

Many thanks!

答:
spark.yarn.executor.memoryOverhead is used in StaticMemoryManager. This is used in older Spark Version like 1.2.

The amount of off heap memory (in megabytes) to be allocated per executor. This is memory that accounts for things like VM overheads, interned strings, other native overheads, etc. This tends to grow with the executor size (typically 6-10%).

You can find this in older Spark docs,like Spark1.2 docs:

```<code>https://spark.apache.org/docs/1.2.0/running-on-yarn.html
</code>```

spark.memory.offHeap.size is used in UnifiedMemoryManager, which is used by default after version 1.6

The absolute amount of memory in bytes which can be used for off-heap allocation. This setting has no impact on heap memory usage, so if your executors' total memory consumption must fit within some hard limit then be sure to shrink your JVM heap size accordingly. This must be set to a positive value when spark.memory.offHeap.enabled=true.

You can find this in lates Spark docs,like Spark2.4 docs:

```<code>https://spark.apache.org/docs/2.4.4/configuration.html
</code>```

Body:
spark.yarn.executor.memoryOverhead is used in StaticMemoryManager. This is used in older Spark Version like 1.2.

The amount of off heap memory (in megabytes) to be allocated per executor. This is memory that accounts for things like VM overheads, interned strings, other native overheads, etc. This tends to grow with the executor size (typically 6-10%).

You can find this in older Spark docs,like Spark1.2 docs:

https://spark.apache.org/docs/1.2.0/running-on-yarn.html

spark.memory.offHeap.size is used in UnifiedMemoryManager, which is used by default after version 1.6

The absolute amount of memory in bytes which can be used for off-heap allocation. This setting has no impact on heap memory usage, so if your executors' total memory consumption must fit within some hard limit then be sure to shrink your JVM heap size accordingly. This must be set to a positive value when spark.memory.offHeap.enabled=true.

You can find this in lates Spark docs,like Spark2.4 docs:

https://spark.apache.org/docs/2.4.4/configuration.html


问:
Perceptron, two different algorithms
Try to re-visit perceptron material I run into two different algorithms. This is the first one:

The second one just says :

Whenever an example X is misclassified do
  W_new = W_old + X or W_new = W_old - X dippendes on the relative position
  of X with respect to the hyperplane (usually line in the case of 2D).

Is the 2nd one just a special case of the 1st where the learning rate is 1,
or those are two different algorithms? Thanks!

答: Yes, the 2nd case is the same as the first, when the learning rate = 1.

Title: Perceptron, two different algorithms


问:
Updated AndroidStudio(3.5.3) not building Android Project, Caused by: org.gradle.api.resources.ResourceException:Unable to load Maven meta-data
Updated Android Studio not building Android Project, before it was building.
I have checked with Proxy settings still it is getting same
Below are the exceptions after rebuilding the Android Project.

```<code>    org.gradle.api.ProjectConfigurationException: A problem occurred configuring root project 'Gsa2_NewMenu'.
Caused by: org.gradle.api.resources.ResourceException: Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.pom'.
    at org.gradle.internal.resource.ResourceExceptions.failure(ResourceExceptions.java:74)
    at org.gradle.internal.resource.ResourceExceptions.getFailed(ResourceExceptions.java:57)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.copyToCache(DefaultCacheAwareExternalResourceAccessor.java:201)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.access$300(DefaultCacheAwareExternalResourceAccessor.java:55)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.create(DefaultCacheAwareExternalResourceAccessor.java:90)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.create(DefaultCacheAwareExternalResourceAccessor.java:82)
    at org.gradle.cache.internal.ProducerGuard$AdaptiveProducerGuard.guardByKey(ProducerGuard.java:97)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.getResource(DefaultCacheAwareExternalResourceAccessor.java:82)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadByCoords(DefaultExternalResourceArtifactResolver.java:138)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadStaticResource(DefaultExternalResourceArtifactResolver.java:98)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.resolveArtifact(DefaultExternalResourceArtifactResolver.java:65)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.parseMetaDataFromArtifact(AbstractRepositoryMetadataSource.java:69)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.create(AbstractRepositoryMetadataSource.java:59)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:199)
    at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.doResolveComponentMetaData(MavenResolver.java:117)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveComponentMetaData(ExternalResourceResolver.java:400)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveComponentMetaData(CachingModuleComponentRepository.java:381)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveComponentMetaData(ErrorHandlingModuleComponentRepository.java:136)
    ... 133 more
Caused by: org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.pom'.
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:96)
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performRawGet(HttpClientHelper.java:80)
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performGet(HttpClientHelper.java:84)
    at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:43)
    at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:29)
    at org.gradle.internal.resource.transfer.DefaultExternalResourceConnector.openResource(DefaultExternalResourceConnector.java:56)
    at org.gradle.internal.resource.transfer.ProgressLoggingExternalResourceAccessor.openResource(ProgressLoggingExternalResourceAccessor.java:36)
    at org.gradle.internal.resource.transfer.AccessorBackedExternalResource.withContentIfPresent(AccessorBackedExternalResource.java:130)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:237)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:229)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:350)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:340)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:120)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator.withContentIfPresent(BuildOperationFiringExternalResourceDecorator.java:229)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.copyToCache(DefaultCacheAwareExternalResourceAccessor.java:199)
    ... 148 more
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)
</code>```

Below is the app gradle file.

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

android {
    compileSdkVersion 26
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "XX.XX.XXX"
        minSdkVersion 22
        targetSdkVersion 26
        versionCode 13
        versionName "6.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories{
    maven { url "jitpack.io" }
    maven { name 'glide-snapshot'; url 'oss.sonatype.org/content/repositories/snapshots' }
    mavenCentral()
}

dependencies {
    /*implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })*/
    implementation files('libs/apache-httpcomponents-httpclient.jar')
    implementation files('libs/apache-httpcomponents-httpcore.jar')

    implementation files('libs/commons-codec-1.11.jar')
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.4.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.google.android.gms:play-services-location:11.0.4'
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
    implementation 'com.jakewharton.timber:timber:4.5.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'me.dm7.barcodescanner:zxing:1.8.4'
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.github.antonKozyriatskyi:CircularProgressIndicator:1.3.0'

    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
    implementation 'com.android.support:recyclerview-v7:27.1.0'

    implementation(name:'merchantsdk', ext:'aar')
    implementation(name:'ezetapandroidsdk', ext:'aar')

    testImplementation 'junit:junit:4.12'
    implementation files('libs/org.apache.commons.io.jar')
}

apply plugin: 'com.google.gms.google-services'
</code>```

Below is the Project build gradle file

```<code>buildscript {
    repositories {

        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }

        flatDir {
            dirs 'libs'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}
</code>```

I have checked online, but none worked.I am stuck from 4 days, Please check my App and Project gradle files and let me know.Please help me on this.Thanks in Advance.

答:
As per my knowledge Your Android Studio Version is Updated to 3.5.3 as You mention on Title
and You are Using 3.3.2 Build Gradle Version. i think Gradle Version is Creating an issue try to update you Gradle Version to 3.5.0, 3.5.1 or 3.5.2 [Gradle Version]

in Your Project build Gradle

```<code>dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
</code>```

Body:
Updated Android Studio not building Android Project, before it was building.
I have checked with Proxy settings still it is getting same
Below are the exceptions after rebuilding the Android Project.

    org.gradle.api.ProjectConfigurationException: A problem occurred configuring root project 'Gsa2_NewMenu'.
Caused by: org.gradle.api.resources.ResourceException: Could not get resource 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.pom'.
    at org.gradle.internal.resource.ResourceExceptions.failure(ResourceExceptions.java:74)
    at org.gradle.internal.resource.ResourceExceptions.getFailed(ResourceExceptions.java:57)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.copyToCache(DefaultCacheAwareExternalResourceAccessor.java:201)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.access$300(DefaultCacheAwareExternalResourceAccessor.java:55)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.create(DefaultCacheAwareExternalResourceAccessor.java:90)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor$1.create(DefaultCacheAwareExternalResourceAccessor.java:82)
    at org.gradle.cache.internal.ProducerGuard$AdaptiveProducerGuard.guardByKey(ProducerGuard.java:97)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.getResource(DefaultCacheAwareExternalResourceAccessor.java:82)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadByCoords(DefaultExternalResourceArtifactResolver.java:138)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.downloadStaticResource(DefaultExternalResourceArtifactResolver.java:98)
    at org.gradle.api.internal.artifacts.repositories.resolver.DefaultExternalResourceArtifactResolver.resolveArtifact(DefaultExternalResourceArtifactResolver.java:65)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.parseMetaDataFromArtifact(AbstractRepositoryMetadataSource.java:69)
    at org.gradle.api.internal.artifacts.repositories.metadata.AbstractRepositoryMetadataSource.create(AbstractRepositoryMetadataSource.java:59)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver.resolveStaticDependency(ExternalResourceResolver.java:199)
    at org.gradle.api.internal.artifacts.repositories.resolver.MavenResolver.doResolveComponentMetaData(MavenResolver.java:117)
    at org.gradle.api.internal.artifacts.repositories.resolver.ExternalResourceResolver$RemoteRepositoryAccess.resolveComponentMetaData(ExternalResourceResolver.java:400)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.CachingModuleComponentRepository$ResolveAndCacheRepositoryAccess.resolveComponentMetaData(CachingModuleComponentRepository.java:381)
    at org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ErrorHandlingModuleComponentRepository$ErrorHandlingModuleComponentRepositoryAccess.resolveComponentMetaData(ErrorHandlingModuleComponentRepository.java:136)
    ... 133 more
Caused by: org.gradle.internal.resource.transport.http.HttpRequestException: Could not GET 'https://dl.google.com/dl/android/maven2/com/android/tools/build/gradle/3.3.2/gradle-3.3.2.pom'.
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performRequest(HttpClientHelper.java:96)
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performRawGet(HttpClientHelper.java:80)
    at org.gradle.internal.resource.transport.http.HttpClientHelper.performGet(HttpClientHelper.java:84)
    at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:43)
    at org.gradle.internal.resource.transport.http.HttpResourceAccessor.openResource(HttpResourceAccessor.java:29)
    at org.gradle.internal.resource.transfer.DefaultExternalResourceConnector.openResource(DefaultExternalResourceConnector.java:56)
    at org.gradle.internal.resource.transfer.ProgressLoggingExternalResourceAccessor.openResource(ProgressLoggingExternalResourceAccessor.java:36)
    at org.gradle.internal.resource.transfer.AccessorBackedExternalResource.withContentIfPresent(AccessorBackedExternalResource.java:130)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:237)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator$11.call(BuildOperationFiringExternalResourceDecorator.java:229)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:350)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:340)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:199)
    at org.gradle.internal.progress.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:120)
    at org.gradle.internal.resource.BuildOperationFiringExternalResourceDecorator.withContentIfPresent(BuildOperationFiringExternalResourceDecorator.java:229)
    at org.gradle.internal.resource.transfer.DefaultCacheAwareExternalResourceAccessor.copyToCache(DefaultCacheAwareExternalResourceAccessor.java:199)
    ... 148 more
Caused by: java.net.SocketTimeoutException: Read timed out
    at java.net.SocketInputStream.socketRead0(Native Method)

Below is the app gradle file.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "XX.XX.XXX"
        minSdkVersion 22
        targetSdkVersion 26
        versionCode 13
        versionName "6.0"
        multiDexEnabled true
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
}

repositories{
    maven { url "jitpack.io" }
    maven { name 'glide-snapshot'; url 'oss.sonatype.org/content/repositories/snapshots' }
    mavenCentral()
}

dependencies {
    /*implementation fileTree(include: ['*.jar'], dir: 'libs')
    androidTestImplementation('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })*/
    implementation files('libs/apache-httpcomponents-httpclient.jar')
    implementation files('libs/apache-httpcomponents-httpcore.jar')

    implementation files('libs/commons-codec-1.11.jar')
    implementation 'com.android.support:appcompat-v7:27.1.0'
    implementation 'com.android.support:design:27.1.0'
    implementation 'com.journeyapps:zxing-android-embedded:3.4.0'
    implementation 'com.android.support:cardview-v7:27.1.0'
    implementation 'com.google.android.gms:play-services-location:11.0.4'
    implementation 'com.google.firebase:firebase-messaging:11.0.4'
    implementation 'com.jakewharton.timber:timber:4.5.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'

    implementation 'com.android.support:support-v4:27.1.0'
    implementation 'com.github.bumptech.glide:glide:4.9.0'
    implementation 'me.dm7.barcodescanner:zxing:1.8.4'
    implementation 'com.loopj.android:android-async-http:1.4.9'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.android.support:multidex:1.0.3'
    implementation 'com.github.antonKozyriatskyi:CircularProgressIndicator:1.3.0'

    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:retrofit:2.0.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.0.2'
    implementation 'com.android.support:recyclerview-v7:27.1.0'

    implementation(name:'merchantsdk', ext:'aar')
    implementation(name:'ezetapandroidsdk', ext:'aar')

    testImplementation 'junit:junit:4.12'
    implementation files('libs/org.apache.commons.io.jar')
}

apply plugin: 'com.google.gms.google-services'

Below is the Project build gradle file

buildscript {
    repositories {

        jcenter()
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url 'https://jitpack.io'
        }
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }

        flatDir {
            dirs 'libs'
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

I have checked online, but none worked.I am stuck from 4 days, Please check my App and Project gradle files and let me know.Please help me on this.Thanks in Advance.

Body:
As per my knowledge Your Android Studio Version is Updated to 3.5.3 as You mention on Title
and You are Using 3.3.2 Build Gradle Version. i think Gradle Version is Creating an issue try to update you Gradle Version to 3.5.0, 3.5.1 or 3.5.2 [Gradle Version]

in Your Project build Gradle

dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
        classpath 'com.google.gms:google-services:3.0.0'
    }


问:
Print key if any nested value matches a set value
This is best explained with expected input and output.

Given this input:

```<code>{
  "27852380038": {
    "compute_id": 34234234,
    "to_compute": [
      {
        "asset_id": 304221854,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 12123121,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  },
  "31352333022": {
    "compute_id": 43888877,
    "to_compute": [
      {
        "asset_id": 404221555,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 52123444,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  }
}
</code>```

And the asset_id that I'm searching for, 12123121, the output should be:

```<code>27852380038
</code>```

So I want the top level keys where any of the asset_ids in to_compute match my input asset_id.

I haven't seen any jq example so far that combines nested access with an any test / if else.

答:
The task can be accomplished without using environment variables, e.g.

```<code>< input.json jq -r --argjson ASSET_ID 12123121 '
  to_entries[]
  | {key, asset_id: .value.to_compute[].asset_id}
  | select(.asset_id==$ASSET_ID)
  | .key'
</code>```

or more efficiently, using the filter:

```<code>to_entries[]
| select( any( .value.to_compute[]; .asset_id==$ASSET_ID) )
| .key
</code>```

Body:
This is best explained with expected input and output.

Given this input:

{
  "27852380038": {
    "compute_id": 34234234,
    "to_compute": [
      {
        "asset_id": 304221854,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 12123121,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  },
  "31352333022": {
    "compute_id": 43888877,
    "to_compute": [
      {
        "asset_id": 404221555,
        "new_scheme": "mynewscheme",
        "original_host": "oldscheme1234.location.com"
      },
      {
        "asset_id": 52123444,
        "new_scheme": "myotherscheme",
        "original_host": "olderscheme1234.location.com"
      }
    ]
  }
}

And the asset_id that I'm searching for, 12123121, the output should be:

27852380038

So I want the top level keys where any of the asset_ids in to_compute match my input asset_id.

I haven't seen any jq example so far that combines nested access with an any test / if else.

Body:
The task can be accomplished without using environment variables, e.g.

< input.json jq -r --argjson ASSET_ID 12123121 '
  to_entries[]
  | {key, asset_id: .value.to_compute[].asset_id}
  | select(.asset_id==$ASSET_ID)
  | .key'

or more efficiently, using the filter:

to_entries[]
| select( any( .value.to_compute[]; .asset_id==$ASSET_ID) )
| .key


问:
php, how to run a link when check box checked?
```<code><input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';
</code>```

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

```<code>if ($('#checket:checked').val() !== undefined) {
</code>```

// Insert code here.
}

答:
Load the jquery library and then use the following code:</p>

```<code>$('input[type=checkbox]#checket').click(function() {
    if($(this).is(':checked')) {
       $.get('urlhere', function(data) {
          // Process return data here
       });
    }
});
</code>```

Body:
<input type="checkbox" name="checket" id="checket" />
$url  = 'test.com';

and when i check it i want it to go to a url: href='$url'
and remember that has been checked.

any ideas?

thanks

edit:
maybe

if ($('#checket:checked').val() !== undefined) {

// Insert code here.
}

Body:
Load the jquery library and then use the following code:

$('input[type=checkbox]#checket').click(function() {
    if($(this).is(':checked')) {
       $.get('urlhere', function(data) {
          // Process return data here
       });
    }
});


问:
GA showing (not set) for Google Ads campaigns
I am seeing something absolutely crazy in my GA. I have a Google Ads account which is properly linked to my GA. Auto-tagging is also enabled. I have one Search and one Display campaign. But when I look at the reports in GA, this is what I see:

As you can see GA correctly records the clicks as coming from the the campaigns but then there is this (not set) campaign which is receiving all the users. The the Search and Diplay campaigns have no users respectively. This is the only landing page of the campaigns:

https://www.devimax.com/%D0%BF%D1%80%D0%BE%D0%BC%D0%BE%D1%86%D0%B8%D0%B8-%D1%81%D0%BF%D0%B0%D1%80%D0%BA%D0%B8

All the standard articles and answers why you might be getting (not set) talk about linking your Adwords account to GA and enabling auto tagging. But this is all done.

答:
Go to the GA admin page, then click on the eCommerce setting, if it is not enabled then click turn ON.

Set UTM Code in Google Adwords - In the left corner, click on the setting, then go to the account setting, you will see a tracking code option if the code is not set then paste this code -

{lpurl}?utm_campaign={campaignid}&utm_source=google&utm_medium=cpc&utm_content={creative}&utm_term={keyword}&adgroupid={adgroupid}

then save it.
It's Done. Please, give feedback to us after applying all setting.


问:
Screen Responsive PHP tables in HTML
So I have an html page that uses PHP calls to fill the various tables. The page looks great on my one screen and horrible everywhere else. Hoping its sort of a simple fix but any feedback would be greatly appreciated. I know I shouldn't use px but the percentage wasn't working correctly for me.

The CSS

```<code>td.COMPLETE {
background-color: green;
color: black;
text-align: center;
}

td{
color: white;
text-align: center;
}
td.Blue {
background-color: blue;
color: white;
text-align: center;
}
td.Yellow {
background-color: yellow;
color: black;
text-align: center;
}
td.Orange {
background-color: orange;
color: black;
text-align: center;
}
td.Red {
background-color: red;
color: black;
text-align: center;
}
#dTitle { position: fixed; visibility: visible; left: 1295px; top: 135px;}
#dTable { position: fixed; visibility: visible; left: 1050px; top: 175px;}
#cTitle { position: fixed; visibility: visible; left: 865px; top: 135px;}
#cTable { position: fixed; visibility: visible; left: 855px; top: 175px; width:20%}
#rTitle { position: fixed; visibility: visible; left: 350px; top: 135px;}
#rTable { position: fixed; visibility: visible; left: 50px; top: 175px; width:45%}
#sTitle { position: fixed; visibility: visible; left: 450px; top: 550px; }
#sTable { position: fixed; visibility: visible; left: 50px; top: 590px; width:60%}
</code>```

The HTML

```<code><title>Reports</title>
<link href="status.css" rel="stylesheet">
<body bgcolor = #000000>
<font color = "white">
<head>
 <META HTTP-EQUIV="refresh" CONTENT="86400">
<center><h1 id="logo"><img src="reports.png" alt="reports logo" height="75" width="75" /><u>Reports</u> </h1></center>
<style>
        body {
            animation: fadeInAnimation ease 3s;
            animation-iteration-count: 1;
            animation-fill-mode: forwards;
        }
        @keyframes fadeInAnimation {
            0% {
                opacity: 0;
            }
            100% {
                opacity: 1;
            }
        }
    </style>
</head>

<?php

  try

  {

    $db = new PDO("sqlite:root/.db");
    $count = $db->query('SELECT COUNT(*) from reported');
    foreach($count as $row)
    {
            print "<center>Total Database Entires: ".$row['COUNT(*)']. "</center>";
    }
    print "<div id=dupiTitle><h4>Progress</h4></div>";
    print "<div id=dupiTable><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td><u>Operator</u></td><td><u>Total Reports</u></td><td><u>Unique Users</u></td><td><u>Percent of reports Entered</u></td></tr>";
    $result = $db->query('SELECT operator, COUNT(DISTINCT userID), COUNT(userID) FROM reported GROUP BY operator ORDER BY COUNT(DISTINCT userID) DESC');

    foreach($result as $row)
    {

      print "<tr><td>".$row['operator']."</td>";
      print "<td>".$row['COUNT(userID)']."</td>";
      print "<td>".$row['COUNT(DISTINCT userID)']."</td>";

    $sql = "SELECT dupi, COUNT(DISTINCT userID) FROM reported WHERE operator = '" .$row['operator'] ."' AND report is NULL";

    $results = $db->query($sql);
    $complete = "COMPLETE";
    foreach($results as $rows)
    {
    if ($rows['COUNT(DISTINCT userID)'] == 0){
    print "<td class=".$complete.">COMPLETE</td></tr>";
    }elseif(100 - round(($rows['COUNT(DISTINCT userID)']/$row['COUNT(DISTINCT userID)']) * 100) == 100){
    print "<td>99%</td></tr>";
    }else{
    $per = 100 - round(($rows['COUNT(DISTINCT userID)']/$row['COUNT(DISTINCT userID)']) * 100);
    print "<td>" .$per. "%</td></tr>";
    }
    }
    }
    print "</table></div>";
        echo "<div id=cTitle><h4>Color Break Down</h4></div>";
    print "<div id=cTable><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td><u>Color Code</u></td><td><u>Count</u></td></tr>";
        $result = $db->query("SELECT color_code,COUNT(*) FROM reported GROUP BY color_code ORDER BY COUNT(*) DESC");
    foreach($result as $row)
            {
            print "<tr><td class=".$row['color_code'].">".$row['color_code']."</td>";
            print "<td>".$row['COUNT(*)']."</td></tr>";
        }
        print "</table></div>";

    echo "<div id=rTitle><h4>Top Reported</h4></div>";
    print "<div id=r><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td><u>Operator</u></td><td><u>Username/UserID</u></td><td><u>Report</u></td><td><u>Times Reported</u></td></tr>";
    $result2 = $db->query('SELECT operator, userID, report, COUNT(*) FROM reported  WHERE report is NOT NULL AND report is NOT "TEST" AND report is NOT "Not Found" AND report is NOT "Restricted" AND report is NOT "Not Verified" GROUP BY report ORDER BY COUNT(*) DESC LIMIT 10');

    foreach($result2 as $row)
    {

      print "<tr><td>".$row['operator']."</td>";
      print "<td>".$row['userID']."</td>";
      print "<td>".$row['report']."</td>";
      print "<td>".$row['COUNT(*)']."</td></tr>";

    }
    print "</table></div>";

    echo "<div id=rTitle><h4>Top Reasons Reported</h4></div>";
    print "<div id=rTable><table border=10 bordercolorlight=#383838 bordercolordark=Gray>";
    print "<tr><td><u>Reason</u></td><td><u>Times Reported</u></td></tr>";
    $result2 = $db->query('SELECT explanation, COUNT(*) FROM reported GROUP BY explanation ORDER BY COUNT(*) DESC LIMIT 10');

    foreach($result2 as $row)
    {

      print "<tr><td>".$row['explanation']."</td>";
      print "<td>".$row['COUNT(*)']."</td></tr>";

    }
    print "</table></div>";

    $db = NULL;
  }
  catch(PDOException $e) {
      echo $e->getMessage();
}
?>
</code>```

答:
You can either use CSS Media Queries by which you can have separate styles for different screen sizes or any HTML5 Boilerplate like Bootstrap, by which you don't need to explicitly write media queries. In the case of bootstrap add the library CSS link in your HTML head tag and you are good to go.

Example for Responsive Table using media query.

Example for Responsive table using Bootstrap.

Suggestion

 tag you are using is depreciated please try to use CSS instead (Refer me).

First, add <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1,0"> to your head section.

The following code snippet you have added in head is causing your page refresh.<META HTTP-EQUIV="refresh" CONTENT="86400"> (Refer me).

Always try to use CSS classes instead of giving styles directly to html elements.

You can also omit some columns in mobile view (if not mandatory) or else you can enable horizontal scroll for your HTML table (Refer me).

Title: Screen Responsive PHP tables in HTML

Body:
So I have an html page that uses PHP calls to fill the various tables. The page looks great on my one screen and horrible everywhere else. Hoping its sort of a simple fix but any feedback would be greatly appreciated. I know I shouldn't use px but the percentage wasn't working correctly for me.

The CSS

td.COMPLETE {
background-color: green;
color: black;
text-align: center;
}

td{
color: white;
text-align: center;
}
td.Blue {
background-color: blue;
color: white;
text-align: center;
}
td.Yellow {
background-color: yellow;
color: black;
text-align: center;
}
td.Orange {
background-color: orange;
color: black;
text-align: center;
}
td.Red {
background-color: red;
color: black;
text-align: center;
}
#dTitle { position: fixed; visibility: visible; left: 1295px; top: 135px;}
#dTable { position: fixed; visibility: visible; left: 1050px; top: 175px;}
#cTitle { position: fixed; visibility: visible; left: 865px; top: 135px;}
#cTable { position: fixed; visibility: visible; left: 855px; top: 175px; width:20%}
#rTitle { position: fixed; visibility: visible; left: 350px; top: 135px;}
#rTable { position: fixed; visibility: visible; left: 50px; top: 175px; width:45%}
#sTitle { position: fixed; visibility: visible; left: 450px; top: 550px; }
#sTable { position: fixed; visibility: visible; left: 50px; top: 590px; width:60%}

The HTML

<title>Reports</title>
<link href="status.css" rel="stylesheet">

 <META HTTP-EQUIV="refresh" CONTENT="86400">

Reports

<?php

  try

  {

    $db = new PDO("sqlite:root/.db");
    $count = $db->query('SELECT COUNT(*) from reported');
    foreach($count as $row)
    {
            print "Total Database Entires: ".$row['COUNT(*)']. "";
    }
    print "

Progress

";
    print "

";
    print "
Operator	Total Reports	Unique Users	Percent of reports Entered
";
    $result = $db->query('SELECT operator, COUNT(DISTINCT userID), COUNT(userID) FROM reported GROUP BY operator ORDER BY COUNT(DISTINCT userID) DESC');

    foreach($result as $row)
    {

      print "
".$row['operator']."	";
      print "".$row['COUNT(userID)']."	";
      print "".$row['COUNT(DISTINCT userID)']."	";

    $sql = "SELECT dupi, COUNT(DISTINCT userID) FROM reported WHERE operator = '" .$row['operator'] ."' AND report is NULL";

    $results = $db->query($sql);
    $complete = "COMPLETE";
    foreach($results as $rows)
    {
    if ($rows['COUNT(DISTINCT userID)'] == 0){
    print "COMPLETE
";
    }elseif(100 - round(($rows['COUNT(DISTINCT userID)']/$row['COUNT(DISTINCT userID)']) * 100) == 100){
    print "99%
";
    }else{
    $per = 100 - round(($rows['COUNT(DISTINCT userID)']/$row['COUNT(DISTINCT userID)']) * 100);
    print "" .$per. "%
";
    }
    }
    }
    print "

";
        echo "

Color Break Down

";
    print "

";
    print "
Color Code	Count
";
        $result = $db->query("SELECT color_code,COUNT(*) FROM reported GROUP BY color_code ORDER BY COUNT(*) DESC");
    foreach($result as $row)
            {
            print "
".$row['color_code']."	";
            print "".$row['COUNT(*)']."
";
        }
        print "

";

    echo "

Top Reported

";
    print "

";
    print "
Operator	Username/UserID	Report	Times Reported
";
    $result2 = $db->query('SELECT operator, userID, report, COUNT(*) FROM reported  WHERE report is NOT NULL AND report is NOT "TEST" AND report is NOT "Not Found" AND report is NOT "Restricted" AND report is NOT "Not Verified" GROUP BY report ORDER BY COUNT(*) DESC LIMIT 10');

    foreach($result2 as $row)
    {

      print "
".$row['operator']."	";
      print "".$row['userID']."	";
      print "".$row['report']."	";
      print "".$row['COUNT(*)']."
";

    }
    print "

";

    echo "

Top Reasons Reported

";
    print "

";
    print "
Reason	Times Reported
";
    $result2 = $db->query('SELECT explanation, COUNT(*) FROM reported GROUP BY explanation ORDER BY COUNT(*) DESC LIMIT 10');

    foreach($result2 as $row)
    {

      print "
".$row['explanation']."	";
      print "".$row['COUNT(*)']."
";

    }
    print "

";

    $db = NULL;
  }
  catch(PDOException $e) {
      echo $e->getMessage();
}
?>

Body:
You can either use CSS Media Queries by which you can have separate styles for different screen sizes or any HTML5 Boilerplate like Bootstrap, by which you don't need to explicitly write media queries. In the case of bootstrap add the library CSS link in your HTML head tag and you are good to go.

Example for Responsive Table using media query.

Example for Responsive table using Bootstrap.

Suggestion

<center> tag you are using is depreciated please try to use CSS instead (Refer me).

First, add <meta charset="utf-8" name="viewport" content="width=device-width, initial-scale=1,0"> to your head section.

The following code snippet you have added in head is causing your page refresh.<META HTTP-EQUIV="refresh" CONTENT="86400"> (Refer me).

Always try to use CSS classes instead of giving styles directly to html elements.

You can also omit some columns in mobile view (if not mandatory) or else you can enable horizontal scroll for your HTML table (Refer me).


问:
Counting the number of repeated entries in a file
When I read a file, it gives me an output like this:

```<code>CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749
</code>```

I want to count the total number of CW and CS in the file. The output should look like this:

```<code>3 #For CW
3 #For CS
</code>```

I tried using the following code:

```<code>with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)
</code>```

But it gives me this output

```<code>2
2
2
2
2
2
</code>```

I even tried importing counter, but it gives me output like this:

```<code>C 1
W 1
C 1
W 1
C 1
S 1
</code>```

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
When I read a file, it gives me an output like this:

CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749

I want to count the total number of CW and CS in the file. The output should look like this:

3 #For CW
3 #For CS

I tried using the following code:

with open ("file", 'r') as rf:
    v=rf.read().split('\n')

 i=[]
 for e in v[1::47]: #(only the names)
     r=(e[:12])
     s=(r[:2])
     q= sum(c != ' ' for c in s)
    print(q)

But it gives me this output

2
2
2
2
2
2

I even tried importing counter, but it gives me output like this:

C 1
W 1
C 1
W 1
C 1
S 1

Please suggest some method so that I can get the expected output. Any help will be highly appreciated.

Body:
You can try following code.

>>> text = '''CW  0.000000  0.003822  0.006380  0.005100  0.016987  0.307042
... CW  0.007136  0.019635  0.329683  0.315180  0.302634  0.007076
... CW  0.015666  0.299244  0.290860  0.292623  0.325943  0.005236
... CS  0.022060  0.288761  0.311449  0.289165  0.289937  0.317213
... CS  0.019635  0.040511  0.301167  0.011418  0.295902  0.017166
... CS  0.020990  0.345277  0.352370  0.034237  0.020962  0.015749'''
>>> items = [line.split()[0] for line in text.splitlines()]
>>> val = set([line.split()[0] for line in text.splitlines()])
>>> for item in val:
...     print(f'{items.count(item)} #For {item}')
...
3 #For CW
3 #For CS


问:
Exclude jQuery From Specific Div Using CSS
The site uses this js which breaks the search-form input fields added within the site-branding div

```<code>/**
 * Remove all off-canvas states
 */
 function removeAllFocusStates() {
    'use strict';

    var siteBranding = document.getElementsByClassName('site-branding')[0];
    var getFocusedElements = siteBranding.querySelectorAll(':hover, :focus, :focus-within');
    var getFocusedClassElements = siteBranding.querySelectorAll('.is-focused');
    var i;
    var o;

    for (i = 0; i < getFocusedElements.length; i++) {
        getFocusedElements[i].blur();
    }

    for (o = 0; o < getFocusedClassElements.length; o++) {
        deleteClass(getFocusedClassElements[o], 'is-focused');
    }
}
</code>```

Here's the HTML output for the site-branding container

```<code><div class="site-branding">
    <form role="search" method="get" class="search-form" action="http://dev.local/">
        <label>
            <span class="screen-reader-text">Search for:</span>
            <input type="search" class="search-field" placeholder="Search …" value="" name="s" />
        </label>
        <input type="submit" class="search-submit" value="Search" />
    </form>
</div>
</code>```

Update : Here's the removeAllFocusStates() function in use which needs modifying to exclude the search-form

```<code>  ...
  document.addEventListener('click', function(event) {

      // Remove all focused menu states when clicking outside site branding
      if (event.target !== document.getElementsByClassName('site-branding')[0]) {
          removeAllFocusStates();
      } else {
          // nothing
      }

  }, false);
}
</code>```

Users cannot enter text in the search input field because the js is modifying default input field.

Is there a way to use CSS to fix this so it doesn't apply to the search-form input field added within the site-branding div within the header?

Otherwise, is there a way to modify the js so it doesn't effect the search-form?

I did search the similar questions however couldn't find anything which applies specifically to this problem.

答:
Try not calling removeAllFocusStates() when the user clicks the input.

So

```<code>if (event.target !== document.getElementsByClassName('site-branding')[0]) {
</code>```

becomes something like

```<code>if ( (event.target !== document.getElementsByClassName('site-branding')[0]) && (event.target !== document.getElementsByClassName('search-field')[0]) ) {
</code>```

Body:
The site uses this js which breaks the search-form input fields added within the site-branding div

/**
 * Remove all off-canvas states
 */
 function removeAllFocusStates() {
    'use strict';

    var siteBranding = document.getElementsByClassName('site-branding')[0];
    var getFocusedElements = siteBranding.querySelectorAll(':hover, :focus, :focus-within');
    var getFocusedClassElements = siteBranding.querySelectorAll('.is-focused');
    var i;
    var o;

    for (i = 0; i < getFocusedElements.length; i++) {
        getFocusedElements[i].blur();
    }

    for (o = 0; o < getFocusedClassElements.length; o++) {
        deleteClass(getFocusedClassElements[o], 'is-focused');
    }
}

Here's the HTML output for the site-branding container

    <form role="search" method="get" class="search-form" action="http://dev.local/">

            Search for:
            <input type="search" class="search-field" placeholder="Search …" value="" name="s" />

        <input type="submit" class="search-submit" value="Search" />
    </form>

Update : Here's the removeAllFocusStates() function in use which needs modifying to exclude the search-form

  ...
  document.addEventListener('click', function(event) {

      // Remove all focused menu states when clicking outside site branding
      if (event.target !== document.getElementsByClassName('site-branding')[0]) {
          removeAllFocusStates();
      } else {
          // nothing
      }

  }, false);
}

Users cannot enter text in the search input field because the js is modifying default input field.

Is there a way to use CSS to fix this so it doesn't apply to the search-form input field added within the site-branding div within the header?

Otherwise, is there a way to modify the js so it doesn't effect the search-form?

I did search the similar questions however couldn't find anything which applies specifically to this problem.

Body:
Try not calling removeAllFocusStates() when the user clicks the input.

So

if (event.target !== document.getElementsByClassName('site-branding')[0]) {

becomes something like

if ( (event.target !== document.getElementsByClassName('site-branding')[0]) && (event.target !== document.getElementsByClassName('search-field')[0]) ) {


问:
Setting the timeout of a HAPI FHIR IGenericClient
I'm trying to run a fhir search using the following code;

```<code>FhirContext ctx = FhirContext.forDstu2();
ctx.getRestfulClientFactory().setConnectTimeout(2000000);
IGenericClient client = ctx.newRestfulGenericClient("http://localhost:1080/hapi-fhir-jpaserver-example/baseDstu2");

Bundle results = client.search().forResource(Basic.class).returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();
</code>```

However when it runs, it always throws the exception 'FhirClientConnectionException' which is caused by the exception 'SocketTimeoutException'.  Am I to assume that this is the server timing out, and not my local connection, since I set my local to 2000000?

How do I go about fixing thing?  I'm using HAPI in it's out of the box config, and it times out searching through a relatively small amount of resources within about 10-15 seconds.

答:
Try setSocketTimeout() instead.

Like this:

FhirContext ctx = FhirContext.forDstu2();
ctx.getRestfulClientFactory().setSocketTimeout(200 * 1000);
IGenericClient client = ctx.newRestfulGenericClient("http://localhost:1080/hapi-fhir-jpaserver-example/baseDstu2");

Bundle results = client.search().forResource(Basic.class).returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();
```

<p>v3 example:</p>

<pre class="lang-java prettyprint-override"><code>serverBase =  "http://hapi.fhir.org/baseDstu3";
ctx = FhirContext.forDstu3();
ctx.getRestfulClientFactory().setSocketTimeout(200 * 1000);

// Create the client
client = ctx.newRestfulGenericClient(serverBase);
</code>```

I found the answer reading source code here: https://github.com/jamesagnew/hapi-fhir/blob/master/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java#L1710

Body:
I'm trying to run a fhir search using the following code;

FhirContext ctx = FhirContext.forDstu2();
ctx.getRestfulClientFactory().setConnectTimeout(2000000);
IGenericClient client = ctx.newRestfulGenericClient("http://localhost:1080/hapi-fhir-jpaserver-example/baseDstu2");

Bundle results = client.search().forResource(Basic.class).returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();

However when it runs, it always throws the exception 'FhirClientConnectionException' which is caused by the exception 'SocketTimeoutException'.  Am I to assume that this is the server timing out, and not my local connection, since I set my local to 2000000?

How do I go about fixing thing?  I'm using HAPI in it's out of the box config, and it times out searching through a relatively small amount of resources within about 10-15 seconds.

Body:
Try setSocketTimeout() instead.

Like this:

FhirContext ctx = FhirContext.forDstu2();
ctx.getRestfulClientFactory().setSocketTimeout(200 * 1000);
IGenericClient client = ctx.newRestfulGenericClient("http://localhost:1080/hapi-fhir-jpaserver-example/baseDstu2");

Bundle results = client.search().forResource(Basic.class).returnBundle(ca.uhn.fhir.model.dstu2.resource.Bundle.class).execute();

v3 example:

serverBase =  "http://hapi.fhir.org/baseDstu3";
ctx = FhirContext.forDstu3();
ctx.getRestfulClientFactory().setSocketTimeout(200 * 1000);

// Create the client
client = ctx.newRestfulGenericClient(serverBase);

I found the answer reading source code here: https://github.com/jamesagnew/hapi-fhir/blob/master/hapi-fhir-jpaserver-base/src/test/java/ca/uhn/fhir/jpa/provider/dstu3/ResourceProviderDstu3Test.java#L1710


问:
Swift: cannot convert value of type 'SomeType<T>' to expected argument type 'SomeType<_>'
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}
```

<p>the call to <code>completion(pageData)</code> produces the following error:</p>

<blockquote>
  <p>Cannot convert value of type <code>PageData<ItemType>?</code> to expected argument type <code>PageData<_>?</code></p>
</blockquote>

<p>This workaround casting with <code>as?</code> gets rid of the error:</p>

<pre class="lang-swift prettyprint-override"><code>class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}
</code>```

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

答:
The following code worked for me.</p>

```<code>struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    associatedtype T
    var pageData: PageData<T>? { get set }
    func fetchPage(page: Int, completion: @escaping (PageData<T>?) -> Void)
}

class TestPagedServiceProvider: PagedServiceProvider {

    var pageData: PageData<String>?

    func fetchPage(page: Int, completion: @escaping (PageData<String>?) -> Void) {
        completion(pageData)
    }

}

</code>```

Body:
I am using generics to build a paging library where I have code similar to this one (simplified):

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void)
}

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData) // COMPILATION ERROR HERE
    }
}

the call to completion(pageData) produces the following error:

Cannot convert value of type PageData<ItemType>? to expected argument type PageData<_>?

This workaround casting with as? gets rid of the error:

class TestPagedServiceProvider<ItemType>: PagedServiceProvider {
    var pageData: PageData<ItemType>?

    func fetchPage<ItemType>(page: Int, completion: @escaping (PageData<ItemType>?) -> Void) {
        completion(pageData as? PageData<ItemType>)
    }
}

Also if var pageData: PageData<ItemType>? is declared as a local variable inside the fetchPage<ItemType>... method, the error is gone as well.

NOTE: This gist provides additional context.

I am confused as to why the compiler requires an explicit cast (that looks redundant to me in this case).

Could it be a matter of placeholder types scope (the ItemType in the fetchPage<ItemType>... method is not the same as the ItemType for the TestPagedServiceProvider<ItemType> class)?

I tried giving them different names and using where clauses to no avail.

Body:
The following code worked for me.

struct PageData<T> {
    let item: T
    let pageNumber: Int
}

protocol PagedServiceProvider: class {
    associatedtype T
    var pageData: PageData<T>? { get set }
    func fetchPage(page: Int, completion: @escaping (PageData<T>?) -> Void)
}

class TestPagedServiceProvider: PagedServiceProvider {

    var pageData: PageData<String>?

    func fetchPage(page: Int, completion: @escaping (PageData<String>?) -> Void) {
        completion(pageData)
    }

}


问:
PyTorch Geometric CUDA installation issues on Google Colab
I was working on a PyTorch Geometric project using Google Colab for CUDA support. Since it's library isn't present by default, I run:

```<code>!pip install --upgrade torch-scatter
!pip install --upgrade torch-sparse
!pip install --upgrade torch-cluster
!pip install --upgrade torch-spline-conv
!pip install torch-geometric
</code>```

Recently, while importing torch_geometric, owing to version upgrades, there's a CUDA version mismatch saying:

RuntimeError: Detected that PyTorch and torch_sparse were compiled with different CUDA versions. PyTorch has CUDA version 10.1 and torch_sparse has CUDA version 10.0. Please reinstall the torch_sparse that matches your PyTorch install.

To solve this, I tried using conda for specific CUDA version as:

!conda install pytorch==1.4.0 cudatoolkit=10.0 -c pytorch

Yet, on running print(torch.version.cuda), I get 10.1 as the output and not 10.0 as I wanted.

This is a recent error since it wasn't throwing up this issue in past week. Any best practice to solve this issue?

答:
From their website

Try this

```<code>!pip install torch-geometric \
  torch-sparse==latest+cu101 \
  torch-scatter==latest+cu101 \
  torch-cluster==latest+cu101 \
  -f https://pytorch-geometric.com/whl/torch-1.4.0.html
</code>```

Body:
I was working on a PyTorch Geometric project using Google Colab for CUDA support. Since it's library isn't present by default, I run:

!pip install --upgrade torch-scatter
!pip install --upgrade torch-sparse
!pip install --upgrade torch-cluster
!pip install --upgrade torch-spline-conv
!pip install torch-geometric

Recently, while importing torch_geometric, owing to version upgrades, there's a CUDA version mismatch saying:

RuntimeError: Detected that PyTorch and torch_sparse were compiled with different CUDA versions. PyTorch has CUDA version 10.1 and torch_sparse has CUDA version 10.0. Please reinstall the torch_sparse that matches your PyTorch install.

To solve this, I tried using conda for specific CUDA version as:

!conda install pytorch==1.4.0 cudatoolkit=10.0 -c pytorch

Yet, on running print(torch.version.cuda), I get 10.1 as the output and not 10.0 as I wanted.

This is a recent error since it wasn't throwing up this issue in past week. Any best practice to solve this issue?

Body:
From their website

Try this

!pip install torch-geometric \
  torch-sparse==latest+cu101 \
  torch-scatter==latest+cu101 \
  torch-cluster==latest+cu101 \
  -f https://pytorch-geometric.com/whl/torch-1.4.0.html


问:
Gatekeeper/OPA constraints on a subset of namespaces without using labels
I'm using gatekeeper/OPA to create constraints for various services I have running in specific namespaces. To do so, I'm relying on namespaceSelectors to match the constraint to only a set of namespaces. My CI/CD process is responsible for labeling all my custom namespaces with the required labels that my constraint will be looking for.

However I now need to make sure that no new namespace is created without the required labels (otherwise this namespace will ignore all my constraints). The fact that my CI/CD tooling applies these labels does not allow me to be certain that no other namespace has been created in my cluster without these labels.

If I apply the k8srequiredlabels[2] constraint template on all namespaces, this will find a violation on system namespaces such as kube-system. The gatekeeper constraints allow you to specify either of the following to match your constraint[1]:

```<code>labelSelector
namespaceSelector
namespaces list
</code>```

Ideally I'd like to be able to say that I want to ensure that all namespaces have x labels on them, except the namespaces in an exclusion list (e.g kube-system). However there's no option to use the above 'Namespaces' list in an exclusive way and the other 2 options require someone to manually add labels to the newly created namespaces (which opens up room for error).

Any suggestions on how you can ensure that a subset of your clusters
namespace's have x labels without having to manually label them and
use a label/namespaceSelector?

How would you prevent a namespace from being created using OPA &
Gatekeeper if it does not meet certain criteria such as having x
label on it?

[1] https://github.com/open-policy-agent/gatekeeper/pull/131/files

[2] https://github.com/open-policy-agent/gatekeeper/blob/master/demo/agilebank/templates/k8srequiredlabels_template.yaml

答:
Problem 1 can be solved by using OPA itself. You can write mutating webhook using OPA (https://github.com/open-policy-agent/opa/issues/943) to add labels to your newly created namespaces or you can write a mutating controller (using Golang). Underneath both does the same thing.

For 2nd problem, you need to add validation rule in your rego files on namespace creation and verify if the label exists.

Extra relevant information: To perform actions on specific namespaces based on the label, you can add namesapceSelector in your validating/mutating webhook configuration.

Body:
I'm using gatekeeper/OPA to create constraints for various services I have running in specific namespaces. To do so, I'm relying on namespaceSelectors to match the constraint to only a set of namespaces. My CI/CD process is responsible for labeling all my custom namespaces with the required labels that my constraint will be looking for.

However I now need to make sure that no new namespace is created without the required labels (otherwise this namespace will ignore all my constraints). The fact that my CI/CD tooling applies these labels does not allow me to be certain that no other namespace has been created in my cluster without these labels.

If I apply the k8srequiredlabels[2] constraint template on all namespaces, this will find a violation on system namespaces such as kube-system. The gatekeeper constraints allow you to specify either of the following to match your constraint[1]:

labelSelector
namespaceSelector
namespaces list

Ideally I'd like to be able to say that I want to ensure that all namespaces have x labels on them, except the namespaces in an exclusion list (e.g kube-system). However there's no option to use the above 'Namespaces' list in an exclusive way and the other 2 options require someone to manually add labels to the newly created namespaces (which opens up room for error).

Any suggestions on how you can ensure that a subset of your clusters
namespace's have x labels without having to manually label them and
use a label/namespaceSelector?

How would you prevent a namespace from being created using OPA &
Gatekeeper if it does not meet certain criteria such as having x
label on it?

[1] https://github.com/open-policy-agent/gatekeeper/pull/131/files

[2] https://github.com/open-policy-agent/gatekeeper/blob/master/demo/agilebank/templates/k8srequiredlabels_template.yaml


问:
How do I use jquery datetimepicker with webpacker in rails 6
So far this isn't working Nothing happens when I click on the field in the form I have jquery-datetimepicker installed as a node module

application.js:

```<code>// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("jquery")
require("jquery-datetimepicker")
//require("bootstrap-datepicker")
require("js.cookie")
require("turbolinks").start()
require("@rails/activestorage").start()
require.context('../images', true)
require.context('../stylesheets/fonts', true)
require("trix")
require("@rails/actiontext")

import "bootstrap"
// import "blueimp-gallery"
import "../stylesheets/application"
document.addEventListener("turbolinks:load", () => {
  $('[data-toggle="tooltip"]').tooltip()
  $('[data-toggle="popover"]').popover()

})

import JQuery from 'jquery';
window.jQuery = $;
window.$ = $;

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
</code>```

_press_release_form.js:

```<code>$(document).ready(function () {

$('#showdate').datepicker();
$('#showtime').timepicker();

})
</code>```

答:
you are using require("jquery-datetimepicker")

it should be $('#showdate').datetimepicker() instead

```<code>document.addEventListener("turbolinks:load", () => {
  $('#showdate').datetimepicker()
})
</code>```

Body:
So far this isn't working Nothing happens when I click on the field in the form I have jquery-datetimepicker installed as a node module

application.js:

// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("jquery")
require("jquery-datetimepicker")
//require("bootstrap-datepicker")
require("js.cookie")
require("turbolinks").start()
require("@rails/activestorage").start()
require.context('../images', true)
require.context('../stylesheets/fonts', true)
require("trix")
require("@rails/actiontext")

import "bootstrap"
// import "blueimp-gallery"
import "../stylesheets/application"
document.addEventListener("turbolinks:load", () => {
  $('[data-toggle="tooltip"]').tooltip()
  $('[data-toggle="popover"]').popover()

})

import JQuery from 'jquery';
window.jQuery = $;
window.$ = $;

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)

_press_release_form.js:

$(document).ready(function () {

$('#showdate').datepicker();
$('#showtime').timepicker();

})

Body:
you are using require("jquery-datetimepicker")

it should be $('#showdate').datetimepicker() instead

document.addEventListener("turbolinks:load", () => {
  $('#showdate').datetimepicker()
})


问:
Can't find why a InputMismatchException is occurring
I am stuck in one spot on a program have that I writing that takes information from text documents and assigns them to three doubles. However, I keep getting at "Exception in thread "main java.util.InputMismatchException" error (full log below) which normally means the wrong type of variable is being asked to be inputted, but I can't seem to see why that would be the case.

Here is the log:

```<code>Enter file name: Ellipsoid_data_1.txt
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at EllipsoidListApp.main(EllipsoidListApp.java:39)
</code>```

This only one of three files, but this is where the problem is. Anything you can do to help would be fantastic, and I can provied the other files if need be.

Here is the full program:

```<code>import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
*This class prints a list of Ellipsoids.
*Comp 1210 - project 5
*Steven Manings
*Version 2/14/2020
*/

public class EllipsoidListApp {

/**
 * Reads file with ellipsoid data, creates EllipsoidList, prints EllipsoidList,
 * prints summary of EllipsoidList.
 *
 * @param args - is not used.
 * @throws FileNotFoundException required by Scanner for File
 */

   public static void main(String[] args) throws FileNotFoundException {

      ArrayList<Ellipsoid> tList = new ArrayList<Ellipsoid>();

      Scanner scan = new Scanner(System.in);
      System.out.print("Enter file name: ");
      String fileName = scan.nextLine();

      Scanner scanFile = new Scanner(new File(fileName));

      String ellipsoidListName = scanFile.nextLine();

      while (scanFile.hasNext()) {

         double a = scanFile.nextDouble();
         double b = scanFile.nextDouble();
         double c = scanFile.nextDouble();

         Ellipsoid t = new Ellipsoid(null, a , b, c);
         tList.add(t);
      }

      scanFile.close();

      EllipsoidList myEList = new EllipsoidList(ellipsoidListName, tList);

      System.out.println(myEList);

      System.out.println(myEList.summaryInfo());

   }

}

</code>```

I have gone and added the contents of the data file here:

```<code>Ellipsoid Test List
Ex 1
1
2
3
 Ex 2
2.3
5.5
7.4
Ex 3
123.4
234.5
345.6
</code>```

答:
NomadMaker is correct in the comment. After opening the file you read the list name Ellipsoid Test List by calling scanFile.nextLine(). Now the scanner is positioned at the line Ex 1. After that you enter the loop. The first thing you do in your loop is call scanFile.nextDouble(). Since your scanner is positioned at Ex and Ex does not match the syntax of a double, you get the InputMismatchException that you reported.

I think that a solution is to call nextLine() once more at the beginning of your loop to read Ex 1 (and next time Ex 2 and so forth).

This might — and I’m only guessing here — also give you something to pass in as first argument to the Ellipsoid constructor instead of null.

Body:
I am stuck in one spot on a program have that I writing that takes information from text documents and assigns them to three doubles. However, I keep getting at "Exception in thread "main java.util.InputMismatchException" error (full log below) which normally means the wrong type of variable is being asked to be inputted, but I can't seem to see why that would be the case.

Here is the log:

Enter file name: Ellipsoid_data_1.txt
Exception in thread "main" java.util.InputMismatchException
    at java.base/java.util.Scanner.throwFor(Scanner.java:939)
    at java.base/java.util.Scanner.next(Scanner.java:1594)
    at java.base/java.util.Scanner.nextDouble(Scanner.java:2564)
    at EllipsoidListApp.main(EllipsoidListApp.java:39)

This only one of three files, but this is where the problem is. Anything you can do to help would be fantastic, and I can provied the other files if need be.

Here is the full program:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;

/**
*This class prints a list of Ellipsoids.
*Comp 1210 - project 5
*Steven Manings
*Version 2/14/2020
*/

public class EllipsoidListApp {

/**
 * Reads file with ellipsoid data, creates EllipsoidList, prints EllipsoidList,
 * prints summary of EllipsoidList.
 *
 * @param args - is not used.
 * @throws FileNotFoundException required by Scanner for File
 */

   public static void main(String[] args) throws FileNotFoundException {

      ArrayList<Ellipsoid> tList = new ArrayList<Ellipsoid>();

      Scanner scan = new Scanner(System.in);
      System.out.print("Enter file name: ");
      String fileName = scan.nextLine();

      Scanner scanFile = new Scanner(new File(fileName));

      String ellipsoidListName = scanFile.nextLine();

      while (scanFile.hasNext()) {

         double a = scanFile.nextDouble();
         double b = scanFile.nextDouble();
         double c = scanFile.nextDouble();

         Ellipsoid t = new Ellipsoid(null, a , b, c);
         tList.add(t);
      }

      scanFile.close();

      EllipsoidList myEList = new EllipsoidList(ellipsoidListName, tList);

      System.out.println(myEList);

      System.out.println(myEList.summaryInfo());

   }

}

I have gone and added the contents of the data file here:

Ellipsoid Test List
Ex 1
1
2
3
 Ex 2
2.3
5.5
7.4
Ex 3
123.4
234.5
345.6