问:
create and write in binary file
I'm trying to open image in .b file, take a subpart and write in a new file in an other folder (the same were is my python script)

here is my code :

```<code>import numpy as np

for i in range(11):
    # open and read :
    filename='data/img_t'+str(i+700)+'.b'
    data=np.fromfile(filename, dtype=np.float64, sep="")
    data=data.reshape([9636,9636])
    # take a part :
    r = 2200
    c = 2200
    lenr = data.shape[0]/r
    lenc = data.shape[1]/c
    data1=np.array([data[i*r:(i+1)*r,j*c:(j+1)*c] for (i,j) in np.ndindex(lenr,lenc)]).reshape(lenr,lenc,r,c)
     # write in new file :
    outfn='img_part_'+str(i+700)+'.b'
    out_file = open(outfn, "wb")
    out_file.write(data1[1,1])
    out_file.close()
</code>```

My problem is that it only create img_part_703.b which is very strange...

I also try :

```<code>data1[1,1].tofile(outfn, sep="", format="%s")
</code>```

but same problem....

答: You are overwriting the i variable in your outer loop with the i in that inner list comprehension; I guess it ends up as 3 after the final iteration of the listcomp, so you always write to the same filename.

Title: create and write in binary file

Body:
I'm trying to open image in .b file, take a subpart and write in a new file in an other folder (the same were is my python script)

here is my code :

import numpy as np

for i in range(11):
    # open and read :
    filename='data/img_t'+str(i+700)+'.b'
    data=np.fromfile(filename, dtype=np.float64, sep="")
    data=data.reshape([9636,9636])
    # take a part :
    r = 2200
    c = 2200
    lenr = data.shape[0]/r
    lenc = data.shape[1]/c
    data1=np.array([data[i*r:(i+1)*r,j*c:(j+1)*c] for (i,j) in np.ndindex(lenr,lenc)]).reshape(lenr,lenc,r,c)
     # write in new file :
    outfn='img_part_'+str(i+700)+'.b'
    out_file = open(outfn, "wb")
    out_file.write(data1[1,1])
    out_file.close()

My problem is that it only create img_part_703.b which is very strange...

I also try :

data1[1,1].tofile(outfn, sep="", format="%s")

but same problem....


来源: stackexchange

问:
Problem when assigning a pointer to an enum variable in C
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

```<code>//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!
</code>```

答:
This is because enum error_type * isn't compatible with int *, because they point to values of different types (and possibly even different sizes).  You should declare the_go_status as:

```<code>enum error_type the_go_status;
</code>```

Although simply casting the pointer (i.e. (enum error_type *)&the_go_status) will make the warning go away, it may result in bugs on some platforms.  See Is the sizeof(enum) == sizeof(int), always?

ContentLicense: CC BY-SA 2.5

Body:
I am getting a warning of "assigment from incompatible pointer type".  I don't understand why this warning is happening. I don't know what else to declare "the_go_status" variable to other than an integer. (Note: this is not all the code, but just a simplified version I posted to illustrate the problem.)

The warning occurs on the last line of the example I included below.

//In a header file
enum error_type
{
    ERR_1 = 0,
    ERR_2 = 1,
    ERR_3 = 2,
    ERR_4 = 4,
};

//In a header file
struct error_struct
{
   int value;
   enum error_type *status;
};

//In a C file
int the_go_status;

the_go_status = ERR_1;

//Have the error_struct "status" point to the address of "the_go_status"
error_struct.status = &the_go_status;    //WARNING HERE!

Body:
This is because enum error_type * isn't compatible with int *, because they point to values of different types (and possibly even different sizes).  You should declare the_go_status as:

enum error_type the_go_status;

Although simply casting the pointer (i.e. (enum error_type *)&the_go_status) will make the warning go away, it may result in bugs on some platforms.  See Is the sizeof(enum) == sizeof(int), always?


问:
AngularJS - provider state is lost, or it's not a singleton?
bootstrap.js

```<code>angular.element(document).ready(function() {
    var auth = angular.injector(['auth', 'ngStorage', 'ng']).get('auth');
    auth.user().then(function(user){
        if (user && user.id) {
            angular.bootstrap(document, ['app']);
        }
    });
});
</code>```

auth.js

```<code>module.provider('auth', [function(){
    this.$get = ['$http', '$localStorage', function($http, $storage){
        return {
            _user: null,

            user: function(){
                var self = this;

                return $http.get('/auth/user').then(function(response){
                    self._user = response.data;
                    console.log(self._user); // <- has the user object
                    return self._user;
                });
            },
        }
    }]
}]);
</code>```

app.js

```<code>module.run(function(auth, $state){
    console.log(auth._user); // <- is null
});
</code>```

In my app, when i inject the auth service, seems like the status is lost - or, the injected auth is a a new instance (not a singleton).

Can anybody explain why?

答:
Difference between Services, Factories and Providers: https://stackoverflow.com/a/15666049/1735789

Providers

Syntax: module.provider( 'providerName', function );
Result: When declaring providerName as an injectable argument you will be provided with (new ProviderFunction()).$get(). The constructor function is instantiated before the $get method is called - ProviderFunction is the function reference passed to module.provider.

ContentLicense: CC BY-SA 3.0

Body:
bootstrap.js

angular.element(document).ready(function() {
    var auth = angular.injector(['auth', 'ngStorage', 'ng']).get('auth');
    auth.user().then(function(user){
        if (user && user.id) {
            angular.bootstrap(document, ['app']);
        }
    });
});

auth.js

module.provider('auth', [function(){
    this.$get = ['$http', '$localStorage', function($http, $storage){
        return {
            _user: null,

            user: function(){
                var self = this;

                return $http.get('/auth/user').then(function(response){
                    self._user = response.data;
                    console.log(self._user); // <- has the user object
                    return self._user;
                });
            },
        }
    }]
}]);

app.js

module.run(function(auth, $state){
    console.log(auth._user); // <- is null
});

In my app, when i inject the auth service, seems like the status is lost - or, the injected auth is a a new instance (not a singleton).

Can anybody explain why?


问:
How to retrive data in complex string using regex and grouping?
This text is a query result of a old system in an educational institution which needs to be parses and inserted in new SQL database.

```<code>1- DX 1203 /FA D0 R0   AM02XXL RAVT 1200   1330   UNQ 0 TT   Y
             H0 QB KA MC G0 O0 ZT N0 L1 EA RA TB BB
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
   ...REGISTERED BY USER021/AMIN SARVI/79/02/01...
2  D0 2743 /FB D1 R1   PM12XLL RAFT 1000   1000   UNP 0 TS   Y
             HX QX KA MX GX OX ZX NZ L1 EA R1 TB B0
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
3  DX 1151 /FA DX RX   AM02XLL RAVT 1200   1130   UNP 0 TS   N
             HA QC KX MA GA OA Z0 N0 L0 E0 R0 TX BX
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT(FAILED UNDER C)
   ...REGISTERED BY USER021/AMIN SARVI/79/02/12...
4+ DA 2081 /FX DX RX   AM22XXL RAET 1200   1330   UNQ 0 SS   N
             H0 QB KB MA GD OD Z0 NX L0 EA R0 T0 B0
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
   ...REGISTERED BY USER083/NAHID NAVABI/78/11/21...
</code>```

We want to parse this string with RegEx and grouping in c#, but for any entity exists one or two lines of description.
We succeeded in retrieving the original information, but we could not recover those lines.

Regex pattern:

```<code>((?<rownumber>[1-9])(\-|\+|\*|\s)\s*(?<unitCode>\w\w)\s*(?<studentCode>\d+)\s/(?<codeScore>(\w\w\s)+)\s*(?<time>\w\w\d\d\w\w\w)\s*(?<testCode>\w\w)(?<testState>\w\w)\s*(?<starttime>\d\d\d\d)\s*(?<endtime>\d\d\d\d)(?<addedTime>(\s|\+\d))\s*(?<commit>\w\w\w)\s*(?<retry>\d)\s*(?<equ>\w+)\s*(?<active>\w)\s*(?<codeScore1>(\w\w\s+)*))+
</code>```

A test case can be found here: regexstorm

答:
```<code>(?<rownumber>[1-9])([-+*\s])\s*(?<unitCode>\w\w)\s*(?<studentCode>\d+)\s\/(?<codeScore>(\w\w\s)+)\s*(?<time>\w\w\d\d\w\w\w)\s*((?<testCode>\w\w)(?<testState>\w\w?)\s*(?<starttime>\d\d\d\d)\s*(?<endtime>\d\d\d\d)(?<addedTime>(\s|\+\d))\s*(?<commit>\w\w\w)\s*(?<retry>\d)\s*(?<equ>\w+)\s*(?<active>\w)\s*(?<codeScore1>(\w\w\s+)*)\s*)+(?<comments>(\r?\n\s+[^\r\n]*)+)
</code>```

Something like this?

Basically, I fixed up the original regex so it matched your sample data (testCode and testState cannot be four characters combined, since there are only three characters there), then added (?<comments>(\r\n\s+[^\r\n]*)*) to the end. That matches any sequences of linebreaks, indentation, then comments.

This assumes that the first data line won't begin with a space.

See it in action here (regexstorm site won't let me link to it very well): https://regex101.com/r/WkTyP0/2

Body:
This text is a query result of a old system in an educational institution which needs to be parses and inserted in new SQL database.

1- DX 1203 /FA D0 R0   AM02XXL RAVT 1200   1330   UNQ 0 TT   Y
             H0 QB KA MC G0 O0 ZT N0 L1 EA RA TB BB
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
   ...REGISTERED BY USER021/AMIN SARVI/79/02/01...
2  D0 2743 /FB D1 R1   PM12XLL RAFT 1000   1000   UNP 0 TS   Y
             HX QX KA MX GX OX ZX NZ L1 EA R1 TB B0
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
3  DX 1151 /FA DX RX   AM02XLL RAVT 1200   1130   UNP 0 TS   N
             HA QC KX MA GA OA Z0 N0 L0 E0 R0 TX BX
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT(FAILED UNDER C)
   ...REGISTERED BY USER021/AMIN SARVI/79/02/12...
4+ DA 2081 /FX DX RX   AM22XXL RAET 1200   1330   UNQ 0 SS   N
             H0 QB KB MA GD OD Z0 NX L0 EA R0 T0 B0
      TEST MAY 2001 AND RESULT SEND TO ANALYS UNIT
   ...REGISTERED BY USER083/NAHID NAVABI/78/11/21...

We want to parse this string with RegEx and grouping in c#, but for any entity exists one or two lines of description.
We succeeded in retrieving the original information, but we could not recover those lines.

Regex pattern:

((?<rownumber>[1-9])(\-|\+|\*|\s)\s*(?<unitCode>\w\w)\s*(?<studentCode>\d+)\s/(?<codeScore>(\w\w\s)+)\s*(?<time>\w\w\d\d\w\w\w)\s*(?<testCode>\w\w)(?<testState>\w\w)\s*(?<starttime>\d\d\d\d)\s*(?<endtime>\d\d\d\d)(?<addedTime>(\s|\+\d))\s*(?<commit>\w\w\w)\s*(?<retry>\d)\s*(?<equ>\w+)\s*(?<active>\w)\s*(?<codeScore1>(\w\w\s+)*))+

A test case can be found here: regexstorm

Body:
(?<rownumber>[1-9])([-+*\s])\s*(?<unitCode>\w\w)\s*(?<studentCode>\d+)\s\/(?<codeScore>(\w\w\s)+)\s*(?<time>\w\w\d\d\w\w\w)\s*((?<testCode>\w\w)(?<testState>\w\w?)\s*(?<starttime>\d\d\d\d)\s*(?<endtime>\d\d\d\d)(?<addedTime>(\s|\+\d))\s*(?<commit>\w\w\w)\s*(?<retry>\d)\s*(?<equ>\w+)\s*(?<active>\w)\s*(?<codeScore1>(\w\w\s+)*)\s*)+(?<comments>(\r?\n\s+[^\r\n]*)+)

Something like this?

Basically, I fixed up the original regex so it matched your sample data (testCode and testState cannot be four characters combined, since there are only three characters there), then added (?<comments>(\r\n\s+[^\r\n]*)*) to the end. That matches any sequences of linebreaks, indentation, then comments.

This assumes that the first data line won't begin with a space.

See it in action here (regexstorm site won't let me link to it very well): https://regex101.com/r/WkTyP0/2


问:
How to create an integer or number from array of digits or string of digits in JavaScript
I want to create an integer or number that contains all the digits from an array of digits or string. How can I achieve that ?

for example:

```<code>digitArry = [9', '8', '7', '4', '5', '6'];
</code>```

should become

```<code>integer = 987456;
</code>```

答:
You can use join and parseInt:

var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = parseInt(digitArry.join(''), 10);

console.log(integer);```
</div>
</div>
</p>

<p>EDIT: As suggested by @kay, another alternative is using <code>+</code> to convert string to number:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = +digitArry.join('');

console.log(integer);</code>```

Body:
I want to create an integer or number that contains all the digits from an array of digits or string. How can I achieve that ?

for example:

digitArry = [9', '8', '7', '4', '5', '6'];

should become

integer = 987456;

Body:
You can use join and parseInt:

var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = parseInt(digitArry.join(''), 10);

console.log(integer);

EDIT: As suggested by @kay, another alternative is using + to convert string to number:

var digitArry = ['9', '8', '7', '4', '5', '6'];
var integer = +digitArry.join('');

console.log(integer);


问:
Breaking a form with a partial
I have this form made by rails scaffold:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :objective %><br>
    <%= f.cktext_area :objective %>
  </div>
  <div class="field">
    <%= f.label :settings %><br>
    <%= f.cktext_area :settings %>
  </div>
  <div class="field">
    <%= f.label :related_documents %><br>
    <%= f.cktext_area :related_documents %>
  </div>
  <div class="field">
    <%= f.label :responsability %><br>
    <%= f.cktext_area :responsability %>
  </div>
  <div class="field">
    <%= f.label :material_needed %><br>
    <%= f.cktext_area :material_needed %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.cktext_area :description %>
  </div>
  <div class="field">
    <%= f.label :preventive_measures %><br>
    <%= f.cktext_area :preventive_measures %>
  </div>
  <div class="field">
    <%= f.label :corrective_actions %><br>
    <%= f.cktext_area :corrective_actions %>
  </div>
  <div class="field">
    <%= f.label :execution %><br>
    <%= f.cktext_area :execution %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

```<code><%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:</h2>

      <ul>
      <% @archive.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

<%= render partial 'fields', 'field_name' %>

 <!-- Call many times and pass the field name -->

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
</code>```

partial:

```<code>  <div class="field">
    <%= f.label :field_name%><br>
    <%= f.cktext_area :field_name %>
  </div>
</code>```

答:
You probably have to pass f into the partial...

<%= render partial 'fields', locals: { f: f } %>

You could possibly iterate over a list of attributes you want to render your fields partial for and pass the current iteration into the partial:

```<code><% %w(objective settings related_documents).each do |field| %>
    <%= render partial 'fields', locals: { f: f, field: field } %>
<% end %>
</code>```

partial

```<code><div class="field">
    <%= f.label field.to_sym %><br>
    <%= f.cktext_area field.to_sym %>
</div>
</code>```

Title: Breaking a form with a partial

Body:
I have this form made by rails scaffold:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

    <%= f.label :objective %>

    <%= f.cktext_area :objective %>

    <%= f.label :settings %>

    <%= f.cktext_area :settings %>

    <%= f.label :related_documents %>

    <%= f.cktext_area :related_documents %>

    <%= f.label :responsability %>

    <%= f.cktext_area :responsability %>

    <%= f.label :material_needed %>

    <%= f.cktext_area :material_needed %>

    <%= f.label :description %>

    <%= f.cktext_area :description %>

    <%= f.label :preventive_measures %>

    <%= f.cktext_area :preventive_measures %>

    <%= f.label :corrective_actions %>

    <%= f.cktext_area :corrective_actions %>

    <%= f.label :execution %>

    <%= f.cktext_area :execution %>

    <%= f.submit %>

<% end %>

And I wanted to separate the fields, I wanted to use partials because it keeps repeating, what changes is the name of the field, I wanted to render the partial form of a field and pass the field name. Because of the fact that I'm going to use the custom ckeditor, and I'll keep repeating on the form, it may give the error chance. Am I right to think that? Is my idea correct? If so, how can I do to pass the field? Will this influence something in the database?
I wanted to do something like this.

form:

<%= form_for(@archive) do |f| %>
  <% if @archive.errors.any? %>

<%= pluralize(@archive.errors.count, "error") %> prohibited this archive from being saved:

      <% @archive.errors.full_messages.each do |message| %>

<%= message %>

      <% end %>

  <% end %>

<%= render partial 'fields', 'field_name' %>

    <%= f.submit %>

<% end %>

partial:

    <%= f.label :field_name%>

    <%= f.cktext_area :field_name %>

Body:
You probably have to pass f into the partial...

<%= render partial 'fields', locals: { f: f } %>

You could possibly iterate over a list of attributes you want to render your fields partial for and pass the current iteration into the partial:

<% %w(objective settings related_documents).each do |field| %>
    <%= render partial 'fields', locals: { f: f, field: field } %>
<% end %>

partial

<div class="field">
    <%= f.label field.to_sym %><br>
    <%= f.cktext_area field.to_sym %>
</div>


问:
Spring boot java.util.MissingResourceException while accessing properties file
In spring boot application i have the below code for accessing the properties file(errors.properties), when I access the code it gives the below exception:

```<code>exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties
</code>```

the errors.properties file is under src/main/resources/

Below is the code

```<code>@Configuration
@PropertySource("classpath:errors.properties") // tried with both the annotations
@ConfigurationProperties("classpath:errors.properties") //  tried with both the annotations
public class ApplicationProperties {

    public static String getProperty(final String key) {
        ResourceBundle bundle = ResourceBundle.getBundle("errors.properties");
        return bundle.getString(key);
    }
}
</code>```

I am not able to understand why its not picking up the errors.properties file under resources folder, could somebody please help me?

答:
This question is not specific to Spring Boot, as the exception is thrown by ResourceBundle.

When using ResourceBundle.getBundle() method you should not specify the extension of the file based on the documentation, it will be appended automatically.

So the correct usage is:

```<code>ResourceBundle.getBundle("errors");
</code>```

Note: For localization in Spring Boot you probably should use MessageSource instead of Java ResourceBundle.

The PropertySource annotation probably worked, otherwise it would have thrown an exception on context startup (since ignoreResourceNotFound is not set to false), you can inject the values from your error.properties file using the @Value annotation to any Spring bean.
For example

```<code>@Configuration
@PropertySource("classpath:error.properties")
public class ApplicationProperties {

    @Value("${property.in.errors.properties}")
    private String propertyValue;

    @PostConstruct
    public void writeProperty() {
        System.out.println(propertyValue);
    }
}
</code>```

If you cannot see the property value, make sure that your ComponentScan includes this configuration.

Alternatively you can inject Environment directly to beans and use getProperty() as per Sudhakar's answer.

Body:
In spring boot application i have the below code for accessing the properties file(errors.properties), when I access the code it gives the below exception:

exception":"java.util.MissingResourceException","message":"Can't find bundle for base name errors.properties

the errors.properties file is under src/main/resources/

Below is the code

@Configuration
@PropertySource("classpath:errors.properties") // tried with both the annotations
@ConfigurationProperties("classpath:errors.properties") //  tried with both the annotations
public class ApplicationProperties {

    public static String getProperty(final String key) {
        ResourceBundle bundle = ResourceBundle.getBundle("errors.properties");
        return bundle.getString(key);
    }
}

I am not able to understand why its not picking up the errors.properties file under resources folder, could somebody please help me?

Body:
This question is not specific to Spring Boot, as the exception is thrown by ResourceBundle.

When using ResourceBundle.getBundle() method you should not specify the extension of the file based on the documentation, it will be appended automatically.

So the correct usage is:

ResourceBundle.getBundle("errors");

Note: For localization in Spring Boot you probably should use MessageSource instead of Java ResourceBundle.

The PropertySource annotation probably worked, otherwise it would have thrown an exception on context startup (since ignoreResourceNotFound is not set to false), you can inject the values from your error.properties file using the @Value annotation to any Spring bean.
For example

@Configuration
@PropertySource("classpath:error.properties")
public class ApplicationProperties {

    @Value("${property.in.errors.properties}")
    private String propertyValue;

    @PostConstruct
    public void writeProperty() {
        System.out.println(propertyValue);
    }
}

If you cannot see the property value, make sure that your ComponentScan includes this configuration.

Alternatively you can inject Environment directly to beans and use getProperty() as per Sudhakar's answer.


问:
Can a progressive web app be registered as a share option in Android?
Total newbie question.

Tl;dr - Can a progressive web app be registered as a share option in Android?

In Android, we can “Share” things to other installed Android apps. For example, let’s say I have Chrome for Android and the Google+ app installed on my Android device. I can share a web site which I am viewing in Chrome to Google+ by going to Chrome’s hamburger menu → Share… → Google+ (with a list of other installed native apps). Can a progressive web app be registered in this list of installed native apps?
If yes, can you show me some examples or code labs?
If no, is this feature in progressive web app or Android’s roadmap?

答:
This has been available since Feb 2017, according to this article:
https://blog.chromium.org/2017/02/integrating-progressive-web-apps-deeply.html

This works on Chrome 71+ on Android only.

You have to add this block into your PWA's manifest.json:

```<code>"share_target":
{
  "action": "/share",
  "params":
  {
    "title": "title",
    "text": "text",
    "url": "url"
  }
}
</code>```

Body:
This has been available since Feb 2017, according to this article:
https://blog.chromium.org/2017/02/integrating-progressive-web-apps-deeply.html

This works on Chrome 71+ on Android only.

You have to add this block into your PWA's manifest.json:

"share_target":
{
  "action": "/share",
  "params":
  {
    "title": "title",
    "text": "text",
    "url": "url"
  }
}

ContentLicense: CC BY-SA 4.0


问:
jQuery - Given a DIV with a bunch of
 tags, how to find the first
 that isn't empty
Given a DIV with a lot of paragraph tags:

```<code><div>
 <p></p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
 <p>ADSADASAD ADS ADS  A </p>
</div>
</code>```

How to magically find the first
 which isn't empty using just jQUery? ideas?

答:
You can use the :not selector with the :empty selector, like so:

```<code>var notEmpty = $('#container').find('p:not(:empty):first');
// or
var notEmpty = $('#container > p:not(:empty):first');
</code>```

Live example

The above uses an ID to find the container of the divs, but of course this is jQuery, you can use any selector.

Title: jQuery - Given a DIV with a bunch of <P> tags, how to find the first <P> that isn't empty

Body:
Given a DIV with a lot of paragraph tags:

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

ADSADASAD ADS ADS  A

How to magically find the first
 which isn't empty using just jQUery? ideas?

Body:
You can use the :not selector with the :empty selector, like so:

var notEmpty = $('#container').find('p:not(:empty):first');
// or
var notEmpty = $('#container > p:not(:empty):first');

Live example

The above uses an ID to find the container of the divs, but of course this is jQuery, you can use any selector.


问:
Printing Out File Names that are Different
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

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

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}
</code>```

答:
After you've created and populated both the lists, use the following code :-

```<code>for(String fileName : fileNames1)
{
 if(!fileNames2.contains(fileName))
   {
     System.out.println(fileName + " is not in both");
   }
 else
   {
     System.out.println(fileName + " is in both the lists");
   }
}
</code>```

What this code does is that for each fileName in the first ArrayList it checks if the second ArrayList contains the same file name or not, and prints the output accordingly.

Body:
My code below works and the logic works. However, I want to print out the names of the actual files that are not the same in both folders, which are held in the arrays of fileNames1 and fileNames2. I have been searching for the answer with no solution. I am just getting back into the groove with Java after being away form it a while. Any help would be appreciated.

import java.io.File;
import java.util.ArrayList;

public class nameCompare {

    public static void main(String[] args) {

        String path1 = "C:/Users/hoflerj/Desktop/test";
        String path2 = "C:/Users/hoflerj/Desktop/test2";

        File folder1 = new File(path1);
        File folder2 = new File(path2);

        File[] listOfFiles1 = folder1.listFiles();
        File[] listOfFiles2 = folder2.listFiles();

        ArrayList<String> fileNames1 = new ArrayList<String>();
        ArrayList<String> fileNames2 = new ArrayList<String>();

        for (int i = 0; i < listOfFiles1.length; i++)
        {

            if (listOfFiles1[i].isFile())
            {
                fileNames1.add(listOfFiles1[i].getName());//wow
            }
        }

        for (int i = 0; i < listOfFiles2.length; i++)
        {

            if (listOfFiles2[i].isFile())
            {
                fileNames2.add(listOfFiles2[i].getName());//seriously wow
            }
        }

        for ( int i = 0; i < 1; i++ )
        {
            if (fileNames1.equals(fileNames2) )
            {
                System.out.println("Files names are the same");
            }

            else if (fileNames1 != fileNames2 )
            {
                System.out.println("Files names are not equal");
            }
        }

    }

}

Body:
After you've created and populated both the lists, use the following code :-

for(String fileName : fileNames1)
{
 if(!fileNames2.contains(fileName))
   {
     System.out.println(fileName + " is not in both");
   }
 else
   {
     System.out.println(fileName + " is in both the lists");
   }
}

What this code does is that for each fileName in the first ArrayList it checks if the second ArrayList contains the same file name or not, and prints the output accordingly.


问:
SQL conditional select with for/while loop
This is the table:

```<code>Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent
</code>```

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

```<code>A - Urgent
B - Normal
C - Urgent
</code>```

答:
Another way to do this with SQL would be to simply get the MAX(Priority) for each Order_ID and join back to that table using a SUBSELECT:

```<code>SELECT  x.ORDER_ID + ' - ' + x.Status AS [Output],
    x.Priority ,
    x.Status
FROM    ( SELECT    Order_ID AS Order_ID ,
                MAX(Priority) AS [Priority]
      FROM      @your_table
      GROUP BY ORDER_ID
    ) t
    JOIN @your_table x ON x.Order_ID = t.Order_ID
                       AND x.[Priority] = t.[Priority];
</code>```

Where @your_table is whatever the name of your table is.

This is the output of the query:

```<code>Output      Priority    Status
A - Urgent  4           Urgent
B - Normal  7           Normal
C - Urgent  9           Urgent
</code>```

Body:
This is the table:

Order_ID|Priority|Status
A       |3       |Normal
A       |4       |Urgent
B       |6       |Urgent
B       |7       |Normal
C       |8       |Normal
C       |9       |Urgent

How do I select the Order_ID and Status where a row's priority is higher for that ID? For example, in this case, the output of the query given the above data should be:

A - Urgent
B - Normal
C - Urgent

Body:
Another way to do this with SQL would be to simply get the MAX(Priority) for each Order_ID and join back to that table using a SUBSELECT:

SELECT  x.ORDER_ID + ' - ' + x.Status AS [Output],
    x.Priority ,
    x.Status
FROM    ( SELECT    Order_ID AS Order_ID ,
                MAX(Priority) AS [Priority]
      FROM      @your_table
      GROUP BY ORDER_ID
    ) t
    JOIN @your_table x ON x.Order_ID = t.Order_ID
                       AND x.[Priority] = t.[Priority];

Where @your_table is whatever the name of your table is.

This is the output of the query:

Output      Priority    Status
A - Urgent  4           Urgent
B - Normal  7           Normal
C - Urgent  9           Urgent


问:
Best package for scraping HTML with Python from site that needs cookies enabled
I am currently using Python 3.6 to crawl a file of URLs and search for a certain string. After running the script, the HTML returned indicated that cookies needed to be enabled. Mechanize and every other library I find is not supported for any versions of python 3.x. Can someone point me in the right direction of libraries that can enable cookies so the correct HTML is rendered? </p>

答:
You can both retrieve and send cookies with the awesome requests package.

Sending cookies:

```<code>cookies = {
    cookies_are:'working'
    }

requests.get(url, cookies=cookies)
</code>```

Retrieving cookies:

```<code>r = requests.get(url)
r.cookies #return a dictionary
</code>```

More information check out the requests documentation. Hope it helps!

Body:
You can both retrieve and send cookies with the awesome requests package.

Sending cookies:

cookies = {
    cookies_are:'working'
    }

requests.get(url, cookies=cookies)

Retrieving cookies:

r = requests.get(url)
r.cookies #return a dictionary

More information check out the requests documentation. Hope it helps!


问:
Sudden ArgumentError: invalid byte sequence in UTF-8 while seeding
While working on my Rails app I was experimenting with some way to crop images, I went from Rails Casts #182 , back to what I previously had and then to this blog post, after finishing setting all up, I decided to restart my database and seed it, however I got ArgumentError: invalid byte sequence in UTF-8 when I tried to seed my db.

I've never encountered this error before and after some small research I found this is due to some characters not being able to be read by ruby, however, after skimming my code I've found no difference between what I had before I started with cropping images and after further examining I've yet to find the cause.

It also doesn't help that I've yet to learn how to read and trace rails/rake bugs, here is what I get:

```<code>rails aborted!
ArgumentError: invalid byte sequence in UTF-8
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `==='
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `blank?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:131:in `is_path?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:97:in `size'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:140:in `empty?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/uploader/cache.rb:120:in `cache!'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:44:in `block in cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `map'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mount.rb:300:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/orm/activerecord.rb:70:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `public_send'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/core.rb:319:in `initialize'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/persistence.rb:50:in `create!'
/home/ubuntu/workspace/db/seeds.rb:60:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/engine.rb:549:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/railties/databases.rake:196:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
/home/ubuntu/workspace/bin/rails:9:in `require'
/home/ubuntu/workspace/bin/rails:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'
/home/ubuntu/workspace/bin/spring:15:in `require'
/home/ubuntu/workspace/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `<main>'
Tasks: TOP => db:seed
(See full trace by running task with --trace)
</code>```

My main question is where exactly could this error be happening? so far I've learned through experience that it could be either the seeds.rb or the model( in this case event.rb) however I don't see anything different and I had them both working before, I was even able to upload images and seed them no problem until I implemented and removed the code from the Rails Cast and implemented the code in the blog post, any direction into the solution will be of great help.

Here is the seed from the model, it was working fine beforehand.

```<code>Event.create!(
    name: "  1",
    spanish_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    english_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    place_name: "mamita's",
    place_type: "beach club",
    address: "Calle 28 Norte Mza 10, Lote 8, Centro",
    county: 'meh',
    city: "Playa del Carmen",
    state: "Quintana Roo",
    postal_code: 77710,

    user_id: 1,
    main_image: File.open(File.join(Rails.root, 'test.jpg')),
    sub_images: [File.open(File.join(Rails.root, 'chinchi.jpg'))],

    eventdates_attributes:[{
      start_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      finish_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      start_hour: "08:00am",
      finish_hour: "11:00am",
    }],

    tickets_attributes:[{
      ticket_type: "Solo una vez",
      price: 100,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }, {
      ticket_type: "Otra vez",
      price: 150,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }]
)
</code>```

IMPORTANT EDIT: So I decided to just return to previous commits just to not deal with this problem anymore, and for some reason the error keeps popping up, which leads me to believe there is a problem with the platform I'm using, which is Cloud9, I've also read this isn't a problem that should be happening on Rails 5.0

答: I found the cause of the problem, I was using mount_uploaders for a singular upload, making the upload an array and thus creating the error. changing it to mount_uploader was the solution, you really have to pay attention to these details, well, lesson learned. I'd advise to close this question unless it's somewhat useful for newcomers.

Body:
While working on my Rails app I was experimenting with some way to crop images, I went from Rails Casts #182 , back to what I previously had and then to this blog post, after finishing setting all up, I decided to restart my database and seed it, however I got ArgumentError: invalid byte sequence in UTF-8 when I tried to seed my db.

I've never encountered this error before and after some small research I found this is due to some characters not being able to be read by ruby, however, after skimming my code I've found no difference between what I had before I started with cropping images and after further examining I've yet to find the cause.

It also doesn't help that I've yet to learn how to read and trace rails/rake bugs, here is what I get:

rails aborted!
ArgumentError: invalid byte sequence in UTF-8
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `==='
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/core_ext/object/blank.rb:118:in `blank?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:131:in `is_path?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:97:in `size'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/sanitized_file.rb:140:in `empty?'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/uploader/cache.rb:120:in `cache!'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:44:in `block in cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `map'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mounter.rb:42:in `cache'
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/mount.rb:300:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/carrierwave-1.1.0/lib/carrierwave/orm/activerecord.rb:70:in `main_image='
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `public_send'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:46:in `_assign_attribute'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:40:in `block in _assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `each'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:39:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/attribute_assignment.rb:26:in `_assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activemodel-5.0.1/lib/active_model/attribute_assignment.rb:33:in `assign_attributes'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/core.rb:319:in `initialize'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/inheritance.rb:65:in `new'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/persistence.rb:50:in `create!'
/home/ubuntu/workspace/db/seeds.rb:60:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `block in load'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:259:in `load_dependency'
/usr/local/rvm/gems/ruby-2.3.0/gems/activesupport-5.0.1/lib/active_support/dependencies.rb:287:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/engine.rb:549:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/tasks/database_tasks.rb:268:in `load_seed'
/usr/local/rvm/gems/ruby-2.3.0/gems/activerecord-5.0.1/lib/active_record/railties/databases.rake:196:in `block (2 levels) in <top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:14:in `block in run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/rake_proxy.rb:11:in `run_rake_task'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands/commands_tasks.rb:51:in `run_command!'
/usr/local/rvm/gems/ruby-2.3.0/gems/railties-5.0.1/lib/rails/commands.rb:18:in `<top (required)>'
/home/ubuntu/workspace/bin/rails:9:in `require'
/home/ubuntu/workspace/bin/rails:9:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/rails.rb:28:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client/command.rb:7:in `call'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/client.rb:30:in `run'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/bin/spring:49:in `<top (required)>'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `load'
/usr/local/rvm/gems/ruby-2.3.0/gems/spring-1.7.2/lib/spring/binstub.rb:11:in `<top (required)>'
/home/ubuntu/workspace/bin/spring:15:in `require'
/home/ubuntu/workspace/bin/spring:15:in `<top (required)>'
bin/rails:3:in `load'
bin/rails:3:in `'
Tasks: TOP => db:seed
(See full trace by running task with --trace)

My main question is where exactly could this error be happening? so far I've learned through experience that it could be either the seeds.rb or the model( in this case event.rb) however I don't see anything different and I had them both working before, I was even able to upload images and seed them no problem until I implemented and removed the code from the Rails Cast and implemented the code in the blog post, any direction into the solution will be of great help.

Here is the seed from the model, it was working fine beforehand.

Event.create!(
    name: "  1",
    spanish_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    english_description: "El mejor programa para este sábado con los peques ! #kids #gratis #petfriendly. En Kuchitril. De 6 a 10 pm. #localmarket #tendencias #buenavibra. #corranlavoz!",
    place_name: "mamita's",
    place_type: "beach club",
    address: "Calle 28 Norte Mza 10, Lote 8, Centro",
    county: 'meh',
    city: "Playa del Carmen",
    state: "Quintana Roo",
    postal_code: 77710,

    user_id: 1,
    main_image: File.open(File.join(Rails.root, 'test.jpg')),
    sub_images: [File.open(File.join(Rails.root, 'chinchi.jpg'))],

    eventdates_attributes:[{
      start_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      finish_date: Time.now.in_time_zone("Eastern Time (US & Canada)"),
      start_hour: "08:00am",
      finish_hour: "11:00am",
    }],

    tickets_attributes:[{
      ticket_type: "Solo una vez",
      price: 100,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }, {
      ticket_type: "Otra vez",
      price: 150,
      currency: "mxn",
      quantity: 150,
      description: "Un boleto muy divertido!"
    }]
)

IMPORTANT EDIT: So I decided to just return to previous commits just to not deal with this problem anymore, and for some reason the error keeps popping up, which leads me to believe there is a problem with the platform I'm using, which is Cloud9, I've also read this isn't a problem that should be happening on Rails 5.0


问:
website dropbdown button component name
Does anyone know the name of the of the a webpage component which acts as an expandable read-only textarea.

So basically, the component initially looks like a button with a title and an arrow marker indicating that there is more to view if the user clicks below, then once the user clicks on the arrow, the button's area expands and displays text below.

I know this is vague but any references or ideas would be helpful

答:
accordion (may be) here is an example
https://bootsnipp.com/snippets/featured/accordion-menu

here is an example of text only accordion

```<code>https://bootsnipp.com/snippets/l1bPQ
</code>```

Title: website dropbdown button component name

Body:
accordion (may be) here is an example
https://bootsnipp.com/snippets/featured/accordion-menu

here is an example of text only accordion

https://bootsnipp.com/snippets/l1bPQ


问:
Javascript Regex - get div IDs from string html
Consider the following code:

```<code>const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})
</code>```

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

答:
This answer explains an approach to getting DOM information from a string of HTML without the need for Regular Expressions (prone to bugs and errors when parsing DOM).

I am using a simple library (html-fragment) to create a DocumentFragment from the string of HTML. Since that string becomes a simple DOM tree in memory, you can querySelectorAll elements with the id attribute. You can then map the elements to get the array of ids.

const content = "

Lorem Ipsum

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

";

const fragment = HtmlFragment(content);
let ids = Array
  .from(fragment.querySelectorAll('[id]'))
  .map(el => el.id);

console.log(ids);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script></code>```

Body:
Consider the following code:

const content = "

Lorem Ipsum

is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s

"

let ids = content.match(/id='(.*?)'/g).map((val) => {
    return val.replace(/id='/g,'');
})

And when I do console.log(ids) - I get the output like this 'x\'' but I need only 'x'. I'm wondering how to achive that result, I've tried by randomly changing regex symbols, because I don't know regex at all - and nothing seems to be working.

No jquery please. Thank you in advance

Body:
This answer explains an approach to getting DOM information from a string of HTML without the need for Regular Expressions (prone to bugs and errors when parsing DOM).

I am using a simple library (html-fragment) to create a DocumentFragment from the string of HTML. Since that string becomes a simple DOM tree in memory, you can querySelectorAll elements with the id attribute. You can then map the elements to get the array of ids.

const content = "<div id='x'><h2>Lorem Ipsum</h2> <p>is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p></div>";

const fragment = HtmlFragment(content);
let ids = Array
  .from(fragment.querySelectorAll('[id]'))
  .map(el => el.id);

console.log(ids);

<script src="https://unpkg.com/html-fragment@1.1.0/lib/html-fragment.min.js"></script>


问:
How to get Excel 2010 to automatically change the row numbers in a function
I am computing a final report and I need to compute the value of a specific column in a spreadsheet of 150 rows

The function which i wrote is

```<code>=((SUM(I6:W6)/75)*.35*4)+(Y6*.1)+(Z6*.15)+(AA6*.3)+((AB6*4)/10 *.1)
</code>```

is working fine but then I am forced to copy it to each row of that specific column and update the row numbers to get the correct answer.

For example ,if I wanted to calculate the value for row number 16 for that column,I would have to manually enter this :

```<code>=((SUM(I16:W16)/75)*.35*4)+(Y16*.1)+(Z16*.15)+(AA16*.3)+((AB16*4)/10 *.1)
</code>```

This process is going to take a lot of time if I do it for all the records,any inputs on how to automatically get excel to update the row numbers ?

Thanks !!

答: Just double-click the lower-right-little-black-square that will appear on the cell containing the formula</p>

Body:
I am computing a final report and I need to compute the value of a specific column in a spreadsheet of 150 rows

The function which i wrote is

=((SUM(I6:W6)/75)*.35*4)+(Y6*.1)+(Z6*.15)+(AA6*.3)+((AB6*4)/10 *.1)

is working fine but then I am forced to copy it to each row of that specific column and update the row numbers to get the correct answer.

For example ,if I wanted to calculate the value for row number 16 for that column,I would have to manually enter this :

=((SUM(I16:W16)/75)*.35*4)+(Y16*.1)+(Z16*.15)+(AA16*.3)+((AB16*4)/10 *.1)

This process is going to take a lot of time if I do it for all the records,any inputs on how to automatically get excel to update the row numbers ?

Thanks !!


问:
iOS 11 navigationItem.titleView Width Not Set
Seeing a behavior on iOS11 with a navigationItem.titleView where the width of the titleView is not the full width of the screen.

I have a custom view that I set as the titleView. Previous to iOS11 the view would fill the navigation bar area. But iOS 11 it is not resizing to fill the width of the screen.

I've tried setting the frame of the view before setting titleView but no luck. I've tried to force the titleViews superview to layout constraints as well but no luck.

Screenshots attached:

iOS10:

iOS11:

Anyone else experience this?

答:
I figured it out. I had to override the intrinsicContentSize getter for the view, and the text field.

I set the width to CGFloat.greatestFiniteMagnitude so it'll always be as wide as the screen.

Update:

Since I've spent couple of hours on this issue, hope that some else will catch up faster by having all things tight up together

I've created a custom sub class of TitleView, called CustomTitleView, here's the code:

```<code>import UIKit

class CustomTitleView: UIView {

  override var intrinsicContentSize: CGSize {
    return UIView.layoutFittingExpandedSize
  }
}
</code>```

and the most important part which I missed from the start was this:

Body:
I figured it out. I had to override the intrinsicContentSize getter for the view, and the text field.

I set the width to CGFloat.greatestFiniteMagnitude so it'll always be as wide as the screen.

Update:

Since I've spent couple of hours on this issue, hope that some else will catch up faster by having all things tight up together

I've created a custom sub class of TitleView, called CustomTitleView, here's the code:

import UIKit

class CustomTitleView: UIView {

  override var intrinsicContentSize: CGSize {
    return UIView.layoutFittingExpandedSize
  }
}

and the most important part which I missed from the start was this:


问:
Why does changing the order of variable definitions change the functioning of code
There is two code written in Dev-c++ first one is working properly and another one is not, Why??

```<code>/* this code is working properly*/

#include<stdio.h>
int main()
{
    char op;    // this is the point
    int a,b,c;  // where another code differs
    printf("Enter the two no.s:");
    scanf("%d %d",&a,&b);
    printf("Enter the operation(+/-/*//):");
    scanf("%s",&op);
    switch(op)
    {
     case '+': c=a+b;
               printf("%d",c);
               break;

     case '-': c=a-b;
               printf("%d",c);
               break;

     case '*': c=a*b;
               printf("%d",c);
               break;

     case '/': c=a/b;
               printf("%d",c);
               break;

     default: printf("Invalid Operation");
     }
}
</code>```

```<code>/* this code is not working properly; only altered the declaration sequence of int and char*/

#include<stdio.h>
int main()
{
     int a,b,c;
     char op;
     printf("Enter the a:");
     scanf("%d %d",&a,&b);
     printf("Enter the operation(+/-/*//):");
     scanf("%s",&op);
     switch(op)
     {
     case '+' : c=a+b;
               printf("%d",c);
               break;

     case '-' : c=a-b;
               printf("%d",c);
               break;

     case '*' : c=a*b;
               printf("%d",c);
               break;

     case '/' : c=a/b;
               printf("%d",c);
               break;

     default: printf("Invalid Operation");
     }
}
</code>```

答:
Here's your problem:

```<code>scanf("%s",&op);
</code>```

The %s format specifier expects a pointer to the first character of an array that can store a string.  What you're passing in is the address of a single character.

As a result, when you enter a symbol such as +, this gets written to op, but then a null byte is written to whatever memory happens to be next after op to complete the string.  By writing to memory you're not supposed to, this invokes undefined behavior.

With undefined behavior, anything can happen.   You program may crash, it may show unexpected results, or it may appear to work properly.  Also, making a seemingly unrelated change such as adding a printf for debugging or (as in your case) changing the order of variables can change the way undefined behavior manifests itself.

To read a single character, you need to use the %c format specifier.  You'll also need to add a space to the format string before it to consume whitespace, namely the newline from the prior scanf call.  This is needed because %c does not skip whitespace by itself, unlike other format specifiers such as %d or %s.

```<code>scanf(" %c",&op);
</code>```

Body:
There is two code written in Dev-c++ first one is working properly and another one is not, Why??

/* this code is working properly*/

#include<stdio.h>
int main()
{
    char op;    // this is the point
    int a,b,c;  // where another code differs
    printf("Enter the two no.s:");
    scanf("%d %d",&a,&b);
    printf("Enter the operation(+/-/*//):");
    scanf("%s",&op);
    switch(op)
    {
     case '+': c=a+b;
               printf("%d",c);
               break;

     case '-': c=a-b;
               printf("%d",c);
               break;

     case '*': c=a*b;
               printf("%d",c);
               break;

     case '/': c=a/b;
               printf("%d",c);
               break;

     default: printf("Invalid Operation");
     }
}

/* this code is not working properly; only altered the declaration sequence of int and char*/

#include<stdio.h>
int main()
{
     int a,b,c;
     char op;
     printf("Enter the a:");
     scanf("%d %d",&a,&b);
     printf("Enter the operation(+/-/*//):");
     scanf("%s",&op);
     switch(op)
     {
     case '+' : c=a+b;
               printf("%d",c);
               break;

     case '-' : c=a-b;
               printf("%d",c);
               break;

     case '*' : c=a*b;
               printf("%d",c);
               break;

     case '/' : c=a/b;
               printf("%d",c);
               break;

     default: printf("Invalid Operation");
     }
}

Body:
Here's your problem:

scanf("%s",&op);

The %s format specifier expects a pointer to the first character of an array that can store a string.  What you're passing in is the address of a single character.

As a result, when you enter a symbol such as +, this gets written to op, but then a null byte is written to whatever memory happens to be next after op to complete the string.  By writing to memory you're not supposed to, this invokes undefined behavior.

With undefined behavior, anything can happen.   You program may crash, it may show unexpected results, or it may appear to work properly.  Also, making a seemingly unrelated change such as adding a printf for debugging or (as in your case) changing the order of variables can change the way undefined behavior manifests itself.

To read a single character, you need to use the %c format specifier.  You'll also need to add a space to the format string before it to consume whitespace, namely the newline from the prior scanf call.  This is needed because %c does not skip whitespace by itself, unlike other format specifiers such as %d or %s.

scanf(" %c",&op);


问:
How to add custom claims to access token in IdentityServer4?
I am using IdentityServer4.

I want to add other custom claims to access token but I'm unable to do this. I have modified Quickstart5 and added ASP.NET Identity Core and the custom claims via ProfileService as suggested by Coemgen below.

You can download my code here: [zip package][3]. (It is based on: Quickstart5 with ASP.NET Identity Core and added claims via ProfileService).

Issue: GetProfileDataAsync does not executed.

答:
Ok the issue here is this:

although you have configured your available Identity resources correctly (both standard & custom), you also need to explicitly define which ones are a necessity when calling your api resource. In order to define this you must go to your Config.cs class on ExampleIdentityServer project and provide a third argument like on the new ApiResouirce constructor. Only those will be included into the access_token

```<code>// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API", new[] { JwtClaimTypes.Subject, JwtClaimTypes.Email, JwtClaimTypes.Phone, etc... })
    };
}
</code>```

In essence this means that I got my identity claims configured for my organization but there may be more than one APIs involved and not all of the APIs make use of all available profile claims. This also means that these will be present inside your ClaimsPrincipal all the rest can still be accessed through the "userinfo" endpoint as a normal http call.

NOTE: regarding refresh tokens:

If you chose to enable refresh tokens via AllowOfflineAccess = true, you may experience the same behavior upon refreshing the access_token "GetProfileDataAsync does not executed!". So the claims inside the access_token stay the same although you get a new access_token with updated lifetime. If that is the case you can force them to always refresh from the Profile service by setting UpdateAccessTokenClaimsOnRefresh=true on the client configuration.

Body:
Ok the issue here is this:

although you have configured your available Identity resources correctly (both standard & custom), you also need to explicitly define which ones are a necessity when calling your api resource. In order to define this you must go to your Config.cs class on ExampleIdentityServer project and provide a third argument like on the new ApiResouirce constructor. Only those will be included into the access_token

// scopes define the API resources in your system
public static IEnumerable<ApiResource> GetApiResources()
{
    return new List<ApiResource>
    {
        new ApiResource("api1", "My API", new[] { JwtClaimTypes.Subject, JwtClaimTypes.Email, JwtClaimTypes.Phone, etc... })
    };
}

In essence this means that I got my identity claims configured for my organization but there may be more than one APIs involved and not all of the APIs make use of all available profile claims. This also means that these will be present inside your ClaimsPrincipal all the rest can still be accessed through the "userinfo" endpoint as a normal http call.

NOTE: regarding refresh tokens:

If you chose to enable refresh tokens via AllowOfflineAccess = true, you may experience the same behavior upon refreshing the access_token "GetProfileDataAsync does not executed!". So the claims inside the access_token stay the same although you get a new access_token with updated lifetime. If that is the case you can force them to always refresh from the Profile service by setting UpdateAccessTokenClaimsOnRefresh=true on the client configuration.


问:
List of controls in code behind
How can I add to a list<> some controls of my dashboard? I do something like List<String> NewList = new List<Strings>(){} but this throw me errors

I'm trying to add some linkButtons into the list.

I'm tying to do something like this but is wrong

```<code>protected void listLink(){
            List<LinkButton> linksList = new List<LinkButton>();
            listLink{

            }
        }
</code>```

I want to use that list in other events

my linkbuttons are in visible = false;

答:
From what i understand you want to create a list of LinkButtons using Object Initialization way.

Below code snippet should help you.

Aspx code:

```<code><form id="form1" runat="server">
   <asp:LinkButton ID="lnkBtn1" runat="server"></asp:LinkButton>
   <asp:LinkButton ID="lnkBtn2" runat="server"></asp:LinkButton>
</form>
</code>```

Aspx.cs code:

```<code>List<LinkButton> lnkBtnCollection = null;

protected void Page_Init(object sender, EventArgs e)
    {
        //Object Initialization way
        lnkBtnCollection = new List<LinkButton>
        {
            lnkBtn1, lnkBtn2
        };

        //Second way  where items are added to the list after the list is created
        //lnkBtnCollection = new List<LinkButton>();
        //lnkBtnCollection.Add(lnkBtn1);
        //lnkBtnCollection.Add(lnkBtn2);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       //Use LinkBtn Collection here
       foreach (var lnkBtn in lnkBtnCollection)
       {

       }
    }
</code>```

Title: List of controls in code behind

Body:
How can I add to a list<> some controls of my dashboard? I do something like List<String> NewList = new List<Strings>(){} but this throw me errors

I'm trying to add some linkButtons into the list.

I'm tying to do something like this but is wrong

protected void listLink(){
            List<LinkButton> linksList = new List<LinkButton>();
            listLink{

            }
        }

I want to use that list in other events

my linkbuttons are in visible = false;

Body:
From what i understand you want to create a list of LinkButtons using Object Initialization way.

Below code snippet should help you.

Aspx code:

<form id="form1" runat="server">
   <asp:LinkButton ID="lnkBtn1" runat="server"></asp:LinkButton>
   <asp:LinkButton ID="lnkBtn2" runat="server"></asp:LinkButton>
</form>

Aspx.cs code:

List<LinkButton> lnkBtnCollection = null;

protected void Page_Init(object sender, EventArgs e)
    {
        //Object Initialization way
        lnkBtnCollection = new List<LinkButton>
        {
            lnkBtn1, lnkBtn2
        };

        //Second way  where items are added to the list after the list is created
        //lnkBtnCollection = new List<LinkButton>();
        //lnkBtnCollection.Add(lnkBtn1);
        //lnkBtnCollection.Add(lnkBtn2);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
       //Use LinkBtn Collection here
       foreach (var lnkBtn in lnkBtnCollection)
       {

       }
    }


问:
Enternal Data Refresh - Preparing Worksheet
I have an excel file that was saved with only minor- manually entered updates. The issue is the external data connection on another sheet was somehow impacted. It used to go from reading source data to calculating when the refresh button was clicked. Now it goes from reading source data to preparing worksheet where it lingers. The difference in function changes it from a <20 second refresh to a 5+ min refresh. Any ideas on how to restore its original functionality?</p>

答: It turns out this was not an excel issue. The sharepoint connection was just slow at points. A few days later, without any updates, the file worked again. </p>


问:
On table loaded from angular's ng-repeat, call a function
Is it possible to fire off a JavaScript function after a table has been fully filled from the ng-repeat directive?</p>

答:
Yes you can do this using the below directive

```<code>var module = angular.module('testApp', [])
    .directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});
</code>```

then in your controller, you can catch it with $on:

```<code>$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
      //do stuff, execute functions -- whatever...
});
</code>```

add below directives into  your table rebdering code

```<code>ng-repeat="item in items" on-finish-render="ngRepeatFinished"
</code>```

Body:
Yes you can do this using the below directive

var module = angular.module('testApp', [])
    .directive('onFinishRender', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            if (scope.$last === true) {
                $timeout(function () {
                    scope.$emit(attr.onFinishRender);
                });
            }
        }
    }
});

then in your controller, you can catch it with $on:

$scope.$on('ngRepeatFinished', function(ngRepeatFinishedEvent) {
      //do stuff, execute functions -- whatever...
});

add below directives into  your table rebdering code

ng-repeat="item in items" on-finish-render="ngRepeatFinished"


问:
jquery-confirm plugin - submit form confirmation
I am using this plugin - https://craftpip.github.io/jquery-confirm/
for confirming before submitting a form.
Here is my HTML:

```<code><form action="" method="post">
<input type="hidden" name="comment_id" value="">
<button name="delete" class="btn btn-danger btn-xs confirm_delete"><span class="glyphicon glyphicon-remove"></span> Delete</button>
</form>
</code>```

And my javascript:

```<code>$("button.confirm_delete").confirm({
    title: '',
    content: 'Please confirm you want to delete this item. This action is irreversible!',
    buttons: {
        confirm: function () {
            this.$target.submit();
        },
        cancel: function () {

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

And upon confirmation, nothing happens. In the console I get [button.btn.btn-danger.btn-xs.confirm_delete] on this line: this.$target.submit(); What am I doing wrong?

答:
you need to use this in your confirm click

```<code>this.$target.parent().submit()
</code>```

this

is the Confirm object

$target

being your delete button

and

parent()

being your form

here is a fiddle for you
https://jsfiddle.net/fxabnk4o/5/

Note this will work if you have set up your HTML the way you have shown

Body:
I am using this plugin - https://craftpip.github.io/jquery-confirm/
for confirming before submitting a form.
Here is my HTML:

<form action="" method="post">
<input type="hidden" name="comment_id" value="">
<button name="delete" class="btn btn-danger btn-xs confirm_delete"> Delete</button>
</form>

And my javascript:

$("button.confirm_delete").confirm({
    title: '',
    content: 'Please confirm you want to delete this item. This action is irreversible!',
    buttons: {
        confirm: function () {
            this.$target.submit();
        },
        cancel: function () {

        }
    }
});

And upon confirmation, nothing happens. In the console I get [button.btn.btn-danger.btn-xs.confirm_delete] on this line: this.$target.submit(); What am I doing wrong?

Body:
you need to use this in your confirm click

this.$target.parent().submit()

this

is the Confirm object

$target

being your delete button

and

parent()

being your form

here is a fiddle for you
https://jsfiddle.net/fxabnk4o/5/

Note this will work if you have set up your HTML the way you have shown


问:
Is it a good practice for a module to return a JSONArray?
Before I converted my app into a library, I could get a JSONArray from the server and process everything internally, assigning values to my own POJO, which could be sorted into an ArrayList of that POJO type. Now with the new library, I want that POJO to be determined by the third-party developer for flexibility. My question is: is it good practice (regarding both security and structure standards) to return the raw JSONArray to the developer? And if not, what should I return? ArrayList? List? </p>

答: its always better to retrieve some information from user or client side for the betterment regarding durability of application. In doing so the developer will be updated with issues the application is facing</p>


问:
Using ScrollView Programmatically in Swift 3
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

```<code>import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}
</code>```

答:
Two things.

1. Add the labels to scroll view, not your view

You want your label to scroll with scroll view, then you should not add it on your view. When running your code, you can scroll but the fixed label there is pinned to your view, not on your scroll view

2. Make sure you added your constraints correctly

Try it on your storyboard about what combination of constraint is enough for a view. At least 4 constraints are needed for a label.

Bottom line

Here is a modified version of your code. For constraint I added padding left, padding top, width and height and it works. My code is

```<code>let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))

    scrollView.addSubview(labelTwo)

    NSLayoutConstraint(item: labelTwo, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leadingMargin, multiplier: 1, constant: 10).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .topMargin, multiplier: 1, constant: 10).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true

    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    view.addSubview(scrollView)

}
</code>```

And the scroll view looks like this

Body:
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}

Body:
Two things.

1. Add the labels to scroll view, not your view

You want your label to scroll with scroll view, then you should not add it on your view. When running your code, you can scroll but the fixed label there is pinned to your view, not on your scroll view

2. Make sure you added your constraints correctly

Try it on your storyboard about what combination of constraint is enough for a view. At least 4 constraints are needed for a label.

Bottom line

Here is a modified version of your code. For constraint I added padding left, padding top, width and height and it works. My code is

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))

    scrollView.addSubview(labelTwo)

    NSLayoutConstraint(item: labelTwo, attribute: .leading, relatedBy: .equal, toItem: scrollView, attribute: .leadingMargin, multiplier: 1, constant: 10).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: scrollView, attribute: .topMargin, multiplier: 1, constant: 10).isActive = true
    NSLayoutConstraint(item: labelTwo, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30).isActive = true

    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    view.addSubview(scrollView)

}

And the scroll view looks like this


问:
Space Gap on mobile devices
I'm designing a Wordpress website with Enfold theme for one of my clients and I'm getting a strange space gap only on mobile devices.

Any thoughts on how to fix this?

The website is:

http://pishdad.org

Thank you so much

答:
Disable WP Rocket Plugin.
Clearly at first inspect you can see it is the cause...
Probably you did not implement it correctly.

Title: Space Gap on mobile devices


问:
MarkLogic generic language support
As per the documentation:
The generic language support only stems words to themselves, queries in these languages will not include variations of words based on their meanings in the results.

```<code>xdmp:document-insert("/lang/test.xml", <el xml:lang="fr">chats</el>)
</code>```

Considering I do not have a license for french language, will the word
"chats" be stemmed to "chat" in the term list ? or will it be indexed as chats, i.e. without any variations ?

答:
You can easily check this yourself using cts:stem:

```<code>cts:stem("chats", "fr")
</code>```

Without necessary licenses it simply returns chats.

HTH!

Title: MarkLogic generic language support

Body:
As per the documentation:
The generic language support only stems words to themselves, queries in these languages will not include variations of words based on their meanings in the results.

xdmp:document-insert("/lang/test.xml", <el xml:lang="fr">chats</el>)

Considering I do not have a license for french language, will the word
"chats" be stemmed to "chat" in the term list ? or will it be indexed as chats, i.e. without any variations ?

Body:
You can easily check this yourself using cts:stem:

cts:stem("chats", "fr")

Without necessary licenses it simply returns chats.

HTH!


问:
Unable to add and display list of ASP.Net Identity Users to object model (MVC5)
I have a Ticket model with some basic ticket information.

What I want to do now is I want to be able to assign Agent to each Ticket.

For the Agent, I want to use the ASP.Net Identity Users which I already have.

I want to add property called AgentName and AgentID to this Ticket model.

In my Index View, I want to see a single Agent Name assigned to AgentName property and When I am editing a Ticket I want to have a drop down list of all available ASP.Net Identity Users (Agent Name) so that I can assign the ticket to.

I want to also have the ability to query all assigned Ticket to an specific Agent using AgentID so somehow I need to link each Ticket to an Agent using the AgentID.

How can I make this happen with code? Any help is appreciated.

So far I have this:

```<code>   Public class Ticket
{
    public int Id { get; set; }
    Display(Name = "Ticket comes from")]
    public string Source { get; set; }
}
</code>```

In my ticket Edit(int id) HttpGet method I am fetching a Ticket information with the following code.

```<code>//HttpGet
public ActionResult Edit(int id)
{
    Models.Ticket model = db.Ticket
        .Include("Source")
        .SingleOrDefault(m => m.Id == id);

    if (model == null)
    {
        return new HttpNotFoundResult();
    }

    return View(model);
}
</code>```

What I have tried

I have tried changing my Ticket model to something like this

```<code>Public class Ticket
{
    public int Id { get; set; }
    Display(Name = "Ticket comes from")]
    public string Source { get; set; }
    //....

    // Now I want to have a property called AgentName and AgentID
    //...something like this
    public string AgentName {get; set;} //***I want this to display the User Name of the User in Index View page. But, I also want a dropdown list of user when I am in Edit mode so that I can change the AssignedToUser to have different user.
    public string AgentID {get; set;}
}
</code>```

To get all ASP.Net Identity User (Agents) I have something like this:

```<code>ViewBag.Agents = new SelectList(db.Users);
</code>```

To display as drop down list in Edit mode I have something like this:

```<code>            <div class="form-group">
                @Html.LabelFor(model => model.AgentName, new { @class = "col-sm-4 control-label" })
                <div class="col-sm-8">
                    @Html.DropDownList("Agents", ViewBag.Agents as SelectList, String.Empty, new { @class = "form-control" })
                </div>
            </div>
</code>```

But nothing is working. When I am editing a Ticket, the Agent drop down list display some weir character like shown in the picture here. I want this to be a list of User Name.

DEBUG

@nurdyguy Put a debug stop on the line in the controller where you do ViewBag.Agents = new SelectList(db.Users);
This is what I got:

答:
This is not an Entity Framework issue, this is just the default behavior for DropDown when you give it a complex object. Try keeping your View code the same and try something like the following in your Controller:

```<code>// change Name to the display property you want to show up in the dropdown
//                               source,    value,  display
ViewBag.Agents = new SelectList( db.Users,  "Id",   "Name");
</code>```

References:

DropDownList Property to display

ASP.NET MVC Html.DropDownList SelectedValue

Body:
I have a Ticket model with some basic ticket information.

What I want to do now is I want to be able to assign Agent to each Ticket.

For the Agent, I want to use the ASP.Net Identity Users which I already have.

I want to add property called AgentName and AgentID to this Ticket model.

In my Index View, I want to see a single Agent Name assigned to AgentName property and When I am editing a Ticket I want to have a drop down list of all available ASP.Net Identity Users (Agent Name) so that I can assign the ticket to.

I want to also have the ability to query all assigned Ticket to an specific Agent using AgentID so somehow I need to link each Ticket to an Agent using the AgentID.

How can I make this happen with code? Any help is appreciated.

So far I have this:

   Public class Ticket
{
    public int Id { get; set; }
    Display(Name = "Ticket comes from")]
    public string Source { get; set; }
}

In my ticket Edit(int id) HttpGet method I am fetching a Ticket information with the following code.

//HttpGet
public ActionResult Edit(int id)
{
    Models.Ticket model = db.Ticket
        .Include("Source")
        .SingleOrDefault(m => m.Id == id);

    if (model == null)
    {
        return new HttpNotFoundResult();
    }

    return View(model);
}

What I have tried

I have tried changing my Ticket model to something like this

Public class Ticket
{
    public int Id { get; set; }
    Display(Name = "Ticket comes from")]
    public string Source { get; set; }
    //....

    // Now I want to have a property called AgentName and AgentID
    //...something like this
    public string AgentName {get; set;} //***I want this to display the User Name of the User in Index View page. But, I also want a dropdown list of user when I am in Edit mode so that I can change the AssignedToUser to have different user.
    public string AgentID {get; set;}
}

To get all ASP.Net Identity User (Agents) I have something like this:

ViewBag.Agents = new SelectList(db.Users);

To display as drop down list in Edit mode I have something like this:

                @Html.LabelFor(model => model.AgentName, new { @class = "col-sm-4 control-label" })

                    @Html.DropDownList("Agents", ViewBag.Agents as SelectList, String.Empty, new { @class = "form-control" })

But nothing is working. When I am editing a Ticket, the Agent drop down list display some weir character like shown in the picture here. I want this to be a list of User Name.

DEBUG

@nurdyguy Put a debug stop on the line in the controller where you do ViewBag.Agents = new SelectList(db.Users);
This is what I got:

Body:
This is not an Entity Framework issue, this is just the default behavior for DropDown when you give it a complex object. Try keeping your View code the same and try something like the following in your Controller:

// change Name to the display property you want to show up in the dropdown
//                               source,    value,  display
ViewBag.Agents = new SelectList( db.Users,  "Id",   "Name");

References:

DropDownList Property to display

ASP.NET MVC Html.DropDownList SelectedValue


问:
Access @Model when @Model is a Task
How am I supposed to use a @Model thats a Task?

Razor:

```<code>@model Task<AreBuraas.Core.v1.Models.Category>

<article class="panel panel-primary">
    <section class="panel-heading">
        <h1>
            @Model.Name
        </h1>
        <h3>
            @Model.Description
        </h3>
    </section>
    <section class="panel-body">
        her kommer content!
    </section>
</article>
</code>```

Controller:

```<code>public IActionResult Display(int id)
{
    return View(_data.GetCategory(id));
}
</code>```

Error:

'Task' does not contain a definition for 'Name' and no
  extension method 'Name' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

```<code>            @Model.Name
</code>```

'Task' does not contain a definition for 'Description' and
  no extension method 'Description' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

```<code>                @Model.Description
</code>```

答:
Landed on this solution:

```<code>public IActionResult Display(int id)
{
    var data = _data.GetCategory(id);
    var result = data.Result;

    return View(result);
}
</code>```

Title: Access @Model when @Model is a Task

Body:
How am I supposed to use a @Model thats a Task?

Razor:

@model Task<AreBuraas.Core.v1.Models.Category>

            @Model.Name

            @Model.Description

        her kommer content!

Controller:

public IActionResult Display(int id)
{
    return View(_data.GetCategory(id));
}

Error:

'Task' does not contain a definition for 'Name' and no
  extension method 'Name' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

            @Model.Name

'Task' does not contain a definition for 'Description' and
  no extension method 'Description' accepting a first argument of type
  'Task' could be found (are you missing a using directive or
  an assembly reference?)

                @Model.Description

Body:
Landed on this solution:

public IActionResult Display(int id)
{
    var data = _data.GetCategory(id);
    var result = data.Result;

    return View(result);
}


问:
WP_Query change code
In my theme WordPress to display the post uses this (code #1):

```<code>function inner($posts, $td_column_number = '') {
    $buffy = '';

    if (!empty($posts)) {
        foreach ($posts as $post) {
            $td_module_17 = new td_module_17($post);
            $buffy .= $td_module_17->render($post);
        }
    }

    return $buffy;
}
</code>```

I need to show posts using this code (code #2):

```<code><?php
$custom_query = new WP_Query('posts_per_page= 5');
while($custom_query->have_posts()):
    $custom_query->the_post();
    ?>
    <div class="post-1">
        <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">
            <h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
            <div class="float-tags">
                <div class="bb-td-post-small-box clearfix">
                    <?php the_tags('','',''); ?>
                </div>
            </div>
            <div class="post-2">
                <?php the_content(); ?>
            </div>
        </div>
    </div>
    <?php
endwhile;
wp_reset_postdata(); // reset the query
?>
</code>```

If I insert code #2 into module 17, then the posts are output immediately all in one block, and not one at a time.

答:
Solved a problem. The code was looped. Here is the working code.</p>

```<code>   <?php

    class td_module_17 extends td_module {

       function __construct($post) {
           //run the parrent constructor
           parent::__construct($post);

    }

    function render($Post = false) {
       ob_start();
    ?>

                 <div class="post-1">
                   <div

 <?php //post_class(); ?> id="post-<?= $Post->ID; ?>">
                 <h3><a href="<?= get_permalink($Post->ID); ?>"><?= $Post->post_title; ?></a> </h3>
                    <div class="float-tags">
                                   <div class="bb-td-post-small-box clearfix">
                                     <?php $tags = get_the_tags($Post->ID); ?>
                                     <? foreach ($tags as $tag) : ?>
                                            <a href="http://prikol2.ru/tag/<?= $tag->name; ?>/" rel="tag"><?= $tag->name; ?></a>
                                     <? endforeach; ?>
                                   </div>
                    </div>
                 <div class="post-2">
                   <?= apply_filters('the_content', $Post->post_content); ?>
                 </div>

               </div>
             </div>

   <?php return ob_get_clean();
}
}
</code>```

Title: WP_Query change code

Body:
In my theme WordPress to display the post uses this (code #1):

function inner($posts, $td_column_number = '') {
    $buffy = '';

    if (!empty($posts)) {
        foreach ($posts as $post) {
            $td_module_17 = new td_module_17($post);
            $buffy .= $td_module_17->render($post);
        }
    }

    return $buffy;
}

I need to show posts using this code (code #2):

<?php
$custom_query = new WP_Query('posts_per_page= 5');
while($custom_query->have_posts()):
    $custom_query->the_post();
    ?>

        <div <?php post_class(); ?> id="post-<?php the_ID(); ?>">

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

                    <?php the_tags('','',''); ?>

                <?php the_content(); ?>

    <?php
endwhile;
wp_reset_postdata(); // reset the query
?>

If I insert code #2 into module 17, then the posts are output immediately all in one block, and not one at a time.

Body:
Solved a problem. The code was looped. Here is the working code.

   <?php

    class td_module_17 extends td_module {

       function __construct($post) {
           //run the parrent constructor
           parent::__construct($post);

    }

    function render($Post = false) {
       ob_start();
    ?>

                 <div class="post-1">
                   <div

 <?php //post_class(); ?> id="post-<?= $Post->ID; ?>">
                 <h3><a href="<?= get_permalink($Post->ID); ?>"><?= $Post->post_title; ?></a> </h3>
                    <div class="float-tags">
                                   <div class="bb-td-post-small-box clearfix">
                                     <?php $tags = get_the_tags($Post->ID); ?>
                                     <? foreach ($tags as $tag) : ?>
                                            <a href="http://prikol2.ru/tag/<?= $tag->name; ?>/" rel="tag"><?= $tag->name; ?></a>
                                     <? endforeach; ?>
                                   </div>
                    </div>
                 <div class="post-2">
                   <?= apply_filters('the_content', $Post->post_content); ?>
                 </div>

               </div>
             </div>

   <?php return ob_get_clean();
}
}