问:
A Foreign key referring Triple from Annotation has the wrong number of columns.
Although I made a little research on this, and I found a lot of threats opened in Internet, I couldn't solve my problem. I attach my code:

Triple.java  the primary key is made by 3 URIs from three different concepts, but it is the same column (is it a problem?)

```<code>        @Entity
        @IdClass(ConceptPk.class)
        @Table(name = "triple")
        public class TripleDBModel {

            protected List<Annotation> annotations;
            public String conceptUriSubject;
            public String conceptUriObject;
            public String conceptUriPredicate;
            public String id;

            @ManyToMany(
                    cascade={CascadeType.ALL},
                    fetch=FetchType.LAZY
            )
            @JoinTable(name = "triple_has_annotation",
                    joinColumns=@JoinColumn(name="annotation_id"),
                    inverseJoinColumns={@JoinColumn(name="uri_concept_subject", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_object", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_predicate", referencedColumnName="triple_id")
         })//EDIT
            public List<Annotation> getAnnotations() {
                return annotations;
            }
            public void setAnnotations(List<Annotation> annotations) {
                this.annotations = annotations;
            }
            @Id
            @Column(name = "uri_concept_subject", length = 100)
            public String getConceptUriSubject() {
                return conceptUriSubject;
            }
            public void setConceptUriSubject(String conceptUriSubject) {
                this.conceptUriSubject = conceptUriSubject;
            }
            @Id
            @Column(name = "uri_concept_object", length = 100)
            public String getConceptUriObject() {
                return conceptUriObject;
            }
            public void setConceptUriObject(String conceptUriObject) {
                this.conceptUriObject = conceptUriObject;
            }
            @Id
            @Column(name = "uri_concept_predicate", length = 100)
            public String getConceptUriPredicate() {
                return conceptUriPredicate;
            }
            public void setConceptUriPredicate(String conceptUriPredicate) {
                this.conceptUriPredicate = conceptUriPredicate;
            }

 @Id
        @Column(name = "triple_id", unique = true, nullable = false)
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }
</code>```

ConceptPk.java

```<code>    @Embeddable
    public class ConceptPk implements java.io.Serializable {

        private static final long serialVersionUID = 1L;
        public String conceptUriSubject;
        public String conceptUriObject;
        public String conceptUriPredicate;

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriSubject() {
            return conceptUriSubject;
        }
        public void setConceptUriSubject(String conceptUriSubject) {
            this.conceptUriSubject = conceptUriSubject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriObject() {
            return conceptUriObject;
        }
        public void setConceptUriObject(String conceptUriObject) {
            this.conceptUriObject = conceptUriObject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriPredicate() {
            return conceptUriPredicate;
        }
        public void setConceptUriPredicate(String conceptUriPredicate) {
            this.conceptUriPredicate = conceptUriPredicate;
        }
</code>```

Annotation.java

```<code>    @Entity
    @Table(name = "annotations")
    public class Annotation {

        private Integer id;
        private List<TripleDBModel> triples;

    @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "annotation_id", unique = true, nullable = false)
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

    @ManyToMany(
                cascade={CascadeType.ALL},
                mappedBy = "annotations", //EDIT
                fetch=FetchType.LAZY
        )
        public List<TripleDBModel> getTriples() {
            return triples;
        }

        public void setTriples(List<TripleDBModel> triples) {
            this.triples = triples;
        }
</code>```

But I am getting this error:

```<code>Caused by: org.hibernate.AnnotationException: A Foreign key refering TripleDBModel from Annotation has the wrong number of column. should be 3
</code>```

What am I doing wrong?? Thanks in advance

答:
I'm not sure this is the cause of the error message you get, but your mapping has several errors:

Each of the @JoinColumn in your inverseJoinColumns attribute should have their referencedColumnName attribute specified.

The values of the joinColumns and inverseJoinColumns attributes should be switched. joinColumns is used to reference the source entity. inverseJoinColumns is used to reference the target entity.

The mappedBy attribute should be annotations, and not annotation

(unrelated, but probably incorrect) : cascade=CascadeType.ALL is probably not what you want on a many-to-many. You don't want to delete all the annotations of a triple when this triple is deleted, since these annotations are referenced by other triples.

Body:
Although I made a little research on this, and I found a lot of threats opened in Internet, I couldn't solve my problem. I attach my code:

Triple.java  the primary key is made by 3 URIs from three different concepts, but it is the same column (is it a problem?)

        @Entity
        @IdClass(ConceptPk.class)
        @Table(name = "triple")
        public class TripleDBModel {

            protected List<Annotation> annotations;
            public String conceptUriSubject;
            public String conceptUriObject;
            public String conceptUriPredicate;
            public String id;

            @ManyToMany(
                    cascade={CascadeType.ALL},
                    fetch=FetchType.LAZY
            )
            @JoinTable(name = "triple_has_annotation",
                    joinColumns=@JoinColumn(name="annotation_id"),
                    inverseJoinColumns={@JoinColumn(name="uri_concept_subject", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_object", referencedColumnName="triple_id"), @JoinColumn(name="uri_concept_predicate", referencedColumnName="triple_id")
         })//EDIT
            public List<Annotation> getAnnotations() {
                return annotations;
            }
            public void setAnnotations(List<Annotation> annotations) {
                this.annotations = annotations;
            }
            @Id
            @Column(name = "uri_concept_subject", length = 100)
            public String getConceptUriSubject() {
                return conceptUriSubject;
            }
            public void setConceptUriSubject(String conceptUriSubject) {
                this.conceptUriSubject = conceptUriSubject;
            }
            @Id
            @Column(name = "uri_concept_object", length = 100)
            public String getConceptUriObject() {
                return conceptUriObject;
            }
            public void setConceptUriObject(String conceptUriObject) {
                this.conceptUriObject = conceptUriObject;
            }
            @Id
            @Column(name = "uri_concept_predicate", length = 100)
            public String getConceptUriPredicate() {
                return conceptUriPredicate;
            }
            public void setConceptUriPredicate(String conceptUriPredicate) {
                this.conceptUriPredicate = conceptUriPredicate;
            }

 @Id
        @Column(name = "triple_id", unique = true, nullable = false)
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
    }

ConceptPk.java

    @Embeddable
    public class ConceptPk implements java.io.Serializable {

        private static final long serialVersionUID = 1L;
        public String conceptUriSubject;
        public String conceptUriObject;
        public String conceptUriPredicate;

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriSubject() {
            return conceptUriSubject;
        }
        public void setConceptUriSubject(String conceptUriSubject) {
            this.conceptUriSubject = conceptUriSubject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriObject() {
            return conceptUriObject;
        }
        public void setConceptUriObject(String conceptUriObject) {
            this.conceptUriObject = conceptUriObject;
        }

        @Id
        @Column(name = "uri", length = 100, unique = true, nullable = false)
        public String getConceptUriPredicate() {
            return conceptUriPredicate;
        }
        public void setConceptUriPredicate(String conceptUriPredicate) {
            this.conceptUriPredicate = conceptUriPredicate;
        }

Annotation.java

    @Entity
    @Table(name = "annotations")
    public class Annotation {

        private Integer id;
        private List<TripleDBModel> triples;

    @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "annotation_id", unique = true, nullable = false)
        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

    @ManyToMany(
                cascade={CascadeType.ALL},
                mappedBy = "annotations", //EDIT
                fetch=FetchType.LAZY
        )
        public List<TripleDBModel> getTriples() {
            return triples;
        }

        public void setTriples(List<TripleDBModel> triples) {
            this.triples = triples;
        }

But I am getting this error:

Caused by: org.hibernate.AnnotationException: A Foreign key refering TripleDBModel from Annotation has the wrong number of column. should be 3

What am I doing wrong?? Thanks in advance


来源: stackexchange

问:
How can I add a border to the label for checkboxes when they are selected?
I am trying to set up a word guessing game, and I want the user to have multiple 'word banks' to choose from. I'm using checkboxes, wrapped in labels, for the selections. I want to put a border around the label element when the checkbox is checked because ideally, I want the actual checkbox hidden/not showing.

I've tried adding a border to the button only while checked using :checked, but that did not work. I also tried looking for solutions online but most solutions I was able to dig up were only adding styling to the actual box, not the label, and I want the border around the whole label so that I can hide the checkboxes but still indicate which 'bank' is selected.

```<code><form id="wordBanks">
    <label for="perksCheck">Perks<input type="checkbox" id="perksCheck" selected></label>
    <label for="equipmentCheck">Euipment<input type="checkbox" id="equipmentCheck"></label>
</form>
</code>```

I'd paste my CSS, too, but since the code I have doesn't work I'll leave it out. Can provide on request if you want, though.

答:
My go to solution is usually to wrap the label in a span, and place the checkbox before the label.

```<code><form id="wordBanks">
         <span><input type="checkbox" id="perksCheck" checked><label for="perksCheck">Perks</label></span>
         <span><input type="checkbox" id="equipmentCheck"><label for="equipmentCheck">Euipment</label></span>
</form>
</code>```

You can possibly even avoid wrapping it into a span, but I find it easier to reason about when you have several attributes (e.g start throwing in accessibility attributes and your element will wrap on a new line on most screens).

This example doesn't lose any functionality an you can style the label with:

```<code>    input[type=checkbox]:checked + label
</code>```

Sidenote: A checkbox is "checked" not "selected".

ContentLicense: CC BY-SA 4.0

Body:
I am trying to set up a word guessing game, and I want the user to have multiple 'word banks' to choose from. I'm using checkboxes, wrapped in labels, for the selections. I want to put a border around the label element when the checkbox is checked because ideally, I want the actual checkbox hidden/not showing.

I've tried adding a border to the button only while checked using :checked, but that did not work. I also tried looking for solutions online but most solutions I was able to dig up were only adding styling to the actual box, not the label, and I want the border around the whole label so that I can hide the checkboxes but still indicate which 'bank' is selected.

<form id="wordBanks">
    Perks<input type="checkbox" id="perksCheck" selected>
    Euipment<input type="checkbox" id="equipmentCheck">
</form>

I'd paste my CSS, too, but since the code I have doesn't work I'll leave it out. Can provide on request if you want, though.

Body:
My go to solution is usually to wrap the label in a span, and place the checkbox before the label.

<form id="wordBanks">
         <span><input type="checkbox" id="perksCheck" checked><label for="perksCheck">Perks</label></span>
         <span><input type="checkbox" id="equipmentCheck"><label for="equipmentCheck">Euipment</label></span>
</form>

You can possibly even avoid wrapping it into a span, but I find it easier to reason about when you have several attributes (e.g start throwing in accessibility attributes and your element will wrap on a new line on most screens).

This example doesn't lose any functionality an you can style the label with:

    input[type=checkbox]:checked + label

Sidenote: A checkbox is "checked" not "selected".


问:
return userdata result of ec2 with terraform
I want to create a Jenkins pipeline, which deploys an application on aws autoscaling group using user_data.

Sometimes the deployment fail, but I don't how to show the deployment result when terraform is running, especially user data script result.

So is it possible to print the user data output (script result) with terraform?

Thank you in advance,

答:
You can use the Terraform EC2 data resource to extract the instances metadata including the SHA-1 userdata. https://www.terraform.io/docs/providers/aws/d/instance.html

```<code>data "aws_instance" "foo" {
instance_id = "i-instanceid"
get_user_data = true
}
</code>```

Keep

Body:
You can use the Terraform EC2 data resource to extract the instances metadata including the SHA-1 userdata. https://www.terraform.io/docs/providers/aws/d/instance.html

data "aws_instance" "foo" {
instance_id = "i-instanceid"
get_user_data = true
}

Keep


答:
Rather than wrapping the checkbox inside the label you could do something like:

```<code><input type="checkbox" id="perksCheck" checked>
<label for="perksCheck">Perks</label>
</code>```

In your CSS, you can then target the label if the checkbox above it has been checked by using an adjacent sibling combinator.

```<code>input[type=checkbox]:checked + label {
    border: 1px solid red;
}
</code>```

Title: How can I add a border to the label for checkboxes when they are selected?

Body:
Rather than wrapping the checkbox inside the label you could do something like:

<input type="checkbox" id="perksCheck" checked>
<label for="perksCheck">Perks</label>

In your CSS, you can then target the label if the checkbox above it has been checked by using an adjacent sibling combinator.

input[type=checkbox]:checked + label {
    border: 1px solid red;
}


问:
Android DynamoDBMappingException: Expected S in value
I'm trying to map a json object from my dynamodb table using DynamoDbMapper and with the latest aws android sdk: com.amazonaws:aws-android-sdk-ddb-mapper:2.13.0, I'm seeing this exception: "DynamoDBMappingException: Expected S in value...

The json object in my table has 3 attributes, 2 of which are string and the third is a list of complex objects. I've created an object using the @DynamoDbDocument annotation for the complex object and used the proper marshaling annotation but it doesn't seem to be unmarshaling the json object into a java object correctly.
The complex object is a json object in this format:

```<code>{
  "allCitiesList": [
    {
      "city": "Auckland, New Zealand",
      "times": {
        "recTimes": [
          "Jan1",
          "Jan2"
        ]
      }
    }
}
</code>```

```<code>public class CitiesDO {
    private String city;
    private String country;
    private List<AllCitiesObject> allCitiesList;
...get/setters for other fields...

    @DynamoDBMarshalling(marshallerClass =
    AllCitiesJSONMarshaller.class)
    public List<AllCitiesObject> getAllCitiesList() {
        return allCitiesList;
    }

    public void setAllCitiesList(List<AllCitiesObject> allCitiesList) {
        this.allCitiesList = allCitiesList;
    }
}
</code>```

```<code>@DynamoDBDocument
public class AllCitiesObject {
    @DynamoDBAttribute(attributeName = "allCitiesList")
    private String data;

    public AllCitiesObject(){}

    public String getData() {
        return data.toString();
    }

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

class AllCitiesJSONMarshaller extends JsonMarshaller<AllCitiesObject> {}

Have also tried this approach with a custom marshaller but no success:

```<code>public class MyCustomMarshaller implements DynamoDBMarshaller<List<AllCitiesObject>> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final ObjectWriter writer = mapper.writer();

    @Override
    public String marshall(List<AllCitiesObject> obj) {

        try {
            return writer.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(
                    "Unable to marshall the instance of " + obj.getClass()
                            + "into a string", e);
        }
    }

    @Override
    public List<AllCitiesObject> unmarshall(Class<List<AllCitiesObject>> clazz, String json) {
        final CollectionType
                type =
                mapper.getTypeFactory().constructCollectionType(List.class, AllCitiesObject.class);
        try {
            return mapper.readValue(json, type);
        } catch (Exception e) {
            throw new RuntimeException("Unable to unmarshall the string " + json
                    + "into " + clazz, e);
        }
    }

}
</code>```

The exception is:
DynamoDBMappingException: Expected S in value {L: [{M: {times={M: {recTimes={L: [{S: Jan1,}, {S: Jan2,}

I'm having difficulty unmarshalling the json to a string although I think I have it set up correctly. Can anyone please help me understand what I'm missing and how to approach this issue? I would really appreciate your help!

答: If anyone else is absolutely stuck on this issue with the ddbMapper, consider using the ddbClient to explicitly convert and map your DO object with your ddb table data. Due to time constraints, I'll come back to this and figure out the mapping issue at a later time and post the answer here in case it helps anyone else.</p>

Body:
I'm trying to map a json object from my dynamodb table using DynamoDbMapper and with the latest aws android sdk: com.amazonaws:aws-android-sdk-ddb-mapper:2.13.0, I'm seeing this exception: "DynamoDBMappingException: Expected S in value...

The json object in my table has 3 attributes, 2 of which are string and the third is a list of complex objects. I've created an object using the @DynamoDbDocument annotation for the complex object and used the proper marshaling annotation but it doesn't seem to be unmarshaling the json object into a java object correctly.
The complex object is a json object in this format:

{
  "allCitiesList": [
    {
      "city": "Auckland, New Zealand",
      "times": {
        "recTimes": [
          "Jan1",
          "Jan2"
        ]
      }
    }
}

public class CitiesDO {
    private String city;
    private String country;
    private List<AllCitiesObject> allCitiesList;
...get/setters for other fields...

    @DynamoDBMarshalling(marshallerClass =
    AllCitiesJSONMarshaller.class)
    public List<AllCitiesObject> getAllCitiesList() {
        return allCitiesList;
    }

    public void setAllCitiesList(List<AllCitiesObject> allCitiesList) {
        this.allCitiesList = allCitiesList;
    }
}

@DynamoDBDocument
public class AllCitiesObject {
    @DynamoDBAttribute(attributeName = "allCitiesList")
    private String data;

    public AllCitiesObject(){}

    public String getData() {
        return data.toString();
    }

    public void setData(String data) {
        this.data = data;
    }
}

class AllCitiesJSONMarshaller extends JsonMarshaller<AllCitiesObject> {}

Have also tried this approach with a custom marshaller but no success:

public class MyCustomMarshaller implements DynamoDBMarshaller<List<AllCitiesObject>> {

    private static final ObjectMapper mapper = new ObjectMapper();
    private static final ObjectWriter writer = mapper.writer();

    @Override
    public String marshall(List<AllCitiesObject> obj) {

        try {
            return writer.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(
                    "Unable to marshall the instance of " + obj.getClass()
                            + "into a string", e);
        }
    }

    @Override
    public List<AllCitiesObject> unmarshall(Class<List<AllCitiesObject>> clazz, String json) {
        final CollectionType
                type =
                mapper.getTypeFactory().constructCollectionType(List.class, AllCitiesObject.class);
        try {
            return mapper.readValue(json, type);
        } catch (Exception e) {
            throw new RuntimeException("Unable to unmarshall the string " + json
                    + "into " + clazz, e);
        }
    }

}

The exception is:
DynamoDBMappingException: Expected S in value {L: [{M: {times={M: {recTimes={L: [{S: Jan1,}, {S: Jan2,}

I'm having difficulty unmarshalling the json to a string although I think I have it set up correctly. Can anyone please help me understand what I'm missing and how to approach this issue? I would really appreciate your help!


问:
Access 2003 - Field from another database on form
I am 'fixing up' an old Access Database, and the client requested that a DATE field be added to a form.
Problem is, I have NEVER used Access before.  I'm a SQL guy, and I build my own UI's.
This forms thing is getting the better of me.

Ok - So I have two tables:
tblQuestionairre
QuestionairreID
EventID
blah blah blah

tblEvent
EventID
DateTime
blah blah blah

Now, I am editing the frmQuestionairre (Questionairre Form).  All the information from the Questionairre Table (tblQuestionairre) is here.
Problem is, I need to add the DateTime field somewhere on this form so that the client can see when the questionairre was entered.
As you can see, my linking item is EventID.

Try as I might, I cannot just "add" DateTime from the Event table using "expression builder".  I need to load the correct DateTime for the current Questionairre that is loaded.  Each Questionairre is linked to an Event.

How can I add this field to the Questionairre form?  I keep getting a #Name? error, which is obviously because it doesn't know to link the two tables on EventID..
Ideas?

Edit:
Yes this is a simple 1 to 1 relationship.
Yes the field needs to be editable.

ANSWER: =DLookUp("[DateEntered]","tblEvent","EventID=" & Forms!frmQuestionnaire!EventID)

Edit: Now that I have it displaying, I cannot edit it!?

答:
You need to change the RecordSource of the Form so that it is linked to a query joining the two tables rather than just one.

In your case, edit the RecordSource property and either use the designer to create the query or click on the SQL button to enter something like this:

```<code>SELECT tblQuestionaire.QuestionaireID,
       tblQuestionaire.EventID,
       tblQuestionaire.blahblah,
       tblEvent.DateTime,
       tblEvent.blahblahblah
FROM tblQuestionaire
INNER JOIN tblEvent
      ON tblQuestionaire.EventID=tblEvent.EnventID;
</code>```

This assumes that you have a strict 1 to 1 relationship between the tables, otherwise, use a LEFT JOIN if it is a 1 to [0,1] relationship.

OwnerDisplayName: Kolten

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: CodeSlave

Body:
You need to change the RecordSource of the Form so that it is linked to a query joining the two tables rather than just one.

In your case, edit the RecordSource property and either use the designer to create the query or click on the SQL button to enter something like this:

SELECT tblQuestionaire.QuestionaireID,
       tblQuestionaire.EventID,
       tblQuestionaire.blahblah,
       tblEvent.DateTime,
       tblEvent.blahblahblah
FROM tblQuestionaire
INNER JOIN tblEvent
      ON tblQuestionaire.EventID=tblEvent.EnventID;

This assumes that you have a strict 1 to 1 relationship between the tables, otherwise, use a LEFT JOIN if it is a 1 to [0,1] relationship.

OwnerDisplayName: Renaud Bompuis


问:
Named parameters functions in Clojure
This code discussing named arguments in Clojure from "The Joy of Clojure":

```<code>(defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}]
   (float (/ (- (p2 1) (p1 1))
             (- (p2 0) (p1 0)))))

(slope :p1 [4 15] :p2 [3 21])
</code>```

The function itself, I understand it -no problem with destructuring- but I don't understand the calling.

Are we passing four arguments to slope? how vectors are getting assigned to :p1 and :p2?

答: You are passing four arguments to slope, yes. The [] part of slope specifies the parameters, in which & means "slurp all additional parameters into this form", which then specifies that it is looking for arguments that form a map with keys p1 and p2 (and gives default values if either doesn't exist).

ContentLicense: CC BY-SA 3.0

Title: Named parameters functions in Clojure

Body:
This code discussing named arguments in Clojure from "The Joy of Clojure":

(defn slope [& {:keys [p1 p2] :or {p1 [0 0] p2 [1 1]}}]
   (float (/ (- (p2 1) (p1 1))
             (- (p2 0) (p1 0)))))

(slope :p1 [4 15] :p2 [3 21])

The function itself, I understand it -no problem with destructuring- but I don't understand the calling.

Are we passing four arguments to slope? how vectors are getting assigned to :p1 and :p2?


问:
Substitute parts of CWD in bash prompt (Git Bash)
This is in Git Bash

I am trying to make my prompt go from

```<code>/c/folder $
</code>```

to

```<code>c->folder $
</code>```

What would I put in my .bashrc to make this work? Is it even possible?

答:
You can do arbitrary things to your prompt by setting PROMPT_COMMAND to a function that assigns PS1:

```<code>PROMPT_COMMAND="setmyprompt"
setmyprompt() {
  dir="${PWD#/}"
  dir="${dir//\//->}"
  PS1="$dir \\\$ "
}
</code>```

Body:
This is in Git Bash

I am trying to make my prompt go from

/c/folder $

to

c->folder $

What would I put in my .bashrc to make this work? Is it even possible?

Body:
You can do arbitrary things to your prompt by setting PROMPT_COMMAND to a function that assigns PS1:

PROMPT_COMMAND="setmyprompt"
setmyprompt() {
  dir="${PWD#/}"
  dir="${dir//\//->}"
  PS1="$dir \\\$ "
}


Title: One php array with some values for some indexs

Body:
I wanna create an array or a function n php with something like this:

for index between 1-20 returns "type 1"

for index between 20-25 returns "type 2"

for index between 25-35 returns "type 1"

for index between 35-40 returns "type 3"

for index between 40-60 retusn "type 2".

How can I do this?

For example id 1, id 22, id 50 can be type 1, but also id 2, id 23, id 51 are type 2.

I've tried this:

function getSkinType($id) {
    $skins = array(
        0,13,40,46,47,59,60,72,73,76,82,83,84,85,90,91,93,98,102,103,104,105,106,107,108,109,110,111,112, 113,114,115,116,120,121,123,124,125,126,127,128,141,147,150,163,164,165,166,169,170,173,174,175,177,181,185,186,187,189,191,193,194,192,195,203,204,216,219,221,223,228,233,240,258,259,263,269,270,271,272,290,292,293,294,295,296,297,298,299,3 => "premium",
        2,7,9,11,14,15,16,17,19,20,21,22,18,23,24,25,28,29,30,32,33,34,35,36,41,43,44,45,48,51,52,57,58,63,64,66,67,69,88,92,95,96,97,100,101,122,131,133,138,139,140,142,143,148,154,155,156,167,171,172, 176,179,180,182,183, 184,188,190,201,202,206,214,215,222,224,225,226,227,234,238,247,248,249,250,251,252 => "normal",
        1,12,27,31,37,50,56,78,79,129,134,135,136,137,152,153,157,158,159,160,161,162,196,200,212 => "default"
    );
    return $skins[$id];
}

Body:
One possible approach would be to simply make use of an index in the $kins array to represent the category. This could be passed into the function itself. For example, if you wanted to retrieve the 82 skin (at index 10 of the first category), you could use the following:

<?php

function getSkinType($category, $id) {
$skins = array(
    [0,13,40,46,47,59,60,72,73,76,82,83,84,85,90,91,93,98,102,103,104,105,106,107,108,109,110,111,112, 113,114,115,116,120,121,123,124,125,126,127,128,141,147,150,163,164,165,166,169,170,173,174,175,177,181,185,186,187,189,191,193,194,192,195,203,204,216,219,221,223,228,233,240,258,259,263,269,270,271,272,290,292,293,294,295,296,297,298,299,3],
    [2,7,9,11,14,15,16,17,19,20,21,22,18,23,24,25,28,29,30,32,33,34,35,36,41,43,44,45,48,51,52,57,58,63,64,66,67,69,88,92,95,96,97,100,101,122,131,133,138,139,140,142,143,148,154,155,156,167,171,172,176,179,180,182,183, 184,188,190,201,202,206,214,215,222,224,225,226,227,234,238,247,248,249,250,251,252],
    [1,12,27,31,37,50,56,78,79,129,134,135,136,137,152,153,157,158,159,160,161,162,196,200,212]
);
    return $skins[$category][$id];
}

echo getSkinType(0, 10); // 82

In the above, category 0 corresponds to premium, 1 corresponds to normal, and 2 corresponds to default. If you wanted, you could set up variables for these and use the variables instead.

An alternative approach would be to use associative arrays rather than a category index, but that accomplishes essentially the same thing.


问:
Python Dataclasses: FrozenInstanceError a subclass of AttributeError?
I'm doing some self-learning on the new python dataclasses.

One of the parameters that can be passed to the dataclass decorator is frozen=True, to make the object immutable.

The documentation (and experience) indicates that a:

```<code>dataclasses.FrozenInstanceError
</code>```

exception will be raised.

When unit testing though (with pytest) the following test passes:

```<code>def test_change_page_url_values_raises_error(self, PAGE_URL):
    page_url = PageURL(PAGE_URL)
    with pytest.raises(AttributeError) as error:
        page_url.value = PAGE_URL
</code>```

where PageURL is a dataclass with the frozen=True parameter.

Any ideas why why pytest indicates that this action (assigning a value to page_url.value) raises an Attribute Error? Does FrozenInstanceError inherit from AttributeError?

Note: If I change the unit test to test for a different exception (ie. TypeError), the test fails as expected.

答:
This is a subclass, which you can verify easily with built-in function issubclass:

```<code>>>> issubclass(FrozenInstanceError, AttributeError)
True
</code>```

If you want an exact type match in the tests, which I would consider best practice, then you can use an exception instance instead of an exception class. As an added bonus this also allows you to make an assertion on the exception context (i.e. which field has triggered the exception).

```<code>with pytest.raises(FrozenInstanceError("cannot assign to field 'value'")):
    page_url.value = PAGE_URL
</code>```

This usage of pytest.raises requires installing my plugin pytest-raisin.

Body:
I'm doing some self-learning on the new python dataclasses.

One of the parameters that can be passed to the dataclass decorator is frozen=True, to make the object immutable.

The documentation (and experience) indicates that a:

dataclasses.FrozenInstanceError

exception will be raised.

When unit testing though (with pytest) the following test passes:

def test_change_page_url_values_raises_error(self, PAGE_URL):
    page_url = PageURL(PAGE_URL)
    with pytest.raises(AttributeError) as error:
        page_url.value = PAGE_URL

where PageURL is a dataclass with the frozen=True parameter.

Any ideas why why pytest indicates that this action (assigning a value to page_url.value) raises an Attribute Error? Does FrozenInstanceError inherit from AttributeError?

Note: If I change the unit test to test for a different exception (ie. TypeError), the test fails as expected.

Body:
This is a subclass, which you can verify easily with built-in function issubclass:

>>> issubclass(FrozenInstanceError, AttributeError)
True

If you want an exact type match in the tests, which I would consider best practice, then you can use an exception instance instead of an exception class. As an added bonus this also allows you to make an assertion on the exception context (i.e. which field has triggered the exception).

with pytest.raises(FrozenInstanceError("cannot assign to field 'value'")):
    page_url.value = PAGE_URL

This usage of pytest.raises requires installing my plugin pytest-raisin.


问:
How to fix web components not showing in Microsoft Edge
I'm trying out lit-element and everything was going well with browsers such as Chrome and Firefox. But I faced a problem when I tried Microsoft Edge and IE11. The web component that shows in Chrome and Firefox doesn't show in Microsoft Edge and IE11.

I did some search on the internet and also read the documentation of Lit Element and it says I will need to load the polyfills in order for the web components to work in Edge and IE11, however I have encountered problems while trying to do so.

The code that I'm using to load my polyfills are as follow,

```<code><script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js"></script>
  <script src="https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-loader.js"></script>

<script type="module">
  window.WebComponents = window.WebComponents || {
    waitFor(cb){ addEventListener('WebComponentReady', cb) }
  }
  WebComponents.waitFor(async () => {
    import('mypath/somecomponent.js');
  });
</script>
</code>```

I used the developer tools in Microsoft Edge and the following are showing.

SCRIPT5022: SCRIPT5022: Syntax error

When i click into the debugger it also shows the following message

Could not locate https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/ [synthetic:util/global] specified in source map https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js.map.

Any help will be greatly appreciated!!

答:
Read what @Harshal said and:

Don't use WebComponentReady it has been deprecated.

Instead use customElements.whenDefined.

You will also need a Promise polyfill.

You do not need a bundler, like webpack but you will need to transpile your ES6 code into ES5 code using something like Babel. This will convert things that can not be polyfilled into code that will work in IE11 and can convert your export code into plain old IIFE style code.

Body:
I'm trying out lit-element and everything was going well with browsers such as Chrome and Firefox. But I faced a problem when I tried Microsoft Edge and IE11. The web component that shows in Chrome and Firefox doesn't show in Microsoft Edge and IE11.

I did some search on the internet and also read the documentation of Lit Element and it says I will need to load the polyfills in order for the web components to work in Edge and IE11, however I have encountered problems while trying to do so.

The code that I'm using to load my polyfills are as follow,

I used the developer tools in Microsoft Edge and the following are showing.

SCRIPT5022: SCRIPT5022: Syntax error

When i click into the debugger it also shows the following message

Could not locate https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/ [synthetic:util/global] specified in source map https://unpkg.com/@webcomponents/webcomponentsjs@2.2.7/webcomponents-bundle.js.map.

Any help will be greatly appreciated!!


答:
You do not need to wrap the input inside the label.

Highlighting adjacent label only

If you want to highlight the  and do not want to use JS then you have to change the order of the elements. Take <input>' first and` later. Because in CSS when we use

input[type="checkbox"]:checked + label it expect the  to be its next element aka Sibling of the input.

Here is what you can try

input[type="checkbox"]:checked + label {
  border: 2px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="wordBanks">
  <input type="checkbox" id="perksCheck" selected>
  <label for="perksCheck">Perks </label>
  <input type="checkbox" id="equipmentCheck">
  <label for="equipmentCheck">Euipment</label>
</form></code>```

Highlighting Checkbox only

If the goal is to highlight the checkbox then you can add box-shadow to it.

input[type="checkbox"]:checked {
  box-shadow: 0 0 0 3px black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="wordBanks">
  <label for="perksCheck">Perks<input type="checkbox" id="perksCheck" selected></label>
  <label for="equipmentCheck">Euipment<input type="checkbox" id="equipmentCheck"></label>
</form></code>```

Read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:checked

Body:
You do not need to wrap the input inside the label.

Highlighting adjacent label only

If you want to highlight the <label> and do not want to use JS then you have to change the order of the elements. Take <input>' first and` later. Because in CSS when we use

input[type="checkbox"]:checked + label it expect the <label> to be its next element aka Sibling of the input.

Here is what you can try

input[type="checkbox"]:checked + label {
  border: 2px solid black;
}

<form id="wordBanks">
  <input type="checkbox" id="perksCheck" selected>
  <label for="perksCheck">Perks </label>
  <input type="checkbox" id="equipmentCheck">
  <label for="equipmentCheck">Euipment</label>
</form>

Highlighting Checkbox only

If the goal is to highlight the checkbox then you can add box-shadow to it.

input[type="checkbox"]:checked {
  box-shadow: 0 0 0 3px black;
}

<form id="wordBanks">
  <label for="perksCheck">Perks<input type="checkbox" id="perksCheck" selected></label>
  <label for="equipmentCheck">Euipment<input type="checkbox" id="equipmentCheck"></label>
</form>

Read more here https://developer.mozilla.org/en-US/docs/Web/CSS/:checked


问:
Setting netrw like NERDTree

I used nmap <silent> <f2> :NERDTreeToggle<cr> to toggle nerdtree window. How can I do the same with netrw?

nerdtree window is not shown in the buffer list(:ls). netrw is listed in the buffer list. How can I make it not listed?

:bn command works but :bp command does not work in the netrw window. Is this a bug?

答:
The 'Vexplore' command opens a vertical directory browser. You can build on this by adding the following code to your .vimrc file to toggle the vertical browser with Ctrl-E (for example):

```<code>" Toggle Vexplore with Ctrl-E
function! ToggleVExplorer()
  if exists("t:expl_buf_num")
      let expl_win_num = bufwinnr(t:expl_buf_num)
      if expl_win_num != -1
          let cur_win_nr = winnr()
          exec expl_win_num . 'wincmd w'
          close
          exec cur_win_nr . 'wincmd w'
          unlet t:expl_buf_num
      else
          unlet t:expl_buf_num
      endif
  else
      exec '1wincmd w'
      Vexplore
      let t:expl_buf_num = bufnr("%")
  endif
endfunction
map <silent> <C-E> :call ToggleVExplorer()<CR>
</code>```

The code above tries to open the Explorer window on the left hand side of the screen at all times; I use it with multiple split vertical windows open.

[OPTIONAL] You might like to add the following lines to your .vimrc to improve the browsing experience:

```<code>" Hit enter in the file browser to open the selected
" file with :vsplit to the right of the browser.
let g:netrw_browse_split = 4
let g:netrw_altv = 1

" Change directory to the current buffer when opening files.
set autochdir
</code>```

Title: Setting netrw like NERDTree

Body:
The 'Vexplore' command opens a vertical directory browser. You can build on this by adding the following code to your .vimrc file to toggle the vertical browser with Ctrl-E (for example):

" Toggle Vexplore with Ctrl-E
function! ToggleVExplorer()
  if exists("t:expl_buf_num")
      let expl_win_num = bufwinnr(t:expl_buf_num)
      if expl_win_num != -1
          let cur_win_nr = winnr()
          exec expl_win_num . 'wincmd w'
          close
          exec cur_win_nr . 'wincmd w'
          unlet t:expl_buf_num
      else
          unlet t:expl_buf_num
      endif
  else
      exec '1wincmd w'
      Vexplore
      let t:expl_buf_num = bufnr("%")
  endif
endfunction
map <silent> <C-E> :call ToggleVExplorer()<CR>

The code above tries to open the Explorer window on the left hand side of the screen at all times; I use it with multiple split vertical windows open.

[OPTIONAL] You might like to add the following lines to your .vimrc to improve the browsing experience:

" Hit enter in the file browser to open the selected
" file with :vsplit to the right of the browser.
let g:netrw_browse_split = 4
let g:netrw_altv = 1

" Change directory to the current buffer when opening files.
set autochdir


问:
Duplicate 'Content' items were included. .json file in assets folder in .net core angular 6 web app
I have a .Net Core 2.1 web application using Angular 6 for the front-end, developed in Visual Studio 2017.

Inside my Angular assets folder I also have a json folder with a single file: iconClasses.json. When I publish this, I first build the angular app with ng build --prod from within the ClientApp folder. This moves the .json file to the dist folder, as expected:

In my .csproj the only ItemGroups are:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />

    </ItemGroup>
```

<p>Publishing this results in the following error:</p>

<blockquote>
  <p>Duplicate 'Content' items were included. The .NET SDK includes
  'Content' items from your project directory by default. You can either
  remove these items from your project file, or set the
  'EnableDefaultContentItems' property to 'false' if you want to
  explicitly include them in your project file. For more information,
  see https://aka.ms/sdkimplicititems. The duplicate items were: 'ClientApp\dist\assets\json\iconClasses.json'  </p>
</blockquote>

<p>Uncommenting the line that explicitly removes this file allows the publish to proceed, but the file is removed from the final published package. </p>

<p>Comparing the .js files in the dist/assets/js folder to the .json in the dist/assets/json shows that they are all of build action 'Content' and 'Do not copy'. Setting the build action of the .json file to 'None' simply adds the <code><Content Remove /></code> as above, but also:</p>

<pre class="lang-xml prettyprint-override"><code>    <ItemGroup>
      <None Include="ClientApp\dist\assets\json\iconClasses.json" />
    </ItemGroup>
</code>```

Again, this simply results in the .json file being removed from the publish package.

I did notice that the src\assets\json\iconClasses.json file's build action was set to 'Content' whereas the other src\assets files were set to 'None', so I set the .json file to 'None' also. However, this resulted in the same error, unless the dist version was explicitly removed also.

Adding the following to my PropertyGroup in my .csproj includes the .json file in the dist/assets/json but then misses out other files my system needs:

<EnableDefaultContentItems>false</EnableDefaultContentItems>
```

So, how can I have a .json file in the assets folder get moved to the dist assets folder? Is the only way to set EnableDefaultContentItems to false, figure out all the missing files and add them manually?

答:
Solution:

Change the adding of the dist folder from this:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>
```

<p>to this:</p>

<pre class="lang-xml prettyprint-override"><code>    <ItemGroup>
        <None Include="ClientApp\dist\**" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>
</code>```

i.e. change it from Content to None.

Extras:

Only the .json files in the e2e and src folders needed to be explicitly removed, not the whole folders themselves:

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />
        <Content Remove="ClientApp\e2e\tsconfig.e2e.json" />
        <Content Remove="ClientApp\src\tsconfig.app.json" />
        <Content Remove="ClientApp\src\tsconfig.spec.json" />
        <Content Remove="ClientApp\src\tslint.json" />
        <Content Remove="ClientApp\src\assets\json\iconClasses.json" />
    </ItemGroup>
```

<p>This is because any .json (and .config) files are automatically included. <code>wwwroot</code> is also automatically added, but is not used in this angular client app. </p>

<p>And since I'm using <code>ng build --prod</code>, I went ahead and told VS to stop trying to compile the typescript, so added this in the <code>PropertyGroup</code>:</p>

<pre class="lang-xml prettyprint-override"><code>    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
</code>```

Body:
I have a .Net Core 2.1 web application using Angular 6 for the front-end, developed in Visual Studio 2017.

Inside my Angular assets folder I also have a json folder with a single file: iconClasses.json. When I publish this, I first build the angular app with ng build --prod from within the ClientApp folder. This moves the .json file to the dist folder, as expected:

In my .csproj the only ItemGroups are:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />

    </ItemGroup>

Publishing this results in the following error:

Duplicate 'Content' items were included. The .NET SDK includes
  'Content' items from your project directory by default. You can either
  remove these items from your project file, or set the
  'EnableDefaultContentItems' property to 'false' if you want to
  explicitly include them in your project file. For more information,
  see https://aka.ms/sdkimplicititems. The duplicate items were: 'ClientApp\dist\assets\json\iconClasses.json'

Uncommenting the line that explicitly removes this file allows the publish to proceed, but the file is removed from the final published package.

Comparing the .js files in the dist/assets/js folder to the .json in the dist/assets/json shows that they are all of build action 'Content' and 'Do not copy'. Setting the build action of the .json file to 'None' simply adds the <Content Remove /> as above, but also:

    <ItemGroup>
      <None Include="ClientApp\dist\assets\json\iconClasses.json" />
    </ItemGroup>

Again, this simply results in the .json file being removed from the publish package.

I did notice that the src\assets\json\iconClasses.json file's build action was set to 'Content' whereas the other src\assets files were set to 'None', so I set the .json file to 'None' also. However, this resulted in the same error, unless the dist version was explicitly removed also.

Adding the following to my PropertyGroup in my .csproj includes the .json file in the dist/assets/json but then misses out other files my system needs:

<EnableDefaultContentItems>false</EnableDefaultContentItems>

So, how can I have a .json file in the assets folder get moved to the dist assets folder? Is the only way to set EnableDefaultContentItems to false, figure out all the missing files and add them manually?

Body:
Solution:

Change the adding of the dist folder from this:

    <ItemGroup>
        <Content Include="ClientApp\dist\**\*" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

to this:

    <ItemGroup>
        <None Include="ClientApp\dist\**" CopyToPublishDirectory="PreserveNewest" />
    </ItemGroup>

i.e. change it from Content to None.

Extras:

Only the .json files in the e2e and src folders needed to be explicitly removed, not the whole folders themselves:

    <ItemGroup>
        <Content Remove="appsettings.Development.json" />
        <Content Remove="ClientApp\e2e\tsconfig.e2e.json" />
        <Content Remove="ClientApp\src\tsconfig.app.json" />
        <Content Remove="ClientApp\src\tsconfig.spec.json" />
        <Content Remove="ClientApp\src\tslint.json" />
        <Content Remove="ClientApp\src\assets\json\iconClasses.json" />
    </ItemGroup>

This is because any .json (and .config) files are automatically included. wwwroot is also automatically added, but is not used in this angular client app.

And since I'm using ng build --prod, I went ahead and told VS to stop trying to compile the typescript, so added this in the PropertyGroup:

    <TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>


问:
Increased Records while reading tar file with JSON formatted Data
20190528.tar.gz file has 144,390 files and 22,673,735 records. Each file has some thousands JSON formatted data.

One Raw Record in single line [I've structured this to understand better]:

```<code>{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}
</code>```

I'm reading the tar.gz file and trying to make pipe separated CSV Files.

Here Is My Code

```<code>#!/usr/bin/python
import json
import csv
import ast
import tarfile

def write_sms_dat_to_csv_file():
        tar= tarfile.open('20190528.tar.gz','r:gz')
        csv_writer = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
        for member in tar.getmembers():
                f = tar.extractfile(member)
                if f is not None:
                        data = []
                        for line in f.readlines():
                                print(line.strip())
                                data.append(json.loads(line.strip()))
                                for dt in data:
                                        csv_writer.writerow([dt['c_id'],dt['msisdn'],ast.literal_eval(dt['amd'])['mask'],ast.literal_eval(dt['amd'])['ec']])

if __name__=="__main__":
        write_sms_dat_to_csv_file()
</code>```

Above code has no issues, works fine. The problem is its creating the CSV file with more records than it should.  I mean much more records. Code is not finishing even the output records reached 30 million. I had to kill.

I mean output record number should be same as input record number.

I'm failing to find the bug in my code for which record is being duplicated.

Could you help to find the error in logic? Thanks.

答:
The problem is in the data list. It is keeping memory every time you read lines and then you loop over it again to do the csv write. Not too sure why you need data ...

Try this

```<code>if f is not None:
    for line in f.readlines():
        print(line.strip())
        dt = json.loads(line.strip())
        csv_writer.writerow([dt['c_id'], .....
</code>```

Body:
20190528.tar.gz file has 144,390 files and 22,673,735 records. Each file has some thousands JSON formatted data.

One Raw Record in single line [I've structured this to understand better]:

{
    "t_id":"80740185.1558980000000.120184.121164",
    "s_id":"80740185",
    "pt_slot":"null:null",
    "ch_id":1,"o_id":121164,"c_id":120184,
    "msg_type":1,
    "amd":"{
                \"msg\":\" some Bengali text\",
                \"mask\":\"1GB_OFFER\",
                \"ec\":\"1\",
                \"time-out\":\"0\",
                \"validity\":\"30052019 000000\"
           }",
    "time":1558960217731,
    "dlr":"1",
    "msisdn":"xxxxx",
    "entity":1
}

I'm reading the tar.gz file and trying to make pipe separated CSV Files.

Here Is My Code

#!/usr/bin/python
import json
import csv
import ast
import tarfile

def write_sms_dat_to_csv_file():
        tar= tarfile.open('20190528.tar.gz','r:gz')
        csv_writer = csv.writer(open('csv_data.txt','wb+'),delimiter = '|')
        for member in tar.getmembers():
                f = tar.extractfile(member)
                if f is not None:
                        data = []
                        for line in f.readlines():
                                print(line.strip())
                                data.append(json.loads(line.strip()))
                                for dt in data:
                                        csv_writer.writerow([dt['c_id'],dt['msisdn'],ast.literal_eval(dt['amd'])['mask'],ast.literal_eval(dt['amd'])['ec']])

if __name__=="__main__":
        write_sms_dat_to_csv_file()

Above code has no issues, works fine. The problem is its creating the CSV file with more records than it should.  I mean much more records. Code is not finishing even the output records reached 30 million. I had to kill.

I mean output record number should be same as input record number.

I'm failing to find the bug in my code for which record is being duplicated.

Could you help to find the error in logic? Thanks.

Body:
The problem is in the data list. It is keeping memory every time you read lines and then you loop over it again to do the csv write. Not too sure why you need data ...

Try this

if f is not None:
    for line in f.readlines():
        print(line.strip())
        dt = json.loads(line.strip())
        csv_writer.writerow([dt['c_id'], .....


问:
How to create a type containing only the common properties from a type union?
I want to map over union of arrays, how can I make it type safely?

I have a solution, but I want to avoid hard-coding the types from the type union.
When calculating newArr1, as expected, I get an error: Property 'field2' does not exist on type 'Common'
Is there a way to get the same error when calculating newArr2?

(link to code)

interface A {
    field1: string
    field2: number
}
interface B {
    field1: string
}

type Common = {
    [P in keyof A & keyof B]: A[P] | B[P];
}

function mapArray(arr: A[] | B[]) {

    const newArr1 = (arr as Common[]).map(i => i.field2) // error

    // how can I get the same error without hard-coding the types from the type union?
    const newArr2 = (arr as MagicEventuallyFromJcalz<typeof arr>).map(i => i.field2)

    return newArr1
}
```

答:
Thanks jcalz and William Lohan!

A real use case: for 2 different requests from an external api, I get 2 different responses:

an array with users having many details about each user, and

an array with users having a small subset of the details from the previous point

Using the same function which parses either one of the 2 array from above, I want to get the users' ids (id is a common property of users from both arrays), 1) in a type safe manner and 2) without hard-coding the array types in function body. Based on your comments jcalz, I was able to achive that. You deserve the credit for the solution, if you post an answer, I'll mark it as accepted.

The solution I found (link to code):

interface DetailedUser {
    id: number
    many: number
    other: string
    fields: boolean
}
interface CompactUser {
    id: number
}

type Common<T> = Pick<T, keyof T>

type UnpackedFromArray<T> = T extends (infer U)[] ? U : never

function getUserIdsFromApi(usersJsonFromApi: DetailedUser[] | CompactUser[]) {

    // works as expected: in both lines below, a ts error is raised
    // note that the types (DetailedUser[], CompactUser[]) are not hard-coded, but determined from variable usersJsonFromApi

    const userIds1 = (usersJsonFromApi as Common<UnpackedFromArray<typeof usersJsonFromApi>>[]).map(i => i.other)

    const userIds2 = (usersJsonFromApi as Common<typeof usersJsonFromApi[number]>[]).map(i => i.other)

    return userIds1
}
```

Body:
I want to map over union of arrays, how can I make it type safely?

I have a solution, but I want to avoid hard-coding the types from the type union.
When calculating newArr1, as expected, I get an error: Property 'field2' does not exist on type 'Common'
Is there a way to get the same error when calculating newArr2?

(<a href="https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgILIN4Chm+TYCAGwBMBGALmQGcwpQBzHPA4kgJipAFcBbAI2hYAvllCRYiFACFMzXK1KUadRiKxYwATwAOKAMIB7Xr0MgAPKgA0yaQD5kAXjl5kAbQAKyUMgDWELUMYNGQAMj8AoNsAXSpUT2jkAB9bBIBudSwYbhAEMGAzZF44HVQoKDgtAAo4cri3RJTpBoBKOXlkBDNaZBAIAHcyqDInZBry5DhqZCMTM0sbe1aAOmKdKuAnB2BlxQ42gHoDyemIAA89PIgSG2goQygqD3u9KG1kAHI99g-kEkMINMQIYwMhzsAeoVtHpPrNTBZrLY7B8NK4jsgABaGfqdOAgZAASWQDAgoLAGJQ1DgvBQdweyH6wHJhm4oIxtRIAFouiRGMhyShoYD8PdePyKfzdCgcgUQAB+DpdEA9PqDcrsUbjKAnZAAWTgDGACAAogA3CDgbhwIhELQAMVFACkENaAF7mIVRWpQOwtVYlDZbby7QikdgtVF4KCk7hQfGqoZkTJAA" rel="nofollow noreferrer">link to code)

interface A {
    field1: string
    field2: number
}
interface B {
    field1: string
}

type Common = {
    [P in keyof A & keyof B]: A[P] | B[P];
}

function mapArray(arr: A[] | B[]) {

    const newArr1 = (arr as Common[]).map(i => i.field2) // error

    // how can I get the same error without hard-coding the types from the type union?
    const newArr2 = (arr as MagicEventuallyFromJcalz<typeof arr>).map(i => i.field2)

    return newArr1
}

Body:
Thanks jcalz and William Lohan!

A real use case: for 2 different requests from an external api, I get 2 different responses:

an array with users having many details about each user, and

an array with users having a small subset of the details from the previous point

Using the same function which parses either one of the 2 array from above, I want to get the users' ids (id is a common property of users from both arrays), 1) in a type safe manner and 2) without hard-coding the array types in function body. Based on your comments jcalz, I was able to achive that. You deserve the credit for the solution, if you post an answer, I'll mark it as accepted.

The solution I found (<a href="https://typescript-play.js.org/#code/JYOwLgpgTgZghgYwgAgCITHYAbCATAVQGdpkBvAKGWuWDwC5kQBXAWwCNoqbW4QBPRiw5cayAPZgAFtEZEwUUAHNu1GMAjY8RRu3HjcfCgF8KoSLEQoAwuNYAHRGGKlKYukLacoJihTD89jZ2rOIgADwAKgB8yAC8yAAKwAgA1lEANMipEPziMMgxfgFByAQgjmn4AGJQdgCCUFBw-FGxCZHIEAAekCDayAAUoDCkBACUANoAusgA-GXIQhAAblwUMMwgCGDAYchKGC5QAJLatQ32wIPMJFBEAFJEYRes9VeM6Jg4+MczyAAfZC2BxOP7TcbkPxiAD0MOQAHdxFBUkRkHA0T0gjt8IxQMg9NJkNhQBA0ZxsOIEVk4MgwJimsjaGjmsASHhEcBpOJmGBkFI4FA8ABaBDiPDKOkyOmBMnIGB1VhSlBbPYgGVBaE0MUgeTIW7QM5EACM8SGBvuTxeivewHRaJBoQi5UqOTwr0azVaJQg+X1d0ezxAHqu0WiM3GADpePZhvFYsBI5IZFBxlrqDq9RajQAmM03ANW4M2q724EhMLhH1+i2B62XYCTYTeabhiHRuCxu1xBNJ6TQNOqZBQDDMKDq7PaY2+ChAA" rel="nofollow noreferrer">link to code):

interface DetailedUser {
    id: number
    many: number
    other: string
    fields: boolean
}
interface CompactUser {
    id: number
}

type Common<T> = Pick<T, keyof T>

type UnpackedFromArray<T> = T extends (infer U)[] ? U : never

function getUserIdsFromApi(usersJsonFromApi: DetailedUser[] | CompactUser[]) {

    // works as expected: in both lines below, a ts error is raised
    // note that the types (DetailedUser[], CompactUser[]) are not hard-coded, but determined from variable usersJsonFromApi

    const userIds1 = (usersJsonFromApi as Common<UnpackedFromArray<typeof usersJsonFromApi>>[]).map(i => i.other)

    const userIds2 = (usersJsonFromApi as Common<typeof usersJsonFromApi[number]>[]).map(i => i.other)

    return userIds1
}


问:
Why so much noise in my scipy.FFT and does it need normalising?
I have experience of doing ffts in matlab but am new to python, I am trying to generate a signal and perform an fft using scipy/numpy/matplotlib. The output graph seems noisy and the amplitude seems high, what am I doing wrong?
Any help would be appreciated...

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

fs = 44100.0
f = 10000.0
f2 = 6000.0;
ts = 1.0/fs
dur = 1
x = np.arange(0, dur, ts);
y = np.sin(2*np.pi*f*x) + 0.5*np.sin(2*np.pi*f2*x);
y = y/np.max(np.abs(y));

N = len(y);
Y = fft(y, N)
Y = Y[0:round(N/2)]
magsY = abs(Y);
magsY = 20*np.log10(magsY);

f = np.linspace(0, fs/2, round(N/2))
plt.figure()
plt.plot(y)
plt.figure()
plt.plot(f, magsY)
plt.show()
```

答:
I don't think it's noisy at all. It looks that way because of you take the log of magsY. Instead, it may be easier to see if you comment out magsY = 20*np.log10(magsY) and use a semilogy plot on magsY instead. You would just change the plt.plot(f, magsY) to plt.semilogy(f, magsY).

Your noise peaks around a level of 10e-8 and your actual signal is sitting at ~10e4. Your signal-to-noise ratio is then 10e4/10e-8 = 10e12. To me, this isn't noisy but if this is too much for you, then take a closer look at your actual signal (y). If you zoom in you'll see that the points are very jagged. You'll need to increase your resolution to produce a nicer looking signal.

Edit:
To add a little bit more--The absolute amplitude of the peaks is not really what's important. Instead, their amplitudes relative to each other is what is really useful. For your data set, I extracted that the f=10000 peak has an amplitude of 15550.74669 and the f=6000 peak has an amplitude of 7775.37335. The ratio of these is 1.9999999987which is exactly what we should expect from how you constructed y; the frequency f is twice as prevalent as frequency f2.


问:
Integrating Okta with ASP.NET webforms application
I am trying to connect Okta to ASP.NET web forms application and was successful in doing so but I am unable to fetch user ID i.e. Email ID from the okta.

I followed the following link for integrating okta with ASP.NET - https://developer.okta.com/blog/2018/08/29/secure-webforms-with-openidconnect-okta

I was able to fetch user name using -

<%= ((Page.User.Identity.Name).ToString()) %>

Please help me to fetch email id from okta.

答: You need to open Profile Editor on OKTA admin website and update application's Profile Mapping to map user.login -> name. </p>


问:
is it possible to disable mp3 controls when loading an mp3 file via http headers using php
I'm creating a portfolio website for my music and want to allow users to play my songs without them being able to see the source/download the mp3 files.

I'm using PHP for this project and loading the files via HTTP headers.

```<code><?php
 $mp3 ='72vox.mp3';
 if(file_exists($mp3)) {
   header('Content-Type: audio/mpeg');
   header('Content-Disposition: inline; filename="mp3_file.mp3"');
   header('Content-length: '. filesize($mp3));
   header('Cache-Control: no-cache');
   header('Content-Transfer-Encoding: chunked');
   readfile($mp3);
   exit;
  }
?>
</code>```

When the page loads, my mp3 plays. However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div).

Thank you for any help in advance

答:
"However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div)."

As an example...

Save your PHP code in a file called getFile.php.
Now create an HTML page with code like below, and use the PHP file as source in an <audio tag>.
 You can extend the HTML with your own "other stuff" code.

```<code><!DOCTYPE html>
<html>
<body>

<div id="div_myAudio">
    <audio id="myAudio" controls>
    <source crossorigin="anonymous" src="getFile.php" type="audio/mpeg">
    </audio>
</div>

<div id="div_myOtherStuff">

    My "Other Stuff" (HTML code) goes here or anywhere inside this document "body" tag...

</div>

</body>
</html>
</code>```

Body:
I'm creating a portfolio website for my music and want to allow users to play my songs without them being able to see the source/download the mp3 files.

I'm using PHP for this project and loading the files via HTTP headers.

<?php
 $mp3 ='72vox.mp3';
 if(file_exists($mp3)) {
   header('Content-Type: audio/mpeg');
   header('Content-Disposition: inline; filename="mp3_file.mp3"');
   header('Content-length: '. filesize($mp3));
   header('Cache-Control: no-cache');
   header('Content-Transfer-Encoding: chunked');
   readfile($mp3);
   exit;
  }
?>

When the page loads, my mp3 plays. However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div).

Thank you for any help in advance

Body:
"However, I can't seem to figure out how to display any HTML on the page (and more importantly, how to place the audio controls in a div)."

As an example...

Save your PHP code in a file called getFile.php.
Now create an HTML page with code like below, and use the PHP file as source in an <audio tag>.
 You can extend the HTML with your own "other stuff" code.

<!DOCTYPE html>
<html>
<body>

<div id="div_myAudio">
    <audio id="myAudio" controls>
    <source crossorigin="anonymous" src="getFile.php" type="audio/mpeg">
    </audio>
</div>

<div id="div_myOtherStuff">

    My "Other Stuff" (HTML code) goes here or anywhere inside this document "body" tag...

</div>

</body>
</html>


问:
Javascript sort custom comparator function - sorting a sorted array
I have an array of objects of the following form:

```<code>arr[0] = { 'item1' : 1234, 'item2' : 'a string' };
</code>```

I sort it first by 'item1' which is straightforward. Now i want to sort arr (which is sorted by 'item1') again but this time by 'item2' but only for the elements where 'item1' is the same. The final array would look like:

```<code>arr = [
  { 'item1' : 1234, 'item2' : 'apple' },
  { 'item1' : 1234, 'item2' : 'banana' },
  { 'item1' : 1234, 'item2' : 'custard' },
  { 'item1' : 2156, 'item2' : 'melon' },
  { 'item1' : 4345, 'item2' : 'asparagus' }
];
</code>```

I tried to write a sorting function for the second case like so:

```<code>arr.sort(function(a,b){
  if(a.item1 === b.item1){
    return a.item2 > b.item2 ? 1 : a.item2 < b.item2 : -1 : 0;
  }
});
</code>```

I could combine the two sorts in one function to get the final sorted array but there will be cases where I'll have to sort by just 'item1' or just 'item2'.

答:
I'm using this helper in TypeScript:

```<code>// Source
type ComparatorSelector<T> = (value: T, other: T) => number | string | null;

export function createComparator<T>(...selectors: ComparatorSelector<T>[]) {
  return (a: T, b: T) => {
    for (const selector of selectors) {
      const valA = selector(a, b);
      if (valA === null) continue;
      const valB = selector(b, a);
      if (valB === null || valA == valB) continue;
      if (valA > valB) return 1;
      if (valA < valB) return -1;
    }
    return 0;
  };
}
</code>```

```<code>// Usage:
const candidates: any[] = [];
// ...
candidates.sort(createComparator(
  (x) => x.ambiguous,
  (_, y) => y.refCount, // DESC
  (x) => x.name.length,
  (x) => x.name,
));
</code>```

Body:
I have an array of objects of the following form:

arr[0] = { 'item1' : 1234, 'item2' : 'a string' };

I sort it first by 'item1' which is straightforward. Now i want to sort arr (which is sorted by 'item1') again but this time by 'item2' but only for the elements where 'item1' is the same. The final array would look like:

arr = [
  { 'item1' : 1234, 'item2' : 'apple' },
  { 'item1' : 1234, 'item2' : 'banana' },
  { 'item1' : 1234, 'item2' : 'custard' },
  { 'item1' : 2156, 'item2' : 'melon' },
  { 'item1' : 4345, 'item2' : 'asparagus' }
];

I tried to write a sorting function for the second case like so:

arr.sort(function(a,b){
  if(a.item1 === b.item1){
    return a.item2 > b.item2 ? 1 : a.item2 < b.item2 : -1 : 0;
  }
});

I could combine the two sorts in one function to get the final sorted array but there will be cases where I'll have to sort by just 'item1' or just 'item2'.

Body:
I'm using this helper in TypeScript:

// Source
type ComparatorSelector<T> = (value: T, other: T) => number | string | null;

export function createComparator<T>(...selectors: ComparatorSelector<T>[]) {
  return (a: T, b: T) => {
    for (const selector of selectors) {
      const valA = selector(a, b);
      if (valA === null) continue;
      const valB = selector(b, a);
      if (valB === null || valA == valB) continue;
      if (valA > valB) return 1;
      if (valA < valB) return -1;
    }
    return 0;
  };
}

// Usage:
const candidates: any[] = [];
// ...
candidates.sort(createComparator(
  (x) => x.ambiguous,
  (_, y) => y.refCount, // DESC
  (x) => x.name.length,
  (x) => x.name,
));


问:
Spring 3.1.x milestone repository
I am currently searching for a maven repository that contains the recent spring milestones of version 3.1.x.

There are a lot of links when searching google, but they all seem to be dead.

Does anyone know the link to the repository?

答:
http://maven.springframework.org/milestone

You can browse the S3 backed repo with Shrub
http://shrub.appspot.com/maven.springframework.org/

Title: Spring 3.1.x milestone repository


问:
Can I speed up this VBA function that queries an (AWS) mysql db?
I've written a function (see below) that queries an external MySQL database that's set up on AWS and returns a single value. It works fine - just like I wanted it to, really - except that it's fairly slow. If you're just using the function in a spreadsheet once, it's fine, but if you want to pull, say, 10 different numbers from your database into your spreadsheet, there's an annoying pause of several seconds (15?) while they all update.
It's not the end of the world, but it seems like it could/should be faster.

I wondered if the problem was that I was opening a new connection to the db each time I ran the function, so I tried to split the process up into a Sub that connects to the db, and a function that just submits the queries (see further below). I thought I'd run the "Connect" Sub once when I first opened the spreadsheet, and then use the querying function as needed, but that didn't work at all. I just got a "#VALUE" in any cell that included the function.

I realize that this is a pretty open-ended question and I apologize, but I'm stumped, and I thought someone on stackoverflow might have some good suggestions. It just seems like this should be faster than it is.
It probably goes without saying, but: I'm new to VBA and find it pretty wonky and confusing.

Original function:

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim Conn As ADODB.Connection
    Dim rs1 As ADODB.Recordset
    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring

    Dim querystring1 As String

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function
```

<p>Like I said, the above function seemed to work fine, just slow. </p>

<p>My "second attempt" was the following, which tried to split up the main database connection and the individual queries. This was a complete failure, as far as I could tell, but maybe there's some easy fix that I'm missing. Or does it matter? Would this approach be faster even if it worked?</p>

<pre class="lang-vb prettyprint-override"><code>Sub Connect()

    Dim Conn As ADODB.Connection
    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring
End Sub

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim querystring1 As String
    Dim rs1 As ADODB.Recordset

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function

</code>```

Any thoughts or suggestions would be much appreciated.

答:
Based on @Alex K.'s comment above, I changed the code as follows: </p>

```<code>Dim Conn As ADODB.Connection

Sub Connect()

    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring
End Sub

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim querystring1 As String
    Dim rs1 As ADODB.Recordset

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function
</code>```

<p>Conn is now set as a module level variable, so it works in both the Sub Connect() and the Quer function. With this change, the Quer function works and does, indeed, update much faster.
This change does not address the security/vulnerability issues with my code, but it solves my initial problem and helps me considerably with what I'm trying to do.
Thanks to everyone who commented for your help. </p>

Body:
I've written a function (see below) that queries an external MySQL database that's set up on AWS and returns a single value. It works fine - just like I wanted it to, really - except that it's fairly slow. If you're just using the function in a spreadsheet once, it's fine, but if you want to pull, say, 10 different numbers from your database into your spreadsheet, there's an annoying pause of several seconds (15?) while they all update.
It's not the end of the world, but it seems like it could/should be faster.

I wondered if the problem was that I was opening a new connection to the db each time I ran the function, so I tried to split the process up into a Sub that connects to the db, and a function that just submits the queries (see further below). I thought I'd run the "Connect" Sub once when I first opened the spreadsheet, and then use the querying function as needed, but that didn't work at all. I just got a "#VALUE" in any cell that included the function.

I realize that this is a pretty open-ended question and I apologize, but I'm stumped, and I thought someone on stackoverflow might have some good suggestions. It just seems like this should be faster than it is.
It probably goes without saying, but: I'm new to VBA and find it pretty wonky and confusing.

Original function:

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim Conn As ADODB.Connection
    Dim rs1 As ADODB.Recordset
    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring

    Dim querystring1 As String

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function

Like I said, the above function seemed to work fine, just slow.

My "second attempt" was the following, which tried to split up the main database connection and the individual queries. This was a complete failure, as far as I could tell, but maybe there's some easy fix that I'm missing. Or does it matter? Would this approach be faster even if it worked?

Sub Connect()

    Dim Conn As ADODB.Connection
    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring
End Sub

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim querystring1 As String
    Dim rs1 As ADODB.Recordset

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function

Any thoughts or suggestions would be much appreciated.

Body:
Based on @Alex K.'s comment above, I changed the code as follows:

Dim Conn As ADODB.Connection

Sub Connect()

    Dim connstring As String

    Set Conn = New ADODB.Connection

    connstring = "connection string"

    Conn.Open connstring
End Sub

Public Function Quer(Param1 As String, Param2 As String, Param3 As String)

    Dim querystring1 As String
    Dim rs1 As ADODB.Recordset

    querystring1 = "Select " & Param1 & " FROM table WHERE Param2 = " & Param2 & " AND Param3 = " & Param3

    Set rs1 = New ADODB.Recordset
    rs1.Open querystring1, Conn

    Record = rs1.GetRows

    Quer = Record(0, 0)

End Function

Conn is now set as a module level variable, so it works in both the Sub Connect() and the Quer function. With this change, the Quer function works and does, indeed, update much faster.
This change does not address the security/vulnerability issues with my code, but it solves my initial problem and helps me considerably with what I'm trying to do.
Thanks to everyone who commented for your help.


问:
ORA-01002: fetch out of sequence in oracle

ORA-01002: fetch out of sequence in oracle when using sys_refcursor.

I am expecting list of employees in the cursor. In my real scenario I need to check the count of employees and if count greater than zero I should use the same  select statement. Instead of executing same select statement multiple times I tried the below code snippet. But I am getting Fetch out of sequence error in the output cursor.

My table:

```<code>create or replace procedure sp_temp_1  (
var_job in VARCHAR2,
cur_custid out sys_refcursor
)
AS

  /* Declare Ref Cursor */
  --cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    temp_emp.firstname%TYPE,
    lastname     temp_emp.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;
</code>```

I am expecting list of employees , but the sys_refcursor is providing "fetch out of sequence error" in Oracle:

答:
When I use your code with my minor modifications I get no error.  Perhaps my working code can assist you?  Let me know if you have any questions or if I can assist further.

Summary

Declare Ref Cursor

Declare Type based off of the fields in my employees table

Declare Record based off of Type

Open Cursor and enter Loop

Within Loop populate record using the values FETCHed by the Cursor.

Using dbms_output show some output so we know it's working

Last, if zero rows returned by the cursor OPEN Cursor again using different SQL.

Employees Table

Code

```<code>DECLARE

  /* Declare Ref Cursor */
  cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    employees.firstname%TYPE,
    lastname     employees.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM employees
     WHERE JOB like '%Data Analyst%'; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
    dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;
</code>```

Body:
ORA-01002: fetch out of sequence in oracle when using sys_refcursor.

I am expecting list of employees in the cursor. In my real scenario I need to check the count of employees and if count greater than zero I should use the same  select statement. Instead of executing same select statement multiple times I tried the below code snippet. But I am getting Fetch out of sequence error in the output cursor.

My table:

create or replace procedure sp_temp_1  (
var_job in VARCHAR2,
cur_custid out sys_refcursor
)
AS

  /* Declare Ref Cursor */
  --cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    temp_emp.firstname%TYPE,
    lastname     temp_emp.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM temp_emp
     WHERE JOB = var_job; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
  dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;

I am expecting list of employees , but the sys_refcursor is providing "fetch out of sequence error" in Oracle:

Body:
When I use your code with my minor modifications I get no error.  Perhaps my working code can assist you?  Let me know if you have any questions or if I can assist further.

Summary

Declare Ref Cursor

Declare Type based off of the fields in my employees table

Declare Record based off of Type

Open Cursor and enter Loop

Within Loop populate record using the values FETCHed by the Cursor.

Using dbms_output show some output so we know it's working

Last, if zero rows returned by the cursor OPEN Cursor again using different SQL.

Employees Table

Code

DECLARE

  /* Declare Ref Cursor */
  cur_custid  SYS_REFCURSOR;

  /* Declare Type using Fields from the employees table. */
  TYPE t_custrec IS RECORD (
    firstname    employees.firstname%TYPE,
    lastname     employees.lastname%TYPE
  );

  /* Declare Record based off of Type */
  custrec   t_custrec;

BEGIN

  OPEN cur_custid FOR
    SELECT DISTINCT firstname
                   ,lastname
      FROM employees
     WHERE JOB like '%Data Analyst%'; /* Data Analyst does not exist forcing Zero Rows returned */

  LOOP
    FETCH cur_custid
      INTO custrec;
    EXIT WHEN cur_custid%notfound;
    ---looping happens
  END LOOP;

  dbms_output.put_line('Num Rows: ' || cur_custid%rowcount);

  IF cur_custid%rowcount = 0
  THEN
    dbms_output.put_line('Zero Rows Condition Met.  Opening Cursor.');
    OPEN cur_custid FOR
      SELECT '0' AS empid FROM dual;
  END IF;

END;


问:
Is there a way to load a fully functional Menu Bar without PHP?
I'm currently trying to put the menu bar of my HTML Webpage into a separate file without using php.

How do I set this up properly?

Using a php file is not an option because of the CMS I'm using (http://www.coast-cms.de, German only). Therefore I needed to do it without Include. I almost got it to work the way I want it to by using jquery.load.

The navigation bar is loaded correctly, but the dropdown menu in it won't open until I reload, or on some pages won't work at all.

I suspect this has something to do with the order the scripts are loaded in, but given my limited experience with jQuery I was neither able to find out how to sort the loading process, nor which order would have been correct.

```

<pre class="lang-html prettyprint-override"><code><div id="navbar"></div>
<script>
  $("#navbar").load( "/modules/navbar.html");
</script>
</code>```

I expected to be able to just paste another html file into my existing one before anything else happens, but my code seems to load the file at some other point.

EDIT:
I'm using jquery.dropotron for the submenu https://github.com/ajlkn/jquery.dropotron

navbar.html

Company Name

Home

                            X

A

B

C

D

E

F

Über uns

G

H

Kontakt

```

<p>EDIT 2:
The code that I think is used for the hamburger menu in main.js</p>

<pre class="lang-js prettyprint-override"><code>a('').appendTo(b);
        a('<div id="navPanel"><nav>' + a("#nav").navList() + '</nav></div>').appendTo(d).panel({
            delay: 500,
            hideOnClick: true,
            hideOnSwipe: true,
            resetScroll: true,
            resetForms: true,
            side: "right"
        });
</code>```

答:
Finally figured it out. The problem was just the order in which the scripts were loaded.
What fixed it was making sure main.js (in which both the dropdown and the hamburger menu were activated) was not loaded, before the entire page had finished loading.

I achieved that with the following code:

```

Body:
I'm currently trying to put the menu bar of my HTML Webpage into a separate file without using php.

How do I set this up properly?

Using a php file is not an option because of the CMS I'm using (http://www.coast-cms.de, German only). Therefore I needed to do it without Include. I almost got it to work the way I want it to by using jquery.load.

The navigation bar is loaded correctly, but the dropdown menu in it won't open until I reload, or on some pages won't work at all.

I suspect this has something to do with the order the scripts are loaded in, but given my limited experience with jQuery I was neither able to find out how to sort the loading process, nor which order would have been correct.

I expected to be able to just paste another html file into my existing one before anything else happens, but my code seems to load the file at some other point.

EDIT:
I'm using jquery.dropotron for the submenu https://github.com/ajlkn/jquery.dropotron

navbar.html

Company Name

Home

                            X

A

B

C

D

E

F

Über uns

G

H

Kontakt

EDIT 2:
The code that I think is used for the hamburger menu in main.js

a('').appendTo(b);
        a('
' + a("#nav").navList() + '
').appendTo(d).panel({
            delay: 500,
            hideOnClick: true,
            hideOnSwipe: true,
            resetScroll: true,
            resetForms: true,
            side: "right"
        });

Body:
Finally figured it out. The problem was just the order in which the scripts were loaded.
What fixed it was making sure main.js (in which both the dropdown and the hamburger menu were activated) was not loaded, before the entire page had finished loading.

I achieved that with the following code:

<script>$(document).ready(function() {$.getScript("assets/js/main.js");});</script>


问:
Using Laravel to create LMS and assign courses to students
I am trying to create a simple LMS system using Laravel. I'm following a youtube guide and the QuickLMS repo here: https://github.com/LaravelDaily/QuickLMS/. Most of the app is working just fine, however there is one function I want to change and get rid of.

I struggle with a specific function which is assigning a student or user to a course. Whenever a student opens a course on the front page, a button is displayed at the top which says "Buy course", this loads the Stripe popup for the student to pay. when payment is done, course is assigned to student in course_student table.

The code I'm borrowing from uses Stripe to take payment for a course. I want this button to be a "enroll in course" button, rather than a payment button. So that when the student enters the course, a button to enroll in course is displayed instead, which add the students to the course_student table without the need of any payment info.

CoursesController.php:

```<code>public function payment(Request $request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $this->createStripeCharge($request);
        $course->students()->attach(\Auth::id());
        return redirect()->back()->with('success', 'Payment completed successfully.');
    }
    private function createStripeCharge($request)
    {
        Stripe::setApiKey(env('STRIPE_API_KEY'));
        try {
            $customer = Customer::create([
                'email' => $request->get('stripeEmail'),
                'source'  => $request->get('stripeToken')
            ]);
            $charge = Charge::create([
                'customer' => $customer->id,
                'amount' => $request->get('amount'),
                'currency' => "usd"
            ]);
        } catch (\Stripe\Error\Base $e) {
            return redirect()->back()->withError($e->getMessage())->send();
        }
    }
</code>```

course.blade.php:

```<code><form action="{{ route('courses.payment') }}" method="POST">
                    <input type="hidden" name="course_id" value="{{ $course->id }}" />
                    <input type="hidden" name="amount" value="{{ $course->price * 100 }}" />
                    <script
                            src="https://checkout.stripe.com/checkout.js" class="stripe-button"
                            data-key="{{ env('PUB_STRIPE_API_KEY') }}"
                            data-amount="{{ $course->price * 100 }}"
                            data-currency="usd"
                            data-name="Quick LMS"
                            data-label="Buy course (${{ $course->price }})"
                            data-description="Course: {{ $course->title }}"
                            data-image="https://stripe.com/img/documentation/checkout/marketplace.png"
                            data-locale="auto"
                            data-zip-code="false">
                    </script>
</code>```

web.php:

```<code>Route::post('course/payment', ['uses' => 'CoursesController@payment', 'as' => 'courses.payment']);
</code>```

I tried changing all this by removing any references to Stripe, and instead creating a new function that looks like this:

CoursesController.php:

```<code> public function register (Request $request)
    {
        $this->createSubscription($request);
        return redirect()->back()->with('success', 'Payment completed successfully.');

    }

    private function createSubscription($request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $course->students()->attach(\Auth::id());
    }
</code>```

However, this only generates a "page expired" message from Laravel, and I can't figure out how to just drop the Stripe button.

I have tried to replace the whole "payment" function without success. I think this is the code I want, but it obviously needs some change to work, I can't figure it out though:

```<code>        $course->students()->attach(\Auth::id());
</code>```

答:
I solved this myself by creating two new functions:
CoursesController.php:

```<code>public function register (Request $request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $this->createSubscription($request);
        $course->students()->attach(\Auth::id());
        return redirect()->back()->with('success', 'Payment completed successfully.');

    }

    private function createSubscription($request)
    {
        return;

    }
</code>```

And the following form on course.blade.php:

```<code> <form action="{{ route('courses.register') }}" method="POST">
                    {{ csrf_field() }}
                    <input type="hidden" name="course_id" value="{{ $course->id }}" />
                <input type="submit" value="Submit me"></form>
</code>```

Web.php

```<code>Route::post('course/register/', ['uses' => 'CoursesController@register', 'as' => 'courses.register']);

</code>```

It could maybe be done in a better way, but this does what I was looking for.

Body:
I am trying to create a simple LMS system using Laravel. I'm following a youtube guide and the QuickLMS repo here: https://github.com/LaravelDaily/QuickLMS/. Most of the app is working just fine, however there is one function I want to change and get rid of.

I struggle with a specific function which is assigning a student or user to a course. Whenever a student opens a course on the front page, a button is displayed at the top which says "Buy course", this loads the Stripe popup for the student to pay. when payment is done, course is assigned to student in course_student table.

The code I'm borrowing from uses Stripe to take payment for a course. I want this button to be a "enroll in course" button, rather than a payment button. So that when the student enters the course, a button to enroll in course is displayed instead, which add the students to the course_student table without the need of any payment info.

CoursesController.php:

public function payment(Request $request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $this->createStripeCharge($request);
        $course->students()->attach(\Auth::id());
        return redirect()->back()->with('success', 'Payment completed successfully.');
    }
    private function createStripeCharge($request)
    {
        Stripe::setApiKey(env('STRIPE_API_KEY'));
        try {
            $customer = Customer::create([
                'email' => $request->get('stripeEmail'),
                'source'  => $request->get('stripeToken')
            ]);
            $charge = Charge::create([
                'customer' => $customer->id,
                'amount' => $request->get('amount'),
                'currency' => "usd"
            ]);
        } catch (\Stripe\Error\Base $e) {
            return redirect()->back()->withError($e->getMessage())->send();
        }
    }

course.blade.php:

<form action="{{ route('courses.payment') }}" method="POST">
                    <input type="hidden" name="course_id" value="{{ $course->id }}" />
                    <input type="hidden" name="amount" value="{{ $course->price * 100 }}" />

web.php:

Route::post('course/payment', ['uses' => 'CoursesController@payment', 'as' => 'courses.payment']);

I tried changing all this by removing any references to Stripe, and instead creating a new function that looks like this:

CoursesController.php:

 public function register (Request $request)
    {
        $this->createSubscription($request);
        return redirect()->back()->with('success', 'Payment completed successfully.');

    }

    private function createSubscription($request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $course->students()->attach(\Auth::id());
    }

However, this only generates a "page expired" message from Laravel, and I can't figure out how to just drop the Stripe button.

I have tried to replace the whole "payment" function without success. I think this is the code I want, but it obviously needs some change to work, I can't figure it out though:

        $course->students()->attach(\Auth::id());

Body:
I solved this myself by creating two new functions:
CoursesController.php:

public function register (Request $request)
    {
        $course = Course::findOrFail($request->get('course_id'));
        $this->createSubscription($request);
        $course->students()->attach(\Auth::id());
        return redirect()->back()->with('success', 'Payment completed successfully.');

    }

    private function createSubscription($request)
    {
        return;

    }

And the following form on course.blade.php:

 <form action="{{ route('courses.register') }}" method="POST">
                    {{ csrf_field() }}
                    <input type="hidden" name="course_id" value="{{ $course->id }}" />
                <input type="submit" value="Submit me"></form>

Web.php

Route::post('course/register/', ['uses' => 'CoursesController@register', 'as' => 'courses.register']);

It could maybe be done in a better way, but this does what I was looking for.


问:
Does JavaScript take local decimal separators into account?
I've got a web page that displays decimals in a user's localized format, like so:

English: 7.75

Dutch: 7,75

If I add two number variables together in JavaScript on my machine (where the numbers are taken from strings in the above formats) I get the following results:

English: 7.75 + 7.75 = 15.5

Dutch: 7,75 + 7,75 = 0

If I was to run this code on a Dutch users machine, should I expect the English-formatted addition to return 0, and the Dutch-formatted addition to return 15,5?

In short: Does the JavaScript calculation use local decimal separators in its string to number conversions?

答:
Expanding on the solution from @naitsirch we can use Intl.NumberFormat.formatToParts() to have JS parse the group and decimal separators.

function parseLocaleNumber(stringNumber) {
  let num = 123456.789,
    fmt_local = new Intl.NumberFormat(),
    parts_local = fmt_local.formatToParts(num),
    group = '',
    decimal = '';

  parts_local.forEach(function(i) {
    switch (i.type) {
      case 'group':
        group = i.value;
        break;
      case 'decimal':
        decimal = i.value;
        break;
      default:
        break;
    }
  });

  return parseFloat(stringNumber
    .replace(new RegExp('\\' + group, 'g'), '')
    .replace(new RegExp('\\' + decimal), '.')
  );
}

//replace this string with a number formatted for your locale
console.log(parseLocaleNumber("987,654,321.01"));
//output for "en" locale: 987654321.01```