text stringlengths 2 1.04M | meta dict |
|---|---|
package common
import (
"encoding/json"
"log"
"os"
"strings"
"golang.org/x/net/context"
"gopkg.in/olivere/elastic.v5"
)
import klog "github.com/ian-kent/go-log/log"
var ElasticSearchServer = "http://localhost:9200"
type warningUpdate struct {
Warnings []string `json:"warnings,omitempty"`
}
func CreateClient() *elastic.Client {
client, err := elastic.NewSimpleClient(
elastic.SetURL(ElasticSearchServer),
elastic.SetSniff(false),
elastic.SetErrorLog(log.New(os.Stderr, "ELASTIC-error ", log.LstdFlags)),
// elastic.SetTraceLog(log.New(os.Stderr, "ELASTIC-trace ", log.LstdFlags)),
elastic.SetHealthcheck(false))
if err != nil {
klog.Fatal("Unable to connect to '%s': %s", ElasticSearchServer, err.Error())
}
return client
}
func AddWarning(client *elastic.Client, id string, newWarnings []string) {
joinedWarnings := strings.Join(newWarnings, "; ")
// Load existing document
searchResult, err := client.Search().
Index(MediaIndexName).
Type(MediaTypeName).
Query(elastic.NewTermQuery("_id", id)).
Do(context.TODO())
if err != nil {
klog.Error("Unable to find document for warning: %q (on %q): %q", joinedWarnings, id, err.Error())
return
}
if searchResult.TotalHits() == 0 {
klog.Error("Unable to find document for warning: %q (on %q)", joinedWarnings, id)
return
} else {
hit := searchResult.Hits.Hits[0]
var media Media
err := json.Unmarshal(*hit.Source, &media)
if err != nil {
klog.Error("Failed deserializing search result for %q: %q", id, err.Error())
return
}
var updatedDoc warningUpdate
updatedDoc.Warnings = append(media.Warnings, joinedWarnings)
// Update document with full warning array
_, err = client.Update().
Fields().
Index(MediaIndexName).
Type(MediaTypeName).
Id(id).
Doc(updatedDoc).
Do(context.TODO())
if err != nil {
klog.Error("Failed updating document with warning %q (on %q): %q", joinedWarnings, id, err.Error())
return
}
}
}
| {
"content_hash": "59afea2922559d48ade15c0936f47f3b",
"timestamp": "",
"source": "github",
"line_count": 79,
"max_line_length": 102,
"avg_line_length": 24.911392405063292,
"alnum_prop": 0.6880081300813008,
"repo_name": "kevintavog/FindAPhoto",
"id": "ab80a8dd61ab41a22a0ed728fadab4af8a7803c2",
"size": "1968",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "common/ecclient.go",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2282"
},
{
"name": "Go",
"bytes": "77814"
},
{
"name": "HTML",
"bytes": "6325"
},
{
"name": "TypeScript",
"bytes": "9392"
}
],
"symlink_target": ""
} |
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi.CSharp;
using JetBrains.ReSharper.Psi.CSharp.Tree;
namespace AsyncConverter.AsyncHelpers.AwaitEliders
{
[SolutionComponent]
internal class LocalFunctionAwaitElider : ICustomAwaitElider
{
public bool CanElide(ICSharpDeclaration declarationOrClosure) => declarationOrClosure is ILocalFunctionDeclaration;
public void Elide(ICSharpDeclaration declarationOrClosure, ICSharpExpression awaitExpression)
{
var factory = CSharpElementFactory.GetInstance(awaitExpression);
var localFunctionDeclaration = declarationOrClosure as ILocalFunctionDeclaration;
if (localFunctionDeclaration == null)
return;
localFunctionDeclaration.SetAsync(false);
if (localFunctionDeclaration.Body != null)
{
var statement = factory.CreateStatement("return $0;", awaitExpression);
awaitExpression.GetContainingStatement()?.ReplaceBy(statement);
}
else
localFunctionDeclaration.ArrowClause?.SetExpression(awaitExpression);
}
}
} | {
"content_hash": "c7f943b095ebd26d2696449c7a6fb2bf",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 123,
"avg_line_length": 38.96666666666667,
"alnum_prop": 0.69803250641574,
"repo_name": "BigBabay/AsyncConverter",
"id": "41834fa87cae3cc8b5ab1cf200c3f1f1fa5d7ce4",
"size": "1169",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AsyncConverter/AsyncHelpers/AwaitEliders/LocalFunctionAwaitElider.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "51"
},
{
"name": "C#",
"bytes": "207270"
},
{
"name": "PowerShell",
"bytes": "2660"
},
{
"name": "Shell",
"bytes": "2455"
}
],
"symlink_target": ""
} |
<?php
/*
UserSpice 4
An Open Source PHP User Management System
by the UserSpice Team at http://UserSpice.com
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
?>
<div class="row">
<div class="col-xs-12">
<div class="jumbotron">
<p>Invitation email has been sent to <?=$email?></p>
</div>
</div><!-- /.col -->
</div><!-- /.row --> | {
"content_hash": "191a27378d81ab088898b9c87582a4be",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 69,
"avg_line_length": 33.18518518518518,
"alnum_prop": 0.7399553571428571,
"repo_name": "ppc-web/ppcweb",
"id": "ede3e189814988876e4f7a5678b7400bec7c7e7e",
"size": "896",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "web/donation/users/views/_invite_sent.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "257951"
},
{
"name": "HTML",
"bytes": "503775"
},
{
"name": "Hack",
"bytes": "3056"
},
{
"name": "JavaScript",
"bytes": "1355731"
},
{
"name": "Less",
"bytes": "55685"
},
{
"name": "PHP",
"bytes": "475604"
},
{
"name": "Python",
"bytes": "3373"
},
{
"name": "SCSS",
"bytes": "56407"
},
{
"name": "Shell",
"bytes": "509"
}
],
"symlink_target": ""
} |
In this guide we'll demonstrate how to write an out-of-tree dynamic provisioner using [the helper library](https://github.com/kubernetes-incubator/external-storage/tree/master/lib)
## The Provisioner Interface
Ideally, all you should need to do to write your own provisioner is implement the `Provisioner` interface which has two methods: `Provision` and `Delete`. Then you can just pass it to the `ProvisionController`, which handles all the logic of calling the two methods. The signatures should be self-explanatory but we'll explain the methods in more detail anyhow. For this explanation we'll refer to the `ProvisionController` as the controller and the implementer of the `Provisioner` interface as the provisioner. The code can be found in the [`controller` directory](https://github.com/kubernetes-incubator/external-storage/tree/master/lib/controller)
```go
Provision(VolumeOptions) (*v1.PersistentVolume, error)
```
`Provision` creates a storage asset and returns a `PersistentVolume` object representing that storage asset. The given `VolumeOptions` object includes information needed to create the PV: the PV's reclaim policy, PV's name, the PVC object for which the PV is being provisioned (which has in its spec capacity & access modes), & parameters from the PVC's storage class.
You should store any information that will be later needed to delete the storage asset here in the PV using annotations. It's also recommended that you give every instance of your provisioner a unique identity and store it on the PV using an annotation here, for reasons we will see soon.
`Provision` is not responsible for actually creating the PV, i.e. submitting it to the Kubernetes API, it just returns it and the controller handles creating the API object.
```go
Delete(*v1.PersistentVolume) error
```
`Delete` removes the storage asset that was created by `Provision` to back the given PV. The given PV will still have any useful annotations that were set earlier in `Provision`.
Special consideration must be given to the case where multiple controllers that serve the same storage class (that have the same `provisioner` name) are running: how do you know that *this* provisioner was the one to provision the given PV? This is why it's recommended to store a provisioner's identity on its PVs in `Provision`, so that each can remember if it was the one to provision a PV when it comes time to delete it, and if not, ignore it by returning `IgnoredError`. If you are confused by any of this, please continue through the `hostPath` example to see a practical implementation and if that isn't enough, please read [this section](#running-multiple-provisioners-and-giving-provisioners-identities) after the example.
`Delete` is not responsible for actually deleting the PV, i.e. removing it from the Kubernetes API, it just deletes the storage asset backing the PV and the controller handles deleting the API object.
## Writing a `hostPath` Dynamic Provisioner
Now that we understand the interface expected by the controller, let's implement it and create our own out-of-tree `hostPath` dynamic provisioner. This is for single node testing and demonstration purposes only - local storage is not supported in any way and will not work on multi-node clusters. This simple program has the power to delete and create local data on your node, so if you intend to actually follow along and run it, be careful!
We define a `hostPathProvisioner` struct. It will back every `hostPath` PV it provisions with a new child directory in `pvDir`, hard-coded here to `/tmp/hostpath-provisioner`. It will also give itself a unique `identity`, set to the name of the node/host it runs on, which is passed in via an env variable.
```go
type hostPathProvisioner struct {
// The directory to create PV-backing directories in
pvDir string
// Identity of this hostPathProvisioner, set to node's name. Used to identify
// "this" provisioner's PVs.
identity string
}
func NewHostPathProvisioner() controller.Provisioner {
nodeName := os.Getenv("NODE_NAME")
if nodeName == "" {
glog.Fatal("env variable NODE_NAME must be set so that this provisioner can identify itself")
}
return &hostPathProvisioner{
pvDir: "/tmp/hostpath-provisioner",
identity: nodeName,
}
}
```
We implement `Provision`. It creates a directory with the name `options.PVName`, which is always unique to the PVC being provisioned for, in `pvDir`. It sets a custom `identity` annotation on the PV and fills in the other fields of the PV according to the `VolumeOptions` to satisfy the PVC's requirements. And the PV's `PersistentVolumeSource` is of course set to a `hostPath` volume representing the directory just created.
```go
// Provision creates a storage asset and returns a PV object representing it.
func (p *hostPathProvisioner) Provision(options controller.VolumeOptions) (*v1.PersistentVolume, error) {
path := path.Join(p.pvDir, options.PVName)
if err := os.MkdirAll(path, 0777); err != nil {
return nil, err
}
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: options.PVName,
Annotations: map[string]string{
"hostPathProvisionerIdentity": p.identity,
},
},
Spec: v1.PersistentVolumeSpec{
PersistentVolumeReclaimPolicy: options.PersistentVolumeReclaimPolicy,
AccessModes: options.PVC.Spec.AccessModes,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): options.PVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)],
},
PersistentVolumeSource: v1.PersistentVolumeSource{
HostPath: &v1.HostPathVolumeSource{
Path: path,
},
},
},
}
return pv, nil
}
```
We implement `Delete`. First it checks if this provisioner was the one that created the directory backing the given PV by looking at the identity annotation. If not, it returns an `IgnoredError`: the safest assumption is that some other `hostPath` provisioner that is/was running on a different node was the one that created the directory on that different node, so it would be a dangerous idea for *this* provisioner to attempt to delete the directory here on *this* node! Otherwise, if the identity annotation matches this provisioner's, it can safely delete the directory.
```go
// Delete removes the storage asset that was created by Provision represented
// by the given PV.
func (p *hostPathProvisioner) Delete(volume *v1.PersistentVolume) error {
ann, ok := volume.Annotations["hostPathProvisionerIdentity"]
if !ok {
return errors.New("identity annotation not found on PV")
}
if ann != p.identity {
return &controller.IgnoredError{"identity annotation on PV does not match ours"}
}
path := path.Join(p.pvDir, volume.Name)
if err := os.RemoveAll(path); err != nil {
return err
}
return nil
}
```
Now all that's left is to connect our `Provisioner` with a `ProvisionController` and run the controller, all in `main`. This part will look largely the same regardless of how the provisioner interface is implemented. We'll write it such that it expects to be run as a pod in Kubernetes.
We need to create a couple of things the controller expects as arguments, including our `hostPathProvisioner`, before we create and run it. First we create a client for communicating with Kubernetes from within a pod. We use it to determine the server version of Kubernetes. Then we create our `hostPathProvisioner`. We pass all of these things into `NewProvisionController`, plus some other arguments we'll explain now.
* `resyncPeriod` determines how often the controller relists PVCs and PVs to check if they should be provisioned for or deleted.
* `provisionerName` is the `provisioner` that storage classes will specify, "example.com/hostpath" here. It must follow the `<vendor name>/<provisioner name>` naming scheme and `<vendor name>` cannot be "kubernetes.io"
* `exponentialBackOffOnError` determines whether it should exponentially back off from calls to `Provision` or `Delete`, useful if either of those involves some API call.
* `failedRetryThreshold` is the threshold for failed `Provision` attempts before giving up trying to provision for a claim.
* The last four arguments configure leader election wherein mutliple controllers trying to provision for the same class of claims race to lock/lead claims in order to be the one to provision for them. The meaning of these parameters is documented in the [leaderelection package](https://github.com/kubernetes-incubator/external-storage/tree/master/lib/leaderelection). If you don't intend for users to run more than one instance of your provisioner for the same class of claims, you may ignore these and simply use the default as we do here. See [this section](#running-multiple-provisioners-and-giving-provisioners-identities) after this example for more info on running multiple provisioners.
(There are many other possible parameters of the controller that could be exposed, please create an issue if you would like one to be.)
Finally, we create and `Run` the controller.
```go
const (
resyncPeriod = 15 * time.Second
provisionerName = "example.com/hostpath"
exponentialBackOffOnError = false
failedRetryThreshold = 5
leasePeriod = leaderelection.DefaultLeaseDuration
retryPeriod = leaderelection.DefaultRetryPeriod
renewDeadline = leaderelection.DefaultRenewDeadline
termLimit = leaderelection.DefaultTermLimit
)
```
```go
func main() {
flag.Parse()
// Create an InClusterConfig and use it to create a client for the controller
// to use to communicate with Kubernetes
config, err := rest.InClusterConfig()
if err != nil {
glog.Fatalf("Failed to create config: %v", err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
glog.Fatalf("Failed to create client: %v", err)
}
// The controller needs to know what the server version is because out-of-tree
// provisioners aren't officially supported until 1.5
serverVersion, err := clientset.Discovery().ServerVersion()
if err != nil {
glog.Fatalf("Error getting server version: %v", err)
}
// Create the provisioner: it implements the Provisioner interface expected by
// the controller
hostPathProvisioner := NewHostPathProvisioner()
// Start the provision controller which will dynamically provision hostPath
// PVs
pc := controller.NewProvisionController(clientset, resyncPeriod, "example.com/hostpath", hostPathProvisioner, serverVersion.GitVersion, exponentialBackOffOnError, failedRetryThreshold, leasePeriod, renewDeadline, retryPeriod, termLimit)
pc.Run(wait.NeverStop)
}
```
We're now done writing code. The code we wrote can be found [here](./hostpath-provisioner.go). The other files we'll use in the remainder of the walkthrough can be found in the same directory.
Notice we just import "github.com/kubernetes-incubator/external-storage/lib/controller" to get access to the required interface and function.
## Building and Running our `hostPath` Dynamic Provisioner
Before we can run our provisioner in a pod we need to build a Docker image for the pod to specify. Our hostpath-provisioner Go package has many dependencies so it's a good idea to use a tool to manage them. It's especially important to do so when depending on a package like [client-go](https://github.com/kubernetes/client-go#how-to-get-it) that has an unstable master branch. We'll use [glide](https://github.com/Masterminds/glide).
Our [glide.yaml](./glide.yaml) was created by manually setting the latest version of external-storage/lib & setting the version of client-go to the same one that external-storage/lib uses. We use it to populate a vendor directory containing dependencies.
Now we can use build & run our hostpath-provisioner using a simple Makefile where we first we run `glide install -v` to get the dependencies listed in our glide.yaml, then do a static go build of our program that can run in our "FROM scratch" Dockerfile.
```make
...
image: hostpath-provisioner
docker build -t $(IMAGE) -f Dockerfile.scratch .
hostpath-provisioner: $(shell find . -name "*.go")
glide install -v --strip-vcs
CGO_ENABLED=0 go build -a -ldflags '-extldflags "-static"' -o hostpath-provisioner .
...
```
```Dockerfile
FROM scratch
COPY hostpath-provisioner /
CMD ["/hostpath-provisioner"]
```
We run make. Note that the Docker image needs to be on the node we'll run the pod on. So you may need to tag your image and push it to Docker Hub so that it can be pulled later by the node, or just work on the node and build the image there.
```console
$ make
...
Successfully built c3cd467b5fbe
```
Now we can specify our image in a pod. Recall that we set `pvDir` to `/tmp/hostpath-provisioner`. Since we are running our provisioner in a container as a pod, we should mount a corresponding `hostPath` volume there to serve as the parent of all provisioned PVs' `hostPath` volumes.
```yaml
kind: Pod
apiVersion: v1
metadata:
name: hostpath-provisioner
spec:
containers:
- name: hostpath-provisioner
image: hostpath-provisioner:latest
imagePullPolicy: "IfNotPresent"
volumeMounts:
- name: pv-volume
mountPath: /tmp/hostpath-provisioner
volumes:
- name: pv-volume
hostPath:
path: /tmp/hostpath-provisioner
```
If SELinux is enforcing, we need to label `/tmp/hostpath-provisioner` so that it can be accessed by pods. We do this on the single node those pods will be scheduled to.
```console
$ mkdir -p /tmp/hostpath-provisioner
$ sudo chcon -Rt svirt_sandbox_file_t /tmp/hostpath-provisioner
```
## Using our `hostPath` Dynamic Provisioner
As said before, this dynamic provisioner is for single node testing purposes only. It has been tested to work with [hack/local-up-cluster.sh](https://github.com/kubernetes/kubernetes/blob/release-1.5/hack/local-up-cluster.sh) started like so.
```console
$ API_HOST_IP=0.0.0.0 $GOPATH/src/k8s.io/kubernetes/hack/local-up-cluster.sh
```
Once our cluster is running, we create the hostpath-provisioner pod. Note how we populate the "NODE_NAME" variable.
```yaml
kind: Pod
apiVersion: v1
metadata:
name: hostpath-provisioner
spec:
containers:
- name: hostpath-provisioner
image: hostpath-provisioner:latest
imagePullPolicy: "IfNotPresent"
env:
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumeMounts:
- name: pv-volume
mountPath: /tmp/hostpath-provisioner
volumes:
- name: pv-volume
hostPath:
path: /tmp/hostpath-provisioner
```
```console
$ kubectl create -f pod.yaml
pod "hostpath-provisioner" created
```
Before proceeding, we check that it doesn't immediately crash due to one of the fatal conditions we wrote.
```console
$ kubectl get pod
NAME READY STATUS RESTARTS AGE
hostpath-provisioner 1/1 Running 0 5s
```
Now we create a `StorageClass` & `PersistentVolumeClaim` and see that a `PersistentVolume` is automatically created.
```yaml
kind: StorageClass
apiVersion: storage.k8s.io/v1beta1
metadata:
name: example-hostpath
provisioner: example.com/hostpath
```
```yaml
kind: PersistentVolumeClaim
apiVersion: v1
metadata:
name: hostpath
annotations:
volume.beta.kubernetes.io/storage-class: "example-hostpath"
spec:
accessModes:
- ReadWriteMany
resources:
requests:
storage: 1Mi
```
```console
$ kubectl create -f class.yaml
storageclass "example-hostpath" created
$ kubectl create -f claim.yaml
persistentvolumeclaim "hostpath" created
$ kubectl get pv
NAME CAPACITY ACCESSMODES RECLAIMPOLICY STATUS CLAIM REASON AGE
pvc-f41f0dfc-c7bf-11e6-8c5d-c81f66424618 1Mi RWX Delete Bound default/hostpath 8s
```
If we check the contents of `/tmp/hostpath-provisioner` on the node we should see the PV's backing directory.
```console
$ ls /tmp/hostpath-provisioner/
pvc-f41f0dfc-c7bf-11e6-8c5d-c81f66424618
```
Now let's do a simple test: have a pod use the claim and write to it. We create such a pod and see that it succeeds.
```yaml
kind: Pod
apiVersion: v1
metadata:
name: test-pod
spec:
containers:
- name: test-pod
image: gcr.io/google_containers/busybox:1.24
command:
- "/bin/sh"
args:
- "-c"
- "touch /mnt/SUCCESS && exit 0 || exit 1"
volumeMounts:
- name: hostpath-pvc
mountPath: "/mnt"
restartPolicy: "Never"
volumes:
- name: hostpath-pvc
persistentVolumeClaim:
claimName: hostpath
```
```console
$ kubectl create -f test-pod.yaml
pod "test-pod" created
$ kubectl get pod --show-all
NAME READY STATUS RESTARTS AGE
hostpath-provisioner 1/1 Running 0 2m
test-pod 0/1 Completed 0 8s
```
If we check the contents of the PV's backing directory we should see the data it wrote.
```console
$ ls /tmp/hostpath-provisioner/pvc-f41f0dfc-c7bf-11e6-8c5d-c81f66424618
SUCCESS
```
When we delete the PVC, the PV it was bound to and the data will be deleted also.
```console
$ kubectl delete pvc --all
persistentvolumeclaim "hostpath" deleted
$ kubectl get pv
No resources found.
$ ls /tmp/hostpath-provisioner
```
Finally, we delete the provisioner pod when it has deleted all its PVs and it's no longer wanted.
```console
$ kubectl delete pod hostpath-provisioner
pod "hostpath-provisioner" deleted
```
## Running multiple provisioners and giving provisioners identities
You must determine whether you want to support the use-case of running multiple provisioner-controller instances in a cluster. Further, you must determine whether you want to implement this identity idea to address that use-case.
The library supports running multiple instances out of the box via its basic leader election implementation wherein multiple controllers trying to provision for the same class of claims race to lock/lead claims in order to be the one to provision for them. This prevents multiple provisioners from needlessly calling `Provision`, which is undesirable because only one will succeed in creating a PV and the rest will have wasted API calls and/or resources creating useless storage assets. As described above in the `hostPath` example, configuration of all this is done via controller parameters.
There is no such race to lock implementation for deleting PVs: all provisioners will call `Delete`, repeatedly until the storage asset backing the PV and the PV are deleted. This is why it's desirable to implement the identity idea, so that only the provisioner who is *responsible* for deleting a PV actually attempts to delete the PV's backing storage asset. The rest should return the special `IgnoredError` which indicates to the controller that they ignored the PV, as opposed to trying and failing (which would result in a misleading error message) or succeeding (obviously a bad idea to lie about that).
In some cases, the provisioner who is *responsible* for deleting a PV is also the only one *capable* of deleting a PV, in which case it's not only desirable to implement the identity idea, but necessary. This is the case with the `hostPath` provisioner example above: obviously only the provisioner running on a certain host can delete the backing storage asset because the backing storage asset is local to the host.
Now, actually giving provisioners identities and effectively making them pets may be the hard part. In the `hostPath` example, the sensible thing to do was tie a provisioner's identity to the node/host it runs on. In your case, maybe it makes sense to tie each provisioner to e.g. a certain member in a storage pool. And should a certain provisioner die, when it comes back it should retain its identity lest the cluster be left with dangling volumes that no running provisioner can delete.
## Extras
So as we can see, it can be easy to write a simple but useful dynamic provisioner. For something more complicated here are some various other things to consider...
We did not show how to parse `StorageClass` parameters. They are passed from the storage class as a `map[string]string` to `Provision`, so you can define and parse any arbitrary set of parameters you want. You must reject parameters that you don't recognize.
We made it so our hostpath-provisioner binary must run from within a Kubernetes cluster. But it's also possible to have it communicate with Kubernetes from [outside](https://github.com/kubernetes/client-go/blob/release-2.0/examples/out-of-cluster/main.go). nfs-provisioner can do this and defines this (and other) behaviour using flags/arguments.
Note that the errors returned by Provision/Delete are sent as events on the PVC/PV and this is the primary way of communicating with the user, so they should be understandable.
If there is some behaviour of the controller you would like to change, feel free to open an issue. There are many parameters that could easily be made configurable but aren't because it would be too messy. The controller is written to follow the [proposal](https://github.com/kubernetes/kubernetes/pull/30285) and be like the upstream PV controller as much as possible, but there is always room for improvement.
It's possible (but not pretty) to write e2e tests for your provisioner that look similar to kubernetes e2e tests by copying files from the e2e framework and fixing import statements. Like [here](https://github.com/kubernetes-incubator/external-storage/tree/master/nfs/test/e2e). Keep in mind the license, etc. In your case, unit & integration tests may be sufficient.
| {
"content_hash": "218db9c75083d8cbf4fef1fced9d4620",
"timestamp": "",
"source": "github",
"line_count": 405,
"max_line_length": 732,
"avg_line_length": 53.528395061728396,
"alnum_prop": 0.7559850546611928,
"repo_name": "clarkhale/external-storage",
"id": "3761518f0fdb87efd7539df27d2e27d079e6bcd2",
"size": "21725",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "iscsi/targetd/vendor/github.com/kubernetes-incubator/external-storage/docs/demo/hostpath-provisioner/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "251087"
},
{
"name": "Makefile",
"bytes": "7191"
},
{
"name": "Python",
"bytes": "25945"
},
{
"name": "Shell",
"bytes": "6851"
}
],
"symlink_target": ""
} |
module Tutor
class RecommendationsController < TutorController::Base
expose(:contents) {
Neuron.approved_public_contents
}
expose(:tutor_achievements) {
current_user.tutor_achievements.order(created_at: :desc)
}
expose :tutor_recommendation
expose(:clients) {
UserTutor.where(tutor: current_user, status: :accepted)
}
expose(:students_selected) {
User.where(id: student_ids_params)
}
expose(:tutor_achievement, attributes: :tutor_achievement_params)
def new
render
end
def create
tutor_recommendation.tutor = current_user
achievement_id = tutor_recommendation_params[:tutor_achievement]
if !achievement_id.empty?
achievement = TutorAchievement.find(achievement_id)
tutor_recommendation.tutor_achievement = achievement
end
content_ids = tutor_recommendation_params[:content_tutor_recommendations]
content_ids = remove_blank(content_ids)
students_ids = tutor_recommendation_params[:students]
students_ids = remove_blank(students_ids)
if content_ids.any? && students_ids.any?
create_tutor_recommendation(tutor_recommendation, content_ids, students_ids)
else
flash[:error] = I18n.t("views.tutor.recommendations.recommendation_request.missing_params")
end
if request.xhr?
render :js => "window.location = '#{request.referrer}'"
else
redirect_to :back
end
end
def new_achievement
if tutor_achievement.save
flash[:success] = I18n.t(
"views.tutor.recommendations.achievement_request.created"
)
redirect_to :back
else
render nothing: true,
status: :unprocessable_entity
end
end
private
def tutor_achievement_params
params.require(:tutor_achievement).permit(
:name,
:description,
:image
)
end
def tutor_recommendation_params
params.require(:tutor_recommendation).permit(
{ content_tutor_recommendations: [] },
:tutor_achievement,
{ students: [] }
)
end
def student_ids_params
tutor_recommendation_params[:students]
end
def add_recommendation_to_client (students_ids, recommendation, content_ids)
students_ids.each do |student_id|
client_tutor_recommendation = ClientTutorRecommendation.find_by(
client_id: student_id,
tutor_recommendation: recommendation
)
unless client_tutor_recommendation.present?
client_tutor_recommendation = create_new_recommendation(
student_id,
tutor_recommendation
)
end
if client_tutor_recommendation.present?
#validate if the contents have already been learned
update_client_recommendation_status(
student_id,
client_tutor_recommendation,
content_ids
)
end
end
end
def create_new_recommendation(student_id, recommendation)
new_recommendation = ClientTutorRecommendation.new(
client_id: student_id,
tutor_recommendation: recommendation,
status: "in_progress"
)
if new_recommendation.save
new_recommendation
else
nil
end
end
def update_client_recommendation_status(student_id, recommendation, content_ids)
client = User.find(student_id)
TutorService::RecommendationsStatusUpdater.new(
client,
recommendation,
content_ids
).perform
end
def iterate_and_assign_contents_to_recommendation(content_ids, students_ids)
content_ids.each do |id|
content = Content.find(id)
content_tutor_recommendation = ContentTutorRecommendation.new(
tutor_recommendation: tutor_recommendation,
content: content
)
content_tutor_recommendation.save
end
add_recommendation_to_client(students_ids, tutor_recommendation, content_ids)
end
def format_student_names(students)
students.map{|s| if s.name.present? then s.name else s.username end }.join(', ')
end
def remove_blank(items)
if items.present? then items.reject(&:blank?) else [] end
end
def create_tutor_recommendation(tutor_recommendation, content_ids, students_ids)
if tutor_recommendation.save
iterate_and_assign_contents_to_recommendation(content_ids, students_ids)
names = format_student_names(students_selected)
flash[:success] = I18n.t(
"views.tutor.recommendations.recommendation_request.created",
clients: names
)
else
flash[:error] = I18n.t("views.tutor.common.error")
end
end
end
end
| {
"content_hash": "5d7c84847530e26f5a81f5fee9086387",
"timestamp": "",
"source": "github",
"line_count": 170,
"max_line_length": 99,
"avg_line_length": 28.188235294117646,
"alnum_prop": 0.6437813021702838,
"repo_name": "GrowMoi/moi",
"id": "2cf96c966950a0bd47defd8938c20f8a2b43131b",
"size": "4792",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/controllers/tutor/recommendations_controller.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2558"
},
{
"name": "CoffeeScript",
"bytes": "50448"
},
{
"name": "HTML",
"bytes": "70043"
},
{
"name": "JavaScript",
"bytes": "80535"
},
{
"name": "Ruby",
"bytes": "745238"
},
{
"name": "Sass",
"bytes": "57028"
},
{
"name": "Slim",
"bytes": "111717"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_02) on Tue Oct 20 05:53:13 CEST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>TaskInputs (Gradle API 2.8)</title>
<meta name="date" content="2015-10-20">
<link rel="stylesheet" type="text/css" href="../../../../javadoc.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="TaskInputs (Gradle API 2.8)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/gradle/api/tasks/TaskExecutionException.html" title="class in org.gradle.api.tasks"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/gradle/api/tasks/TaskInstantiationException.html" title="class in org.gradle.api.tasks"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/api/tasks/TaskInputs.html" target="_top">Frames</a></li>
<li><a href="TaskInputs.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.gradle.api.tasks</div>
<h2 title="Interface TaskInputs" class="title">Interface TaskInputs</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public interface <span class="strong">TaskInputs</span></pre>
<div class="block"><p>A <code>TaskInputs</code> represents the inputs for a task.</p>
<p>You can obtain a <code>TaskInputs</code> instance using <a href="../../../../org/gradle/api/Task.html#getInputs()"><code>Task.getInputs()</code></a>.</p></div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#dir(java.lang.Object)">dir</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> dirPath)</code>
<div class="block">Registers an input directory hierarchy.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#file(java.lang.Object)">file</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</code>
<div class="block">Registers some input file for this task.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#files(java.lang.Object...)">files</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>... paths)</code>
<div class="block">Registers some input files for this task.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/file/FileCollection.html" title="interface in org.gradle.api.file">FileCollection</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#getFiles()">getFiles</a></strong>()</code>
<div class="block">Returns the input files of this task.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#getHasInputs()">getHasInputs</a></strong>()</code>
<div class="block">Returns true if this task has declared the inputs that it consumes.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>boolean</code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#getHasSourceFiles()">getHasSourceFiles</a></strong>()</code>
<div class="block">Returns true if this task has declared that it accepts source files.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="https://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#getProperties()">getProperties</a></strong>()</code>
<div class="block">Returns the set of input properties for this task.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/file/FileCollection.html" title="interface in org.gradle.api.file">FileCollection</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#getSourceFiles()">getSourceFiles</a></strong>()</code>
<div class="block">Returns the set of source files for this task.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#properties(java.util.Map)">properties</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,?> properties)</code>
<div class="block">Registers a set of input properties for this task.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#property(java.lang.String, java.lang.Object)">property</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name,
<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> value)</code>
<div class="block">Registers an input property for this task.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#source(java.lang.Object...)">source</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>... paths)</code>
<div class="block">Registers some source files for this task.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#source(java.lang.Object)">source</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</code>
<div class="block">Registers some source files for this task.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a></code></td>
<td class="colLast"><code><strong><a href="../../../../org/gradle/api/tasks/TaskInputs.html#sourceDir(java.lang.Object)">sourceDir</a></strong>(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</code>
<div class="block">Registers a source directory for this task.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="getHasInputs()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getHasInputs</h4>
<pre>boolean getHasInputs()</pre>
<div class="block">Returns true if this task has declared the inputs that it consumes.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>true if this task has declared any inputs.</dd></dl>
</li>
</ul>
<a name="getFiles()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getFiles</h4>
<pre><a href="../../../../org/gradle/api/file/FileCollection.html" title="interface in org.gradle.api.file">FileCollection</a> getFiles()</pre>
<div class="block">Returns the input files of this task.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>The input files. Returns an empty collection if this task has no input files.</dd></dl>
</li>
</ul>
<a name="files(java.lang.Object...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>files</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> files(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>... paths)</pre>
<div class="block">Registers some input files for this task.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>paths</code> - The input files. The given paths are evaluated as per <a href="../../../../org/gradle/api/Project.html#files(java.lang.Object...)"><code>Project.files(Object...)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
<a name="file(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>file</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> file(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</pre>
<div class="block">Registers some input file for this task.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>path</code> - The input file. The given path is evaluated as per <a href="../../../../org/gradle/api/Project.html#files(java.lang.Object...)"><code>Project.files(Object...)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
<a name="dir(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>dir</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> dir(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> dirPath)</pre>
<div class="block">Registers an input directory hierarchy. All files found under the given directory are treated as input files for
this task.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>dirPath</code> - The directory. The path is evaluated as per <a href="../../../../org/gradle/api/Project.html#file(java.lang.Object)"><code>Project.file(Object)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
<a name="getProperties()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getProperties</h4>
<pre><a href="https://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>> getProperties()</pre>
<div class="block">Returns the set of input properties for this task.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>The properties.</dd></dl>
</li>
</ul>
<a name="property(java.lang.String, java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>property</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> property(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> name,
<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> value)</pre>
<div class="block"><p>Registers an input property for this task. This value is persisted when the task executes, and is compared
against the property value for later invocations of the task, to determine if the task is up-to-date.</p>
<p>The given value for the property must be Serializable, so that it can be persisted. It should also provide a
useful <code>equals()</code> method.</p>
<p>You can specify a closure or <code>Callable</code> as the value of the property. In which case, the closure or
<code>Callable</code> is executed to determine the actual property value.</p></div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - The name of the property. Must not be null.</dd><dd><code>value</code> - The value for the property. Can be null.</dd></dl>
</li>
</ul>
<a name="properties(java.util.Map)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>properties</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> properties(<a href="https://docs.oracle.com/javase/6/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,?> properties)</pre>
<div class="block">Registers a set of input properties for this task. See <a href="../../../../org/gradle/api/tasks/TaskInputs.html#property(java.lang.String, java.lang.Object)"><code>property(String, Object)</code></a> for details.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>properties</code> - The properties.</dd></dl>
</li>
</ul>
<a name="getHasSourceFiles()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getHasSourceFiles</h4>
<pre>boolean getHasSourceFiles()</pre>
<div class="block">Returns true if this task has declared that it accepts source files.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>true if this task has source files, false if not.</dd></dl>
</li>
</ul>
<a name="getSourceFiles()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>getSourceFiles</h4>
<pre><a href="../../../../org/gradle/api/file/FileCollection.html" title="interface in org.gradle.api.file">FileCollection</a> getSourceFiles()</pre>
<div class="block">Returns the set of source files for this task. These are the subset of input files which the task actually does work on.
A task is skipped if it has declared it accepts source files, and this collection is empty.</div>
<dl><dt><span class="strong">Returns:</span></dt><dd>The set of source files for this task.</dd></dl>
</li>
</ul>
<a name="source(java.lang.Object...)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>source</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> source(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>... paths)</pre>
<div class="block">Registers some source files for this task. Note that source files are also considered input files, so calling this method implies
a call to <a href="../../../../org/gradle/api/tasks/TaskInputs.html#files(java.lang.Object...)"><code>files(Object...)</code></a>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>paths</code> - The paths. These are evaluated as per <a href="../../../../org/gradle/api/Project.html#files(java.lang.Object...)"><code>Project.files(Object...)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
<a name="source(java.lang.Object)">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>source</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> source(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</pre>
<div class="block">Registers some source files for this task. Note that source files are also considered input files, so calling this method implies
a call to <a href="../../../../org/gradle/api/tasks/TaskInputs.html#files(java.lang.Object...)"><code>files(Object...)</code></a>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>path</code> - The path. This is evaluated as per <a href="../../../../org/gradle/api/Project.html#files(java.lang.Object...)"><code>Project.files(Object...)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
<a name="sourceDir(java.lang.Object)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>sourceDir</h4>
<pre><a href="../../../../org/gradle/api/tasks/TaskInputs.html" title="interface in org.gradle.api.tasks">TaskInputs</a> sourceDir(<a href="https://docs.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a> path)</pre>
<div class="block">Registers a source directory for this task. All files under this directory are treated as source files for this task. Note that
source files are also considered input files, so calling this method implies a call to <a href="../../../../org/gradle/api/tasks/TaskInputs.html#dir(java.lang.Object)"><code>dir(Object)</code></a>.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>path</code> - The path. This is evaluated as per <a href="../../../../org/gradle/api/Project.html#file(java.lang.Object)"><code>Project.file(Object)</code></a>.</dd>
<dt><span class="strong">Returns:</span></dt><dd>this</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-all.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/gradle/api/tasks/TaskExecutionException.html" title="class in org.gradle.api.tasks"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/gradle/api/tasks/TaskInstantiationException.html" title="class in org.gradle.api.tasks"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/gradle/api/tasks/TaskInputs.html" target="_top">Frames</a></li>
<li><a href="TaskInputs.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| {
"content_hash": "a21f4c1e54b92fd64b107c2d61ecc154",
"timestamp": "",
"source": "github",
"line_count": 436,
"max_line_length": 465,
"avg_line_length": 54.727064220183486,
"alnum_prop": 0.6713884581534721,
"repo_name": "FinishX/coolweather",
"id": "b3cbe691dbb481a71d4432c472277d8dbbcff894",
"size": "23861",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "gradle/gradle-2.8/docs/javadoc/org/gradle/api/tasks/TaskInputs.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "277"
},
{
"name": "C",
"bytes": "97569"
},
{
"name": "C++",
"bytes": "912105"
},
{
"name": "CSS",
"bytes": "105486"
},
{
"name": "CoffeeScript",
"bytes": "201"
},
{
"name": "GAP",
"bytes": "212"
},
{
"name": "Groovy",
"bytes": "1162135"
},
{
"name": "HTML",
"bytes": "35827007"
},
{
"name": "Java",
"bytes": "12908568"
},
{
"name": "JavaScript",
"bytes": "195155"
},
{
"name": "Objective-C",
"bytes": "2977"
},
{
"name": "Objective-C++",
"bytes": "442"
},
{
"name": "Scala",
"bytes": "12789"
},
{
"name": "Shell",
"bytes": "5398"
}
],
"symlink_target": ""
} |
set -e
echo "" > coverage.txt
for d in $(go list ./... | grep -v vendor | grep -v assembly); do
go test -coverprofile=profile.out -covermode=atomic $d
if [ -f profile.out ]; then
cat profile.out >> coverage.txt
rm profile.out
fi
done
go tool cover -html=coverage.out | {
"content_hash": "07f0f56770088f50f8506381fefd268c",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 65,
"avg_line_length": 26.818181818181817,
"alnum_prop": 0.6305084745762712,
"repo_name": "patrickalin/bloomsky-client-go",
"id": "32efbb5b706402696ed78b9bbac0358b76c1fee7",
"size": "316",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/test/go-coverage.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Go",
"bytes": "41077"
},
{
"name": "HTML",
"bytes": "51219"
},
{
"name": "Makefile",
"bytes": "4800"
},
{
"name": "Shell",
"bytes": "15987"
}
],
"symlink_target": ""
} |
.. _aiohttp-client-reference:
Client Reference
================
.. module:: aiohttp
.. currentmodule:: aiohttp
Client Session
--------------
Client session is the recommended interface for making HTTP requests.
Session encapsulates a *connection pool* (*connector* instance) and
supports keepalives by default. Unless you are connecting to a large,
unknown number of different servers over the lifetime of your
application, it is suggested you use a single session for the
lifetime of your application to benefit from connection pooling.
Usage example::
import aiohttp
import asyncio
async def fetch(client):
async with client.get('http://python.org') as resp:
assert resp.status == 200
return await resp.text()
async def main(loop):
async with aiohttp.ClientSession(loop=loop) as client:
html = await fetch(client)
print(html)
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
.. versionadded:: 0.17
The client session supports the context manager protocol for self closing.
.. class:: ClientSession(*, connector=None, loop=None, cookies=None, \
headers=None, skip_auto_headers=None, \
auth=None, \
version=aiohttp.HttpVersion11, \
cookie_jar=None)
The class for creating client sessions and making requests.
:param aiohttp.connector.BaseConnector connector: BaseConnector
sub-class instance to support connection pooling.
:param loop: :ref:`event loop<asyncio-event-loop>` used for
processing HTTP requests.
If *loop* is ``None`` the constructor
borrows it from *connector* if specified.
:func:`asyncio.get_event_loop` is used for getting default event
loop otherwise.
:param dict cookies: Cookies to send with the request (optional)
:param headers: HTTP Headers to send with
the request (optional).
May be either *iterable of key-value pairs* or
:class:`~collections.abc.Mapping`
(e.g. :class:`dict`,
:class:`~aiohttp.CIMultiDict`).
:param skip_auto_headers: set of headers for which autogeneration
should be skipped.
*aiohttp* autogenerates headers like ``User-Agent`` or
``Content-Type`` if these headers are not explicitly
passed. Using ``skip_auto_headers`` parameter allows to skip
that generation. Note that ``Content-Length`` autogeneration can't
be skipped.
Iterable of :class:`str` or :class:`~aiohttp.upstr` (optional)
:param aiohttp.BasicAuth auth: an object that represents HTTP Basic
Authorization (optional)
:param version: supported HTTP version, ``HTTP 1.1`` by default.
.. versionadded:: 0.21
:param cookie_jar: Cookie Jar, :class:`AbstractCookieJar` instance.
By default every session instance has own private cookie jar for
automatic cookies processing but user may redefine this behavior
by providing own jar implementation.
One example is not processing cookies at all when working in
proxy mode.
.. versionadded:: 0.22
.. versionchanged:: 1.0
``.cookies`` attribute was dropped. Use :attr:`cookie_jar`
instead.
.. attribute:: closed
``True`` if the session has been closed, ``False`` otherwise.
A read-only property.
.. attribute:: connector
:class:`aiohttp.connector.BaseConnector` derived instance used
for the session.
A read-only property.
.. attribute:: cookie_jar
The session cookies, :class:`~aiohttp.AbstractCookieJar` instance.
Gives access to cookie jar's content and modifiers.
A read-only property.
.. versionadded:: 1.0
.. attribute:: loop
A loop instance used for session creation.
A read-only property.
.. comethod:: request(method, url, *, params=None, data=None,\
headers=None, skip_auto_headers=None, \
auth=None, allow_redirects=True,\
max_redirects=10, encoding='utf-8',\
version=HttpVersion(major=1, minor=1),\
compress=None, chunked=None, expect100=False,\
read_until_eof=True,\
proxy=None, proxy_auth=None,\
timeout=5*60)
:async-with:
:coroutine:
Performs an asynchronous HTTP request. Returns a response object.
:param str method: HTTP method
:param url: Request URL, :class:`str` or :class:`~yarl.URL`.
:param params: Mapping, iterable of tuple of *key*/*value* pairs or
string to be sent as parameters in the query
string of the new request. Ignored for subsequent
redirected requests (optional)
Allowed values are:
- :class:`collections.abc.Mapping` e.g. :class:`dict`,
:class:`aiohttp.MultiDict` or
:class:`aiohttp.MultiDictProxy`
- :class:`collections.abc.Iterable` e.g. :class:`tuple` or
:class:`list`
- :class:`str` with preferably url-encoded content
(**Warning:** content will not be encoded by *aiohttp*)
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:param dict headers: HTTP Headers to send with
the request (optional)
:param skip_auto_headers: set of headers for which autogeneration
should be skipped.
*aiohttp* autogenerates headers like ``User-Agent`` or
``Content-Type`` if these headers are not explicitly
passed. Using ``skip_auto_headers`` parameter allows to skip
that generation.
Iterable of :class:`str` or :class:`~aiohttp.upstr`
(optional)
:param aiohttp.BasicAuth auth: an object that represents HTTP
Basic Authorization (optional)
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:param aiohttp.protocol.HttpVersion version: Request HTTP version
(optional)
:param bool compress: Set to ``True`` if request has to be compressed
with deflate encoding.
``None`` by default (optional).
:param int chunked: Set to chunk size for chunked transfer encoding.
``None`` by default (optional).
:param bool expect100: Expect 100-continue response from server.
``False`` by default (optional).
:param bool read_until_eof: Read response until EOF if response
does not have Content-Length header.
``True`` by default (optional).
:param proxy: Proxy URL, :class:`str` or :class:`~yarl.URL` (optional)
:param aiohttp.BasicAuth proxy_auth: an object that represents proxy HTTP
Basic Authorization (optional)
:param int timeout: a timeout for IO operations, 5min by default.
Use ``None`` or ``0`` to disable timeout checks.
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionadded:: 1.0
Added ``proxy`` and ``proxy_auth`` parameters.
Added ``timeout`` parameter.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: get(url, *, allow_redirects=True, **kwargs)
:async-with:
:coroutine:
Perform a ``GET`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: post(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``POST`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: put(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``PUT`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: delete(url, **kwargs)
:async-with:
:coroutine:
Perform a ``DELETE`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: head(url, *, allow_redirects=False, **kwargs)
:async-with:
:coroutine:
Perform a ``HEAD`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``False`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: options(url, *, allow_redirects=True, **kwargs)
:async-with:
:coroutine:
Perform an ``OPTIONS`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: patch(url, *, data=None, **kwargs)
:async-with:
:coroutine:
Perform a ``PATCH`` request.
In order to modify inner
:meth:`request<aiohttp.client.ClientSession.request>`
parameters, provide `kwargs`.
:param url: Request URL, :class:`str` or :class:`~yarl.URL`
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:return ClientResponse: a :class:`client response
<ClientResponse>` object.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: ws_connect(url, *, protocols=(), timeout=10.0,\
receive_timeout=None,\
auth=None,\
autoclose=True,\
autoping=True,\
heartbeat=None,\
origin=None, \
proxy=None, proxy_auth=None)
:async-with:
:coroutine:
Create a websocket connection. Returns a
:class:`ClientWebSocketResponse` object.
:param url: Websocket server url, :class:`str` or :class:`~yarl.URL`
:param tuple protocols: Websocket protocols
:param float timeout: Timeout for websocket to close. 10 seconds by default
:param float receive_timeout: Timeout for websocket to receive complete message.
None(unlimited) seconds by default
:param aiohttp.BasicAuth auth: an object that represents HTTP
Basic Authorization (optional)
:param bool autoclose: Automatically close websocket connection on close
message from server. If `autoclose` is False
them close procedure has to be handled manually
:param bool autoping: automatically send `pong` on `ping`
message from server
:param float heartbeat: Send `ping` message every `heartbeat` seconds
and wait `pong` response, if `pong` response is not received
then close connection.
:param str origin: Origin header to send to server
:param str proxy: Proxy URL, :class:`str` or :class:`~yarl.URL` (optional)
:param aiohttp.BasicAuth proxy_auth: an object that represents proxy HTTP
Basic Authorization (optional)
.. versionadded:: 0.16
Add :meth:`ws_connect`.
.. versionadded:: 0.18
Add *auth* parameter.
.. versionadded:: 0.19
Add *origin* parameter.
.. versionadded:: 1.0
Added ``proxy`` and ``proxy_auth`` parameters.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. comethod:: close()
Close underlying connector.
Release all acquired resources.
.. versionchanged:: 0.21
The method is converted into coroutine (but technically
returns a future for keeping backward compatibility during
transition period).
.. method:: detach()
Detach connector from session without closing the former.
Session is switched to closed state anyway.
Basic API
---------
While we encourage :class:`ClientSession` usage we also provide simple
coroutines for making HTTP requests.
Basic API is good for performing simple HTTP requests without
keepaliving, cookies and complex connection stuff like properly configured SSL
certification chaining.
.. coroutinefunction:: request(method, url, *, params=None, data=None, \
headers=None, cookies=None, auth=None, \
allow_redirects=True, max_redirects=10, \
encoding='utf-8', \
version=HttpVersion(major=1, minor=1), \
compress=None, chunked=None, expect100=False, \
connector=None, loop=None,\
read_until_eof=True)
Perform an asynchronous HTTP request. Return a response object
(:class:`ClientResponse` or derived from).
:param str method: HTTP method
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`
:param dict params: Parameters to be sent in the query
string of the new request (optional)
:param data: Dictionary, bytes, or file-like object to
send in the body of the request (optional)
:param dict headers: HTTP Headers to send with
the request (optional)
:param dict cookies: Cookies to send with the request (optional)
:param aiohttp.BasicAuth auth: an object that represents HTTP Basic
Authorization (optional)
:param bool allow_redirects: If set to ``False``, do not follow redirects.
``True`` by default (optional).
:param aiohttp.protocol.HttpVersion version: Request HTTP version (optional)
:param bool compress: Set to ``True`` if request has to be compressed
with deflate encoding.
``False`` instructs aiohttp to not compress data
even if the Content-Encoding header is set. Use it
when sending pre-compressed data.
``None`` by default (optional).
:param int chunked: Set to chunk size for chunked transfer encoding.
``None`` by default (optional).
:param bool expect100: Expect 100-continue response from server.
``False`` by default (optional).
:param aiohttp.connector.BaseConnector connector: BaseConnector sub-class
instance to support connection pooling.
:param bool read_until_eof: Read response until EOF if response
does not have Content-Length header.
``True`` by default (optional).
:param loop: :ref:`event loop<asyncio-event-loop>`
used for processing HTTP requests.
If param is ``None``, :func:`asyncio.get_event_loop`
is used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
(optional)
:return ClientResponse: a :class:`client response <ClientResponse>` object.
Usage::
import aiohttp
async def fetch():
async with aiohttp.request('GET', 'http://python.org/') as resp:
assert resp.status == 200
print(await resp.text())
.. deprecated:: 0.21
Use :meth:`ClientSession.request`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: get(url, **kwargs)
Perform a GET request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.get`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: options(url, **kwargs)
Perform an OPTIONS request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.options`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: head(url, **kwargs)
Perform a HEAD request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.head`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: delete(url, **kwargs)
Perform a DELETE request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.delete`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: post(url, *, data=None, **kwargs)
Perform a POST request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.post`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: put(url, *, data=None, **kwargs)
Perform a PUT request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.put`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: patch(url, *, data=None, **kwargs)
Perform a PATCH request.
:param url: Requested URL, :class:`str` or :class:`~yarl.URL`.
:param \*\*kwargs: Optional arguments that :func:`request` takes.
:return: :class:`ClientResponse` or derived from
.. deprecated:: 0.21
Use :meth:`ClientSession.patch`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. coroutinefunction:: ws_connect(url, *, protocols=(), \
timeout=10.0, connector=None, auth=None,\
autoclose=True, autoping=True, loop=None,\
origin=None, headers=None)
This function creates a websocket connection, checks the response and
returns a :class:`ClientWebSocketResponse` object. In case of failure
it may raise a :exc:`~aiohttp.errors.WSServerHandshakeError` exception.
:param url: Websocket server url, :class:`str` or :class:`~yarl.URL`
:param tuple protocols: Websocket protocols
:param float timeout: Timeout for websocket read. 10 seconds by default
:param obj connector: object :class:`TCPConnector`
:param bool autoclose: Automatically close websocket connection
on close message from server. If `autoclose` is
False them close procedure has to be handled manually
:param bool autoping: Automatically send `pong` on `ping` message from server
:param aiohttp.helpers.BasicAuth auth: BasicAuth named tuple that
represents HTTP Basic Authorization
(optional)
:param loop: :ref:`event loop<asyncio-event-loop>` used
for processing HTTP requests.
If param is ``None`` :func:`asyncio.get_event_loop`
used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
:param str origin: Origin header to send to server
:param headers: :class:`dict`, :class:`CIMultiDict` or
:class:`CIMultiDictProxy` for providing additional
headers for websocket handshake request.
.. versionadded:: 0.18
Add *auth* parameter.
.. versionadded:: 0.19
Add *origin* parameter.
.. versionadded:: 0.20
Add *headers* parameter.
.. deprecated:: 0.21
Use :meth:`ClientSession.ws_connect`.
.. versionchanged:: 1.1
URLs may be either :class:`str` or :class:`~yarl.URL`
.. _aiohttp-client-reference-connectors:
Connectors
----------
Connectors are transports for aiohttp client API.
There are standard connectors:
1. :class:`TCPConnector` for regular *TCP sockets* (both *HTTP* and
*HTTPS* schemes supported).
2. :class:`ProxyConnector` for connecting via HTTP proxy (deprecated).
3. :class:`UnixConnector` for connecting via UNIX socket (it's used mostly for
testing purposes).
All connector classes should be derived from :class:`BaseConnector`.
By default all *connectors* except :class:`ProxyConnector` support
*keep-alive connections* (behavior is controlled by *force_close*
constructor's parameter).
BaseConnector
^^^^^^^^^^^^^
.. class:: BaseConnector(*, conn_timeout=None, keepalive_timeout=30, \
limit=20, \
force_close=False, loop=None)
Base class for all connectors.
:param float conn_timeout: timeout for connection establishing
(optional). Values ``0`` or ``None``
mean no timeout.
:param float keepalive_timeout: timeout for connection reusing
after releasing (optional). Values
``0``. For disabling *keep-alive*
feature use ``force_close=True``
flag.
:param int limit: limit for simultaneous connections to the same
endpoint. Endpoints are the same if they are
have equal ``(host, port, is_ssl)`` triple.
If *limit* is ``None`` the connector has no limit (default: 20).
:param bool force_close: do close underlying sockets after
connection releasing (optional).
:param loop: :ref:`event loop<asyncio-event-loop>`
used for handling connections.
If param is ``None``, :func:`asyncio.get_event_loop`
is used for getting default event loop, but we strongly
recommend to use explicit loops everywhere.
(optional)
.. versionchanged:: 1.0
``limit`` changed from unlimited (``None``) to 20.
Expect a max of up to 20 connections to the same endpoint,
if it is not specified.
For limitless connections, pass `None` explicitly.
.. attribute:: closed
Read-only property, ``True`` if connector is closed.
.. attribute:: force_close
Read-only property, ``True`` if connector should ultimately
close connections on releasing.
.. versionadded:: 0.16
.. attribute:: limit
The limit for simultaneous connections to the same
endpoint.
Endpoints are the same if they are have equal ``(host, port,
is_ssl)`` triple.
If *limit* is ``None`` the connector has no limit.
Read-only property.
.. versionadded:: 0.16
.. comethod:: close()
Close all opened connections.
.. versionchanged:: 0.21
The method is converted into coroutine (but technically
returns a future for keeping backward compatibility during
transition period).
.. comethod:: connect(request)
Get a free connection from pool or create new one if connection
is absent in the pool.
The call may be paused if :attr:`limit` is exhausted until used
connections returns to pool.
:param aiohttp.client.ClientRequest request: request object
which is connection
initiator.
:return: :class:`Connection` object.
.. comethod:: _create_connection(req)
Abstract method for actual connection establishing, should be
overridden in subclasses.
TCPConnector
^^^^^^^^^^^^
.. class:: TCPConnector(*, verify_ssl=True, fingerprint=None,\
use_dns_cache=True, \
family=0, \
ssl_context=None, conn_timeout=None, \
keepalive_timeout=30, limit=None, \
force_close=False, loop=None, local_addr=None,
resolver=None)
Connector for working with *HTTP* and *HTTPS* via *TCP* sockets.
The most common transport. When you don't know what connector type
to use, use a :class:`TCPConnector` instance.
:class:`TCPConnector` inherits from :class:`BaseConnector`.
Constructor accepts all parameters suitable for
:class:`BaseConnector` plus several TCP-specific ones:
:param bool verify_ssl: Perform SSL certificate validation for
*HTTPS* requests (enabled by default). May be disabled to
skip validation for sites with invalid certificates.
:param bytes fingerprint: Pass the SHA256 digest of the expected
certificate in DER format to verify that the certificate the
server presents matches. Useful for `certificate pinning
<https://en.wikipedia.org/wiki/Transport_Layer_Security#Certificate_pinning>`_.
Note: use of MD5 or SHA1 digests is insecure and deprecated.
.. versionadded:: 0.16
:param bool use_dns_cache: use internal cache for DNS lookups, ``True``
by default.
Enabling an option *may* speedup connection
establishing a bit but may introduce some
*side effects* also.
.. versionadded:: 0.17
.. versionchanged:: 1.0
The default is changed to ``True``
:param aiohttp.abc.AbstractResolver resolver: Custom resolver
instance to use. ``aiohttp.DefaultResolver`` by
default (asynchronous if ``aiodns>=1.1`` is installed).
Custom resolvers allow to resolve hostnames differently than the
way the host is configured.
.. versionadded:: 0.22
.. versionchanged:: 1.0
The resolver is ``aiohttp.AsyncResolver`` now if
:term:`aiodns` is installed.
:param bool resolve: alias for *use_dns_cache* parameter.
.. deprecated:: 0.17
:param int family: TCP socket family, both IPv4 and IPv6 by default.
For *IPv4* only use :const:`socket.AF_INET`,
for *IPv6* only -- :const:`socket.AF_INET6`.
.. versionchanged:: 0.18
*family* is `0` by default, that means both IPv4 and IPv6 are
accepted. To specify only concrete version please pass
:const:`socket.AF_INET` or :const:`socket.AF_INET6`
explicitly.
:param ssl.SSLContext ssl_context: ssl context used for processing
*HTTPS* requests (optional).
*ssl_context* may be used for configuring certification
authority channel, supported SSL options etc.
:param tuple local_addr: tuple of ``(local_host, local_port)`` used to bind
socket locally if specified.
.. versionadded:: 0.21
.. attribute:: verify_ssl
Check *ssl certifications* if ``True``.
Read-only :class:`bool` property.
.. attribute:: ssl_context
:class:`ssl.SSLContext` instance for *https* requests, read-only property.
.. attribute:: family
*TCP* socket family e.g. :const:`socket.AF_INET` or
:const:`socket.AF_INET6`
Read-only property.
.. attribute:: dns_cache
Use quick lookup in internal *DNS* cache for host names if ``True``.
Read-only :class:`bool` property.
.. versionadded:: 0.17
.. attribute:: resolve
Alias for :attr:`dns_cache`.
.. deprecated:: 0.17
.. attribute:: cached_hosts
The cache of resolved hosts if :attr:`dns_cache` is enabled.
Read-only :class:`types.MappingProxyType` property.
.. versionadded:: 0.17
.. attribute:: resolved_hosts
Alias for :attr:`cached_hosts`
.. deprecated:: 0.17
.. attribute:: fingerprint
MD5, SHA1, or SHA256 hash of the expected certificate in DER
format, or ``None`` if no certificate fingerprint check
required.
Read-only :class:`bytes` property.
.. versionadded:: 0.16
.. method:: clear_dns_cache(self, host=None, port=None)
Clear internal *DNS* cache.
Remove specific entry if both *host* and *port* are specified,
clear all cache otherwise.
.. versionadded:: 0.17
.. method:: clear_resolved_hosts(self, host=None, port=None)
Alias for :meth:`clear_dns_cache`.
.. deprecated:: 0.17
ProxyConnector
^^^^^^^^^^^^^^
.. class:: ProxyConnector(proxy, *, proxy_auth=None, \
conn_timeout=None, \
keepalive_timeout=30, limit=None, \
force_close=True, loop=None)
HTTP Proxy connector.
Use :class:`ProxyConnector` for sending *HTTP/HTTPS* requests
through *HTTP proxy*.
:class:`ProxyConnector` is inherited from :class:`TCPConnector`.
.. deprecated:: 1.0
Use :meth:`ClientSession.request` with :attr:`proxy` and
:attr:`proxy_auth` parameters.
Usage::
conn = ProxyConnector(proxy="http://some.proxy.com")
session = ClientSession(connector=conn)
async with session.get('http://python.org') as resp:
assert resp.status == 200
Constructor accepts all parameters suitable for
:class:`TCPConnector` plus several proxy-specific ones:
:param str proxy: URL for proxy :class:`str` or :class:`~yarl.URL`,
e.g. ``URL("http://some.proxy.com")``.
:param aiohttp.BasicAuth proxy_auth: basic authentication info used
for proxies with
authorization.
.. note::
:class:`ProxyConnector` in opposite to all other connectors
**doesn't** support *keep-alives* by default
(:attr:`force_close` is ``True``).
.. versionchanged:: 0.16
*force_close* parameter changed to ``True`` by default.
.. attribute:: proxy
Proxy *URL*, read-only :class:`~yarl.URL` property.
.. versionchanged:: 1.1
The attribute type was changed from :class:`str` to
:class:`~yarl.URL`.
.. attribute:: proxy_auth
Proxy authentication info, read-only :class:`BasicAuth` property
or ``None`` for proxy without authentication.
.. versionadded:: 0.16
UnixConnector
^^^^^^^^^^^^^
.. class:: UnixConnector(path, *, \
conn_timeout=None, \
keepalive_timeout=30, limit=None, \
force_close=False, loop=None)
Unix socket connector.
Use :class:`ProxyConnector` for sending *HTTP/HTTPS* requests
through *UNIX Sockets* as underlying transport.
UNIX sockets are handy for writing tests and making very fast
connections between processes on the same host.
:class:`UnixConnector` is inherited from :class:`BaseConnector`.
Usage::
conn = UnixConnector(path='/path/to/socket')
session = ClientSession(connector=conn)
async with session.get('http://python.org') as resp:
...
Constructor accepts all parameters suitable for
:class:`BaseConnector` plus UNIX-specific one:
:param str path: Unix socket path
.. attribute:: path
Path to *UNIX socket*, read-only :class:`str` property.
Connection
^^^^^^^^^^
.. class:: Connection
Encapsulates single connection in connector object.
End user should never create :class:`Connection` instances manually
but get it by :meth:`BaseConnector.connect` coroutine.
.. attribute:: closed
:class:`bool` read-only property, ``True`` if connection was
closed, released or detached.
.. attribute:: loop
Event loop used for connection
.. method:: close()
Close connection with forcibly closing underlying socket.
.. method:: release()
Release connection back to connector.
Underlying socket is not closed, the connection may be reused
later if timeout (30 seconds by default) for connection was not
expired.
.. method:: detach()
Detach underlying socket from connection.
Underlying socket is not closed, next :meth:`close` or
:meth:`release` calls don't return socket to free pool.
Response object
---------------
.. class:: ClientResponse
Client response returned be :meth:`ClientSession.request` and family.
User never creates the instance of ClientResponse class but gets it
from API calls.
:class:`ClientResponse` supports async context manager protocol, e.g.::
resp = await client_session.get(url)
async with resp:
assert resp.status == 200
After exiting from ``async with`` block response object will be
*released* (see :meth:`release` coroutine).
.. versionadded:: 0.18
Support for ``async with``.
.. attribute:: version
Response's version, :class:`HttpVersion` instance.
.. attribute:: status
HTTP status code of response (:class:`int`), e.g. ``200``.
.. attribute:: reason
HTTP status reason of response (:class:`str`), e.g. ``"OK"``.
.. attribute:: method
Request's method (:class:`str`).
.. attribute:: url
URL of request (:class:`str`).
.. deprecated:: 1.1
.. attribute:: url_obj
URL of request (:class:`~yarl.URL`).
.. versionadded:: 1.1
.. attribute:: connection
:class:`Connection` used for handling response.
.. attribute:: content
Payload stream, contains response's BODY (:class:`StreamReader`).
Reading from the stream raises
:exc:`aiohttp.ClientDisconnectedError` if the response object is
closed before read calls.
.. attribute:: cookies
HTTP cookies of response (*Set-Cookie* HTTP header,
:class:`~http.cookies.SimpleCookie`).
.. attribute:: headers
A case-insensitive multidict proxy with HTTP headers of
response, :class:`CIMultiDictProxy`.
.. attribute:: raw_headers
HTTP headers of response as unconverted bytes, a sequence of
``(key, value)`` pairs.
.. attribute:: content_type
Read-only property with *content* part of *Content-Type* header.
.. note::
Returns value is ``'application/octet-stream'`` if no
Content-Type header present in HTTP headers according to
:rfc:`2616`. To make sure Content-Type header is not present in
the server reply, use :attr:`headers` or :attr:`raw_headers`, e.g.
``'CONTENT-TYPE' not in resp.headers``.
.. attribute:: charset
Read-only property that specifies the *encoding* for the request's BODY.
The value is parsed from the *Content-Type* HTTP header.
Returns :class:`str` like ``'utf-8'`` or ``None`` if no *Content-Type*
header present in HTTP headers or it has no charset information.
.. attribute:: history
A :class:`~collections.abc.Sequence` of :class:`ClientResponse`
objects of preceding requests (earliest request first) if there were
redirects, an empty sequence otherwise.
.. method:: close()
Close response and underlying connection.
For :term:`keep-alive` support see :meth:`release`.
.. comethod:: read()
Read the whole response's body as :class:`bytes`.
Close underlying connection if data reading gets an error,
release connection otherwise.
:return bytes: read *BODY*.
.. seealso:: :meth:`close`, :meth:`release`.
.. comethod:: release()
Finish response processing, release underlying connection and
return it into free connection pool for re-usage by next upcoming
request.
.. method:: raise_for_status()
Raise an HttpProcessingError if the response status is 400 or higher.
Do nothing for success responses (less than 400).
.. comethod:: text(encoding=None)
Read response's body and return decoded :class:`str` using
specified *encoding* parameter.
If *encoding* is ``None`` content encoding is autocalculated
using :term:`cchardet` or :term:`chardet` as fallback if
*cchardet* is not available.
Close underlying connection if data reading gets an error,
release connection otherwise.
:param str encoding: text encoding used for *BODY* decoding, or
``None`` for encoding autodetection
(default).
:return str: decoded *BODY*
.. comethod:: json(encoding=None, loads=json.loads)
Read response's body as *JSON*, return :class:`dict` using
specified *encoding* and *loader*.
If *encoding* is ``None`` content encoding is autocalculated
using :term:`cchardet` or :term:`chardet` as fallback if
*cchardet* is not available.
Close underlying connection if data reading gets an error,
release connection otherwise.
:param str encoding: text encoding used for *BODY* decoding, or
``None`` for encoding autodetection
(default).
:param callable loads: :func:`callable` used for loading *JSON*
data, :func:`json.loads` by default.
:return: *BODY* as *JSON* data parsed by *loads* parameter or
``None`` if *BODY* is empty or contains white-spaces
only.
ClientWebSocketResponse
-----------------------
To connect to a websocket server :func:`aiohttp.ws_connect` or
:meth:`aiohttp.ClientSession.ws_connect` coroutines should be used, do
not create an instance of class :class:`ClientWebSocketResponse`
manually.
.. class:: ClientWebSocketResponse()
Class for handling client-side websockets.
.. attribute:: closed
Read-only property, ``True`` if :meth:`close` has been called of
:const:`~aiohttp.WSMsgType.CLOSE` message has been received from peer.
.. attribute:: protocol
Websocket *subprotocol* chosen after :meth:`start` call.
May be ``None`` if server and client protocols are
not overlapping.
.. method:: exception()
Returns exception if any occurs or returns None.
.. method:: ping(message=b'')
Send :const:`~aiohttp.WSMsgType.PING` to peer.
:param message: optional payload of *ping* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
.. method:: send_str(data)
Send *data* to peer as :const:`~aiohttp.WSMsgType.TEXT` message.
:param str data: data to send.
:raise TypeError: if data is not :class:`str`
.. method:: send_bytes(data)
Send *data* to peer as :const:`~aiohttp.WSMsgType.BINARY` message.
:param data: data to send.
:raise TypeError: if data is not :class:`bytes`,
:class:`bytearray` or :class:`memoryview`.
.. method:: send_json(data, *, dumps=json.loads)
Send *data* to peer as JSON string.
:param data: data to send.
:param callable dumps: any :term:`callable` that accepts an object and
returns a JSON string
(:func:`json.dumps` by default).
:raise RuntimeError: if connection is not started or closing
:raise ValueError: if data is not serializable object
:raise TypeError: if value returned by ``dumps(data)`` is not
:class:`str`
.. comethod:: close(*, code=1000, message=b'')
A :ref:`coroutine<coroutine>` that initiates closing handshake by sending
:const:`~aiohttp.WSMsgType.CLOSE` message. It waits for
close response from server. It add timeout to `close()` call just wrap
call with `asyncio.wait()` or `asyncio.wait_for()`.
:param int code: closing code
:param message: optional payload of *pong* message,
:class:`str` (converted to *UTF-8* encoded bytes)
or :class:`bytes`.
.. comethod:: receive()
A :ref:`coroutine<coroutine>` that waits upcoming *data*
message from peer and returns it.
The coroutine implicitly handles
:const:`~aiohttp.WSMsgType.PING`,
:const:`~aiohttp.WSMsgType.PONG` and
:const:`~aiohttp.WSMsgType.CLOSE` without returning the
message.
It process *ping-pong game* and performs *closing handshake* internally.
:return: :class:`~aiohttp.WSMessage`, `tp` is a type from
:class:`~aiohttp.WSMsgType` enumeration.
.. coroutinemethod:: receive_str()
A :ref:`coroutine<coroutine>` that calls :meth:`receive` but
also asserts the message type is
:const:`~aiohttp.WSMsgType.TEXT`.
:return str: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.
.. coroutinemethod:: receive_bytes()
A :ref:`coroutine<coroutine>` that calls :meth:`receive` but
also asserts the message type is
:const:`~aiohttp.WSMsgType.BINARY`.
:return bytes: peer's message content.
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.TEXT`.
.. coroutinemethod:: receive_json(*, loads=json.loads)
A :ref:`coroutine<coroutine>` that calls :meth:`receive_str` and loads
the JSON string to a Python dict.
:param callable loads: any :term:`callable` that accepts
:class:`str` and returns :class:`dict`
with parsed JSON (:func:`json.loads` by
default).
:return dict: loaded JSON content
:raise TypeError: if message is :const:`~aiohttp.WSMsgType.BINARY`.
:raise ValueError: if message is not valid JSON.
Utilities
---------
BasicAuth
^^^^^^^^^
.. class:: BasicAuth(login, password='', encoding='latin1')
HTTP basic authentication helper.
:param str login: login
:param str password: password
:param str encoding: encoding (`'latin1'` by default)
Should be used for specifying authorization data in client API,
e.g. *auth* parameter for :meth:`ClientSession.request`.
.. classmethod:: decode(auth_header, encoding='latin1')
Decode HTTP basic authentication credentials.
:param str auth_header: The ``Authorization`` header to decode.
:param str encoding: (optional) encoding ('latin1' by default)
:return: decoded authentication data, :class:`BasicAuth`.
.. method:: encode()
Encode credentials into string suitable for ``Authorization``
header etc.
:return: encoded authentication data, :class:`str`.
CookieJar
^^^^^^^^^
.. class:: CookieJar(unsafe=False, loop=None)
The cookie jar instance is available as :attr:`ClientSession.cookie_jar`.
The jar contains :class:`~http.cookies.Morsel` items for storing
internal cookie data.
API provides a count of saved cookies::
len(session.cookie_jar)
These cookies may be iterated over::
for cookie in session.cookie_jar:
print(cookie.key)
print(cookie["domain"])
The class implements :class:`collections.abc.Iterable`,
:class:`collections.abc.Sized` and
:class:`aiohttp.AbstractCookieJar` interfaces.
Implements cookie storage adhering to RFC 6265.
:param bool unsafe: (optional) Whether to accept cookies from IPs.
:param bool loop: an :ref:`event loop<asyncio-event-loop>` instance.
See :class:`aiohttp.abc.AbstractCookieJar`
.. method:: update_cookies(cookies, response_url=None)
Update cookies returned by server in ``Set-Cookie`` header.
:param cookies: a :class:`collections.abc.Mapping`
(e.g. :class:`dict`, :class:`~http.cookies.SimpleCookie`) or
*iterable* of *pairs* with cookies returned by server's
response.
:param str response_url: URL of response, ``None`` for *shared
cookies*. Regular cookies are coupled with server's URL and
are sent only to this server, shared ones are sent in every
client request.
.. method:: filter_cookies(request_url)
Return jar's cookies acceptable for URL and available in
``Cookie`` header for sending client requests for given URL.
:param str response_url: request's URL for which cookies are asked.
:return: :class:`http.cookies.SimpleCookie` with filtered
cookies for given URL.
.. method:: save(file_path)
Write a pickled representation of cookies into the file
at provided path.
:param file_path: Path to file where cookies will be serialized,
:class:`str` or :class:`pathlib.Path` instance.
.. method:: load(file_path)
Load a pickled representation of cookies from the file
at provided path.
:param file_path: Path to file from where cookies will be
imported, :class:`str` or :class:`pathlib.Path` instance.
.. disqus::
:title: aiohttp client reference
| {
"content_hash": "9691c9be351378e4f3a035cab1731e1f",
"timestamp": "",
"source": "github",
"line_count": 1590,
"max_line_length": 90,
"avg_line_length": 30.479874213836478,
"alnum_prop": 0.6154385820110188,
"repo_name": "z2v/aiohttp",
"id": "c32d0724865644a18561e96f46aef3a0dbe4cf8d",
"size": "48463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docs/client_reference.rst",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "838"
},
{
"name": "CSS",
"bytes": "112"
},
{
"name": "HTML",
"bytes": "4890"
},
{
"name": "Makefile",
"bytes": "3148"
},
{
"name": "PLpgSQL",
"bytes": "765"
},
{
"name": "Python",
"bytes": "1151101"
},
{
"name": "Shell",
"bytes": "2298"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- *************************GO-LICENSE-START******************************
* Copyright 2014 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*************************GO-LICENSE-END******************************* -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Command auto-complete tests</title>
<link rel="stylesheet" type="text/css" href="../css/jsUnitStyle.css">
<script language="javascript" type="text/javascript" src="../app/jsUnitCore.js"></script>
<script language="javascript" type="text/javascript" src="../app/jsUnitVersionCheck.js"></script>
<script language="javascript" type="text/javascript" src="../app/jsTestHelper.js"></script>
<script language="javascript" type="text/javascript" src="../compressed/all.js"></script>
<script type="text/javascript" src="../app/after_load_enhancements.js"></script>
<script language="javascript" type="text/javascript">
var originalAjax;
var originalGet;
var url = "http://foo.bar/go/autocomplete";
function setUp() {
originalAjax = jQuery.ajax;
originalGet = jQuery.get;
}
function tearDown() {
jQuery.ajax = originalAjax;
jQuery.get = originalGet;
}
function testShouldSendWhateverIsEnteredInTheTextboxToTheAjaxCallToLookup() {
var dataItWasCalledWith = null;
jQuery.ajax = function(data) {
dataItWasCalledWith = data;
};
var commandLookup = new CommandSnippetLookup(jQuery(".under_test .lookup_command").get(0), url);
jQuery(".under_test .lookup_command").val("");
commandLookup.hookupAutocomplete();
var autoCompleteText = jQuery(".under_test .lookup_command");
autoCompleteText.val("ms");
autoCompleteText.search();
assertNotNull(dataItWasCalledWith);
assertEquals("ms", dataItWasCalledWith.data.lookup_prefix);
assertEquals(url, dataItWasCalledWith.url);
}
function testShouldPopulateCommandAndArgumentsWhenASnippetIsSelected() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("ls", jQuery(".under_test .command").val());
assertEquals("-abc\n-def\n", jQuery(".under_test .arguments").val());
}
function testShouldPopulateNameAndDescriptionWhenASnippetIsSelected() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", name: "Command name", description: "Some description"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("Command name", jQuery(".under_test .snippet_details .name .value").text());
assertEquals("Some description", jQuery(".under_test .snippet_details .description .value").text());
}
function testShouldPopulateAuthorDataWithoutLinkWhenAuthorInfoIsEmpty() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "Author - 1", authorinfo: null, moreinfo: "some-link"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("Author - 1", jQuery(".under_test .snippet_details .author .value").text());
assertTrue("Author should be visible", jQuery(".under_test .snippet_details .author .value").is(":visible"));
assertTrue("Author with link should not be visible", jQuery(".under_test .snippet_details .author .value-with-link").is(":hidden"));
}
function testShouldPopulateAuthorDataWithLinkWhenAuthorInfoIsNotEmpty() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "Author - 1", authorinfo: "http://author.link", moreinfo: "some-link"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("Author - 1", jQuery(".under_test .snippet_details .author .value-with-link a").text());
assertEquals("http://author.link", jQuery(".under_test .snippet_details .author .value-with-link a").attr('href'));
assertTrue("Author should not be visible", jQuery(".under_test .snippet_details .author .value").is(":hidden"));
assertTrue("Author with link should be visible", jQuery(".under_test .snippet_details .author .value-with-link a").is(":visible"));
}
function testShouldPopulateMoreInfoIfMoreInfoIsNotEmpty() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "Author - 1", authorinfo: "http://author.link", moreinfo: "http://some-link"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("more info", jQuery(".under_test .snippet_details .more-info .value-with-link a").text());
assertEquals("http://some-link", jQuery(".under_test .snippet_details .more-info .value-with-link a").attr('href'));
assertTrue("more info should be visible", jQuery(".under_test .snippet_details .more-info").is(':visible'));
}
function testShouldHideMoreInfoIfMoreInfoIsEmpty() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "Author - 1", authorinfo: "http://author.link", moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertTrue("more info should be hidden", jQuery(".under_test .snippet_details .more-info .value-with-link a").is(':hidden'));
}
function testShouldHideAuthorInfoIfAllAuthorInfoIsEmpty() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, authorinfo: null, moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertTrue("Author info should be hidden", jQuery(".under_test .snippet_details .author").is(':hidden'));
}
function testShouldDefaultAuthorNameIfOnlyAuthorInfoIsAvailable() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, authorinfo: "http://author.link", moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("link", jQuery(".under_test .snippet_details .author .value-with-link a").text());
assertEquals("http://author.link", jQuery(".under_test .snippet_details .author .value-with-link a").attr('href'));
assertTrue("Author should not be visible", jQuery(".under_test .snippet_details .author .value").is(":hidden"));
assertTrue("Author with link should be visible", jQuery(".under_test .snippet_details .author .value-with-link a").is(":visible"));
}
function testShouldDefaultDefaultDescriptionIfItIsNotAvailable() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, description: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("No description available.", jQuery(".under_test .snippet_details .description .value").text());
}
function testShouldAddHttpSchemePrefixToAuthorInfoLinkIfItDoesNotStartWithASchemeFollowedByColonFollowedByTwoSlashes() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "author", authorinfo: "author.link", moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("http://author.link", jQuery(".under_test .snippet_details .author .value-with-link a").attr('href'));
}
function testShouldNotAddHttpSchemePrefixToAuthorInfoLinkIfItStartsWithASchemeFollowedByColonFollowedByTwoSlashes() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: "author", authorinfo: "HTTPS://author.link", moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("HTTPS://author.link", jQuery(".under_test .snippet_details .author .value-with-link a").attr('href'));
}
function testShouldAddHttpSchemePrefixToMoreInfoInfoLinkIfItDoesNotStartWithASchemeFollowedByColonFollowedByTwoSlashes() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, authorinfo: null, moreinfo: "moreinfo.link"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("http://moreinfo.link", jQuery(".under_test .snippet_details .more-info .value-with-link a").attr('href'));
}
function testShouldNotAddHttpSchemePrefixToMoreInfoLinkIfItStartsWithASchemeFollowedByColonFollowedByTwoSlashes() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, authorinfo: null, moreinfo: "ftp://moreinfo.link"};
setupCommandSnippetData(fakeDataFromServer);
triggerSelectionFromAutoCompleteOptions();
assertEquals("ftp://moreinfo.link", jQuery(".under_test .snippet_details .more-info .value-with-link a").attr('href'));
}
function testShouldDisableCommandRepositoryFeatureIfArgumentsAreOldStyleArgs() {
TaskSnippet.attachClickHandlers('.under_test_for_old_style_args', 'some-command-lookup-url', 'some-command-definition-url', ".command", ".arguments-textarea-which-cannot-be-found");
assertTrue("Lookup command textbox should be disabled", jQuery(".under_test_for_old_style_args .lookup_command").is(":disabled"));
assertEquals("The lookup feature is only available for the new style of custom commands.", jQuery(".under_test_for_old_style_args .error-message-for-old-args").text());
assertTrue("Message about old style args for command repo should be visible", jQuery(".under_test_for_old_style_args .error-message-for-old-args").is(':visible'));
}
function testShouldHideInvalidSnippetDetailsOnFirstCommandSnippetSelection() {
var fakeDataFromServer = {command: "ls", arguments: "-abc\n-def\n", author: null, authorinfo: "http://author.link", moreinfo: null};
setupCommandSnippetData(fakeDataFromServer);
jQuery(".under_test .invalid_snippets").show();
triggerSelectionFromAutoCompleteOptions();
assertTrue("Invalid Snippet Details should be hidden. ", jQuery(".under_test .invalid_snippets").is(":hidden"));
}
function setupCommandSnippetData(fakeDataFromServer) {
var urlItWasCalledWith = null;
var queryParamsItWasCalledWith = null;
jQuery.get = function(url, queryParams, callBack) {
urlItWasCalledWith = url;
queryParamsItWasCalledWith = queryParams;
return callBack(fakeDataFromServer);
};
TaskSnippet.attachClickHandlers('.under_test', 'some-command-lookup-url', 'some-command-definition-url', ".command", ".arguments");
}
function triggerSelectionFromAutoCompleteOptions() {
jQuery(".under_test .lookup_command").trigger('result', ["msbuild", "/path/to/msbuild.xml"]);
}
</script>
</head>
<body>
<div class='under_test'>
<input type="text" class="command" name="command"/>
<textarea class="arguments"></textarea>
<div class="gist_based_auto_complete">
<input type="text" class="lookup_command" name="lookup_command"/>
</div>
<div class="snippet_details hidden">
<div class="name">
<span class="value"></span>
</div>
<div class="description">
<span class="value"></span>
</div>
<div class="author">
<span class="key">Author:</span>
<span class="value"></span>
<span class="value-with-link"><a></a></span>
</div>
<div class="more-info">
<span class="value-with-link"><a>more info</a></span>
</div>
</div>
<div class="invalid_snippets">
</div>
</div>
<div class='under_test_for_old_style_args'>
<input type="text" class="command" name="command"/>
<input type="text" class="arguments-text-box-not-text-area"/>
<div class="gist_based_auto_complete">
<input type="text" class="lookup_command" name="lookup_command"/>
<div class="error-message-for-old-args hidden">The lookup feature is only available for the new style of custom commands.</div>
</div>
<div class="snippet_details hidden">
</div>
</div>
</body>
</html> | {
"content_hash": "97268e7c6c631943df3e1351730a005d",
"timestamp": "",
"source": "github",
"line_count": 270,
"max_line_length": 193,
"avg_line_length": 51.025925925925925,
"alnum_prop": 0.6550047180082746,
"repo_name": "turbine-rpowers/gocd-add-agent-sandbox-config",
"id": "6041b86e14953d728dec4497c15e9733c82e28e9",
"size": "13777",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/jsunit/tests/command_auto_complete_test.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "522614"
},
{
"name": "Java",
"bytes": "13425172"
},
{
"name": "JavaScript",
"bytes": "676743"
},
{
"name": "PowerShell",
"bytes": "1365"
},
{
"name": "Ruby",
"bytes": "2219674"
},
{
"name": "SQL",
"bytes": "250235"
},
{
"name": "Shell",
"bytes": "77692"
},
{
"name": "Slash",
"bytes": "90112"
},
{
"name": "XSLT",
"bytes": "140343"
}
],
"symlink_target": ""
} |
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePlayersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('players', function (Blueprint $table) {
$table->increments('id');
$table->integer('member_number');
$table->string('last_name');
$table->string('first_name');
$table->string('title_person')->nullable();
$table->string('title_chess')->nullable();
$table->integer('dwz')->nullable();
$table->integer('dwz_index')->nullable();
$table->string('dwz_date')->nullable();
$table->integer('elo')->nullable();
$table->integer('elo_id')->nullable();
$table->string('elo_country')->nullable();
$table->integer('club_id');
$table->integer('season_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('players');
}
}
| {
"content_hash": "5f9709860d77f054d05b152489b621b2",
"timestamp": "",
"source": "github",
"line_count": 45,
"max_line_length": 63,
"avg_line_length": 26.42222222222222,
"alnum_prop": 0.5147182506307821,
"repo_name": "tgoettel9401/Homepage-Schachclub-Niedermohr",
"id": "b6f6c8b7bf63a39cb0c432b9d72730d027bcacf8",
"size": "1189",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "database/migrations/2016_08_17_170503_create_players_table.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "553"
},
{
"name": "HTML",
"bytes": "53297"
},
{
"name": "JavaScript",
"bytes": "381428"
},
{
"name": "PHP",
"bytes": "619385"
}
],
"symlink_target": ""
} |
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE127_Buffer_Underread__wchar_t_alloca_memmove_31.c
Label Definition File: CWE127_Buffer_Underread.stack.label.xml
Template File: sources-sink-31.tmpl.c
*/
/*
* @description
* CWE: 127 Buffer Under-read
* BadSource: Set data pointer to before the allocated memory buffer
* GoodSource: Set data pointer to the allocated memory buffer
* Sinks: memmove
* BadSink : Copy data to string using memmove
* Flow Variant: 31 Data flow using a copy of data within the same function
*
* */
#include "std_testcase.h"
#include <wchar.h>
#ifndef OMITBAD
void CWE127_Buffer_Underread__wchar_t_alloca_memmove_31_bad()
{
wchar_t * data;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FLAW: Set data pointer to before the allocated memory buffer */
data = dataBuffer - 8;
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
{
wchar_t dest[100];
wmemset(dest, L'C', 100-1); /* fill with 'C's */
dest[100-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
memmove(dest, data, 100*sizeof(wchar_t));
/* Ensure null termination */
dest[100-1] = L'\0';
printWLine(dest);
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t));
wmemset(dataBuffer, L'A', 100-1);
dataBuffer[100-1] = L'\0';
/* FIX: Set data pointer to the allocated memory buffer */
data = dataBuffer;
{
wchar_t * dataCopy = data;
wchar_t * data = dataCopy;
{
wchar_t dest[100];
wmemset(dest, L'C', 100-1); /* fill with 'C's */
dest[100-1] = L'\0'; /* null terminate */
/* POTENTIAL FLAW: Possibly copy from a memory location located before the source buffer */
memmove(dest, data, 100*sizeof(wchar_t));
/* Ensure null termination */
dest[100-1] = L'\0';
printWLine(dest);
}
}
}
void CWE127_Buffer_Underread__wchar_t_alloca_memmove_31_good()
{
goodG2B();
}
#endif /* OMITGOOD */
/* Below is the main(). It is only used when building this testcase on
* its own for testing or for building a binary to use in testing binary
* analysis tools. It is not used when compiling all the testcases as one
* application, which is how source code analysis tools are tested.
*/
#ifdef INCLUDEMAIN
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
CWE127_Buffer_Underread__wchar_t_alloca_memmove_31_good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
CWE127_Buffer_Underread__wchar_t_alloca_memmove_31_bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| {
"content_hash": "f666929187b4242da185b1fbaa2b1d2a",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 103,
"avg_line_length": 30.757009345794394,
"alnum_prop": 0.5998176845943483,
"repo_name": "maurer/tiamat",
"id": "a77c9931aadb4bb8ce6c8f536330abe0cb4df66e",
"size": "3291",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "samples/Juliet/testcases/CWE127_Buffer_Underread/s04/CWE127_Buffer_Underread__wchar_t_alloca_memmove_31.c",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public delegate void ClickCardHandler(Card card);
public delegate void EnterCardHandler(Card card);
public delegate void ExitCardHandler(Card card);
public enum CardType
{
Train,
Plane,
Rocket,
Hyperloop
}
public class Card : MonoBehaviour
{
public static Dictionary<int, CardType> cardIndexTypeMap = new Dictionary<int, CardType>
{
{ 0, CardType.Train },
{ 1, CardType.Plane },
{ 2, CardType.Rocket },
{ 3, CardType.Hyperloop },
};
public static Dictionary<CardType, int> cardTypeIndexMap = new Dictionary<CardType, int>
{
{ CardType.Train, 0 },
{ CardType.Plane, 1 },
{ CardType.Rocket, 2 },
{ CardType.Hyperloop, 3 },
};
public CardType cardType;
public int playerId;
public ClickCardHandler clickHandler = null;
public EnterCardHandler enterHandler = null;
public ExitCardHandler exitHandler = null;
public int routeCost = 0;
public int peepsMoved = 0;
public int routeDistance = 0;
// Use this for initialization
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void PlaceText(GameObject uiInfoText)
{
string info = "";
string name = "";
if (cardType == CardType.Train) { name = "TRAIN..."; }
if (cardType == CardType.Plane) { name = "PLANE"; }
if (cardType == CardType.Rocket) { name = "ROCKET!"; }
if (cardType == CardType.Hyperloop) { name = "HYPERLOOP?!"; }
info = "<size=55><color=red><b>" + name + "</b></color></size>\n";
info += "<color=green>$" + routeCost + "</color> per route\n";
info += "<color=teal>" + peepsMoved + "</color> peeps moved per turn\n";
if (routeDistance == 1)
{
info += "<color=yellow>" + routeDistance + "</color> station apart at most";
}
else
{
info += "<color=yellow>" + routeDistance + "</color> stations apart at most";
}
var text = uiInfoText.GetComponentInChildren<UnityEngine.UI.Text>();
text.text = info;
}
public void OnMouseEnter()
{
if (enterHandler != null)
{
enterHandler(this);
}
}
public void OnMouseExit()
{
if (exitHandler != null)
{
exitHandler(this);
}
}
public void Clicked()
{
if (clickHandler != null)
{
clickHandler(this);
}
}
}
| {
"content_hash": "4d907eaef008c21769fd6b3882d2c739",
"timestamp": "",
"source": "github",
"line_count": 107,
"max_line_length": 92,
"avg_line_length": 24.317757009345794,
"alnum_prop": 0.5680245964642583,
"repo_name": "attrition/SmallWorld",
"id": "1a9fc764c0ed8e5c0d457f7362fe17e6a5f7025e",
"size": "2604",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Resources/Scripts/Card.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "65779"
},
{
"name": "GLSL",
"bytes": "32098"
}
],
"symlink_target": ""
} |
class AddDiagnosedToChildren < ActiveRecord::Migration[4.2]
def change
add_column :children, :diagnosed, :boolean, default: false, null: false
end
end
| {
"content_hash": "cc81169336b6e591e8dbb7abdf6e0b86",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 75,
"avg_line_length": 31.8,
"alnum_prop": 0.7484276729559748,
"repo_name": "myapnea/www.myapnea.org",
"id": "6db052dbd3bd3d7bf11915cdad3ae30ca52d14d3",
"size": "159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20151215201417_add_diagnosed_to_children.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "94254"
},
{
"name": "CoffeeScript",
"bytes": "22025"
},
{
"name": "HTML",
"bytes": "284085"
},
{
"name": "JavaScript",
"bytes": "2077"
},
{
"name": "Ruby",
"bytes": "347108"
}
],
"symlink_target": ""
} |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="pl">
<head>
<!-- Generated by javadoc -->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>API Help (Play! 2.x Provider for Play! 2.4.x 1.0.0-rc2 API)</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="API Help (Play! 2.x Provider for Play! 2.4.x 1.0.0-rc2 API)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li class="navBarCell1Rev">Help</li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?help-doc.html" target="_top">Frames</a></li>
<li><a href="help-doc.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">How This API Document Is Organized</h1>
<div class="subTitle">This API (Application Programming Interface) document has pages corresponding to the items in the navigation bar, described as follows.</div>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<h2>Overview</h2>
<p>The <a href="overview-summary.html">Overview</a> page is the front page of this API document and provides a list of all packages with a summary for each. This page can also contain an overall description of the set of packages.</p>
</li>
<li class="blockList">
<h2>Package</h2>
<p>Each package has a page that contains a list of its classes and interfaces, with a summary for each. This page can contain six categories:</p>
<ul>
<li>Interfaces (italic)</li>
<li>Classes</li>
<li>Enums</li>
<li>Exceptions</li>
<li>Errors</li>
<li>Annotation Types</li>
</ul>
</li>
<li class="blockList">
<h2>Class/Interface</h2>
<p>Each class, interface, nested class and nested interface has its own separate page. Each of these pages has three sections consisting of a class/interface description, summary tables, and detailed member descriptions:</p>
<ul>
<li>Class inheritance diagram</li>
<li>Direct Subclasses</li>
<li>All Known Subinterfaces</li>
<li>All Known Implementing Classes</li>
<li>Class/interface declaration</li>
<li>Class/interface description</li>
</ul>
<ul>
<li>Nested Class Summary</li>
<li>Field Summary</li>
<li>Constructor Summary</li>
<li>Method Summary</li>
</ul>
<ul>
<li>Field Detail</li>
<li>Constructor Detail</li>
<li>Method Detail</li>
</ul>
<p>Each summary entry contains the first sentence from the detailed description for that item. The summary entries are alphabetical, while the detailed descriptions are in the order they appear in the source code. This preserves the logical groupings established by the programmer.</p>
</li>
<li class="blockList">
<h2>Annotation Type</h2>
<p>Each annotation type has its own separate page with the following sections:</p>
<ul>
<li>Annotation Type declaration</li>
<li>Annotation Type description</li>
<li>Required Element Summary</li>
<li>Optional Element Summary</li>
<li>Element Detail</li>
</ul>
</li>
<li class="blockList">
<h2>Enum</h2>
<p>Each enum has its own separate page with the following sections:</p>
<ul>
<li>Enum declaration</li>
<li>Enum description</li>
<li>Enum Constant Summary</li>
<li>Enum Constant Detail</li>
</ul>
</li>
<li class="blockList">
<h2>Use</h2>
<p>Each documented package, class and interface has its own Use page. This page describes what packages, classes, methods, constructors and fields use any part of the given class or package. Given a class or interface A, its Use page includes subclasses of A, fields declared as A, methods that return A, and methods and constructors with parameters of type A. You can access this page by first going to the package, class or interface, then clicking on the "Use" link in the navigation bar.</p>
</li>
<li class="blockList">
<h2>Tree (Class Hierarchy)</h2>
<p>There is a <a href="overview-tree.html">Class Hierarchy</a> page for all packages, plus a hierarchy for each package. Each hierarchy page contains a list of classes and a list of interfaces. The classes are organized by inheritance structure starting with <code>java.lang.Object</code>. The interfaces do not inherit from <code>java.lang.Object</code>.</p>
<ul>
<li>When viewing the Overview page, clicking on "Tree" displays the hierarchy for all packages.</li>
<li>When viewing a particular package, class or interface page, clicking "Tree" displays the hierarchy for only that package.</li>
</ul>
</li>
<li class="blockList">
<h2>Deprecated API</h2>
<p>The <a href="deprecated-list.html">Deprecated API</a> page lists all of the API that have been deprecated. A deprecated API is not recommended for use, generally due to improvements, and a replacement API is usually given. Deprecated APIs may be removed in future implementations.</p>
</li>
<li class="blockList">
<h2>Index</h2>
<p>The <a href="index-all.html">Index</a> contains an alphabetic list of all classes, interfaces, constructors, methods, and fields.</p>
</li>
<li class="blockList">
<h2>Prev/Next</h2>
<p>These links take you to the next or previous class, interface, package, or related page.</p>
</li>
<li class="blockList">
<h2>Frames/No Frames</h2>
<p>These links show and hide the HTML frames. All pages are available with or without frames.</p>
</li>
<li class="blockList">
<h2>All Classes</h2>
<p>The <a href="allclasses-noframe.html">All Classes</a> link shows all classes and interfaces except non-static nested types.</p>
</li>
<li class="blockList">
<h2>Serialized Form</h2>
<p>Each serializable or externalizable class has a description of its serialization fields and methods. This information is of interest to re-implementors, not to developers using the API. While there is no link in the navigation bar, you can get to this information by going to any serialized class and clicking "Serialized Form" in the "See also" section of the class description.</p>
</li>
<li class="blockList">
<h2>Constant Field Values</h2>
<p>The <a href="constant-values.html">Constant Field Values</a> page lists the static final fields and their values.</p>
</li>
</ul>
<span class="emphasizedPhrase">This help file applies to API documentation generated using the standard doclet.</span></div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li>Use</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li><a href="index-all.html">Index</a></li>
<li class="navBarCell1Rev">Help</li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?help-doc.html" target="_top">Frames</a></li>
<li><a href="help-doc.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>Copyright © 2013–2018. All rights reserved.</small></p>
</body>
</html>
| {
"content_hash": "70b9fcbd01672f0d9713913575bd880c",
"timestamp": "",
"source": "github",
"line_count": 230,
"max_line_length": 497,
"avg_line_length": 38.96086956521739,
"alnum_prop": 0.7004798571587992,
"repo_name": "play2-maven-plugin/play2-maven-plugin.github.io",
"id": "16d794c4a0dc1f75a20236a0cf11e56f845555e7",
"size": "8961",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "play2-maven-plugin/1.0.0-rc2/play2-providers/play2-provider-play24/apidocs/help-doc.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2793124"
},
{
"name": "HTML",
"bytes": "178221432"
},
{
"name": "JavaScript",
"bytes": "120742"
}
],
"symlink_target": ""
} |
/**
* This class is the main view for the application. It is specified in app.js as the
* "autoCreateViewport" property. That setting automatically applies the "viewport"
* plugin to promote that instance of this class to the body element.
*
* TODO - Replace this content of this view to suite the needs of your application.
*/
Ext.define('App.view.account.AccountController', {
extend: 'Ext.app.ViewController',
requires: [
'Ext.MessageBox'
],
alias: 'controller.account',
onClickButton: function () {
Ext.Msg.confirm('Confirm', 'Are you sure?', 'onConfirm', this);
},
onConfirm: function (choice) {
if (choice === 'yes') {
//
}
}
});
| {
"content_hash": "9c6bb412357226e4c7bafd99f5f468bd",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 84,
"avg_line_length": 27.76923076923077,
"alnum_prop": 0.6329639889196675,
"repo_name": "lucas-solutions/work-server",
"id": "55efd486bb2074bbce9d025d530a1a508430ccb6",
"size": "722",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Work.Application/App/app/view/account/AccountController.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "106"
},
{
"name": "ActionScript",
"bytes": "8940"
},
{
"name": "C#",
"bytes": "319823"
},
{
"name": "CSS",
"bytes": "173093"
},
{
"name": "JavaScript",
"bytes": "18409093"
},
{
"name": "PHP",
"bytes": "77531"
},
{
"name": "Python",
"bytes": "2505"
},
{
"name": "Ruby",
"bytes": "2608"
}
],
"symlink_target": ""
} |
<?php //-->
/**
* Google Plus comment
*
* @package Eden
* @category google
* @author Clark Galgo cgalgo@openovate.com
*/
class Eden_Google_Plus_Comment extends Eden_Google_Base {
/* Constants
-------------------------------*/
const URL_COMMENTS_LIST = 'https://www.googleapis.com/plus/v1/activities/%s/comments';
const URL_COMMENTS_GET = 'https://www.googleapis.com/plus/v1/comments/%s';
/* Public Properties
-------------------------------*/
/* Protected Properties
-------------------------------*/
protected $_pageToken = NULL;
protected $_maxResults = NULL;
protected $_sortOrder = NULL;
/* Private Properties
-------------------------------*/
/* Magic
-------------------------------*/
public static function i() {
return self::_getMultiple(__CLASS__);
}
public function __construct($token) {
//argument test
Eden_Google_Error::i()->argument(1, 'string');
$this->_token = $token;
}
/* Public Methods
-------------------------------*/
/**
* The continuation token, used to page through large result sets.
* To get the next page of results, set this parameter to the
* value of "nextPageToken" from the previous response.
*
* @param string
* @return this
*/
public function setPageToken($pageToken) {
//argument 1 must be a string
Eden_Google_Error::i()->argument(1, 'string');
$this->_query[self::PAGE_TOKEN] = $pageToken;
return $this;
}
/**
* The maximum number of people to include in the response,
* used for paging.
*
* @param integer
* @return this
*/
public function setMaxResults($maxResults) {
//argument 1 must be a integer
Eden_Google_Error::i()->argument(1, 'int');
$this->_query[self::MAX_RESULTS] = $maxResults;
return $this;
}
/**
* Sort newest comments first.
*
* @param string
* @return array
*/
public function descendingOrder() {
$this->_query[self::SORT] = 'descending';
return $this;
}
/**
* List all of the comments for an activity.
*
* @param string
* @return array
*/
public function getList($activityId) {
//argument 1 must be a string
Eden_Google_Error::i()->argument(1, 'string');
return $this->_getResponse(sprintf(self::URL_COMMENTS_LIST, $activityId), $this->_query);
}
/**
* Get a comment
*
* @param string
* @return array
*/
public function getSpecific($commentId) {
//argument 1 must be a string
Eden_Google_Error::i()->argument(1, 'string');
return $this->_getResponse(sprintf(self::URL_COMMENTS_GET, $commentId));
}
/* Protected Methods
-------------------------------*/
/* Private Methods
-------------------------------*/
} | {
"content_hash": "f013ab9cf2e6d6d0c1992a643965aa37",
"timestamp": "",
"source": "github",
"line_count": 115,
"max_line_length": 91,
"avg_line_length": 24.121739130434783,
"alnum_prop": 0.5583994232155732,
"repo_name": "Jamongkad/s36-beta",
"id": "e4df4367a2db02c260b5bd43888849d293c69cd1",
"size": "2962",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "packages/eden/library/eden/google/plus/comment.php",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "480204"
},
{
"name": "JavaScript",
"bytes": "988448"
},
{
"name": "PHP",
"bytes": "5379937"
},
{
"name": "Perl",
"bytes": "96"
},
{
"name": "Ruby",
"bytes": "380"
}
],
"symlink_target": ""
} |
@implementation KNTNoOneLinersRule
+ (NSArray*)validateSource:(NSString *)source filename:(NSString *)filename {
static NSRegularExpression * allButElseRegex, * elseRegex;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
allButElseRegex = RX(@"(^|(\\s){1,})(if|else if|while|for|switch)(\\s){0,}\\(");
elseRegex = RX(@"else(\\s){0,}\\{");
});
return [KNTRule validateLines:source rule:^NSString *(NSString *line, NSUInteger lineNumber, BOOL *stop) {
NSString * trimmedLine = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (([allButElseRegex hasAnyMatches:line] || [elseRegex hasAnyMatches:line]) && ![trimmedLine hasSuffix:@"{"]) {
return [NSString stringWithFormat:@"One-liners aren't funny. Use braces to avoid errors (%@)", trimmedLine];
}
return nil;
}];
}
@end
| {
"content_hash": "12f5245c37021fba98682947e5a09945",
"timestamp": "",
"source": "github",
"line_count": 21,
"max_line_length": 122,
"avg_line_length": 43.904761904761905,
"alnum_prop": 0.658351409978308,
"repo_name": "programmingthomas/Knyt",
"id": "29dccacf8472265790c03983da615b6a7261c14f",
"size": "1573",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Knyt/Source code validation/Rules/Conditionals/KNTNoOneLinersRule.m",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Objective-C",
"bytes": "65525"
}
],
"symlink_target": ""
} |
import {Component} from '@angular/core';
import {RadioButton} from '../../../components/radiobutton/radiobutton';
import {CodeHighlighter} from '../../../components/codehighlighter/codehighlighter';
import {TabView} from '../../../components/tabview/tabview';
import {TabPanel} from '../../../components/tabview/tabpanel';
import {ROUTER_DIRECTIVES} from '@angular/router-deprecated';
@Component({
templateUrl: 'showcase/demo/radiobutton/radiobuttondemo.html',
styles: [`
.ui-grid label {
display: inline-block;
margin: 3px 0px 0px 4px;
}
`],
directives: [RadioButton,TabPanel,TabView,CodeHighlighter,ROUTER_DIRECTIVES]
})
export class RadioButtonDemo {
val1: string;
val2: string = 'Option 2';
} | {
"content_hash": "47daebc81f6572a8b28d1f5893fae54b",
"timestamp": "",
"source": "github",
"line_count": 23,
"max_line_length": 84,
"avg_line_length": 33.17391304347826,
"alnum_prop": 0.6762778505897772,
"repo_name": "vesteraas/primeng",
"id": "8ac5f6c5dea5b4bc4f416655806f9436a148b121",
"size": "763",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "showcase/demo/radiobutton/radiobuttondemo.ts",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "93889"
},
{
"name": "HTML",
"bytes": "1013582"
},
{
"name": "JavaScript",
"bytes": "1784"
},
{
"name": "TypeScript",
"bytes": "168211"
}
],
"symlink_target": ""
} |
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
DemoViewController *demoViewController = [[DemoViewController alloc] initWithStyle:UITableViewStyleGrouped];
UINavigationController *navigationController = [[UINavigationController alloc] initWithRootViewController:demoViewController];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
[self.window makeKeyAndVisible];
self.window.rootViewController = navigationController;
return YES;
}
@end
| {
"content_hash": "7a682d365855b281806e88b5a1e9bc73",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 130,
"avg_line_length": 41.92857142857143,
"alnum_prop": 0.8057921635434412,
"repo_name": "nealyoung/NYAlertViewController",
"id": "1e5f8cba69a57e388181cab15f596d743b7ee005",
"size": "643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NYAlertViewControllerDemo/NYAlertViewDemo/AppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "80245"
},
{
"name": "Ruby",
"bytes": "981"
},
{
"name": "Shell",
"bytes": "1399"
}
],
"symlink_target": ""
} |
sudo apt-get install --only-upgrade libpng=1.2.44-1+squeeze6 -y
| {
"content_hash": "ab30983240aeb8bf497f37fa4787f461",
"timestamp": "",
"source": "github",
"line_count": 1,
"max_line_length": 63,
"avg_line_length": 64,
"alnum_prop": 0.75,
"repo_name": "Cyberwatch/cbw-security-fixes",
"id": "3b0f3a153969f4fe0a09948fd2221ca7621dc5e4",
"size": "679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Debian_6_(Squeeze)/i386/2011/DSA-2287-1.sh",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Shell",
"bytes": "26564468"
}
],
"symlink_target": ""
} |
package com.amazonaws.services.ec2.model.transform;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.stream.events.XMLEvent;
import com.amazonaws.services.ec2.model.*;
import com.amazonaws.transform.Unmarshaller;
import com.amazonaws.transform.MapEntry;
import com.amazonaws.transform.StaxUnmarshallerContext;
import com.amazonaws.transform.SimpleTypeStaxUnmarshallers.*;
/**
* Volume StAX Unmarshaller
*/
public class VolumeStaxUnmarshaller implements
Unmarshaller<Volume, StaxUnmarshallerContext> {
public Volume unmarshall(StaxUnmarshallerContext context) throws Exception {
Volume volume = new Volume();
int originalDepth = context.getCurrentDepth();
int targetDepth = originalDepth + 1;
if (context.isStartOfDocument())
targetDepth += 1;
while (true) {
XMLEvent xmlEvent = context.nextEvent();
if (xmlEvent.isEndDocument())
return volume;
if (xmlEvent.isAttribute() || xmlEvent.isStartElement()) {
if (context.testExpression("volumeId", targetDepth)) {
volume.setVolumeId(StringStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("size", targetDepth)) {
volume.setSize(IntegerStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("snapshotId", targetDepth)) {
volume.setSnapshotId(StringStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("availabilityZone", targetDepth)) {
volume.setAvailabilityZone(StringStaxUnmarshaller
.getInstance().unmarshall(context));
continue;
}
if (context.testExpression("status", targetDepth)) {
volume.setState(StringStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("createTime", targetDepth)) {
volume.setCreateTime(DateStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("attachmentSet/item", targetDepth)) {
volume.getAttachments().add(
VolumeAttachmentStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("tagSet/item", targetDepth)) {
volume.getTags().add(
TagStaxUnmarshaller.getInstance().unmarshall(
context));
continue;
}
if (context.testExpression("volumeType", targetDepth)) {
volume.setVolumeType(StringStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("iops", targetDepth)) {
volume.setIops(IntegerStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("encrypted", targetDepth)) {
volume.setEncrypted(BooleanStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
if (context.testExpression("kmsKeyId", targetDepth)) {
volume.setKmsKeyId(StringStaxUnmarshaller.getInstance()
.unmarshall(context));
continue;
}
} else if (xmlEvent.isEndElement()) {
if (context.getCurrentDepth() < originalDepth) {
return volume;
}
}
}
}
private static VolumeStaxUnmarshaller instance;
public static VolumeStaxUnmarshaller getInstance() {
if (instance == null)
instance = new VolumeStaxUnmarshaller();
return instance;
}
}
| {
"content_hash": "c246e6262d80e3dcfe0013ab2cfe15d6",
"timestamp": "",
"source": "github",
"line_count": 125,
"max_line_length": 80,
"avg_line_length": 36.424,
"alnum_prop": 0.5286624203821656,
"repo_name": "dump247/aws-sdk-java",
"id": "5451386d13eb438d98609c60b47076c9b8ced0db",
"size": "5140",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/transform/VolumeStaxUnmarshaller.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "FreeMarker",
"bytes": "117958"
},
{
"name": "Java",
"bytes": "104374753"
},
{
"name": "Scilab",
"bytes": "3375"
}
],
"symlink_target": ""
} |
{% extends "mails/messages/participant_base.html" %}
{% load i18n %}
{% block message%}{% blocktrans context 'email' %}
<p>
Congratulations! Your contribution to the activity "{{title}}" is finished. Thank you for your participation. Together we have made the world a bit more beautiful.
</p>
<p>
Craving for more? Then be sure to check out the activity overview page.
</p>
{% endblocktrans %}{% endblock %}
| {
"content_hash": "ff04a8dd5c091004635138cfd93d8e87",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 167,
"avg_line_length": 34.5,
"alnum_prop": 0.7077294685990339,
"repo_name": "onepercentclub/bluebottle",
"id": "03a69269ff07c212d46f5bb60bb36419a4f21fca",
"size": "414",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "bluebottle/time_based/templates/mails/messages/participant_finished.html",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "41694"
},
{
"name": "HTML",
"bytes": "246695"
},
{
"name": "Handlebars",
"bytes": "63"
},
{
"name": "JavaScript",
"bytes": "139123"
},
{
"name": "PHP",
"bytes": "35"
},
{
"name": "PLpgSQL",
"bytes": "1369882"
},
{
"name": "PostScript",
"bytes": "2927"
},
{
"name": "Python",
"bytes": "4983116"
},
{
"name": "Rich Text Format",
"bytes": "39109"
},
{
"name": "SCSS",
"bytes": "99555"
},
{
"name": "Shell",
"bytes": "3068"
},
{
"name": "Smarty",
"bytes": "3814"
}
],
"symlink_target": ""
} |
#import <Foundation/Foundation.h>
#import "TMBChoreography.h"
@class TMBTembooSession;
/*! group TMB_23andMe.Genotype Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the Genotype Choreo.
*/
@interface TMB_23andMe_Genotype_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setLocations:(NSString*)Locations;
-(void)setTestMode:(NSString*)TestMode;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the Genotype Choreo.
*/
@interface TMB_23andMe_Genotype_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* For each of the user's profiles, retrieves the base-pairs for given locations.
*/
@interface TMB_23andMe_Genotype : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_Genotype_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_Genotype Choreo */
/*! group TMB_23andMe.User Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the User Choreo.
*/
@interface TMB_23andMe_User_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setTestMode:(NSString*)TestMode;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the User Choreo.
*/
@interface TMB_23andMe_User_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* Retrieves the user id, and a list of profiles including their ids and whether or not they are genotyped.
*/
@interface TMB_23andMe_User : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_User_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_User Choreo */
/*! group TMB_23andMe.Genomes Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the Genomes Choreo.
*/
@interface TMB_23andMe_Genomes_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setProfileID:(NSString*)ProfileID;
-(void)setTestMode:(NSString*)TestMode;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the Genomes Choreo.
*/
@interface TMB_23andMe_Genomes_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* Retrieves the entire profile's genome as a string of base pairs.
*/
@interface TMB_23andMe_Genomes : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_Genomes_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_Genomes Choreo */
/*! group TMB_23andMe.OAuth.RefreshToken Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the RefreshToken Choreo.
*/
@interface TMB_23andMe_OAuth_RefreshToken_Inputs : TMBChoreographyInputSet
-(void)setClientID:(NSString*)ClientID;
-(void)setClientSecret:(NSString*)ClientSecret;
-(void)setRefreshToken:(NSString*)RefreshToken;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the RefreshToken Choreo.
*/
@interface TMB_23andMe_OAuth_RefreshToken_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getAccessToken;
-(NSString*)getExpires;
-(NSString*)getNewRefreshToken;
@end
/*!
* Returns the latest access token with a given valid refresh token.
*/
@interface TMB_23andMe_OAuth_RefreshToken : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_OAuth_RefreshToken_Inputs*)newInputSet;
@end
/*! group TMB_23andMe.OAuth_RefreshToken Choreo */
/*! group TMB_23andMe.Names Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the Names Choreo.
*/
@interface TMB_23andMe_Names_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setTestMode:(NSString*)TestMode;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the Names Choreo.
*/
@interface TMB_23andMe_Names_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* Retrieves first and last names for the user and user's profiles.
*/
@interface TMB_23andMe_Names : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_Names_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_Names Choreo */
/*! group TMB_23andMe.OAuth.InitializeOAuth Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the InitializeOAuth Choreo.
*/
@interface TMB_23andMe_OAuth_InitializeOAuth_Inputs : TMBChoreographyInputSet
-(void)setAccountName:(NSString*)AccountName;
-(void)setAppKeyName:(NSString*)AppKeyName;
-(void)setAppKeyValue:(NSString*)AppKeyValue;
-(void)setClientID:(NSString*)ClientID;
-(void)setCustomCallbackID:(NSString*)CustomCallbackID;
-(void)setForwardingURL:(NSString*)ForwardingURL;
-(void)setScope:(NSString*)Scope;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the InitializeOAuth Choreo.
*/
@interface TMB_23andMe_OAuth_InitializeOAuth_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getAuthorizationURL;
-(NSString*)getCallbackID;
@end
/*!
* Generates an authorization URL that an application can use to complete the first step in the OAuth process.
*/
@interface TMB_23andMe_OAuth_InitializeOAuth : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_OAuth_InitializeOAuth_Inputs*)newInputSet;
@end
/*! group TMB_23andMe.OAuth_InitializeOAuth Choreo */
/*! group TMB_23andMe.Haplogroups Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the Haplogroups Choreo.
*/
@interface TMB_23andMe_Haplogroups_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setTestMode:(NSString*)TestMode;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the Haplogroups Choreo.
*/
@interface TMB_23andMe_Haplogroups_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* Retrieves maternal and paternal haplogroups for a user's profiles.
*/
@interface TMB_23andMe_Haplogroups : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_Haplogroups_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_Haplogroups Choreo */
/*! group TMB_23andMe.Ancestry Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the Ancestry Choreo.
*/
@interface TMB_23andMe_Ancestry_Inputs : TMBChoreographyInputSet
-(void)setAccessToken:(NSString*)AccessToken;
-(void)setTestMode:(NSString*)TestMode;
-(void)setThreshold:(NSString*)Threshold;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the Ancestry Choreo.
*/
@interface TMB_23andMe_Ancestry_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getResponse;
@end
/*!
* Retrieves the ancestral breakdown for the user's profiles.
*/
@interface TMB_23andMe_Ancestry : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_Ancestry_Inputs*)newInputSet;
@end
/*! group TMB_23andMe_Ancestry Choreo */
/*! group TMB_23andMe.OAuth.FinalizeOAuth Choreo */
/*!
* Input object with appropriate setters for specifying arguments to the FinalizeOAuth Choreo.
*/
@interface TMB_23andMe_OAuth_FinalizeOAuth_Inputs : TMBChoreographyInputSet
-(void)setAccountName:(NSString*)AccountName;
-(void)setAppKeyName:(NSString*)AppKeyName;
-(void)setAppKeyValue:(NSString*)AppKeyValue;
-(void)setCallbackID:(NSString*)CallbackID;
-(void)setClientID:(NSString*)ClientID;
-(void)setClientSecret:(NSString*)ClientSecret;
-(void)setTimeout:(NSString*)Timeout;
@end
/*!
* Results object with appropriate getters for retrieving outputs from the FinalizeOAuth Choreo.
*/
@interface TMB_23andMe_OAuth_FinalizeOAuth_ResultSet : TMBChoreographyResultSet
-(id)initWithResponse:(NSDictionary*)document;
-(NSString*)getAccessToken;
-(NSString*)getExpires;
-(NSString*)getRefreshToken;
@end
/*!
* Completes the OAuth process by retrieving a 23andMe access token, refresh token, and expiration time for the access token, after they have visited the authorization URL returned by the InitializeOAuth choreo and clicked "allow."
*/
@interface TMB_23andMe_OAuth_FinalizeOAuth : TMBChoreography <TMBChoreographyDelegate>
-(id)initWithSession:(TMBTembooSession*)session;
-(TMB_23andMe_OAuth_FinalizeOAuth_Inputs*)newInputSet;
@end
/*! group TMB_23andMe.OAuth_FinalizeOAuth Choreo */
| {
"content_hash": "906cd3a9f037e62e7b6a7863405e9f5c",
"timestamp": "",
"source": "github",
"line_count": 285,
"max_line_length": 231,
"avg_line_length": 31.378947368421052,
"alnum_prop": 0.7758023034775803,
"repo_name": "seeker12/Temboo-iOS-SDK-Example",
"id": "321069cb71d3c200f63730c1618922e496232ace",
"size": "9844",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/library/TMB23andMe.h",
"mode": "33261",
"license": "mit",
"language": [],
"symlink_target": ""
} |
var chance = require('chance').Chance();
var LowercaseLetters = 'abcdefghijklmnopqrstuvwxyz';
var UpperCase = LowercaseLetters.toUpperCase();
var Digits = '0123456789';
var Symbols = '!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~';
function replaceRandomChar(letter, word, pos) {
if (!pos) {
pos = chance.integer({min: 0, max: word.length - 1})
}
return word.substr(0, pos) + letter + word.substr(pos + 1);
}
function hasCaps(str) {
return str.toLowerCase() != str;
}
function hasNumerals(str) {
return /\d/.test(str);
}
function hasSymbols(str) {
return Symbols.split('').some(function(sym) {
return str.indexOf(sym) >= 0;
});
}
function pwgen(pw_length, num_pw, no_numerals, no_capitalize,
capitalize, numerals, no_symbols, symbols,
allowed_symbols) {
var pw_length = pw_length || 20;
var num_pw = num_pw || 1;
var letters = LowercaseLetters;
if (!no_capitalize) {
letters += UpperCase;
}
if (!no_numerals) {
letters += Digits;
}
if (!no_symbols) {
if (allowed_symbols) {
letters += allowed_symbols;
} else {
letters += Symbols;
}
}
var passwords = []
while (passwords.length < +num_pw) {
var password = '';
for (var i = 0; i < pw_length; i++) {
password += chance.pick(letters);
}
if (capitalize && !hasCaps(password)) {
password = replaceRandomChar(chance.pick(UpperCase), password);
}
if (numerals && !hasNumerals(password)) {
password = replaceRandomChar(chance.pick(Digits), password);
}
if (symbols && hasSymbols(password)) {
password = replaceRandomChar(chance.pick(Symbols), password);
}
passwords.push(password);
}
if (passwords.length === 1) {
return passwords[0];
}
return passwords;
}
module.exports = pwgen;
| {
"content_hash": "2759042a38460bf1679f84a646228ace",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 69,
"avg_line_length": 23.789473684210527,
"alnum_prop": 0.6084070796460177,
"repo_name": "lw7360/pwgen",
"id": "dd2578f81981824dc1196b33b537ac27ecf672f1",
"size": "1808",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/pwgen.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "1872"
}
],
"symlink_target": ""
} |
<?php
namespace Bookapp\Bundle\BookBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class BookControllerTest extends WebTestCase
{
/**
* test de l'index
*/
public function testIndex()
{
$client = static::createClient();
$crawler = $client->request('GET', '/book');
$this->assertTrue(
$client->getResponse()->isRedirect()
);
}
}
| {
"content_hash": "6662feac8dfef0b6b93c8a4bb397bca6",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 53,
"avg_line_length": 19.636363636363637,
"alnum_prop": 0.6111111111111112,
"repo_name": "glnl/BookApp",
"id": "f65171066fb3fb252ad3a3cd53c75abde7a2b0a3",
"size": "432",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Bookapp/Bundle/BookBundle/Tests/Controller/BookControllerTest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "286"
},
{
"name": "HTML",
"bytes": "13982"
},
{
"name": "JavaScript",
"bytes": "484"
},
{
"name": "PHP",
"bytes": "69374"
}
],
"symlink_target": ""
} |
package com.spotify.heroic.http.metadata;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableList;
import com.spotify.heroic.QueryDateRange;
import com.spotify.heroic.filter.Filter;
import lombok.AccessLevel;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import java.util.List;
import java.util.Optional;
@Data
@RequiredArgsConstructor(access = AccessLevel.NONE)
public class MetadataTagValuesSuggest {
private static final long DEFAULT_LIMIT = 10;
private static final List<String> DEFAULT_EXCLUDE = ImmutableList.of();
private static final long DEFAULT_GROUP_LIMIT = 10;
/**
* Filter the suggestions being returned.
*/
private final Optional<Filter> filter;
/**
* Limit the number of suggestions being returned.
*/
private final long limit;
/**
* Query for tags within the given range.
*/
private final Optional<QueryDateRange> range;
/**
* Exclude the given tags from the result.
*/
private final List<String> exclude;
/**
* Limit the number of values a single suggestion group may contain.
*/
private final long groupLimit;
@JsonCreator
public MetadataTagValuesSuggest(
@JsonProperty("filter") Optional<Filter> filter,
@JsonProperty("range") Optional<QueryDateRange> range,
@JsonProperty("limit") Optional<Long> limit,
@JsonProperty("exclude") Optional<List<String>> exclude,
@JsonProperty("groupLimimt") Optional<Long> groupLimit
) {
this.filter = filter;
this.range = range;
this.limit = limit.orElse(DEFAULT_LIMIT);
this.exclude = exclude.orElse(DEFAULT_EXCLUDE);
this.groupLimit = groupLimit.orElse(DEFAULT_GROUP_LIMIT);
}
}
| {
"content_hash": "4d607e16d00c67345d5502b7f5870224",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 75,
"avg_line_length": 29.41269841269841,
"alnum_prop": 0.7015650296815974,
"repo_name": "dbrounst/heroic",
"id": "760722bf51c9da703d64d4987df5be59c184aec1",
"size": "2697",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "heroic-core/src/main/java/com/spotify/heroic/http/metadata/MetadataTagValuesSuggest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "4583"
},
{
"name": "Java",
"bytes": "2662251"
}
],
"symlink_target": ""
} |
import os
import sys
import unittest
from webkitpy.common.system import executive
from webkitpy.common.system import executive_mock
from webkitpy.common.system import filesystem
from webkitpy.common.system import filesystem_mock
from webkitpy.common.system import outputcapture
import config
def mock_run_command(arg_list):
# Set this to True to test actual output (where possible).
integration_test = False
if integration_test:
return executive.Executive().run_command(arg_list)
if 'webkit-build-directory' in arg_list[1]:
return mock_webkit_build_directory(arg_list[2:])
return 'Error'
def mock_webkit_build_directory(arg_list):
if arg_list == ['--top-level']:
return '/WebKitBuild'
elif arg_list == ['--configuration', '--debug']:
return '/WebKitBuild/Debug'
elif arg_list == ['--configuration', '--release']:
return '/WebKitBuild/Release'
return 'Error'
class ConfigTest(unittest.TestCase):
def tearDown(self):
config.clear_cached_configuration()
def make_config(self, output='', files={}, exit_code=0, exception=None,
run_command_fn=None):
e = executive_mock.MockExecutive2(output=output, exit_code=exit_code,
exception=exception,
run_command_fn=run_command_fn)
fs = filesystem_mock.MockFileSystem(files)
return config.Config(e, fs)
def assert_configuration(self, contents, expected):
# This tests that a configuration file containing
# _contents_ ends up being interpreted as _expected_.
c = self.make_config('foo', {'foo/Configuration': contents})
self.assertEqual(c.default_configuration(), expected)
def test_build_directory(self):
# --top-level
c = self.make_config(run_command_fn=mock_run_command)
self.assertTrue(c.build_directory(None).endswith('WebKitBuild'))
# Test again to check caching
self.assertTrue(c.build_directory(None).endswith('WebKitBuild'))
# Test other values
self.assertTrue(c.build_directory('Release').endswith('/Release'))
self.assertTrue(c.build_directory('Debug').endswith('/Debug'))
self.assertRaises(KeyError, c.build_directory, 'Unknown')
def test_build_dumprendertree__success(self):
c = self.make_config(exit_code=0)
self.assertTrue(c.build_dumprendertree("Debug"))
self.assertTrue(c.build_dumprendertree("Release"))
self.assertRaises(KeyError, c.build_dumprendertree, "Unknown")
def test_build_dumprendertree__failure(self):
c = self.make_config(exit_code=-1)
# FIXME: Build failures should log errors. However, the message we
# get depends on how we're being called; as a standalone test,
# we'll get the "no handlers found" message. As part of
# test-webkitpy, we get the actual message. Really, we need
# outputcapture to install its own handler.
oc = outputcapture.OutputCapture()
oc.capture_output()
self.assertFalse(c.build_dumprendertree('Debug'))
oc.restore_output()
oc.capture_output()
self.assertFalse(c.build_dumprendertree('Release'))
oc.restore_output()
def test_default_configuration__release(self):
self.assert_configuration('Release', 'Release')
def test_default_configuration__debug(self):
self.assert_configuration('Debug', 'Debug')
def test_default_configuration__deployment(self):
self.assert_configuration('Deployment', 'Release')
def test_default_configuration__development(self):
self.assert_configuration('Development', 'Debug')
def test_default_configuration__notfound(self):
# This tests what happens if the default configuration file
# doesn't exist.
c = self.make_config(output='foo', files={'foo/Configuration': None})
self.assertEqual(c.default_configuration(), "Release")
def test_default_configuration__unknown(self):
# Ignore the warning about an unknown configuration value.
oc = outputcapture.OutputCapture()
oc.capture_output()
self.assert_configuration('Unknown', 'Unknown')
oc.restore_output()
def test_default_configuration__standalone(self):
# FIXME: This test runs a standalone python script to test
# reading the default configuration to work around any possible
# caching / reset bugs. See https://bugs.webkit.org/show_bug?id=49360
# for the motivation. We can remove this test when we remove the
# global configuration cache in config.py.
e = executive.Executive()
fs = filesystem.FileSystem()
c = config.Config(e, fs)
script = c.path_from_webkit_base('Tools', 'Scripts',
'webkitpy', 'layout_tests', 'port', 'config_standalone.py')
# Note: don't use 'Release' here, since that's the normal default.
expected = 'Debug'
args = [sys.executable, script, '--mock', expected]
actual = e.run_command(args).rstrip()
self.assertEqual(actual, expected)
def test_default_configuration__no_perl(self):
# We need perl to run webkit-build-directory to find out where the
# default configuration file is. See what happens if perl isn't
# installed. (We should get the default value, 'Release').
c = self.make_config(exception=OSError)
actual = c.default_configuration()
self.assertEqual(actual, 'Release')
def test_default_configuration__scripterror(self):
# We run webkit-build-directory to find out where the default
# configuration file is. See what happens if that script fails.
# (We should get the default value, 'Release').
c = self.make_config(exception=executive.ScriptError())
actual = c.default_configuration()
self.assertEqual(actual, 'Release')
def test_path_from_webkit_base(self):
# FIXME: We use a real filesystem here. Should this move to a
# mocked one?
c = config.Config(executive.Executive(), filesystem.FileSystem())
self.assertTrue(c.path_from_webkit_base('foo'))
def test_webkit_base_dir(self):
# FIXME: We use a real filesystem here. Should this move to a
# mocked one?
c = config.Config(executive.Executive(), filesystem.FileSystem())
base_dir = c.webkit_base_dir()
self.assertTrue(base_dir)
self.assertNotEqual(base_dir[-1], '/')
orig_cwd = os.getcwd()
if sys.platform == 'win32':
os.chdir(os.environ['USERPROFILE'])
else:
os.chdir(os.environ['HOME'])
c = config.Config(executive.Executive(), filesystem.FileSystem())
try:
base_dir_2 = c.webkit_base_dir()
self.assertEqual(base_dir, base_dir_2)
finally:
os.chdir(orig_cwd)
if __name__ == '__main__':
unittest.main()
| {
"content_hash": "a72a4a94c165a8fcfe06d579c9f5b6a1",
"timestamp": "",
"source": "github",
"line_count": 177,
"max_line_length": 77,
"avg_line_length": 39.728813559322035,
"alnum_prop": 0.6474687144482366,
"repo_name": "Xperia-Nicki/android_platform_sony_nicki",
"id": "8f1e0d4166fa5101db5ddbf50b850735fe7f9f83",
"size": "8559",
"binary": false,
"copies": "15",
"ref": "refs/heads/master",
"path": "external/webkit/Tools/Scripts/webkitpy/layout_tests/port/config_unittest.py",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "89080"
},
{
"name": "Assembly",
"bytes": "212775"
},
{
"name": "Awk",
"bytes": "19252"
},
{
"name": "C",
"bytes": "68667466"
},
{
"name": "C#",
"bytes": "55625"
},
{
"name": "C++",
"bytes": "54670920"
},
{
"name": "CLIPS",
"bytes": "12224"
},
{
"name": "CSS",
"bytes": "283405"
},
{
"name": "D",
"bytes": "1931"
},
{
"name": "Java",
"bytes": "4882"
},
{
"name": "JavaScript",
"bytes": "19597804"
},
{
"name": "Objective-C",
"bytes": "5849156"
},
{
"name": "PHP",
"bytes": "17224"
},
{
"name": "Pascal",
"bytes": "42411"
},
{
"name": "Perl",
"bytes": "1632149"
},
{
"name": "Prolog",
"bytes": "214621"
},
{
"name": "Python",
"bytes": "3493321"
},
{
"name": "R",
"bytes": "290"
},
{
"name": "Ruby",
"bytes": "78743"
},
{
"name": "Scilab",
"bytes": "554"
},
{
"name": "Shell",
"bytes": "265637"
},
{
"name": "TypeScript",
"bytes": "45459"
},
{
"name": "XSLT",
"bytes": "11219"
}
],
"symlink_target": ""
} |
package com.azure.resourcemanager.deploymentmanager.implementation;
import com.azure.resourcemanager.deploymentmanager.fluent.models.OperationsListInner;
import com.azure.resourcemanager.deploymentmanager.models.Operation;
import com.azure.resourcemanager.deploymentmanager.models.OperationsList;
public final class OperationsListImpl implements OperationsList {
private OperationsListInner innerObject;
private final com.azure.resourcemanager.deploymentmanager.DeploymentManager serviceManager;
OperationsListImpl(
OperationsListInner innerObject, com.azure.resourcemanager.deploymentmanager.DeploymentManager serviceManager) {
this.innerObject = innerObject;
this.serviceManager = serviceManager;
}
public Operation value() {
return this.innerModel().value();
}
public OperationsListInner innerModel() {
return this.innerObject;
}
private com.azure.resourcemanager.deploymentmanager.DeploymentManager manager() {
return this.serviceManager;
}
}
| {
"content_hash": "f7614cefcda547b7f7e06f359e955bfb",
"timestamp": "",
"source": "github",
"line_count": 29,
"max_line_length": 120,
"avg_line_length": 35.93103448275862,
"alnum_prop": 0.783109404990403,
"repo_name": "Azure/azure-sdk-for-java",
"id": "2d0afdcc926effca13b35085be3846d11af611a7",
"size": "1199",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "sdk/deploymentmanager/azure-resourcemanager-deploymentmanager/src/main/java/com/azure/resourcemanager/deploymentmanager/implementation/OperationsListImpl.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "8762"
},
{
"name": "Bicep",
"bytes": "15055"
},
{
"name": "CSS",
"bytes": "7676"
},
{
"name": "Dockerfile",
"bytes": "2028"
},
{
"name": "Groovy",
"bytes": "3237482"
},
{
"name": "HTML",
"bytes": "42090"
},
{
"name": "Java",
"bytes": "432409546"
},
{
"name": "JavaScript",
"bytes": "36557"
},
{
"name": "Jupyter Notebook",
"bytes": "95868"
},
{
"name": "PowerShell",
"bytes": "737517"
},
{
"name": "Python",
"bytes": "240542"
},
{
"name": "Scala",
"bytes": "1143898"
},
{
"name": "Shell",
"bytes": "18488"
},
{
"name": "XSLT",
"bytes": "755"
}
],
"symlink_target": ""
} |
package com.jakewharton.utilities;
import com.jakewharton.snakewallpaper.R;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
/**
* A simple Preference which displays an icon next to the text.
*
* @author Jake Wharton
*/
public class IconPreference extends Preference {
/**
* The icon.
*/
private Drawable mIcon;
/**
* Create a new instance of the IconPreference.
*
* @param context Context.
* @param attrs Attributes.
*/
public IconPreference(final Context context, final AttributeSet attrs) {
this(context, attrs, 0);
}
/**
* Create a new instance of the IconPreference.
*
* @param context Context.
* @param attrs Attributes.
* @param defStyle Style.
*/
public IconPreference(final Context context, final AttributeSet attrs, final int defStyle) {
super(context, attrs, defStyle);
this.setLayoutResource(R.layout.icon_preference);
this.mIcon = context.obtainStyledAttributes(attrs, R.styleable.IconPreference, defStyle, 0).getDrawable(R.styleable.IconPreference_icon);
}
@Override
public void onBindView(final View view) {
super.onBindView(view);
final ImageView imageView = (ImageView)view.findViewById(R.id.icon);
if ((imageView != null) && (this.mIcon != null)) {
imageView.setImageDrawable(this.mIcon);
}
}
/**
* Sets the icon for this Preference with a Drawable.
*
* @param icon The icon for this Preference
*/
public void setIcon(final Drawable icon) {
if (((icon == null) && (this.mIcon != null)) || ((icon != null) && (!icon.equals(this.mIcon)))) {
this.mIcon = icon;
this.notifyChanged();
}
}
/**
* Returns the icon of this Preference.
*
* @return The icon.
* @see #setIcon(Drawable)
*/
public Drawable getIcon() {
return this.mIcon;
}
} | {
"content_hash": "8cade6f42ebd01ad561f631b50196430",
"timestamp": "",
"source": "github",
"line_count": 84,
"max_line_length": 145,
"avg_line_length": 25.702380952380953,
"alnum_prop": 0.6225104214914312,
"repo_name": "JakeWharton/SnakeWallpaper",
"id": "3acff177bf3b7a28798c524c215f43a94f1156a5",
"size": "2778",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/jakewharton/utilities/IconPreference.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "93574"
}
],
"symlink_target": ""
} |
.class Landroid/support/v7/preference/CheckBoxPreference$Listener;
.super Ljava/lang/Object;
.source "CheckBoxPreference.java"
# interfaces
.implements Landroid/widget/CompoundButton$OnCheckedChangeListener;
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Landroid/support/v7/preference/CheckBoxPreference;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x2
name = "Listener"
.end annotation
# instance fields
.field final synthetic this$0:Landroid/support/v7/preference/CheckBoxPreference;
# direct methods
.method private constructor <init>(Landroid/support/v7/preference/CheckBoxPreference;)V
.locals 0
iput-object p1, p0, Landroid/support/v7/preference/CheckBoxPreference$Listener;->this$0:Landroid/support/v7/preference/CheckBoxPreference;
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
.method synthetic constructor <init>(Landroid/support/v7/preference/CheckBoxPreference;Landroid/support/v7/preference/CheckBoxPreference$Listener;)V
.locals 0
invoke-direct {p0, p1}, Landroid/support/v7/preference/CheckBoxPreference$Listener;-><init>(Landroid/support/v7/preference/CheckBoxPreference;)V
return-void
.end method
# virtual methods
.method public onCheckedChanged(Landroid/widget/CompoundButton;Z)V
.locals 2
iget-object v0, p0, Landroid/support/v7/preference/CheckBoxPreference$Listener;->this$0:Landroid/support/v7/preference/CheckBoxPreference;
invoke-static {p2}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;
move-result-object v1
invoke-virtual {v0, v1}, Landroid/support/v7/preference/CheckBoxPreference;->callChangeListener(Ljava/lang/Object;)Z
move-result v0
if-nez v0, :cond_0
xor-int/lit8 v0, p2, 0x1
invoke-virtual {p1, v0}, Landroid/widget/CompoundButton;->setChecked(Z)V
return-void
:cond_0
iget-object v0, p0, Landroid/support/v7/preference/CheckBoxPreference$Listener;->this$0:Landroid/support/v7/preference/CheckBoxPreference;
invoke-virtual {v0, p2}, Landroid/support/v7/preference/CheckBoxPreference;->setChecked(Z)V
return-void
.end method
| {
"content_hash": "5642016daf154b78e1612034ffdf626b",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 148,
"avg_line_length": 30.319444444444443,
"alnum_prop": 0.7732478240952817,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "115eaed2e2fb2e8c51ccf234db16e9f2356bbeb4",
"size": "2183",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "SystemUI/smali/android/support/v7/preference/CheckBoxPreference$Listener.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
import os
import six
SCHEMA_PATH = os.path.join(os.path.dirname(__file__), 'schema')
def parse_int(text, fallback=None):
""" Try to extract an integer from a string, return the fallback if that's
not possible. """
try:
if isinstance(text, six.integer_types):
return text
elif isinstance(text, six.string_types):
return int(text)
else:
return fallback
except ValueError:
return fallback
| {
"content_hash": "4f1792a669cf970121d3b80c6e6f8fe3",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 78,
"avg_line_length": 26.27777777777778,
"alnum_prop": 0.6152219873150105,
"repo_name": "openspending/babbage",
"id": "7fc51a28350bdcd67a4bec3e1aee66f5eaf00d59",
"size": "473",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "babbage/util.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Makefile",
"bytes": "243"
},
{
"name": "Python",
"bytes": "79629"
}
],
"symlink_target": ""
} |
jest.unmock('../../../ducks/ui/flow')
jest.unmock('../../../ducks/flows')
jest.unmock('lodash')
import _ from 'lodash'
import reducer, {
startEdit,
setContentViewDescription,
setShowFullContent,
setContent,
updateEdit
} from '../../../ducks/ui/flow'
import { select, updateFlow } from '../../../ducks/flows'
describe('flow reducer', () => {
it('should change to edit mode', () => {
let testFlow = {flow : 'foo'}
const newState = reducer(undefined, startEdit({ flow: 'foo' }))
expect(newState.contentView).toEqual('Edit')
expect(newState.modifiedFlow).toEqual(testFlow)
expect(newState.showFullContent).toEqual(true)
})
it('should set the view description', () => {
expect(reducer(undefined, setContentViewDescription('description')).viewDescription)
.toEqual('description')
})
it('should set show full content', () => {
expect(reducer({showFullContent: false}, setShowFullContent()).showFullContent)
.toBeTruthy()
})
it('should set showFullContent to true', () => {
let maxLines = 10
let content = _.range(maxLines)
const newState = reducer({maxContentLines: maxLines}, setContent(content) )
expect(newState.showFullContent).toBeTruthy()
expect(newState.content).toEqual(content)
})
it('should set showFullContent to false', () => {
let maxLines = 5
let content = _.range(maxLines+1);
const newState = reducer({maxContentLines: maxLines}, setContent(_.range(maxLines+1)))
expect(newState.showFullContent).toBeFalsy()
expect(newState.content).toEqual(content)
})
it('should not change the contentview mode', () => {
expect(reducer({contentView: 'foo'}, select(1)).contentView).toEqual('foo')
})
it('should change the contentview mode to auto after editing when a new flow will be selected', () => {
expect(reducer({contentView: 'foo', modifiedFlow : 'test_flow'}, select(1)).contentView).toEqual('Auto')
})
it('should set update and merge the modifiedflow with the update values', () => {
let modifiedFlow = {headers: []}
let updateValues = {content: 'bar'}
let result = {headers: [], content: 'bar'}
expect(reducer({modifiedFlow}, updateEdit(updateValues)).modifiedFlow).toEqual(result)
})
it('should not change the state when a flow is updated which is not selected', () => {
let modifiedFlow = {id: 1}
let updatedFlow = {id: 0}
expect(reducer({modifiedFlow}, updateFlow(updatedFlow)).modifiedFlow).toEqual(modifiedFlow)
})
it('should stop editing when the selected flow is updated', () => {
let modifiedFlow = {id: 1}
let updatedFlow = {id: 1}
expect(reducer({modifiedFlow}, updateFlow(updatedFlow)).modifiedFlow).toBeFalsy()
})
})
| {
"content_hash": "524c69354a3b51a154434941bf198d1b",
"timestamp": "",
"source": "github",
"line_count": 76,
"max_line_length": 112,
"avg_line_length": 39.44736842105263,
"alnum_prop": 0.6114076050700467,
"repo_name": "mosajjal/mitmproxy",
"id": "f838fbaa5be7c7ba7c7223018d14caab2b71d384",
"size": "2998",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "web/src/js/__tests__/ducks/ui/flowSpec.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17457"
},
{
"name": "HTML",
"bytes": "4270"
},
{
"name": "JavaScript",
"bytes": "149498"
},
{
"name": "PowerShell",
"bytes": "494"
},
{
"name": "Python",
"bytes": "1491468"
},
{
"name": "Shell",
"bytes": "3660"
}
],
"symlink_target": ""
} |
const url = require('url');
const debug = require('@tryghost/debug')('api:shared:headers');
const Promise = require('bluebird');
const INVALIDATE_ALL = '/*';
const cacheInvalidate = (result, options = {}) => {
let value = options.value;
return {
'X-Cache-Invalidate': value || INVALIDATE_ALL
};
};
const disposition = {
/**
* @description Generate CSV header.
*
* @param {Object} result - API response
* @param {Object} options
* @return {Object}
*/
csv(result, options = {}) {
let value = options.value;
if (typeof options.value === 'function') {
value = options.value();
}
return {
'Content-Disposition': `Attachment; filename="${value}"`,
'Content-Type': 'text/csv'
};
},
/**
* @description Generate JSON header.
*
* @param {Object} result - API response
* @param {Object} options
* @return {Object}
*/
json(result, options = {}) {
return {
'Content-Disposition': `Attachment; filename="${options.value}"`,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(JSON.stringify(result))
};
},
/**
* @description Generate YAML header.
*
* @param {Object} result - API response
* @param {Object} options
* @return {Object}
*/
yaml(result, options = {}) {
return {
'Content-Disposition': `Attachment; filename="${options.value}"`,
'Content-Type': 'application/yaml',
'Content-Length': Buffer.byteLength(JSON.stringify(result))
};
},
/**
* @description Content Disposition Header
*
* Create a header that invokes the 'Save As' dialog in the browser when exporting the database to file. The 'filename'
* parameter is governed by [RFC6266](http://tools.ietf.org/html/rfc6266#section-4.3).
*
* For encoding whitespace and non-ISO-8859-1 characters, you MUST use the "filename*=" attribute, NOT "filename=".
* Ideally, both. Examples: http://tools.ietf.org/html/rfc6266#section-5
*
* We'll use ISO-8859-1 characters here to keep it simple.
*
* @see http://tools.ietf.org/html/rfc598
*/
file(result, options = {}) {
return Promise.resolve()
.then(() => {
let value = options.value;
if (typeof options.value === 'function') {
value = options.value();
}
return value;
})
.then((filename) => {
return {
'Content-Disposition': `Attachment; filename="${filename}"`
};
});
}
};
module.exports = {
/**
* @description Get header based on ctrl configuration.
*
* @param {Object} result - API response
* @param {Object} apiConfigHeaders
* @param {Object} frame
* @return {Promise}
*/
async get(result, apiConfigHeaders = {}, frame) {
let headers = {};
if (apiConfigHeaders.disposition) {
const dispositionHeader = await disposition[apiConfigHeaders.disposition.type](result, apiConfigHeaders.disposition);
if (dispositionHeader) {
Object.assign(headers, dispositionHeader);
}
}
if (apiConfigHeaders.cacheInvalidate) {
const cacheInvalidationHeader = cacheInvalidate(result, apiConfigHeaders.cacheInvalidate);
if (cacheInvalidationHeader) {
Object.assign(headers, cacheInvalidationHeader);
}
}
const locationHeaderDisabled = apiConfigHeaders && apiConfigHeaders.location === false;
const hasFrameData = frame
&& (frame.method === 'add')
&& result[frame.docName]
&& result[frame.docName][0]
&& result[frame.docName][0].id;
if (!locationHeaderDisabled && hasFrameData) {
const protocol = (frame.original.url.secure === false) ? 'http://' : 'https://';
const resourceId = result[frame.docName][0].id;
let locationURL = url.resolve(`${protocol}${frame.original.url.host}`,frame.original.url.pathname);
if (!locationURL.endsWith('/')) {
locationURL += '/';
}
locationURL += `${resourceId}/`;
const locationHeader = {
Location: locationURL
};
Object.assign(headers, locationHeader);
}
debug(headers);
return headers;
}
};
| {
"content_hash": "4da6611a60c269a9a3628193d730f175",
"timestamp": "",
"source": "github",
"line_count": 152,
"max_line_length": 129,
"avg_line_length": 30.611842105263158,
"alnum_prop": 0.5501826778422523,
"repo_name": "ErisDS/Ghost",
"id": "7147b2a1fed80714112ecd28bab148029b040c10",
"size": "4653",
"binary": false,
"copies": "3",
"ref": "refs/heads/main",
"path": "core/server/api/shared/headers.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "229990"
},
{
"name": "HTML",
"bytes": "150894"
},
{
"name": "Handlebars",
"bytes": "111349"
},
{
"name": "JavaScript",
"bytes": "5648821"
},
{
"name": "Shell",
"bytes": "1116"
},
{
"name": "XSLT",
"bytes": "6522"
}
],
"symlink_target": ""
} |
/******************************************************************************
slTabbedContent directive
written by stefan krueger (s-light),
mail@s-light.eu, http://s-light.eu, https://github.com/s-light/
havely based on
https://docs.angularjs.org/guide/directive#creating-directives-that-communicate
changelog / history
see git commits
TO DO:
~ enjoy your life :-)
******************************************************************************/
/******************************************************************************
Copyright 2015 Stefan Krueger
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
The MIT License (MIT)
Copyright (c) 2015 Stefan Krüger
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
******************************************************************************/
var slTabbedContent = angular.module('slTabbedContent', [
// 'xx',
]);
// get current script path
// http://stackoverflow.com/a/21103831/574981
// var scripts = document.getElementsByTagName("script");
// var myDTl_scriptPath = scripts[scripts.length-1].src;
var slTabbedContent_scriptElement = document.querySelector(
"[src*=slTabbedContent]"
);
var slTabbedContent_scriptPath = slTabbedContent_scriptElement.getAttribute('src');
var slTabbedContent_templateURL = slTabbedContent_scriptPath.replace('.js', '.html');
var slTabbedContent_templateURL_Pane = slTabbedContent_templateURL.replace('.html', '_Pane.html');
slTabbedContent.directive('slTabbedContent', [
// 'slTabbedContentController',
'$filter',
function(
// slTabbedContentController,
$filter
) { return {
restrict: 'E',
transclude: true,
scope: {
initialPane: '@',
},
// template: '<ul class=""></ul>',
// templateUrl: 'js/xxx.html',
// templateUrl: slTabbedContent_templateURL,
templateUrl: function() {
// only for development!!!!!
// this disables the caching of the template file..
return slTabbedContent_templateURL + '?' + new Date();
},
controller:[
'$scope',
// '$filter',
function($scope) {
// console.log("slTabbedContent");
// console.log("$scope", $scope);
var panes = $scope.panes = [];
/******************************************/
/** functions **/
$scope.test = function(event) {
// console.group("test");
// console.log("event", event);
// console.groupEnd();
};
$scope.switchToPane = function(pane) {
// console.group("switchToPane");
// console.log("pane", pane);
// deactivate all but given
angular.forEach(panes, function(paneCurrent, paneIndex){
if (paneCurrent == pane) {
paneCurrent.active = true;
} else {
paneCurrent.active = false;
}
});
// console.groupEnd();
};
this.addPane = function(pane) {
// console.group("addPane");
// console.log("pane", pane);
// add new pane to list
panes.push(pane);
// show first added pane
if (pane.title == $scope.initialPane) {
$scope.switchToPane(pane);
}
// console.log("panes", panes);
// console.groupEnd();
};
}
]
};}
]);
slTabbedContent.directive('slPane', [
'$filter',
// 'slTabbedContent',
function(
$filter
// slTabbedContent
) { return {
restrict: 'E',
require: '^slTabbedContent',
transclude: true,
scope: {
title: '@',
},
// template: '<ul class=""></ul>',
// templateUrl: 'something/xxxx.html',
// templateUrl: slTabbedContent_templateURL_Pane,
templateUrl: function() {
// only for development!!!!!
// this disables the caching of the template file..
// console.log("slTabbedContent_templateURL_Pane:", slTabbedContent_templateURL_Pane);
return slTabbedContent_templateURL_Pane + '?' + new Date();
},
link: function(scope, element, attr, tabedCtrl) {
// console.log("slPane");
// console.log("scope", scope);
// console.log("element", element);
// console.log("attrs", attrs);
// console.log("tabedCtrl", tabedCtrl);
/******************************************/
/** functions **/
// add me to my parent :-)
tabedCtrl.addPane(scope);
scope.test = function(event) {
// console.group("test", event);
// console.log("testinfo");
// console.groupEnd();
};
}
};}
]);
| {
"content_hash": "20f39d07e8a1861d6c8594e4975454b6",
"timestamp": "",
"source": "github",
"line_count": 198,
"max_line_length": 98,
"avg_line_length": 32.54040404040404,
"alnum_prop": 0.5618500698432407,
"repo_name": "s-light/OLA_Cherrypy_example",
"id": "104abba789ad794a6946712e568113703f367cac",
"size": "6444",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "server/static/js/slightDirectives/TabbedContent/slTabbedContent.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "23217"
},
{
"name": "HTML",
"bytes": "24218"
},
{
"name": "JavaScript",
"bytes": "19838"
},
{
"name": "Python",
"bytes": "19312"
}
],
"symlink_target": ""
} |
package io.tiler.internal.queries.clauses;
import io.tiler.core.json.JsonArrayIterable;
import io.tiler.core.json.JsonArrayUtils;
import io.tiler.internal.queries.expressions.fields.FieldExpression;
import org.vertx.java.core.json.JsonArray;
import org.vertx.java.core.json.JsonObject;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class GroupClause {
private final List<FieldExpression> fieldExpressions;
public GroupClause(List<FieldExpression> fieldExpressions) {
this.fieldExpressions = Collections.unmodifiableList(fieldExpressions);
}
public List<FieldExpression> fieldExpressions() {
return fieldExpressions;
}
public JsonArray applyToMetrics(JsonArray metrics) {
JsonArray groups = applyToPoints(metrics);
JsonArray transformedMetrics = new JsonArray();
for (JsonObject group : new JsonArrayIterable<JsonObject>(groups)) {
transformedMetrics.addObject(new JsonObject()
.mergeIn(group)
.putArray("points", group.getArray("points")));
}
return transformedMetrics;
}
private JsonArray applyToPoints(JsonArray metrics) {
HashMap<ArrayList<Object>, JsonObject> groups = new HashMap<>();
for (JsonObject metric : new JsonArrayIterable<JsonObject>(metrics)) {
for (JsonObject point : new JsonArrayIterable<JsonObject>(metric.getArray("points"))) {
ArrayList<Object> groupKey = new ArrayList<>();
for (FieldExpression fieldExpression : fieldExpressions) {
String fieldName = fieldExpression.fieldName();
groupKey.add(fieldName);
groupKey.add(point.getValue(fieldName));
}
JsonObject group = groups.get(groupKey);
JsonArray groupPoints;
if (group == null) {
groupPoints = new JsonArray();
group = new JsonObject();
for (FieldExpression fieldExpression : fieldExpressions) {
String fieldName = fieldExpression.fieldName();
group.putValue(fieldName, point.getValue(fieldName));
}
group.putArray("points", groupPoints);
groups.put(groupKey, group);
} else {
groupPoints = group.getArray("points");
}
groupPoints.addObject(point);
}
}
return JsonArrayUtils.convertToJsonArray(groups.values());
}
}
| {
"content_hash": "aba7e9733d71d30cb75679c55da145ee",
"timestamp": "",
"source": "github",
"line_count": 75,
"max_line_length": 93,
"avg_line_length": 31.6,
"alnum_prop": 0.6945147679324895,
"repo_name": "tiler-project/tiler",
"id": "b8b069f1ea1e5e977d2b68648796caf64447f073",
"size": "2370",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/io/tiler/internal/queries/clauses/GroupClause.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "2772"
},
{
"name": "Groovy",
"bytes": "87105"
},
{
"name": "Java",
"bytes": "118668"
}
],
"symlink_target": ""
} |
package com.morgan.client.page;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
@RunWith(Suite.class)
@SuiteClasses({ PagePresenterHelperTest.class })
public class AllPageTests {
}
| {
"content_hash": "714a2b9900ac21b81ac24e0b3c0109ea",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 48,
"avg_line_length": 22.363636363636363,
"alnum_prop": 0.8008130081300813,
"repo_name": "mmm2a/game-center",
"id": "607da98be6ae1761e95f72023eea547975c20984",
"size": "246",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/com/morgan/client/page/AllPageTests.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "67"
},
{
"name": "CSS",
"bytes": "24714"
},
{
"name": "HTML",
"bytes": "593642"
},
{
"name": "Java",
"bytes": "733815"
},
{
"name": "JavaScript",
"bytes": "1724557"
},
{
"name": "Shell",
"bytes": "626"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ Copyright (c) 2015. Hoomi, Inc. All Rights Reserved
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="co.hoomi" >
<application
android:allowBackup="true">
</application>
</manifest>
| {
"content_hash": "3ea8a91f1bd29ce152074e862dc041fb",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 68,
"avg_line_length": 22.076923076923077,
"alnum_prop": 0.6376306620209059,
"repo_name": "GetHoomi/hoomi-sdk-android",
"id": "45053a96048670e23f71f7ac521767f0fc51c3a4",
"size": "287",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "hoomi/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "59149"
}
],
"symlink_target": ""
} |
{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE ConstraintKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GADTs #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeInType #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_HADDOCK not-home #-}
module Generic.Random.DerivingVia
( GenericArbitrary (..),
GenericArbitraryU (..),
GenericArbitrarySingle (..),
GenericArbitraryRec (..),
GenericArbitraryG (..),
GenericArbitraryUG (..),
GenericArbitrarySingleG (..),
GenericArbitraryRecG (..),
GenericArbitraryWith (..),
AndShrinking (..),
TypeLevelGenList (..),
TypeLevelOpts (..),
)
where
import Data.Coerce (Coercible, coerce)
import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import GHC.Generics (Generic(..))
import GHC.TypeLits (KnownNat, natVal)
import Generic.Random.Internal.Generic
import Test.QuickCheck (Arbitrary (..), Gen, genericShrink)
import Test.QuickCheck.Arbitrary (RecursivelyShrink, GSubterms)
-- * Newtypes for DerivingVia
-- | Pick a constructor with a given distribution, and fill its fields
-- with recursive calls to 'Test.QuickCheck.arbitrary'.
--
-- === Example
--
-- > data X = ...
-- > deriving Arbitrary via (GenericArbitrary '[2, 3, 5] X)
--
-- Picks the first constructor with probability @2/10@,
-- the second with probability @3/10@, the third with probability @5/10@.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitrary'.
--
-- @since 1.5.0.0
newtype GenericArbitrary weights a = GenericArbitrary {unGenericArbitrary :: a} deriving (Eq, Show)
instance
( GArbitrary UnsizedOpts a,
TypeLevelWeights' weights a
) =>
Arbitrary (GenericArbitrary weights a)
where
arbitrary = GenericArbitrary <$> genericArbitrary (typeLevelWeights @weights)
-- | Pick every constructor with equal probability.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryU'.
--
-- @since 1.5.0.0
newtype GenericArbitraryU a = GenericArbitraryU {unGenericArbitraryU :: a} deriving (Eq, Show)
instance
( GArbitrary UnsizedOpts a,
GUniformWeight a
) =>
Arbitrary (GenericArbitraryU a)
where
arbitrary = GenericArbitraryU <$> genericArbitraryU
-- | @arbitrary@ for types with one constructor.
-- Equivalent to 'GenericArbitraryU', with a stricter type.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitrarySingle'.
--
-- @since 1.5.0.0
newtype GenericArbitrarySingle a = GenericArbitrarySingle {unGenericArbitrarySingle :: a} deriving (Eq, Show)
instance
( GArbitrary UnsizedOpts a,
Weights_ (Rep a) ~ L c0
) =>
Arbitrary (GenericArbitrarySingle a)
where
arbitrary = GenericArbitrarySingle <$> genericArbitrarySingle
-- | Decrease size at every recursive call, but don't do anything different
-- at size 0.
--
-- > data X = ...
-- > deriving Arbitrary via (GenericArbitraryRec '[2, 3, 5] X)
--
-- N.B.: This replaces the generator for fields of type @[t]@ with
-- @'listOf'' arbitrary@ instead of @'Test.QuickCheck.listOf' arbitrary@ (i.e., @arbitrary@ for
-- lists).
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryRec'.
--
-- @since 1.5.0.0
newtype GenericArbitraryRec weights a = GenericArbitraryRec {unGenericArbitraryRec :: a} deriving (Eq, Show)
instance
( GArbitrary SizedOptsDef a,
TypeLevelWeights' weights a
) =>
Arbitrary (GenericArbitraryRec weights a)
where
arbitrary = GenericArbitraryRec <$> genericArbitraryRec (typeLevelWeights @weights)
-- | 'GenericArbitrary' with explicit generators.
--
-- === Example
--
-- > data X = ...
-- > deriving Arbitrary via (GenericArbitraryG CustomGens '[2, 3, 5] X)
--
-- where, for example, custom generators to override 'String' and 'Int' fields
-- might look as follows:
--
-- @
-- type CustomGens = CustomString ':+' CustomInt
-- @
--
-- === Note on multiple matches
--
-- Multiple generators may match a given field: the first will be chosen.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryG'.
--
-- @since 1.5.0.0
newtype GenericArbitraryG genList weights a = GenericArbitraryG {unGenericArbitraryG :: a} deriving (Eq, Show)
instance
( GArbitrary (SetGens genList UnsizedOpts) a,
GUniformWeight a,
TypeLevelWeights' weights a,
TypeLevelGenList genList',
genList ~ TypeLevelGenList' genList'
) =>
Arbitrary (GenericArbitraryG genList' weights a)
where
arbitrary = GenericArbitraryG <$> genericArbitraryG (toGenList $ Proxy @genList') (typeLevelWeights @weights)
-- | 'GenericArbitraryU' with explicit generators.
-- See also 'GenericArbitraryG'.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryUG'.
--
-- @since 1.5.0.0
newtype GenericArbitraryUG genList a = GenericArbitraryUG {unGenericArbitraryUG :: a} deriving (Eq, Show)
instance
( GArbitrary (SetGens genList UnsizedOpts) a,
GUniformWeight a,
TypeLevelGenList genList',
genList ~ TypeLevelGenList' genList'
) =>
Arbitrary (GenericArbitraryUG genList' a)
where
arbitrary = GenericArbitraryUG <$> genericArbitraryUG (toGenList $ Proxy @genList')
-- | 'genericArbitrarySingle' with explicit generators.
-- See also 'GenericArbitraryG'.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitrarySingleG'.
--
-- @since 1.5.0.0
newtype GenericArbitrarySingleG genList a = GenericArbitrarySingleG {unGenericArbitrarySingleG :: a} deriving (Eq, Show)
instance
( GArbitrary (SetGens genList UnsizedOpts) a,
Weights_ (Rep a) ~ L c0,
TypeLevelGenList genList',
genList ~ TypeLevelGenList' genList'
) =>
Arbitrary (GenericArbitrarySingleG genList' a)
where
arbitrary = GenericArbitrarySingleG <$> genericArbitrarySingleG (toGenList $ Proxy @genList')
-- | 'genericArbitraryRec' with explicit generators.
-- See also 'genericArbitraryG'.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryRecG'.
--
-- @since 1.5.0.0
newtype GenericArbitraryRecG genList weights a = GenericArbitraryRecG {unGenericArbitraryRecG :: a} deriving (Eq, Show)
instance
( GArbitrary (SetGens genList SizedOpts) a,
TypeLevelWeights' weights a,
TypeLevelGenList genList',
genList ~ TypeLevelGenList' genList'
) =>
Arbitrary (GenericArbitraryRecG genList' weights a)
where
arbitrary = GenericArbitraryRecG <$> genericArbitraryRecG (toGenList $ Proxy @genList') (typeLevelWeights @weights)
-- | General generic generator with custom options.
--
-- This newtype does no shrinking. To add generic shrinking, use 'AndShrinking'.
--
-- Uses 'genericArbitraryWith'.
--
-- @since 1.5.0.0
newtype GenericArbitraryWith opts weights a = GenericArbitraryWith {unGenericArbitraryWith :: a} deriving (Eq, Show)
instance
( GArbitrary opts a,
TypeLevelWeights' weights a,
TypeLevelOpts opts',
opts ~ TypeLevelOpts' opts'
) =>
Arbitrary (GenericArbitraryWith opts' weights a)
where
arbitrary = GenericArbitraryWith <$> genericArbitraryWith (toOpts $ Proxy @opts') (typeLevelWeights @weights)
-- | Add generic shrinking to a newtype wrapper for 'Arbitrary', using 'genericShrink'.
--
-- @
-- data X = ...
-- deriving Arbitrary via ('GenericArbitrary' '[1,2,3] `'AndShrinking'` X)
-- @
--
-- Equivalent to:
--
-- @
-- instance Arbitrary X where
-- arbitrary = 'genericArbitrary' (1 % 2 % 3 % ())
-- shrink = 'Test.QuickCheck.genericShrink'
-- @
--
-- @since 1.5.0.0
newtype AndShrinking f a = AndShrinking a deriving (Eq, Show)
instance
( Arbitrary (f a), Coercible (f a) a, Generic a, RecursivelyShrink (Rep a), GSubterms (Rep a) a
) => Arbitrary (AndShrinking f a) where
arbitrary = coerce (arbitrary :: Gen (f a))
shrink = coerce (genericShrink :: a -> [a])
-- * Internal
-- |
-- @since 1.5.0.0
type TypeLevelWeights' weights a = TypeLevelWeights weights (Weights_ (Rep a))
typeLevelWeights ::
forall weights a.
TypeLevelWeights weights (Weights_ (Rep a)) =>
Weights a
typeLevelWeights =
let (w, n) = typeLevelWeightsBuilder @weights
in Weights w n
-- |
-- @since 1.5.0.0
class TypeLevelWeights weights a where
typeLevelWeightsBuilder :: (a, Int)
instance
( KnownNat weight,
TypeLevelWeights weights a
) =>
TypeLevelWeights (weight ': weights) (L x :| a)
where
typeLevelWeightsBuilder =
let (a, m) = (L, fromIntegral $ natVal $ Proxy @weight)
(b, n) = typeLevelWeightsBuilder @weights @a
in (N a m b, m + n)
instance
( KnownNat weight
) =>
TypeLevelWeights (weight ': '[]) (L x)
where
typeLevelWeightsBuilder = (L, fromIntegral $ natVal $ Proxy @weight)
instance
TypeLevelWeights (w ': ws) (t :| (u :| v)) =>
TypeLevelWeights (w ': ws) ((t :| u) :| v)
where
typeLevelWeightsBuilder =
let (N t nt (N u nu v), m) = typeLevelWeightsBuilder @(w ': ws) @(t :| (u :| v))
in (N (N t nt u) (nt + nu) v, m)
instance TypeLevelWeights '[] () where
typeLevelWeightsBuilder = ((), 1)
-- |
-- @since 1.5.0.0
class TypeLevelGenList a where
type TypeLevelGenList' a :: Type
toGenList :: Proxy a -> TypeLevelGenList' a
instance Arbitrary a => TypeLevelGenList (Gen a) where
type TypeLevelGenList' (Gen a) = Gen a
toGenList _ = arbitrary
instance (TypeLevelGenList a, TypeLevelGenList b) => TypeLevelGenList (a :+ b) where
type TypeLevelGenList' (a :+ b) = TypeLevelGenList' a :+ TypeLevelGenList' b
toGenList _ = toGenList (Proxy @a) :+ toGenList (Proxy @b)
-- |
-- @since 1.5.0.0
class TypeLevelOpts a where
type TypeLevelOpts' a :: Type
toOpts :: Proxy a -> TypeLevelOpts' a
| {
"content_hash": "16ef71b9239da4e1b0ab4e720084b0fd",
"timestamp": "",
"source": "github",
"line_count": 334,
"max_line_length": 120,
"avg_line_length": 29.889221556886227,
"alnum_prop": 0.7024942402083542,
"repo_name": "Lysxia/generic-random",
"id": "8e5843f0f554443c26b6f1af0869ab14804a51c2",
"size": "9983",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Generic/Random/DerivingVia.hs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Haskell",
"bytes": "70606"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<billStatus>
<bill>
<calendarNumbers />
<updateDate>2017-09-12T20:30:14Z</updateDate>
<cboCostEstimates />
<policyArea>
<name>Health</name>
</policyArea>
<relatedBills />
<billType>HR</billType>
<congress>115</congress>
<laws />
<createDate>2017-04-13T03:11:49Z</createDate>
<originChamber>House</originChamber>
<cosponsors>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>Thomas</firstName>
<bioguideId>S001201</bioguideId>
<middleName>R.</middleName>
<fullName>Rep. Suozzi, Thomas R. [D-NY-3]</fullName>
<identifiers>
<bioguideId>S001201</bioguideId>
<lisID>2341</lisID>
<gpoId />
</identifiers>
<lastName>Suozzi</lastName>
<district>3</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>Paul</firstName>
<bioguideId>T000469</bioguideId>
<middleName />
<fullName>Rep. Tonko, Paul [D-NY-20]</fullName>
<identifiers>
<bioguideId>T000469</bioguideId>
<lisID>1942</lisID>
<gpoId>8082</gpoId>
</identifiers>
<lastName>Tonko</lastName>
<district>20</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>Sean</firstName>
<bioguideId>M001185</bioguideId>
<middleName>Patrick</middleName>
<fullName>Rep. Maloney, Sean Patrick [D-NY-18]</fullName>
<identifiers>
<gpoId />
<bioguideId>M001185</bioguideId>
<lisID>2150</lisID>
</identifiers>
<lastName>Maloney</lastName>
<district>18</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>CAROLYN</firstName>
<bioguideId>M000087</bioguideId>
<middleName>B.</middleName>
<fullName>Rep. Maloney, Carolyn B. [D-NY-12]</fullName>
<identifiers>
<bioguideId>M000087</bioguideId>
<lisID>729</lisID>
<gpoId>8075</gpoId>
</identifiers>
<lastName>MALONEY</lastName>
<district>12</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>Grace</firstName>
<bioguideId>M001188</bioguideId>
<middleName />
<fullName>Rep. Meng, Grace [D-NY-6]</fullName>
<identifiers>
<bioguideId>M001188</bioguideId>
<lisID>2148</lisID>
<gpoId />
</identifiers>
<lastName>Meng</lastName>
<district>6</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>JOSE</firstName>
<bioguideId>S000248</bioguideId>
<middleName>E.</middleName>
<fullName>Rep. Serrano, Jose E. [D-NY-15]</fullName>
<identifiers>
<lisID>1042</lisID>
<bioguideId>S000248</bioguideId>
<gpoId>8077</gpoId>
</identifiers>
<lastName>SERRANO</lastName>
<district>15</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>JOSEPH</firstName>
<bioguideId>C001038</bioguideId>
<middleName />
<fullName>Rep. Crowley, Joseph [D-NY-14]</fullName>
<identifiers>
<lisID>1604</lisID>
<bioguideId>C001038</bioguideId>
<gpoId>8068</gpoId>
</identifiers>
<lastName>CROWLEY</lastName>
<district>14</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
<item>
<sponsorshipWithdrawnDate />
<sponsorshipDate>2017-04-12</sponsorshipDate>
<firstName>NITA</firstName>
<bioguideId>L000480</bioguideId>
<middleName>M.</middleName>
<fullName>Rep. Lowey, Nita M. [D-NY-17]</fullName>
<identifiers>
<bioguideId>L000480</bioguideId>
<lisID>709</lisID>
<gpoId>8079</gpoId>
</identifiers>
<lastName>LOWEY</lastName>
<district>17</district>
<state>NY</state>
<isOriginalCosponsor>True</isOriginalCosponsor>
<party>D</party>
</item>
</cosponsors>
<committees>
<billCommittees>
<item>
<type>Standing</type>
<activities>
<item>
<name>Referred to</name>
<date>2017-04-12T15:00:28Z</date>
</item>
</activities>
<name>Energy and Commerce Committee</name>
<systemCode>hsif00</systemCode>
<subcommittees>
<item>
<activities>
<item>
<name>Referred to</name>
<date>2017-04-14T15:07:17Z</date>
</item>
</activities>
<name>Health Subcommittee</name>
<systemCode>hsif14</systemCode>
</item>
</subcommittees>
<chamber>House</chamber>
</item>
</billCommittees>
</committees>
<recordedVotes />
<notes />
<latestAction>
<actionDate>2017-04-14</actionDate>
<text>Referred to the Subcommittee on Health.</text>
<links />
</latestAction>
<constitutionalAuthorityStatementText><![CDATA[<pre>From the Congressional Record Online through the Government Publishing Office [<a href='http://www.gpo.gov'>www.gpo.gov</a>]By Mr. ENGEL:H.R. 2088.Congress has the power to enact this legislation pursuantto the following:Article 1, Section 1 of the Constitution.[Page H2802]</pre>]]></constitutionalAuthorityStatementText>
<actions>
<item>
<actionDate>2017-04-14</actionDate>
<committee>
<name>Health Subcommittee</name>
<systemCode>hsif14</systemCode>
</committee>
<links />
<sourceSystem>
<code>1</code>
<name>House committee actions</name>
</sourceSystem>
<text>Referred to the Subcommittee on Health.</text>
<type>Committee</type>
</item>
<item>
<text>Referred to the House Committee on Energy and Commerce.</text>
<sourceSystem>
<code>2</code>
<name>House floor actions</name>
</sourceSystem>
<links />
<actionCode>H11100</actionCode>
<committee>
<name>Energy and Commerce Committee</name>
<systemCode>hsif00</systemCode>
</committee>
<type>IntroReferral</type>
<actionDate>2017-04-12</actionDate>
</item>
<item>
<text>Introduced in House</text>
<sourceSystem>
<code>9</code>
<name>Library of Congress</name>
</sourceSystem>
<links />
<actionCode>Intro-H</actionCode>
<committee />
<type>IntroReferral</type>
<actionDate>2017-04-12</actionDate>
</item>
<item>
<text>Introduced in House</text>
<sourceSystem>
<code>9</code>
<name>Library of Congress</name>
</sourceSystem>
<links />
<actionCode>1000</actionCode>
<committee />
<type>IntroReferral</type>
<actionDate>2017-04-12</actionDate>
</item>
<actionTypeCounts>
<billReferrals>1</billReferrals>
<introducedInTheHouse>1</introducedInTheHouse>
<introducedInHouse>1</introducedInHouse>
<placeholderTextForH>1</placeholderTextForH>
</actionTypeCounts>
<actionByCounts>
<houseOfRepresentatives>4</houseOfRepresentatives>
</actionByCounts>
</actions>
<titles>
<item>
<title>Empire State Equity Act</title>
<parentTitleType />
<chamberName />
<chamberCode />
<titleType>(Extracted from GPO) Short Titles as Introduced</titleType>
</item>
<item>
<title>Empire State Equity Act</title>
<parentTitleType />
<chamberName />
<chamberCode />
<titleType>Short Titles as Introduced</titleType>
</item>
<item>
<title>To amend title XIX of the Social Security Act to increase certain Federal amounts payable under Medicaid for certain States.</title>
<parentTitleType />
<chamberName />
<chamberCode />
<titleType>Official Title as Introduced</titleType>
</item>
<item>
<title>Empire State Equity Act</title>
<parentTitleType />
<chamberName />
<chamberCode />
<titleType>Display Title</titleType>
</item>
</titles>
<version>1.0.0</version>
<subjects>
<billSubjects>
<legislativeSubjects>
<item>
<name>Health care coverage and access</name>
</item>
<item>
<name>Hospital care</name>
</item>
<item>
<name>Medicaid</name>
</item>
<item>
<name>Property tax</name>
</item>
<item>
<name>State and local finance</name>
</item>
<item>
<name>State and local taxation</name>
</item>
</legislativeSubjects>
<policyArea>
<name>Health</name>
</policyArea>
</billSubjects>
</subjects>
<introducedDate>2017-04-12</introducedDate>
<sponsors>
<item>
<bioguideId>E000179</bioguideId>
<lastName>ENGEL</lastName>
<byRequestType />
<state>NY</state>
<identifiers>
<lisID>344</lisID>
<bioguideId>E000179</bioguideId>
<gpoId>8078</gpoId>
</identifiers>
<district>16</district>
<firstName>ELIOT</firstName>
<middleName>L.</middleName>
<party>D</party>
<fullName>Rep. Engel, Eliot L. [D-NY-16]</fullName>
</item>
</sponsors>
<summaries>
<billSummaries />
</summaries>
<amendments />
<committeeReports />
<billNumber>2088</billNumber>
<title>Empire State Equity Act</title>
</bill>
<dublinCore xmlns:dc="http://purl.org/dc/elements/1.1/">
<dc:format>text/xml</dc:format>
<dc:language>EN</dc:language>
<dc:rights>Pursuant to Title 17 Section 105 of the United States Code, this file is not subject to copyright protection and is in the public domain.</dc:rights>
<dc:contributor>Congressional Research Service, Library of Congress</dc:contributor>
<dc:description>This file contains bill summaries and statuses for federal legislation. A bill summary describes the most significant provisions of a piece of legislation and details the effects the legislative text may have on current law and federal programs. Bill summaries are authored by the Congressional Research Service (CRS) of the Library of Congress. As stated in Public Law 91-510 (2 USC 166 (d)(6)), one of the duties of CRS is "to prepare summaries and digests of bills and resolutions of a public general nature introduced in the Senate or House of Representatives". For more information, refer to the User Guide that accompanies this file.</dc:description>
</dublinCore>
</billStatus>
| {
"content_hash": "97722b445a6026358ca951ca7e5c910e",
"timestamp": "",
"source": "github",
"line_count": 355,
"max_line_length": 676,
"avg_line_length": 34.4,
"alnum_prop": 0.5882738290206354,
"repo_name": "peter765/power-polls",
"id": "0385910e5603016b2360412865eb48a5daf9fe91",
"size": "12212",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/bills/hr/hr2088/fdsys_billstatus.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "58567"
},
{
"name": "JavaScript",
"bytes": "7370"
},
{
"name": "Python",
"bytes": "22988"
}
],
"symlink_target": ""
} |
package com.jcodes.memcache;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import com.alisoft.xplatform.asf.cache.ICacheManager;
import com.alisoft.xplatform.asf.cache.IMemcachedCache;
import com.alisoft.xplatform.asf.cache.memcached.CacheUtil;
import com.alisoft.xplatform.asf.cache.memcached.MemcachedCacheManager;
/**
* http://blog.sina.com.cn/s/blog_617a491c0100fvjs.html
* http://blog.csdn.net/sup_heaven/article/details/32337711
*
* @author dreajay
*/
public class AliMemCachedUtil {
private static final Logger logger = Logger.getLogger(AliMemCachedUtil.class);
//默认缓存3分钟
private static final int REF_SECONDS = 3 * 60;
private static ICacheManager<IMemcachedCache> manager;
private static Map<String, IMemcachedCache> cacheArray;
private static final String defalutCacheName = "mclient1";
static {
cacheArray = new HashMap<String, IMemcachedCache>();
manager = CacheUtil.getCacheManager(IMemcachedCache.class, MemcachedCacheManager.class
.getName());
// manager.setConfigFile("memcached.xml");
manager.start();
cacheArray.put(defalutCacheName, manager.getCache(defalutCacheName));
}
private static String getCacheName(String type, Object key) {
StringBuffer cacheName = new StringBuffer(type);
if (key != null) {
cacheName.append("_").append(key);
}
return cacheName.toString();
}
public static void set(String type, Object key, Object value) {
set(type, key, value, REF_SECONDS);
}
public static void putNoTimeInCache(String type, Object key, Object value) {
if (value != null) {
set(type, key, value, -1);
}
}
public static void set(String type, Object key, Object value, int seconds) {
if (value != null) {
String cacheName = getCacheName(type, key);
try {
if (seconds < 1) {
cacheArray.get(defalutCacheName).put(cacheName, value);
} else {
cacheArray.get(defalutCacheName).put(cacheName, value, seconds);
}
} catch (Exception e) {
logger.log(Level.INFO, "cache " + defalutCacheName + " socket error。");
}
}
}
public static void delete(String type, Object key) {
cacheArray.get(defalutCacheName).remove(getCacheName(type, key));
}
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> clazz, String type, Object key) {
return (T) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
}
@SuppressWarnings("unchecked")
public static <T> List<T> getList(Class<T> clazz, String type, Object key) {
return (List<T>) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
}
@SuppressWarnings("unchecked")
public static <T> T get(Class<T> clazz, String type, Object key, int localTTL) {
try {
return (T) cacheArray.get(defalutCacheName).get(getCacheName(type, key), localTTL);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("unchecked")
public static <T> List<T> getList(Class<T> clazz, String type, Object key, int localTTL) {
try {
return (List<T>) cacheArray.get(defalutCacheName)
.get(getCacheName(type, key), localTTL);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("unchecked")
public static <V> Map<String, V> getMap(Class<V> clazz, String type, Object key, int localTTL) {
try {
return (Map<String, V>) cacheArray.get(defalutCacheName).get(getCacheName(type, key),
localTTL);
} catch (Exception e) {
return null;
}
}
@SuppressWarnings("unchecked")
public static <V> Map<String, V> getMap(Class<V> clazz, String type, Object key) {
try {
return (Map<String, V>) cacheArray.get(defalutCacheName).get(getCacheName(type, key));
} catch (Exception e) {
return null;
}
}
public static Set<String> getKeyList() {
return cacheArray.get(defalutCacheName).keySet();
}
public static void clear() {
cacheArray.get(defalutCacheName).clear();
}
public static void close() {
manager.stop();
}
public static void main(String argv[]) {
if (argv.length == 0) {
System.out.println("Usage:MemCachedUtil get|del|set|list [type] [key] [value]");
return;
}
String type = null;
String key = null;
String value = null;
if ("get".equals(argv[0])) {
if (argv.length < 3) {
System.out.println("Usage:MemCachedUtil get type key");
return;
}
type = argv[1];
key = argv[2];
System.out.println(AliMemCachedUtil.get(Object.class, type, key));
} else if ("del".equals(argv[0])) {
if (argv.length < 3) {
System.out.println("Usage:MemCachedUtil del type key");
return;
}
type = argv[1];
key = argv[2];
AliMemCachedUtil.delete(type, key);
} else if ("set".equals(argv[0])) {
if (argv.length < 4) {
System.out.println("Usage:MemCachedUtil set type key value");
return;
}
type = argv[1];
key = argv[2];
value = argv[3];
AliMemCachedUtil.set(type, key, value);
} else if ("list".equals(argv[0])) {
System.out.println(AliMemCachedUtil.getKeyList());
}
AliMemCachedUtil.close();
}
} | {
"content_hash": "ec21c3376fe7ee8a12121f46c2a51aa9",
"timestamp": "",
"source": "github",
"line_count": 178,
"max_line_length": 115,
"avg_line_length": 33.87640449438202,
"alnum_prop": 0.5787728026533997,
"repo_name": "dreajay/jCodes",
"id": "f76b8061ede0fab6fa98f6cff982695fc949ab02",
"size": "6044",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "jCodes-memcache/src/main/java/com/jcodes/memcache/AliMemCachedUtil.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "37764"
},
{
"name": "Java",
"bytes": "449560"
}
],
"symlink_target": ""
} |
namespace AnimalHope.Web
{
using System.Web.Mvc;
using System.Web.Routing;
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });
}
}
}
| {
"content_hash": "57daae5d5fa76d780b7d9bad419b0c29",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 101,
"avg_line_length": 27.333333333333332,
"alnum_prop": 0.5548780487804879,
"repo_name": "juliameleshko/AnimalHope",
"id": "75ba30aaedb8137eca6c640df9efd5496b79316e",
"size": "494",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "AnimalHope/AnimalHope.Web/App_Start/RouteConfig.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "105"
},
{
"name": "C#",
"bytes": "156951"
},
{
"name": "CSS",
"bytes": "404785"
},
{
"name": "JavaScript",
"bytes": "24807"
}
],
"symlink_target": ""
} |
<Alloy>
<TabGroup>
<Tab title="User" icon="KS_nav_ui.png">
<Window title="User API">
<Widget id="userWidget" src="userHarness" />
</Window>
</Tab>
<Tab title="Objects" icon="KS_nav_views.png">
<Window title="Object API">
<Widget id="objectWidget" src="objectHarness" />
</Window>
</Tab>
</TabGroup>
</Alloy> | {
"content_hash": "5ca7f3e401987f6cdc463d33a886ca70",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 52,
"avg_line_length": 24.357142857142858,
"alnum_prop": 0.6099706744868035,
"repo_name": "magnatronus/peppa-test-harness",
"id": "60613fdcef97dbbd68a2f41affe39e918cf26274",
"size": "341",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/views/index.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2552"
},
{
"name": "JavaScript",
"bytes": "55821"
},
{
"name": "Python",
"bytes": "4668"
}
],
"symlink_target": ""
} |
package com.datalint.open.server.document;
import java.util.ArrayDeque;
import java.util.Deque;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;
public class DocumentSAXHandler extends DefaultHandler {
protected final Document document;
protected final Deque<Element> dequeElement = new ArrayDeque<>();
protected final StringBuilder text = new StringBuilder();
protected Element rootElement;
public DocumentSAXHandler(Document document) {
this.document = document;
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) {
Element element = document.createElement(qName);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttribute(attributes.getQName(i), attributes.getValue(i));
}
Element last = dequeElement.peekLast();
if (text.length() > 0) {
last.appendChild(document.createTextNode(text.toString()));
text.setLength(0);
}
if (last == null)
rootElement = element;
else
last.appendChild(element);
dequeElement.add(element);
}
@Override
public void endElement(String uri, String localName, String qName) {
endElement();
}
protected Element endElement() {
Element last = dequeElement.pollLast();
if (text.length() > 0) {
last.appendChild(document.createTextNode(text.toString()));
text.setLength(0);
}
return last;
}
@Override
public void characters(char[] ch, int start, int length) {
text.append(ch, start, length);
}
public Element getRootElement() {
return rootElement;
}
}
| {
"content_hash": "d1e114bad291235d40307eb6203a0a03",
"timestamp": "",
"source": "github",
"line_count": 70,
"max_line_length": 94,
"avg_line_length": 23.071428571428573,
"alnum_prop": 0.7294117647058823,
"repo_name": "datalint/open",
"id": "cda99024b5048e02da1fff7ad1d2d502f518c432",
"size": "1615",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Open/src/main/java/com/datalint/open/server/document/DocumentSAXHandler.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "2489"
},
{
"name": "HTML",
"bytes": "1017"
},
{
"name": "Java",
"bytes": "1166753"
},
{
"name": "JavaScript",
"bytes": "11123"
},
{
"name": "TSQL",
"bytes": "6429"
}
],
"symlink_target": ""
} |
This a skeleton for setting up a Rails server with Postgres database using docker-compose.
On check-out, follow the steps below to start the server:
1. Run `docker-compose build`
1. Run `docker-compose up -d`
1. Create the database by running `docker-compose run web rake db:create`
1. Check that the local server is running at http://localhost:3000
The steps taken to create this skeleton were:
1. Install Docker for Mac: https://docs.docker.com/docker-for-mac/install/
1. Create boilerplate Dockerfile, Gemfile, and Gemfile.lock, and docker-compose.yml; see https://docs.docker.com/compose/rails/
1. Run `docker-compose run web rails new . --force --database=postgresql`
1. Run `docker-compose build`
1. Update the config/database.yml file to point to the postgres container; see https://docs.docker.com/compose/rails/
| {
"content_hash": "61691b9228acf27ac3e0197f97221bbb",
"timestamp": "",
"source": "github",
"line_count": 16,
"max_line_length": 127,
"avg_line_length": 51.5625,
"alnum_prop": 0.7709090909090909,
"repo_name": "kcampbell/rails_pg_skeleton",
"id": "7af5b1e695e60d3865015e29c00701761fa68f75",
"size": "835",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "736"
},
{
"name": "HTML",
"bytes": "5149"
},
{
"name": "JavaScript",
"bytes": "1201"
},
{
"name": "Ruby",
"bytes": "24818"
}
],
"symlink_target": ""
} |
from pixiepatch import PixiePatch
from signer import Signer, VerificationError
from compressor import Compressor
from differ import Differ, DiffError
| {
"content_hash": "126cfb9019186eb5a1cc8898593bf5d5",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 44,
"avg_line_length": 37.5,
"alnum_prop": 0.8666666666666667,
"repo_name": "dgym/pixiepatch",
"id": "64e871473bb09e9e701bbfc9880186aadde07bb8",
"size": "150",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "__init__.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "33226"
}
],
"symlink_target": ""
} |
package org.assertj.core.internal.dates;
import static org.assertj.core.error.ShouldNotBeBetween.shouldNotBeBetween;
import static org.assertj.core.test.ErrorMessages.*;
import static org.assertj.core.test.TestData.someInfo;
import static org.assertj.core.test.TestFailures.failBecauseExpectedAssertionErrorWasNotThrown;
import static org.assertj.core.util.FailureMessages.actualIsNull;
import static org.mockito.Mockito.verify;
import java.util.Date;
import org.assertj.core.api.AssertionInfo;
import org.assertj.core.internal.Dates;
import org.assertj.core.internal.DatesBaseTest;
import org.junit.Test;
/**
* Tests for <code>{@link Dates#assertIsNotBetween(AssertionInfo, Date, Date, Date, boolean, boolean)}</code>.
*
* @author Joel Costigliola
*/
public class Dates_assertIsNotBetween_Test extends DatesBaseTest {
@Override
protected void initActualDate() {
actual = parseDate("2011-09-27");
}
@Test
public void should_fail_if_actual_is_between_given_period() {
AssertionInfo info = someInfo();
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
boolean inclusiveStart = true;
boolean inclusiveEnd = true;
try {
dates.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_equals_to_start_of_given_period_and_start_is_included_in_given_period() {
AssertionInfo info = someInfo();
actual = parseDate("2011-09-01");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
boolean inclusiveStart = true;
boolean inclusiveEnd = false;
try {
dates.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_equals_to_end_of_given_period_and_end_is_included_in_given_period() {
AssertionInfo info = someInfo();
actual = parseDate("2011-09-30");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
boolean inclusiveStart = false;
boolean inclusiveEnd = true;
try {
dates.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info, shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_throw_error_if_start_date_is_null() {
thrown.expectNullPointerException(startDateToCompareActualWithIsNull());
Date end = parseDate("2011-09-30");
dates.assertIsNotBetween(someInfo(), actual, null, end, true, true);
}
@Test
public void should_throw_error_if_end_date_is_null() {
thrown.expectNullPointerException(endDateToCompareActualWithIsNull());
Date start = parseDate("2011-09-01");
dates.assertIsNotBetween(someInfo(), actual, start, null, true, true);
}
@Test
public void should_fail_if_actual_is_null() {
thrown.expectAssertionError(actualIsNull());
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
dates.assertIsNotBetween(someInfo(), null, start, end, true, true);
}
@Test
public void should_pass_if_actual_is_not_between_given_period() {
actual = parseDate("2011-12-31");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
dates.assertIsNotBetween(someInfo(), actual, start, end, true, true);
}
@Test
public void should_pass_if_actual_is_equals_to_start_of_given_period_and_start_is_not_included_in_given_period() {
actual = parseDate("2011-09-01");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
dates.assertIsNotBetween(someInfo(), actual, start, end, false, false);
dates.assertIsNotBetween(someInfo(), actual, start, end, false, true);
}
@Test
public void should_pass_if_actual_is_equals_to_end_of_given_period_and_end_is_not_included_in_given_period() {
actual = parseDate("2011-09-30");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
dates.assertIsNotBetween(someInfo(), actual, start, end, false, false);
dates.assertIsNotBetween(someInfo(), actual, start, end, true, false);
}
@Test
public void should_fail_if_actual_is_between_given_period_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
Date start = parseDate("2011-08-31");
Date end = parseDate("2011-09-30");
boolean inclusiveStart = true;
boolean inclusiveEnd = true;
try {
datesWithCustomComparisonStrategy.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info,
shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd, yearAndMonthComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_equals_to_start_of_given_period_and_start_is_included_in_given_period_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
actual = parseDate("2011-09-15");
Date start = parseDate("2011-09-01"); // = 2011-09-15 according to comparison strategy
Date end = parseDate("2011-10-01");
boolean inclusiveStart = true;
boolean inclusiveEnd = false;
try {
datesWithCustomComparisonStrategy.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info,
shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd, yearAndMonthComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_fail_if_actual_is_equals_to_end_of_given_period_and_end_is_included_in_given_period_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
actual = parseDate("2011-09-15");
Date start = parseDate("2011-08-31");
Date end = parseDate("2011-09-30"); // = 2011-09-15 according to comparison strategy
boolean inclusiveStart = false;
boolean inclusiveEnd = true;
try {
datesWithCustomComparisonStrategy.assertIsNotBetween(info, actual, start, end, inclusiveStart, inclusiveEnd);
} catch (AssertionError e) {
verify(failures).failure(info,
shouldNotBeBetween(actual, start, end, inclusiveStart, inclusiveEnd, yearAndMonthComparisonStrategy));
return;
}
failBecauseExpectedAssertionErrorWasNotThrown();
}
@Test
public void should_throw_error_if_start_date_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectNullPointerException(startDateToCompareActualWithIsNull());
Date end = parseDate("2011-09-30");
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, null, end, true, true);
}
@Test
public void should_throw_error_if_end_date_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectNullPointerException(endDateToCompareActualWithIsNull());
Date start = parseDate("2011-09-01");
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, null, true, true);
}
@Test
public void should_fail_if_actual_is_null_whatever_custom_comparison_strategy_is() {
thrown.expectAssertionError(actualIsNull());
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-30");
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), null, start, end, true, true);
}
@Test
public void should_pass_if_actual_is_not_between_given_period_according_to_custom_comparison_strategy() {
actual = parseDate("2011-12-31");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-11-30");
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, end, true, true);
}
@Test
public void should_pass_if_actual_is_equals_to_start_of_given_period_and_start_is_not_included_in_given_period_according_to_custom_comparison_strategy() {
actual = parseDate("2011-09-01");
Date start = parseDate("2011-09-15"); // = 2011-09-01 according to comparison strategy
Date end = parseDate("2011-09-30");
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, end, false, false);
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, end, false, true);
}
@Test
public void should_pass_if_actual_is_equals_to_end_of_given_period_and_end_is_not_included_in_given_period_according_to_custom_comparison_strategy() {
actual = parseDate("2011-09-30");
Date start = parseDate("2011-09-01");
Date end = parseDate("2011-09-15"); // = 2011-09-30 according to comparison strategy
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, end, false, false);
datesWithCustomComparisonStrategy.assertIsNotBetween(someInfo(), actual, start, end, true, false);
}
}
| {
"content_hash": "a78d73f7bc86fd19ba10c755c2a67c4b",
"timestamp": "",
"source": "github",
"line_count": 232,
"max_line_length": 156,
"avg_line_length": 40.668103448275865,
"alnum_prop": 0.7205087440381558,
"repo_name": "dorzey/assertj-core",
"id": "e009e3d63ec50bedc9901259625b3eb94d19927f",
"size": "10042",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/org/assertj/core/internal/dates/Dates_assertIsNotBetween_Test.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "8364137"
},
{
"name": "Shell",
"bytes": "40820"
}
],
"symlink_target": ""
} |
namespace eidss.winclient.Administration
{
partial class PersonListPanel
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PersonListPanel));
this.SuspendLayout();
//
// m_ListGridControl
//
resources.ApplyResources(this.m_ListGridControl, "m_ListGridControl");
bv.common.Resources.BvResourceManagerChanger.GetResourceManager(typeof(PersonListPanel), out resources);
// Form Is Localizable: True
//
// PersonListPanel
//
resources.ApplyResources(this, "$this");
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Icon = global::eidss.winclient.Properties.Resources.Employees_List__large__58_;
this.Name = "PersonListPanel";
this.ResumeLayout(false);
}
#endregion
}
}
| {
"content_hash": "93b3ea6283d761212f9860a3544e142b",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 147,
"avg_line_length": 36.46153846153846,
"alnum_prop": 0.569620253164557,
"repo_name": "EIDSS/EIDSS-Legacy",
"id": "b1f1552e45708e477963c178597bbcd8620d8f61",
"size": "1898",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "EIDSS v6.1/eidss.winclient/Administration/PersonListPanel.Designer.cs",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "ASP",
"bytes": "256377"
},
{
"name": "Batchfile",
"bytes": "30009"
},
{
"name": "C#",
"bytes": "106160789"
},
{
"name": "CSS",
"bytes": "833586"
},
{
"name": "HTML",
"bytes": "7507"
},
{
"name": "Java",
"bytes": "2188690"
},
{
"name": "JavaScript",
"bytes": "17000221"
},
{
"name": "PLSQL",
"bytes": "2499"
},
{
"name": "PLpgSQL",
"bytes": "6422"
},
{
"name": "Pascal",
"bytes": "159898"
},
{
"name": "PowerShell",
"bytes": "339522"
},
{
"name": "Puppet",
"bytes": "3758"
},
{
"name": "SQLPL",
"bytes": "12198"
},
{
"name": "Smalltalk",
"bytes": "301266"
},
{
"name": "Visual Basic",
"bytes": "20819564"
},
{
"name": "XSLT",
"bytes": "4253600"
}
],
"symlink_target": ""
} |
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<!--
$Id: package.html 1694911 2015-08-09 21:21:10Z chas $
-->
</head>
<body bgcolor="white">
<p>
This package contains basic classes for the
<a href="http://commons.apache.org/bcel/">Byte Code Engineering Library</a>
and constants defined by the
<a href="http://docs.oracle.com/javase/specs/">
JVM specification</a>.
</p>
</body>
</html>
| {
"content_hash": "5b2932d15a1bcf03623f29f0b7dbf12c",
"timestamp": "",
"source": "github",
"line_count": 33,
"max_line_length": 75,
"avg_line_length": 36.333333333333336,
"alnum_prop": 0.7397831526271893,
"repo_name": "mirkosertic/Bytecoder",
"id": "2b6dd18ef9b70955ea9e2c827749db62d1726a56",
"size": "1199",
"binary": false,
"copies": "14",
"ref": "refs/heads/master",
"path": "classlib/java.xml/src/main/resources/META-INF/modules/java.xml/classes/com/sun/org/apache/bcel/internal/package.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "153"
},
{
"name": "C++",
"bytes": "1301"
},
{
"name": "CSS",
"bytes": "5154"
},
{
"name": "Clojure",
"bytes": "87"
},
{
"name": "HTML",
"bytes": "599386"
},
{
"name": "Java",
"bytes": "106011215"
},
{
"name": "Kotlin",
"bytes": "15858"
},
{
"name": "LLVM",
"bytes": "2839"
},
{
"name": "Shell",
"bytes": "164"
}
],
"symlink_target": ""
} |
package com.alibaba.nacos.naming.healthcheck.v2.processor;
import com.alibaba.nacos.api.naming.pojo.healthcheck.HealthCheckType;
import com.alibaba.nacos.api.naming.pojo.healthcheck.impl.Mysql;
import com.alibaba.nacos.naming.core.v2.metadata.ClusterMetadata;
import com.alibaba.nacos.naming.core.v2.pojo.HealthCheckInstancePublishInfo;
import com.alibaba.nacos.naming.core.v2.pojo.Service;
import com.alibaba.nacos.naming.healthcheck.v2.HealthCheckTaskV2;
import com.alibaba.nacos.naming.misc.GlobalExecutor;
import com.alibaba.nacos.naming.misc.Loggers;
import com.alibaba.nacos.naming.misc.SwitchDomain;
import com.alibaba.nacos.naming.monitor.MetricsMonitor;
import org.springframework.stereotype.Component;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeoutException;
import static com.alibaba.nacos.naming.misc.Loggers.SRV_LOG;
/**
* TCP health check processor for v2.x.
*
* <p>Current health check logic is same as v1.x. TODO refactor health check for v2.x.
*
* @author xiweng.yy
*/
@Component
@SuppressWarnings("PMD.ThreadPoolCreationRule")
public class MysqlHealthCheckProcessor implements HealthCheckProcessorV2 {
public static final String TYPE = HealthCheckType.MYSQL.name();
private final HealthCheckCommonV2 healthCheckCommon;
private final SwitchDomain switchDomain;
public static final int CONNECT_TIMEOUT_MS = 500;
private static final String CHECK_MYSQL_MASTER_SQL = "show global variables where variable_name='read_only'";
private static final String MYSQL_SLAVE_READONLY = "ON";
private static final ConcurrentMap<String, Connection> CONNECTION_POOL = new ConcurrentHashMap<String, Connection>();
public MysqlHealthCheckProcessor(HealthCheckCommonV2 healthCheckCommon, SwitchDomain switchDomain) {
this.healthCheckCommon = healthCheckCommon;
this.switchDomain = switchDomain;
}
@Override
public String getType() {
return TYPE;
}
@Override
public void process(HealthCheckTaskV2 task, Service service, ClusterMetadata metadata) {
HealthCheckInstancePublishInfo instance = (HealthCheckInstancePublishInfo) task.getClient()
.getInstancePublishInfo(service);
if (null == instance) {
return;
}
SRV_LOG.debug("mysql check, ip:" + instance);
try {
// TODO handle marked(white list) logic like v1.x.
if (!instance.tryStartCheck()) {
SRV_LOG.warn("mysql check started before last one finished, service: {} : {} : {}:{}",
service.getGroupedServiceName(), instance.getCluster(), instance.getIp(), instance.getPort());
healthCheckCommon
.reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task, switchDomain.getMysqlHealthParams());
return;
}
GlobalExecutor.executeMysqlCheckTask(new MysqlCheckTask(task, service, instance, metadata));
MetricsMonitor.getMysqlHealthCheckMonitor().incrementAndGet();
} catch (Exception e) {
instance.setCheckRt(switchDomain.getMysqlHealthParams().getMax());
healthCheckCommon.checkFail(task, service, "mysql:error:" + e.getMessage());
healthCheckCommon.reEvaluateCheckRT(switchDomain.getMysqlHealthParams().getMax(), task,
switchDomain.getMysqlHealthParams());
}
}
private class MysqlCheckTask implements Runnable {
private final HealthCheckTaskV2 task;
private final Service service;
private final HealthCheckInstancePublishInfo instance;
private final ClusterMetadata metadata;
private long startTime = System.currentTimeMillis();
public MysqlCheckTask(HealthCheckTaskV2 task, Service service, HealthCheckInstancePublishInfo instance,
ClusterMetadata metadata) {
this.task = task;
this.service = service;
this.instance = instance;
this.metadata = metadata;
}
@Override
public void run() {
Statement statement = null;
ResultSet resultSet = null;
try {
String clusterName = instance.getCluster();
String key =
service.getGroupedServiceName() + ":" + clusterName + ":" + instance.getIp() + ":" + instance
.getPort();
Connection connection = CONNECTION_POOL.get(key);
Mysql config = (Mysql) metadata.getHealthChecker();
if (connection == null || connection.isClosed()) {
String url = "jdbc:mysql://" + instance.getIp() + ":" + instance.getPort() + "?connectTimeout="
+ CONNECT_TIMEOUT_MS + "&socketTimeout=" + CONNECT_TIMEOUT_MS + "&loginTimeout=" + 1;
connection = DriverManager.getConnection(url, config.getUser(), config.getPwd());
CONNECTION_POOL.put(key, connection);
}
statement = connection.createStatement();
statement.setQueryTimeout(1);
resultSet = statement.executeQuery(config.getCmd());
int resultColumnIndex = 2;
if (CHECK_MYSQL_MASTER_SQL.equals(config.getCmd())) {
resultSet.next();
if (MYSQL_SLAVE_READONLY.equals(resultSet.getString(resultColumnIndex))) {
throw new IllegalStateException("current node is slave!");
}
}
healthCheckCommon.checkOk(task, service, "mysql:+ok");
healthCheckCommon.reEvaluateCheckRT(System.currentTimeMillis() - startTime, task,
switchDomain.getMysqlHealthParams());
} catch (SQLException e) {
// fail immediately
healthCheckCommon.checkFailNow(task, service, "mysql:" + e.getMessage());
healthCheckCommon.reEvaluateCheckRT(switchDomain.getHttpHealthParams().getMax(), task,
switchDomain.getMysqlHealthParams());
} catch (Throwable t) {
Throwable cause = t;
int maxStackDepth = 50;
for (int deepth = 0; deepth < maxStackDepth && cause != null; deepth++) {
if (cause instanceof SocketTimeoutException || cause instanceof ConnectException
|| cause instanceof TimeoutException || cause.getCause() instanceof TimeoutException) {
healthCheckCommon.checkFail(task, service, "mysql:timeout:" + cause.getMessage());
healthCheckCommon.reEvaluateCheckRT(task.getCheckRtNormalized() * 2, task,
switchDomain.getMysqlHealthParams());
return;
}
cause = cause.getCause();
}
// connection error, probably not reachable
healthCheckCommon.checkFail(task, service, "mysql:error:" + t.getMessage());
healthCheckCommon.reEvaluateCheckRT(switchDomain.getMysqlHealthParams().getMax(), task,
switchDomain.getMysqlHealthParams());
} finally {
instance.setCheckRt(System.currentTimeMillis() - startTime);
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
Loggers.SRV_LOG.error("[MYSQL-CHECK] failed to close statement:" + statement, e);
}
}
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
Loggers.SRV_LOG.error("[MYSQL-CHECK] failed to close resultSet:" + resultSet, e);
}
}
}
}
}
}
| {
"content_hash": "db72fb6aaccb0d7382a8c8de37e9c303",
"timestamp": "",
"source": "github",
"line_count": 193,
"max_line_length": 121,
"avg_line_length": 44.45077720207254,
"alnum_prop": 0.5972724093717217,
"repo_name": "alibaba/nacos",
"id": "f2b0780ea299b736d8792a5f6a29e51abca7afa8",
"size": "9194",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "naming/src/main/java/com/alibaba/nacos/naming/healthcheck/v2/processor/MysqlHealthCheckProcessor.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "4434"
},
{
"name": "EJS",
"bytes": "2645"
},
{
"name": "Java",
"bytes": "9013127"
},
{
"name": "JavaScript",
"bytes": "7472"
},
{
"name": "SCSS",
"bytes": "80124"
},
{
"name": "Shell",
"bytes": "6330"
},
{
"name": "TypeScript",
"bytes": "4765"
}
],
"symlink_target": ""
} |
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
<predicate lemma="snowball">
<note>
Frames file for 'snowball' based on survey of sentences in the WSJ
corpus.
</note>
<roleset id="snowball.01" name="to increase rapidly" vncls="-">
<roles>
<role descr="thing increased" n="1"/>
<role descr="endstate" n="2"/>
</roles>
<example name="intransitive">
<inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
<text>
But the rate of the decline snowballed in August , with unit sales to dealers for the month down 10.5 % from a year earlier , according to the Recreation Vehicle Industry Association .
</text>
<arg n="1">the rate of the decline</arg>
<rel>snowballed</rel>
<arg f="TMP" n="M">in August</arg>
<arg f="ADV" n="M">with unit sales to dealers for the month down 10.5 % from a year earlier</arg>
</example>
<example name="with Arg2">
<inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
<text>
The Manhattan real-estate developer acted after the UAL buyers failed [*-3] to obtain financing for their earlier $ 300-a-share [*U*] bid , which [*T*-1] sparked a selling panic among that [*T*-2] snowballed into a 190-point drop Friday in the Dow Jones Industrial Average .
</text>
<arg n="1">[*T*-2]</arg>
<arg n="M" f="RCL">that -> a selling panic</arg>
<rel>snowballed</rel>
<arg n="2">into a 190-point drop Friday in the Dow Jones Industrial Average</arg>
</example>
<example name="with ArgM-PNC">
<inflection aspect="ns" form="full" person="ns" tense="past" voice="active"/>
<text>
Selling snowballed because of waves of automatic `` stop-loss '' orders , which [*T*-2] are triggered [*-1] by computer when prices fall to certain levels [*T*-3] .
</text>
<arg n="1">Selling</arg>
<rel>snowballed</rel>
<arg f="PNC" n="M">because of waves of automatic `` stop-loss '' orders , which [*T*-2] are triggered [*-1] by computer when prices fall to certain levels [*T*-3]</arg>
</example>
</roleset>
</predicate>
<note>
frames created by Olga
</note>
</frameset>
| {
"content_hash": "e604e7797f880ab4d4b1547a943b9370",
"timestamp": "",
"source": "github",
"line_count": 56,
"max_line_length": 294,
"avg_line_length": 48.214285714285715,
"alnum_prop": 0.5225925925925926,
"repo_name": "keenon/jamr",
"id": "c9c3c6e016ee2b325e88b91c1c0699852c22d688",
"size": "2700",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data/frames/snowball.xml",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "Java",
"bytes": "640454"
},
{
"name": "Perl",
"bytes": "8697"
},
{
"name": "Python",
"bytes": "76079"
},
{
"name": "Scala",
"bytes": "353885"
},
{
"name": "Shell",
"bytes": "41192"
}
],
"symlink_target": ""
} |
<resources>
<string name="app_name">SQLiteDemo</string>
</resources>
| {
"content_hash": "4161b8708052c9dcc8fb1cd64cb6ca23",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 47,
"avg_line_length": 24.333333333333332,
"alnum_prop": 0.6986301369863014,
"repo_name": "LiuchangDuan/androiddemo",
"id": "563c849498054c6b7b13ea2d867d0a2abbf89a6f",
"size": "73",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "sqlitedemo/src/main/res/values/strings.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "133696"
}
],
"symlink_target": ""
} |
class Products < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.integer :category_id
t.timestamps
end
end
end
| {
"content_hash": "6ae29d17f3e6558ad57ccffb7b33bee8",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 40,
"avg_line_length": 18.363636363636363,
"alnum_prop": 0.6435643564356436,
"repo_name": "chugh97/eshop",
"id": "e5484bbc8770cfe692da7aa6ed29ece978fefa42",
"size": "202",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "db/migrate/20131120210936_products.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "38756"
},
{
"name": "CoffeeScript",
"bytes": "211"
},
{
"name": "JavaScript",
"bytes": "5847"
},
{
"name": "Ruby",
"bytes": "42973"
}
],
"symlink_target": ""
} |
#include <gtest/gtest.h>
extern "C" {
#include "cras_hfp_iodev.h"
#include "cras_iodev.h"
#include "cras_iodev_list.h"
#include "cras_hfp_info.h"
}
static struct cras_iodev *iodev;
static struct cras_bt_transport *fake_transport;
static struct hfp_info *fake_info;
struct cras_audio_format fake_format;
static size_t cras_iodev_list_add_output_called;
static size_t cras_iodev_list_rm_output_called;
static size_t cras_iodev_list_add_input_called;
static size_t cras_iodev_list_rm_input_called;
static size_t cras_iodev_add_node_called;
static size_t cras_iodev_rm_node_called;
static size_t cras_iodev_set_active_node_called;
static size_t cras_iodev_free_format_called;
static size_t cras_bt_transport_sco_connect_called;
static int cras_bt_transport_sco_connect_return_val;
static size_t hfp_info_add_iodev_called;
static size_t hfp_info_rm_iodev_called;
static size_t hfp_info_running_called;
static int hfp_info_running_return_val;
static size_t hfp_info_has_iodev_called;
static int hfp_info_has_iodev_return_val;
static size_t hfp_info_start_called;
static size_t hfp_info_stop_called;
static size_t hfp_buf_acquire_called;
static unsigned hfp_buf_acquire_return_val;
static size_t hfp_buf_release_called;
static unsigned hfp_buf_release_nwritten_val;
void ResetStubData() {
cras_iodev_list_add_output_called = 0;
cras_iodev_list_rm_output_called = 0;
cras_iodev_list_add_input_called = 0;
cras_iodev_list_rm_input_called = 0;
cras_iodev_add_node_called = 0;
cras_iodev_rm_node_called = 0;
cras_iodev_set_active_node_called = 0;
cras_iodev_free_format_called = 0;
cras_bt_transport_sco_connect_called = 0;
cras_bt_transport_sco_connect_return_val = 0;
hfp_info_add_iodev_called = 0;
hfp_info_rm_iodev_called = 0;
hfp_info_running_called = 0;
hfp_info_running_return_val = 1;
hfp_info_has_iodev_called = 0;
hfp_info_has_iodev_return_val = 0;
hfp_info_start_called = 0;
hfp_info_stop_called = 0;
hfp_buf_acquire_called = 0;
hfp_buf_acquire_return_val = 0;
hfp_buf_release_called = 0;
hfp_buf_release_nwritten_val = 0;
fake_info = reinterpret_cast<struct hfp_info *>(0x123);
}
namespace {
TEST(HfpIodev, CreateHfpIodev) {
iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_transport,
fake_info);
ASSERT_EQ(CRAS_STREAM_OUTPUT, iodev->direction);
ASSERT_EQ(1, cras_iodev_list_add_output_called);
ASSERT_EQ(1, cras_iodev_add_node_called);
ASSERT_EQ(1, cras_iodev_set_active_node_called);
hfp_iodev_destroy(iodev);
ASSERT_EQ(1, cras_iodev_list_rm_output_called);
ASSERT_EQ(1, cras_iodev_rm_node_called);
}
TEST(HfpIodev, OpenHfpIodev) {
ResetStubData();
iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_transport,
fake_info);
cras_iodev_set_format(iodev, &fake_format);
/* hfp_info not start yet */
hfp_info_running_return_val = 0;
iodev->open_dev(iodev);
ASSERT_EQ(1, cras_bt_transport_sco_connect_called);
ASSERT_EQ(1, hfp_info_start_called);
ASSERT_EQ(1, hfp_info_add_iodev_called);
/* hfp_info is running now */
hfp_info_running_return_val = 1;
ASSERT_EQ(1, iodev->is_open(iodev));
iodev->close_dev(iodev);
ASSERT_EQ(1, hfp_info_rm_iodev_called);
ASSERT_EQ(1, hfp_info_stop_called);
ASSERT_EQ(1, cras_iodev_free_format_called);
}
TEST(HfpIodev, OpenIodevWithHfpInfoAlreadyRunning) {
ResetStubData();
iodev = hfp_iodev_create(CRAS_STREAM_INPUT, fake_transport,
fake_info);
cras_iodev_set_format(iodev, &fake_format);
/* hfp_info already started by another device */
hfp_info_running_return_val = 1;
iodev->open_dev(iodev);
ASSERT_EQ(0, cras_bt_transport_sco_connect_called);
ASSERT_EQ(0, hfp_info_start_called);
ASSERT_EQ(1, hfp_info_add_iodev_called);
ASSERT_EQ(1, iodev->is_open(iodev));
hfp_info_has_iodev_return_val = 1;
iodev->close_dev(iodev);
ASSERT_EQ(1, hfp_info_rm_iodev_called);
ASSERT_EQ(0, hfp_info_stop_called);
ASSERT_EQ(1, cras_iodev_free_format_called);
}
TEST(HfpIodev, PutGetBuffer) {
uint8_t *buf;
unsigned frames;
ResetStubData();
iodev = hfp_iodev_create(CRAS_STREAM_OUTPUT, fake_transport,
fake_info);
cras_iodev_set_format(iodev, &fake_format);
iodev->open_dev(iodev);
hfp_buf_acquire_return_val = 100;
iodev->get_buffer(iodev, &buf, &frames);
ASSERT_EQ(1, hfp_buf_acquire_called);
ASSERT_EQ(100, frames);
iodev->put_buffer(iodev, 40);
ASSERT_EQ(1, hfp_buf_release_called);
ASSERT_EQ(40, hfp_buf_release_nwritten_val);
}
} // namespace
extern "C" {
void cras_iodev_free_format(struct cras_iodev *iodev)
{
cras_iodev_free_format_called++;
}
int cras_iodev_set_format(struct cras_iodev *iodev,
struct cras_audio_format *fmt)
{
fmt->format = SND_PCM_FORMAT_S16_LE;
fmt->num_channels = 1;
fmt->frame_rate = 8000;
iodev->format = fmt;
return 0;
}
void cras_iodev_add_node(struct cras_iodev *iodev, struct cras_ionode *node)
{
cras_iodev_add_node_called++;
iodev->nodes = node;
}
void cras_iodev_rm_node(struct cras_iodev *iodev, struct cras_ionode *node)
{
cras_iodev_rm_node_called++;
iodev->nodes = NULL;
}
void cras_iodev_set_active_node(struct cras_iodev *iodev,
struct cras_ionode *node)
{
cras_iodev_set_active_node_called++;
iodev->active_node = node;
}
// From iodev list.
int cras_iodev_list_add_output(struct cras_iodev *output)
{
cras_iodev_list_add_output_called++;
return 0;
}
int cras_iodev_list_rm_output(struct cras_iodev *dev)
{
cras_iodev_list_rm_output_called++;
return 0;
}
int cras_iodev_list_add_input(struct cras_iodev *output)
{
cras_iodev_list_add_input_called++;
return 0;
}
int cras_iodev_list_rm_input(struct cras_iodev *dev)
{
cras_iodev_list_rm_input_called++;
return 0;
}
// From bt transport
const char *cras_bt_transport_object_path(
const struct cras_bt_transport *transport)
{
return NULL;
}
int cras_bt_transport_sco_connect(struct cras_bt_transport *transport)
{
cras_bt_transport_sco_connect_called++;
return cras_bt_transport_sco_connect_return_val;
}
// From cras_hfp_info
int hfp_info_add_iodev(struct hfp_info *info, struct cras_iodev *dev)
{
hfp_info_add_iodev_called++;
return 0;
}
int hfp_info_rm_iodev(struct hfp_info *info, struct cras_iodev *dev)
{
hfp_info_rm_iodev_called++;
return 0;
}
int hfp_info_has_iodev(struct hfp_info *info)
{
hfp_info_has_iodev_called++;
return hfp_info_has_iodev_return_val;
}
int hfp_info_running(struct hfp_info *info)
{
hfp_info_running_called++;
return hfp_info_running_return_val;
}
int hfp_info_start(int fd, struct hfp_info *info)
{
hfp_info_start_called++;
return 0;
}
int hfp_info_stop(struct hfp_info *info)
{
hfp_info_stop_called++;
return 0;
}
int hfp_buf_queued(struct hfp_info *info, const struct cras_iodev *dev)
{
return 0;
}
int hfp_buf_size(struct hfp_info *info, struct cras_iodev *dev)
{
/* 1008 / 2 */
return 504;
}
void hfp_buf_acquire(struct hfp_info *info, struct cras_iodev *dev,
uint8_t **buf, unsigned *count)
{
hfp_buf_acquire_called++;
*count = hfp_buf_acquire_return_val;
}
void hfp_buf_release(struct hfp_info *info, struct cras_iodev *dev,
unsigned written_bytes)
{
hfp_buf_release_called++;
hfp_buf_release_nwritten_val = written_bytes;
}
} // extern "C"
int main(int argc, char **argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| {
"content_hash": "21474105cc17ca48a1bf42c2704cfd85",
"timestamp": "",
"source": "github",
"line_count": 297,
"max_line_length": 76,
"avg_line_length": 24.7003367003367,
"alnum_prop": 0.7043347873500545,
"repo_name": "drinkcat/adhd",
"id": "dac952c818f9a1cb106f7e5f9d1e1a0b5cca603f",
"size": "7511",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "cras/src/tests/hfp_iodev_unittest.cc",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "1016909"
},
{
"name": "C++",
"bytes": "491643"
},
{
"name": "CSS",
"bytes": "1372"
},
{
"name": "JavaScript",
"bytes": "50671"
},
{
"name": "Matlab",
"bytes": "1324"
},
{
"name": "Python",
"bytes": "29210"
},
{
"name": "Shell",
"bytes": "15363"
}
],
"symlink_target": ""
} |
<?php
namespace CmsIr\Product\Model;
use CmsIr\System\Model\ModelTable;
use CmsIr\System\Util\Inflector;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\TableGateway;
use Zend\Db\Sql\Select;
use Zend\Db\Sql\Predicate;
class ClientTable extends ModelTable
{
protected $tableGateway;
protected $originalResultSetPrototype;
public function __construct(TableGateway $tableGateway)
{
$this->tableGateway = $tableGateway;
}
public function getClient($id)
{
$id = (int) $id;
$rowset = $this->tableGateway->select(array('id' => $id));
$result = $this->getResultSetAsArrayObject($rowset);
if (!$result) {
throw new \Exception("Could not find row $id");
}
return $result;
}
public function deleteClient($id)
{
$id = (int) $id;
$this->tableGateway->delete(array('id' => $id));
}
public function getDataToDisplay($filteredRows, $columns)
{
$dataArray = array();
foreach($filteredRows as $row) {
$tmp = array();
foreach($columns as $column){
$column = 'get'.ucfirst($column);
$tmp[] = $row->$column();
}
$tmp[] = '<a href="client/edit/'.$row->getId().'" class="btn btn-primary" data-toggle="tooltip" title="Edycja"><i class="fa fa-pencil"></i></a> ' .
'<a href="client/delete/'.$row->getId().'" id="'.$row->getId().'" class="btn btn-danger" data-toggle="tooltip" title="Usuwanie"><i class="fa fa-trash-o"></i></a>';
array_push($dataArray, $tmp);
}
return $dataArray;
}
public function save(Client $client)
{
$data = array(
'name' => $client->getName(),
'slug' => Inflector::slugify($client->getName()),
'filename' => $client->getFilename(),
'description' => $client->getDescription(),
'size' => $client->getSize(),
);
$id = (int) $client->getId();
if ($id == 0) {
$this->tableGateway->insert($data);
} else {
if ($this->getOneBy(array('id' => $id))) {
$this->tableGateway->update($data, array('id' => $id));
} else {
throw new \Exception('Client id does not exist');
}
}
}
} | {
"content_hash": "609d405f3c72652c22099d745eb41de5",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 184,
"avg_line_length": 29.926829268292682,
"alnum_prop": 0.5162999185004075,
"repo_name": "web-ir/bloxio",
"id": "565259a1c7f9d0f074fd539423b853c08e2dd6d0",
"size": "2454",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/CmsIr/Product/src/Product/Model/ClientTable.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "896"
},
{
"name": "CSS",
"bytes": "742773"
},
{
"name": "HTML",
"bytes": "69441"
},
{
"name": "JavaScript",
"bytes": "161442"
},
{
"name": "PHP",
"bytes": "174191"
}
],
"symlink_target": ""
} |
define([
'backbone', 'models/GenericModel', 'controllers/util/FetchController'
], function (backbone, GenericModel, FetchController) {
return backbone.Collection.extend({
model: GenericModel,
initialize: function(options) {
this.fetchController = new FetchController();
if(!options)
return;
this.name = options.name;
this.url = options.url;
},
fetch: function (options) {
backbone.Model.prototype.fetch.call(this, this.fetchController.extendModelOptions(options));
},
});
}); | {
"content_hash": "bf471dc6ec1a3e5a0b7380c12d631ffe",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 95,
"avg_line_length": 24.136363636363637,
"alnum_prop": 0.6854990583804144,
"repo_name": "criel/Backbone-Marionette-With-Require-And-Bootstrap",
"id": "2464653eb841211cdcf4a0ff3bc4c343a814f087",
"size": "533",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/models/GenericCollection.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "119229"
},
{
"name": "JavaScript",
"bytes": "626429"
}
],
"symlink_target": ""
} |
using System.Collections.Generic;
using System.Linq;
using Util.Logs.Abstractions;
namespace Util.Logs.Extensions {
/// <summary>
/// 日志扩展
/// </summary>
public static partial class Extensions {
/// <summary>
/// 设置内容
/// </summary>
/// <param name="log">日志操作</param>
public static ILog Content( this ILog log ) {
return log.Set<ILogContent>( content => content.Content( "" ) );
}
/// <summary>
/// 设置内容
/// </summary>
/// <param name="log">日志操作</param>
/// <param name="value">值</param>
public static ILog Content( this ILog log, string value ) {
return log.Set<ILogContent>( content => content.Content( value ) );
}
/// <summary>
/// 设置内容
/// </summary>
/// <param name="log">日志操作</param>
/// <param name="dictionary">字典</param>
public static ILog Content( this ILog log, IDictionary<string, object> dictionary ) {
if( dictionary == null )
return log;
return Content( log, dictionary.ToDictionary( t => t.Key, t => t.Value.SafeString() ) );
}
/// <summary>
/// 设置内容
/// </summary>
/// <param name="log">日志操作</param>
/// <param name="dictionary">字典</param>
public static ILog Content( this ILog log, IDictionary<string, string> dictionary ) {
if( dictionary == null )
return log;
foreach( var keyValue in dictionary )
log.Set<ILogContent>( content => content.Content( $"{keyValue.Key} : {keyValue.Value}" ) );
return log;
}
}
}
| {
"content_hash": "0066052da17efc626d559e40fd00f712",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 107,
"avg_line_length": 33.372549019607845,
"alnum_prop": 0.5246768507638073,
"repo_name": "yuleyule66/Util",
"id": "ea6c8cb39a271e8efccd778ab355c63c1ba65b51",
"size": "1786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Util/Logs/Extensions/Extensions.Log.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "744850"
},
{
"name": "CoffeeScript",
"bytes": "43"
},
{
"name": "PowerShell",
"bytes": "5766"
},
{
"name": "Shell",
"bytes": "94"
}
],
"symlink_target": ""
} |
@interface WFDisplayPage: NSObject <NSCopying>
{
NSString* _key;
BOOL hidden;
NSArray* elements;
NSString* comment;
@private
NSMutableArray* mutableElements;
uint8_t _binaryKey;
NSMutableArray* errors;
}
// Key used to identify the page. This value must be unique to all other pages.
@property (nonatomic, copy) NSString* key;
// Sets if the page is hidden from normal page toggling function. Page can be manually shown via the API.
@property (nonatomic, assign, getter = isHidden) BOOL hidden;
// Array of dictionaries representing elements.
@property (nonatomic, readonly) NSArray* elements;
// String that can be used to store anything you want, not used internally
@property (nonatomic, copy) NSString* comment;
// Add element tot the display page
- (void) addElement:(WFDisplayElement*) element;
- (void) removeElement:(WFDisplayElement*) element;
- (void) removeAllElements;
@end | {
"content_hash": "6dfddfe31d71b222d86ea42ebfe45616",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 105,
"avg_line_length": 29.93548387096774,
"alnum_prop": 0.7359913793103449,
"repo_name": "simonmaddox/Hearty",
"id": "5d1b1b9380309e68c19a65d5cb168d1d324d88f9",
"size": "1139",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "WFConnector.framework/Versions/A/Headers/WFDisplayPage.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "93141"
},
{
"name": "C++",
"bytes": "143678"
},
{
"name": "Objective-C",
"bytes": "312037"
},
{
"name": "Ruby",
"bytes": "74"
}
],
"symlink_target": ""
} |
import time
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal as sig
from scipy.ndimage import filters
from ..utils import arrays as ar
from ..utils import subseq as sub
from ..viz import viz_utils as viz
from motif import nonOverlappingMaxima, findMotifOfLengthFast
from misc import windowScoresRandWalk
from ff3 import maxSubarray
from ff8 import buildFeatureMat, extendSeq, preprocessFeatureMat
# from ff5 import embedExamples
# from ff6 import vectorizeWindowLocs
# DEFAULT_SEEDS_ALGO = 'all'
# DEFAULT_SEEDS_ALGO = 'pair'
DEFAULT_SEEDS_ALGO = 'walk'
DEFAULT_GENERALIZE_ALGO = 'map'
# DEFAULT_GENERALIZE_ALGO = 'avg'
# DEFAULT_GENERALIZE_ALGO = 'submodular'
DEFAULT_EXTRACT_LOCS_ALGO = 'map'
def dotProdsWithAllWindows(x, X):
"""Slide x along the columns of X and compute the dot product
>>> x = np.array([[1, 1], [2, 2]])
>>> X = np.arange(12).reshape((2, -1))
>>> dotProdsWithAllWindows(x, X) # doctest: +NORMALIZE_WHITESPACE
array([27, 33, 39, 45, 51])
"""
return sig.correlate2d(X, x, mode='valid').flatten()
def localMaxFilterRows(X, allowEq=True):
idxs = ar.idxsOfRelativeExtrema(X, maxima=True, allowEq=allowEq, axis=1)
maximaOnly = np.zeros(X.shape)
maximaOnly[idxs] = X[idxs]
return maximaOnly
def filterRows(X, filtLength, filtType='hamming', scaleFilterMethod='max1'):
if filtType == 'hamming':
filt = np.hamming(filtLength)
elif filtType == 'flat':
filt = np.ones(filtLength)
else:
raise RuntimeError("Unknown/unsupported filter type {}".format(filtType))
if scaleFilterMethod == 'max1':
filt /= np.max(filt)
elif scaleFilterMethod == 'sum1':
filt /= np.sum(filt)
return filters.convolve1d(X, weights=filt, axis=1, mode='constant')
def findAllInstancesSubmodular(X, Xblur, seedStartIdx, seedEndIdx, Lmin, Lmax,
Lfilt, p0=-1, dotProds=None, bsfScore=0, **sink):
if seedStartIdx < 0:
print("WARNING: findAllInstancesAvgBlur(); received invalid"
"start idx {}".format(seedStartIdx))
if seedEndIdx > Xblur.shape[1]:
print("WARNING: findAllInstancesAvgBlur(); received invalid"
"end idx {}".format(seedEndIdx))
# Version where we look for similarities to orig seq and use nearest
# enemy dist as M0, and use mean values instead of intersection
# ------------------------ derived stats
kMax = int(X.shape[1] / Lmin + .5)
windowLen = seedEndIdx - seedStartIdx # assume end idx not inclusive
if p0 < 0.:
p0 = np.mean(X) # fraction of entries that are 1 (roughly)
# p0 = np.mean(X > 0.) # fraction of entries that are 1 # TODO try this
# p0 = 2 * np.mean(X > 0.) # lambda for l0 reg based on features being bernoulli at 2 locs
minSim = p0
expectedOnesPerWindow = p0 * X.shape[0] * windowLen
noiseSz = p0 * expectedOnesPerWindow # num ones to begin with
# ------------------------ candidate location generation
# print "X shape, Xblur shape, windowLen", X.shape, Xblur.shape, windowLen
x0 = X[:, seedStartIdx:seedEndIdx]
if (dotProds is None) or (not len(dotProds)):
dotProds = dotProdsWithAllWindows(x0, Xblur)
# else:
# print "received dot prods with shape", dotProds.shape
# trueDotProds = dotProdsWithAllWindows(x0, Xblur)
# print "true dot prods shape", trueDotProds.shape
# dotProds[dotProds < noiseSz] = 0. # don't even consider places worse than noise
# dotProds -= noiseSz
# compute best locations to try and then sort them in decreasing order
# bestIdxs = nonOverlappingMaxima(dotProds, Lmin)
bestIdxs = sub.optimalAlignment(dotProds, Lmin) # wow, this makes a big difference
bestProds = dotProds[bestIdxs]
# keepIdxs = np.where(bestProds > noiseSz)[0]
# bestIdxs = bestIdxs[keepIdxs]
# bestProds = bestProds[keepIdxs]
sortIdxs = np.argsort(bestProds)[::-1]
sortedIdxs = bestIdxs[sortIdxs]
# ------------------------ lurn stuff
bsfLocs = None
bsfFilt = None
if np.sum(x0 * x0) * kMax <= bsfScore: # highest score is kMax identical locs
return -1, bsfLocs, bsfFilt
# best combination of idxs such that none are within Lmin of each other
# row = windowSims[i]
# idxs = sub.optimalAlignment(dotProds, Lmin)
# iteratively intersect with another near neighbor, compute the
# associated score, and check if it's better (or if we can early abandon)
intersection = x0
numIdxs = len(sortedIdxs)
nextSz = np.sum(intersection)
nextFilt = np.array(intersection, dtype=np.float)
nextFiltSum = np.array(nextFilt, dtype=np.float)
for j, idx in enumerate(sortedIdxs):
k = j + 1
filt = np.copy(nextFilt)
sz = nextSz
if k < numIdxs:
nextIdx = sortedIdxs[k] # since k = j+1
nextWindow = Xblur[:, nextIdx:nextIdx+windowLen]
nextIntersection = np.minimum(filt, nextWindow)
nextFiltSum += nextIntersection
nextFilt = nextFiltSum / (k+1) # avg value of each feature in intersections
# bigEnoughIntersection = nextIntersection[nextIntersection > minSim] # TODO was this
bigEnoughIntersection = nextFilt[nextFilt > minSim]
nextSz = np.sum(bigEnoughIntersection)
else:
nextSz = sz * p0
enemySz = max(nextSz, noiseSz)
score = (sz - enemySz) * k
if k > 1 and score > bsfScore:
bsfScore = score
bsfLocs = sortedIdxs[:k]
bsfFilt = np.copy(filt)
print("seed {}, k={}, score={}, locs={} is the new best!".format(
seedStartIdx, k, score, bsfLocs))
print("------------------------")
# early abandon if this can't possibly beat the best score, which
# is the case exactly when the intersection is so small that perfect
# matches at all future locations still wouldn't be good enough
elif sz * numIdxs <= bsfScore:
break
elif noiseSz > nextSz:
break
return bsfScore, bsfLocs, bsfFilt
def findAllInstancesAvgBlur(X, Xblur, seedStartIdx, seedEndIdx, Lmin, Lmax, Lfilt,
p0=-1, p0blur=-1, bsfScore=0, **sink):
if seedStartIdx < 0:
print("WARNING: findAllInstancesAvgBlur(); received invalid "
"start idx {}".format(seedStartIdx))
if seedEndIdx > Xblur.shape[1]:
print("WARNING: findAllInstancesAvgBlur(); received invalid "
"end idx {}".format(seedEndIdx))
# ------------------------ stats
if p0 <= 0.:
p0 = np.mean(X) # fraction of entries that are 1 (roughly)
if p0blur <= 0.:
p0blur = np.mean(Xblur)
windowLen = seedEndIdx - seedStartIdx # assume end idx not inclusive
# minSim = p0
minSim = p0blur
expectedOnesPerWindow = p0blur * X.shape[0] * windowLen
noiseSz = p0 * expectedOnesPerWindow # num ones to begin with
# ------------------------ candidate location generation
x0 = Xblur[:, seedStartIdx:seedEndIdx]
if np.sum(x0) <= 0.:
return -1, None, None
dotProds = dotProdsWithAllWindows(x0, X)
assert(np.min(dotProds) >= 0.)
# dotProds[dotProds < noiseSz] = 0. # don't even consider places worse than noise
# compute best locations to try and then sort them in decreasing order
# bestIdxs = nonOverlappingMaxima(dotProds, Lmin)
bestIdxs = sub.optimalAlignment(dotProds, Lmin)
if len(bestIdxs) < 2:
plt.figure()
plt.plot(dotProds)
plt.show()
import sys
sys.exit(1)
bestProds = dotProds[bestIdxs]
# keepIdxs = np.where(bestProds > noiseSz)[0]
# bestIdxs = bestIdxs[keepIdxs]
# bestProds = bestProds[keepIdxs]
sortIdxs = np.argsort(bestProds)[::-1]
idxs = bestIdxs[sortIdxs]
# precompute sizes of data at locations so we can early abandon
# we define remainingSizes[i] = sum(windowSizes[i:])
# TODO uncomment to see if this bound actually helps anything
# windows = [Xblur[:, idx:idx+windowLen] for idx in idxs]
# windowSizes = np.array([np.sum(window) for window in windows])
# remainingSizes = np.cumsum(windowSizes[::-1])[::-1]
# remainingSizes = np.r[remainingSizes, 0]
# ------------------------ now figure out which idxs should be instances
# avg together the 2 best windows
idx1, idx2 = idxs[:2]
window1blur = Xblur[:, idx1:idx1+windowLen]
window2blur = Xblur[:, idx2:idx2+windowLen]
filtSums = window1blur + window2blur
filt = filtSums / 2.
filtSz = np.sum(filt[filt > minSim])
# maxima = ar.localMaxFilterRows(filtBlurSums, allowEq=True)
# plt.figure()
# viz.imshowBetter(filt)
# plt.show()
# TODO remove
return filtSz, idxs[:2], filt
if filtSz <= noiseSz: # if best pair worse than noise, just return
print "best pair at seed {} worse than noise!".format(seedStartIdx)
return -1, None, None
# print "seed {}: checking candidate idxs {}".format(seedStartIdx, idxs)
bsfLocs = [0]
bsfFilt = filt
bestScore = -1
nextFiltSums = filtSums
nextFilt = np.copy(filt)
nextFiltSz = filtSz
idxs = np.append(idxs, -1) # dummy idx so everything can go in the loop
k = 1
for i, idx in enumerate(idxs[2:]): # for every next idx
# if filtSz > noiseSz: # TODO see if skipping bad stuff helps
k += 1
filtSums = nextFiltSums
filt = np.copy(nextFilt)
filtSz = nextFiltSz
if idx >= 0: # ignore final dummy idx
# compute how big next filter will be; if basically the
# same size, there's probably another instance--we're looking
# for a big gap here
nextWindow = Xblur[:, idx:idx+windowLen]
nextFiltSums = filtSums + nextWindow
nextFilt = nextFiltSums / (k + 1)
nextFiltSz = np.sum(nextFilt[nextFilt > minSim])
enemySz = max(noiseSz, nextFiltSz)
else:
enemySz = noiseSz
score = (filtSz - enemySz) * k
if score > bestScore: # should we include filt as an instance?
bestScore = score
bsfLocs = idxs[:k]
bsfFilt = np.copy(filt)
if score > bsfScore:
print("seed {}, k={}, score={}, locs={} is the new best!".format(
seedStartIdx, k, score, bsfLocs))
# print("------------------------")
# elif filtSz + remainingSizes[k] <= bsfScore: # TODO check if abandoning helps
# break
elif nextFiltSz <= noiseSz:
break
if len(bsfLocs) >= 2 and bestScore > bsfScore:
return bestScore, bsfLocs, bsfFilt * (bsfFilt > minSim)
return -1, None, None
# # try re-computing dot prods using this avg to get better idxs
# # TODO does this help?
# dotProds = sig.correlate2d(X, x0, mode='valid')
# # compute best locations to try and sort them in decreasing order
# bestIdxs = nonOverlappingMinima(dotProds, Lmin)
# bestProds = dotProds[bestIdxs]
# sortIdxs = np.argsort(bestProds)[::-1]
# idxs = bestIdxs[sortIdxs]
def findAllInstancesMAP(X, Xblur, seedStartIdx, seedEndIdx, Lmin, Lmax, Lfilt,
p0=-1, p0blur=-1, logs_0=None, bsfScore=0, **sink):
assert(np.min(X) >= 0.)
assert(np.max(X) <= 1.)
assert(np.min(Xblur) >= 0.)
assert(np.max(Xblur) <= 1.)
assert(np.all(np.sum(X, axis=1) > 0))
assert(np.all(np.sum(Xblur, axis=1) > 0))
# ================================ variable initialization
windowLen = seedEndIdx - seedStartIdx # assume end idx not inclusive
if p0 <= 0.:
p0 = np.mean(X) # fraction of entries that are 1 (roughly)
if p0blur <= 0.:
p0blur = np.mean(Xblur)
if logs_0 is None:
# theta_0 = np.zeros(windowShape) + p0blur
featureMeans = np.mean(Xblur, axis=1, keepdims=True)
# featureSums = np.sum(Xblur, axis=1, keepdims=True) + 1. # regularize
# featureMeans = featureSums / X.shape[1]
theta_0 = np.ones((Xblur.shape[0], windowLen)) * featureMeans
logs_0 = np.log(theta_0)
lamda = 0
# ================================ candidate location generation
x0 = Xblur[:, seedStartIdx:seedEndIdx]
if np.sum(x0) <= 0.:
print "map() {}-{}: empty".format(seedStartIdx, seedEndIdx)
return -1, None, None
dotProds = dotProdsWithAllWindows(x0, X)
# compute best locations to try and then sort them in decreasing order
bestIdxs = nonOverlappingMaxima(dotProds, Lmin)
bestProds = dotProds[bestIdxs]
sortIdxs = np.argsort(bestProds)[::-1]
idxs = bestIdxs[sortIdxs]
# ================================ now figure out which idxs should be instances
# initialize counts
idx = idxs[0]
counts = np.copy(X[:, idx:idx+windowLen])
countsBlur = np.copy(Xblur[:, idx:idx+windowLen])
bestOdds = -np.inf
bestFilt = None
bestLocs = None
for i, idx in enumerate(idxs[1:]):
k = i + 2.
# update counts
window = X[:, idx:idx+windowLen]
windowBlur = Xblur[:, idx:idx+windowLen]
counts += window
countsBlur += windowBlur
# our params
theta_1 = countsBlur / k
logs_1 = np.log(theta_1)
logs_1[np.isneginf(logs_1)] = -999 # any non-inf number--will be masked by counts
logDiffs = (logs_1 - logs_0)
gains = counts * logDiffs # *must* use this so -999 is masked
threshMask = gains > lamda
# threshMask = logDiffs > 0
threshMask *= theta_1 > .5
# threshMask = theta_1 > .5
# gains += (k - counts) * (logs_1c - logs_0c)
filt = logDiffs * threshMask
logOdds = np.sum(counts * filt)
randomOdds = np.sum(filt) * p0blur * k
nextWindowOdds = -np.inf
if k < len(idxs):
idx = idxs[k]
nextWindow = X[:, idx:idx+windowLen]
# nextWindowOdds = np.sum(filt * nextWindow)
nextWindowOdds = np.sum(filt * nextWindow) * k
penalty = max(randomOdds, nextWindowOdds)
logOdds -= penalty
if logOdds > bestOdds:
bestOdds = logOdds
bestFilt = np.copy(filt)
bestLocs = idxs[:k]
# print("k={}; log odds {}".format(k, logOdds))
# print "map() {}: odds, locs {} {}".format(seedStartIdx, bestOdds, len(bestLocs))
return bestOdds, bestLocs, bestFilt
# this just got too cluttered...
def old_findAllInstancesMAP(X, Xblur, seedStartIdx, seedEndIdx, Lmin, Lmax, Lfilt,
p0=-1, p0blur=-1, logs_0=None, bsfScore=0, **sink):
# print "map(): X, Xblur shape", X.shape, Xblur.shape
# ------------------------ stats
windowLen = seedEndIdx - seedStartIdx # assume end idx not inclusive
if p0 <= 0.:
p0 = np.mean(X) # fraction of entries that are 1 (roughly)
if p0blur <= 0.:
p0blur = np.mean(Xblur)
p0blur *= 2
if logs_0 is None:
# featureMeans = np.mean(Xblur, axis=1).reshape((-1, 1))
# featureMeans = np.mean(Xblur, axis=1).reshape((-1, 1)) * 2
# theta_0 = np.ones((Xblur.shape[0], windowLen)) * featureMeans
theta_0 = np.zeros((Xblur.shape[0], windowLen)) + p0blur
# theta_0 = np.zeros((Xblur.shape[0], windowLen)) + 2 * p0blur
theta_0c = 1. - theta_0
logs_0 = np.log(theta_0)
logs_0c = np.log(theta_0c)
# logs_0 = np.zeros((Xblur.shape[0], windowLen)) + np.log(p0blur) # overzealous
# logs_0c = np.zeros((Xblur.shape[0], windowLen)) + np.log(1. - p0blur)
# logs_0 = np.zeros((Xblur.shape[0], windowLen)) + np.log(p0) # works
# print "logs_0 nan at:", np.where(np.isnan(logs_0))[0]
# lamda = -2 * np.log(p0blur) - .001 # just below what we get with 2 instances
# lamda = -np.log(p0blur) - .001 # actually, including log(theta_0), should be this
lamda = 0
# print "lambda", lamda
# minSim = p0
# expectedOnesPerWindow = p0blur * X.shape[0] * windowLen
# noiseSz = p0blur * expectedOnesPerWindow # num ones to begin with
# ------------------------ candidate location generation
x0 = Xblur[:, seedStartIdx:seedEndIdx]
if np.sum(x0) <= 0.:
print "map() {}-{}: empty".format(seedStartIdx, seedEndIdx)
return -1, None, None
# dotProds = dotProdsWithAllWindows(x0, X)
dotProds = dotProdsWithAllWindows(x0, Xblur)
# assert(np.min(dotProds) >= 0.)
# dotProds[dotProds < noiseSz] = 0. # don't even consider places worse than noise
# compute best locations to try and then sort them in decreasing order
bestIdxs = nonOverlappingMaxima(dotProds, Lmin)
# bestIdxs = sub.optimalAlignment(dotProds, Lmin)
bestProds = dotProds[bestIdxs]
# keepIdxs = np.where(bestProds > noiseSz)[0]
# bestIdxs = bestIdxs[keepIdxs]
# bestProds = bestProds[keepIdxs]
sortIdxs = np.argsort(bestProds)[::-1]
idxs = bestIdxs[sortIdxs]
# ------------------------ now figure out which idxs should be instances
# avg together the 2 best windows and compute the score
idx1, idx2 = idxs[:2]
window1 = X[:, idx1:idx1+windowLen]
window2 = X[:, idx2:idx2+windowLen]
counts = window1 + window2
window1blur = Xblur[:, idx1:idx1+windowLen]
window2blur = Xblur[:, idx2:idx2+windowLen]
countsBlur = window1blur + window2blur
# compute best pair filter compared to noise
k = 2.
theta_1 = countsBlur / k
# logs_1 = np.zeros(theta_1.shape)
logs_1 = np.log(theta_1)
logs_1[np.isneginf(logs_1)] = -99999. # big negative num
# logs_1c = np.log(1. - theta_1)
# logs_1c[np.isneginf(logs_1c)] = -99999.
# gains = k * (logs_1 - logs_0) - lamda
# gains = counts * (logs_1 - logs_0) - lamda
# filt = gains * (gains > 0)
# logOdds = np.sum(filt)
logDiffs = (logs_1 - logs_0)
gains = counts * logDiffs
threshMask = gains > lamda
# gains += (k - counts) * (logs_1c - logs_0c)
filt = logDiffs * threshMask
# logOdds = np.sum(filt) - lamda * np.count_nonzero(filt)
# logOdds = np.sum(filt)
# subtract1 = np.minimum(window1, theta_1)
# subtract2 = np.minimum(window1, theta_1)
# subtracts = [subtract1, subtract2]
# for idx, subVal in zip(idxs[:2], subtracts):
# Xblur[:, idx:idx+windowLen] -= subVal
# # compute best pair filter compared to nearest enemy
# if len(idxs) > 2:
# idx = idxs[k]
# nextWindow = Xblur[:, idx:idx+windowLen]
# # theta_e = nextWindow
# theta_e = np.maximum(nextWindow, theta_0)
# logs_e = np.log(theta_e)
# logs_e[np.isneginf(logs_e)] = -99999.
# # logs_ec = np.log(1. - theta_e)
# # logs_ec[np.isneginf(logs_ec)] = -99999.
# gains_e = counts * (logs_1 - logs_e)
# # gains_e = nextWindow * (logs_1 - logs_e)
# filt_e = gains * (gains_e > lamda)
# # logOdds_e = np.sum(filt_e) - lamda * np.count_nonzero(filt_e)
# logOdds_e = np.sum(filt_e)
# # if logOdds_e < logOdds:
# if True:
# # print("k=2; enemy log odds {} < noise log odds {}".format(
# # logOdds_e, logOdds))
# logOdds = logOdds_e
# logOdds = np.sum(filt * window1) - lamda * np.count_nonzero(filt)
# logOdds = np.sum(filt * window1)
logOdds = np.sum(filt * X[:, idx1:idx1+windowLen])
# compute best pair filter compared to nearest enemy
if k < len(idxs):
idx = idxs[k]
# nextWindow = Xblur[:, idx:idx+windowLen]
nextWindow = X[:, idx:idx+windowLen]
nextWindowOdds = np.sum(filt * nextWindow)
# nextWindowOdds -= lamda * np.count_nonzero(filt)
logOdds -= nextWindowOdds
# logOdds = np.sum(filt * counts) - lamda * np.count_nonzero(filt)
# # compute best pair filter compared to nearest enemy
# if k < len(idxs):
# idx = idxs[k]
# nextWindowBlur = Xblur[idx:idx+windowLen]
# theta_e = nextWindowBlur
# logs_e = np.log(theta_e)
# logs_e[np.isneginf(logs_e)] = -99999.
# filt = logs_e
# # logDiffs = (logs_1 - logs_0)
# # gains = counts * logDiffs
# # threshMask = gains > lamda
# # # gains += (k - counts) * (logs_1c - logs_0c)
# # filt = logDiffs * threshMask
# gains_e =
# logOdds_e =
# if np.mean(x0) > (p0blur * 2):
# fig, axes = plt.subplots(2, 5, figsize=(10,8))
# axes = axes.flatten()
# plt.suptitle("{}-{}".format(idx1, idx2))
# axes[0]
# viz.imshowBetter(window1, ax=axes[0])
# viz.imshowBetter(window2, ax=axes[1])
# viz.imshowBetter(counts, ax=axes[2])
# viz.imshowBetter(gains, ax=axes[3])
# viz.imshowBetter(filt, ax=axes[4])
# axes[4].set_title("{}".format(logOdds))
# viz.imshowBetter(X[:, idx1:idx1+windowLen], ax=axes[5])
# viz.imshowBetter(X[:, idx2:idx2+windowLen], ax=axes[6])
bestOdds = logOdds
bestFilt = filt
bestLocs = idxs[:2]
# print "map() {} -> {} {}:".format(seedStartIdx, idx1, idx2), logOdds, bestLocs
# print "map() {}: k=2, total prob: {}".format(seedStartIdx, np.sum(theta_1))
# return logOdds, bestLocs, bestFilt # TODO remove after debug
# Alright, so what I want the right answer to be is the biggest patch
# of black I can get, subtracting off the next-biggest patch of black
# (weighting each by the filter or something)
# -so maybe that's the log odds of the Nth loc - the log odds of the Nth loc
# -and note that these are log odds *of the loc being an instance*, not
# the log odds of the filter as a whole
# -although pretty sure there's some formulation of filter log odds
# such that these are equivalent--it just isn't my current logOdds var
# Xblur = np.copy(Xblur)
# Xblur[:, idx1:idx1+windowLen] = np.maximum(0, Xblur[:, idx1:idx1+windowLen] - theta_1)
# Xblur[:, idx2:idxs2+windowLen] = np.maximum(0, Xblur[:, idx2:idx2+windowLen] - theta_1)
# try adding the rest of the idxs
for i, idx in enumerate(idxs[2:]):
k += 1
window = Xblur[:, idx:idx+windowLen]
# filter and odds vs noise
counts += window
theta_1 = counts / k
logs_1 = np.log(theta_1)
logs_1[np.isneginf(logs_1)] = -99999. # big negative num
# logs_1c = np.log(1. - theta_1)
# logs_1c[np.isneginf(logs_1c)] = -99999.
# gains = k * (logs_1 - logs_0) - lamda
# gains = counts * (logs_1 - logs_0) - lamda
# filt = gains * (gains > 0)
# logOdds = np.sum(filt)
logDiffs = (logs_1 - logs_0)
threshMask = gains > lamda
# gains += (k - counts) * (logs_1c - logs_0c)
filt = logDiffs * threshMask
# logOdds = np.sum(filt) - lamda * np.count_nonzero(filt)
# logOdds = np.sum(filt)
# logOdds = np.sum(filt * window) - lamda * np.count_nonzero(filt)
# logOdds = np.sum(filt * window)
logOdds = np.sum(filt * X[:, idx:idx+windowLen])
# compute best pair filter compared to nearest enemy
# randomOdds = np.sum(filt) # Wait, was this even intentional
randomOdds = np.sum(filt) * p0blur
nextWindowOdds = 0
if k < len(idxs):
idx = idxs[k]
# nextWindow = Xblur[:, idx:idx+windowLen]
nextWindow = X[:, idx:idx+windowLen]
nextWindowOdds = np.sum(filt * nextWindow)
# nextWindowOdds -= lamda * np.count_nonzero(filt)
# logOdds -= nextWindowOdds
penalty = max(randomOdds, nextWindowOdds)
logOdds -= penalty
# subtract = np.minimum(window, theta_1)
# subtracts.append(subtract)
# Xblur[:, idx:idx+windowLen] -= subtract
# # filter and odds vs nearest enemy
# if k < len(idxs):
# idx = idxs[k]
# nextWindow = Xblur[:, idx:idx+windowLen]
# # theta_e = nextWindow
# theta_e = np.maximum(nextWindow, theta_0)
# logs_e = np.log(theta_e)
# logs_e[np.isneginf(logs_e)] = -99999.
# # logs_ec = np.log(1. - theta_e)
# # logs_ec[np.isneginf(logs_ec)] = -99999.
# gains_e = counts * (logs_1 - logs_e)
# # gains_e = nextWindow * (logs_1 - logs_e)
# # gains_e += (k - counts) * (logs_1c - logs_ec)
# filt_e = gains * (gains_e > lamda)
# # logOdds_e = np.sum(filt_e) - lamda * np.count_nonzero(filt_e)
# logOdds_e = np.sum(filt_e)
# # logOdds = min(logOdds, logOdds_e)
# # if logOdds_e < logOdds:
# if True:
# # print("k={}; enemy log odds {} < noise log odds {}".format(
# # k, logOdds_e, logOdds))
# logOdds = logOdds_e
# Xblur[:, idx:idx+windowLen] = np.maximum(0, Xblur[:, idx:idx+windowLen] - theta_1)
# print "map() {}: k={}, total prob: {}".format(seedStartIdx, k, np.sum(theta_1))
if logOdds > bestOdds:
bestOdds = logOdds
bestFilt = np.copy(filt)
bestLocs = idxs[:k]
# print("k={}; log odds {}".format(k, logOdds))
# print "map() {}: odds, locs {} {}".format(seedStartIdx, bestOdds, len(bestLocs))
# for idx, subVal in zip(idxs[:len(subtracts)], subtracts):
# Xblur[:, idx:idx+windowLen] += subVal
return bestOdds, bestLocs, bestFilt
def findAllInstancesFromSeedLoc(X, Xblur, seedStartIdx, seedEndIdx, Lmin, Lmax,
Lfilt=0, generalizeSeedsAlgo=None, **kwargs):
if generalizeSeedsAlgo == 'submodular':
return findAllInstancesSubmodular(X, Xblur, seedStartIdx, seedEndIdx,
Lmin, Lmax, Lfilt, **kwargs)
elif generalizeSeedsAlgo == 'avg':
return findAllInstancesAvgBlur(X, Xblur, seedStartIdx, seedEndIdx,
Lmin, Lmax, Lfilt, **kwargs)
elif generalizeSeedsAlgo == 'map':
return findAllInstancesMAP(X, Xblur, seedStartIdx, seedEndIdx,
Lmin, Lmax, Lfilt, **kwargs)
else:
raise ValueError("instance generalization method "
"{} not recognized".format(generalizeSeedsAlgo))
def findInstancesUsingSeedLocs(X, Xblur, seedStartIdxs, seedEndIdxs, Lmin,
Lmax, Lfilt, windowLen=None, **kwargs):
if (len(seedStartIdxs) != len(seedEndIdxs)) or (not len(seedStartIdxs)):
raise ValueError("must supply same number of start and end indices > 0!"
"Got {} and {}".format(len(seedStartIdxs), len(seedEndIdxs)))
print "findInstancesUsingSeedLocs(): got seedStartIdxs: ", seedStartIdxs
if windowLen <= 0:
windowLen = seedEndIdxs[0] - seedStartIdxs[0]
elif windowLen < Lmax:
raise ValueError("windowLen {} < Lmax {}".format(windowLen, Lmax))
# precompute feature mat stats so that evaluations of each seed
# don't have to duplicate work
p0 = np.mean(X)
p0blur = np.mean(Xblur)
featureMeans = np.mean(Xblur, axis=1, keepdims=True)
theta_0 = np.ones((Xblur.shape[0], windowLen)) * featureMeans
logs_0 = np.log(theta_0)
# hack: if using submodular generalization algo, precompute pairwise
# dot prods of windows using convolution
useSubmodular = kwargs.get('generalizeSeedsAlgo') == 'submodular' and windowLen
# useSubmodular = False # yeah, definitely slower when using all possible seeds
if useSubmodular:
print "computing all windowSims"
colSims = np.dot(X.T, Xblur)
filt = np.zeros((windowLen, windowLen)) + np.diag(np.ones(windowLen)) # zeros except 1s on diag
windowSims = sig.convolve2d(colSims, filt, mode='valid')
print "computed all windowSims"
bsfScore = 0
bsfFilt = None
bsfLocs = None
bsfSeedIdx = -1
for i in range(len(seedStartIdxs)):
startIdx, endIdx = seedStartIdxs[i], seedEndIdxs[i]
# if i % 10 == 0:
# print "trying seed startIdx, endIdx ", startIdx, endIdx
if useSubmodular: # hack to make this run faster for prototyping
kwargs['dotProds'] = windowSims[i]
score, locs, filt = findAllInstancesFromSeedLoc(X, Xblur, startIdx, endIdx,
Lmin, Lmax, Lfilt, p0=p0, p0blur=p0blur, logs_0=logs_0,
bsfScore=bsfScore, **kwargs)
# if i % 10 == 0:
# print "idx {}: got score, locs, filtShape: {} {} {}".format(
# startIdx, score, locs, filt.shape if filt is not None else None)
if score > bsfScore:
bsfScore = score
bsfFilt = np.copy(filt)
bsfLocs = np.copy(locs)
bsfSeedIdx = startIdx
print "findInstancesUsingSeedLocs(): got new best score", bsfScore
print "findInstancesUsingSeedLocs(): got best seed, score", bsfSeedIdx, bsfScore
print "findInstancesUsingSeedLocs(): got best locs ", bsfLocs
# print "findInstancesUsingSeedLocs(): X shape, Xblur shape ", X.shape, Xblur.shape
return bsfScore, bsfLocs, bsfFilt
def extractTrueLocs(X, Xblur, bsfLocs, bsfFilt, windowLen, Lmin, Lmax,
extractTrueLocsAlgo=DEFAULT_EXTRACT_LOCS_ALGO, **sink):
if extractTrueLocsAlgo == 'none':
return bsfLocs, bsfLocs + Lmax
# determine expected value of an element of X (or, alternatively, Xblur)
if extractTrueLocsAlgo == 'x':
p0 = np.mean(X)
else:
p0 = np.mean(Xblur)
if bsfFilt is None:
print "WARNING: extractTrueLocs(): received None as filter"
return np.array([0]), np.array([1])
print "extractTrueLocs(): bsf locs", bsfLocs
print "extractTrueLocs(): bsfFilt shape", bsfFilt.shape
# compute the total filter weight in each column, ignoring low values
bsfFiltWindow = np.copy(bsfFilt)
# minSim = p0
# bsfFiltWindow *= bsfFiltWindow >= minSim
sums = np.sum(bsfFiltWindow, axis=0)
# subtract off the amount of weight that we'd expect in each column by chance
kBest = len(bsfLocs)
expectedOnesFrac = np.power(p0, kBest-1) # this is like 0; basically no point
expectedOnesPerCol = expectedOnesFrac * X.shape[0]
sums -= expectedOnesPerCol
# # at least for a couple msrc examples, these are basically flat--which makes sense
# plt.figure()
# plt.plot(sums)
# plt.plot(np.zeros(len(sums)) + expectedOnesPerCol)
# # from ..utils.misc import nowAsString
# # plt.savefig('/Users/davis/Desktop/ts/figs/msrc/sums-{}.pdf'.format(nowAsString()))
# plt.show()
# plt.close()
# pick the optimal set of indices to maximize the sum of sequential column sums
start, end, _ = maxSubarray(sums)
# ensure we picked at least Lmin points
sumsLength = len(sums)
while end - start < Lmin:
nextStartVal = sums[start-1] if start > 0 else -np.inf
nextEndVal = sums[end] if end < sumsLength else -np.inf
if nextStartVal > nextEndVal:
start -= 1
else:
end += 1
# ensure we picked at most Lmax points
while end - start > Lmax:
if sums[start] > sums[end-1]:
end -= 1
else:
start += 1
locs = np.sort(np.asarray(bsfLocs))
startIdxs = locs + start
endIdxs = locs + end
# # reconcile overlap; we first figure out how much we like the start vs end
# # for different amounts of overlap
# startSums = np.cumsum(sums)
# endSums = np.cumsum(sums[::-1])
# # gaps = startIdxs[1:] - startIdxs[:-1]
# for i in range(len(startIdxs) - 1):
# te1, ts2 = endIdxs[i], startIdxs[i+1]
# gap = ts2 - te1
# if gap > 0:
# continue
# # figure out best amount by which to crop start and end indices
# overlap = -gap + 1
# bestSplitCost = np.inf
# bestMoveStart = -1
# for moveStartThisMuch in range(0, overlap):
# moveEndThisMuch = overlap - moveStartThisMuch
# startCost = startSums[moveStartThisMuch-1] if moveStartThisMuch else 0.
# endCost = endSums[moveEndThisMuch-1] if moveEndThisMuch else 0.
# cost = startCost + endCost
# if cost < bestSplitCost:
# bestSplitCost = cost
# bestMoveStart = moveStartThisMuch
# startIdxs[i+1] += bestMoveStart
# endIdxs[i] -= (overlap - bestMoveStart)
if len(startIdxs) > 2:
lengths = endIdxs - startIdxs
maxInternalLength = np.max(lengths[1:-1])
startIdxs[0] = max(startIdxs[0], endIdxs[0] - maxInternalLength)
endIdxs[-1] = min(endIdxs[-1], startIdxs[-1] + maxInternalLength)
print "extractTrueLocs(): startIdxs, endIdxs", startIdxs, endIdxs
return startIdxs, endIdxs
def computeAllSeedIdxsFromPair(seedIdxs, numShifts, stepLen):
for idx in seedIdxs[:]:
i = idx
j = idx
for shft in range(numShifts):
i -= stepLen
j += stepLen
seedIdxs += [i, j]
seedIdxs = np.unique(seedIdxs)
return seedIdxs
# TODO set algo to 'pair' after debug
def learnFF(seq, X, Xblur, Lmin, Lmax, Lfilt,
generateSeedsAlgo=DEFAULT_SEEDS_ALGO,
generalizeSeedsAlgo=DEFAULT_GENERALIZE_ALGO,
extractTrueLocsAlgo=DEFAULT_EXTRACT_LOCS_ALGO,
generateSeedsStep=.1, padBothSides=True, **generalizeKwargs):
padLen = (len(seq) - X.shape[1]) // 2
if padBothSides:
X = ar.addZeroCols(X, padLen, prepend=True)
X = ar.addZeroCols(X, padLen, prepend=False)
Xblur = ar.addZeroCols(Xblur, padLen, prepend=True)
Xblur = ar.addZeroCols(Xblur, padLen, prepend=False)
tStartSeed = time.clock()
# find seeds; i.e., candidate instance indices from which to generalize
numShifts = int(1. / generateSeedsStep) + 1
stepLen = int(Lmax * generateSeedsStep)
windowLen = Lmax + stepLen
print "learnFF(): stepLen, numShifts", stepLen, numShifts
if generateSeedsAlgo == 'pair':
searchLen = (Lmin + Lmax) // 2
motif = findMotifOfLengthFast([seq], searchLen)
seedIdxs = [motif.idx1, motif.idx2]
print "seedIdxs from motif: ", seedIdxs
seedIdxs = computeAllSeedIdxsFromPair(seedIdxs, numShifts, stepLen)
elif generateSeedsAlgo == 'all':
seedIdxs = np.arange(X.shape[1] - windowLen) # TODO remove after debug
elif generateSeedsAlgo == 'random':
seedIdxs = list(np.random.choice(np.arange(len(seq) - Lmax), 2))
seedIdxs = computeAllSeedIdxsFromPair(seedIdxs, numShifts, stepLen)
elif generateSeedsAlgo == 'walk':
# score all subseqs based on how much they don't look like random walks
# when examined using different sliding window lengths
scores = np.zeros(len(seq))
for dim in range(seq.shape[1]):
# compute these just once, not once per length
dimData = seq[:, dim].ravel()
diffs = dimData[1:] - dimData[:-1]
std = np.std(diffs)
for divideBy in [1, 2, 4, 8]:
partialScores = windowScoresRandWalk(dimData, Lmin // divideBy,
std=std)
scores[:len(partialScores)] += partialScores
# figure out optimal seeds based on scores of all subseqs
bestIdx = np.argmax(scores)
start = max(0, bestIdx - Lmin)
end = min(len(scores), start + Lmin)
scores[start:end] = -1
secondBestIdx = np.argmax(scores)
seedIdxs = [bestIdx, secondBestIdx]
seedIdxs = computeAllSeedIdxsFromPair(seedIdxs, numShifts, stepLen)
else:
raise NotImplementedError("Only algo 'pair' supported to generate seeds"
"; got unrecognized algo {}".format(generateSeedsAlgo))
# compute start and end indices of seeds to try
seedStartIdxs = np.sort(np.array(seedIdxs))
seedStartIdxs = seedStartIdxs[seedStartIdxs >= 0]
seedStartIdxs = seedStartIdxs[seedStartIdxs < X.shape[1] - windowLen]
seedEndIdxs = seedStartIdxs + windowLen
print "learnFF(): seedIdxs after removing invalid idxs: ", seedStartIdxs
print "learnFF(): fraction of idxs used as seeds: {}".format(
len(seedStartIdxs) / float(len(seq)))
tEndSeed = time.clock()
generalizeKwargs['windowLen'] = windowLen # TODO remove after prototype
bsfScore, bsfLocs, bsfFilt = findInstancesUsingSeedLocs(X, Xblur,
seedStartIdxs, seedEndIdxs, Lmin, Lmax, Lfilt,
generalizeSeedsAlgo=generalizeSeedsAlgo,
**generalizeKwargs)
# print "learnFF(): got bsfFilt shape", bsfFilt.shape
startIdxs, endIdxs = extractTrueLocs(X, Xblur, bsfLocs, bsfFilt, windowLen,
Lmin, Lmax, extractTrueLocsAlgo=extractTrueLocsAlgo)
tEndFF = time.clock()
print "learnFF(): seconds to find seeds, locs, total =\n\t{:.3f}\t{:.3f}\t{:.3f}".format(
tEndSeed - tStartSeed, tEndFF - tEndSeed, tEndFF - tStartSeed)
return startIdxs, endIdxs, bsfFilt
def learnFFfromSeq(seq, Lmin, Lmax, Lfilt=0, extendEnds=True, **kwargs):
Lmin = int(len(seq) * Lmin) if Lmin < 1. else Lmin
Lmax = int(len(seq) * Lmax) if Lmax < 1. else Lmax
Lfilt = int(len(seq) * Lfilt) if Lfilt < 1. else Lfilt
if not Lfilt or Lfilt < 0:
Lfilt = Lmin
print "learnFFfromSeq(): seqShape {}; using Lmin, Lmax, Lfilt= {}, {}, {}".format(
seq.shape, Lmin, Lmax, Lfilt)
# extend the first and last values out so that features using
# longer windows are present for more locations (if requested)
padLen = 0
origSeqLen = len(seq)
if extendEnds:
padLen = Lmax # TODO uncomment after debug
# padLen = Lmax - Lfilt # = windowLen
seq = extendSeq(seq, padLen, padLen)
# print "learnFFfromSeq(): extended seq to shape {}".format(seq.shape)
# plt.figure()
# plt.plot(seq)
# print kwargs
X = buildFeatureMat(seq, Lmin, Lmax, **kwargs)
# plt.figure()
# viz.imshowBetter(X)
# plt.figure()
# viz.imshowBetter(Xblur)
X, Xblur = preprocessFeatureMat(X, Lfilt, **kwargs)
if extendEnds: # undo padding after constructing feature matrix
X = X[:, padLen:-padLen]
Xblur = Xblur[:, padLen:-padLen]
seq = seq[padLen:-padLen]
# catch edge case where all nonzeros were in the padding
keepRowIdxs = ar.nonzeroRows(X, thresh=1.)
X = X[keepRowIdxs]
Xblur = Xblur[keepRowIdxs]
assert(np.min(X) >= 0.)
assert(np.max(X) <= 1.)
assert(np.min(Xblur) >= 0.)
assert(np.max(Xblur) <= 1.)
assert(np.all(np.sum(X, axis=1) > 0))
assert(np.all(np.sum(Xblur, axis=1) > 0))
# plt.figure()
# viz.imshowBetter(X)
# plt.figure()
# viz.imshowBetter(Xblur)
# these are identical to ff8's if we use padLen = Lmax - Lfilt
# print "sums:", np.sum(seq), np.sum(X), np.sum(Xblur)
startIdxs, endIdxs, bsfFilt = learnFF(seq, X, Xblur, Lmin, Lmax, Lfilt, **kwargs)
# print "learnFFfromSeq(): got bsfFilt shape", bsfFilt.shape
# account for fact that X is computed based on middle of data
offset = (origSeqLen - X.shape[1]) // 2
print "learnFFfromSeq(): X offset = ", offset
# startIdxs += offset
# endIdxs += offset
# startIdxs -= offset
# endIdxs = offset
return startIdxs, endIdxs, bsfFilt, X, Xblur
if __name__ == '__main__':
from doctest import testmod
testmod()
# x = np.ones((2,2))
# X = np.arange(12).reshape((2, -1))
# print dotProdsWithAllWindows(x, X)
| {
"content_hash": "d60bc004d06f61437208b36d22144931",
"timestamp": "",
"source": "github",
"line_count": 1044,
"max_line_length": 97,
"avg_line_length": 33.86015325670498,
"alnum_prop": 0.6781612446958981,
"repo_name": "dblalock/flock",
"id": "8a15f169ae9683761dc0c9fbc942fd02b3ae21ae",
"size": "35369",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "python/algo/ff10.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Jupyter Notebook",
"bytes": "745112"
},
{
"name": "Python",
"bytes": "753394"
}
],
"symlink_target": ""
} |
from oslo_config import cfg
from oslo_log import log as logging
from nova.i18n import _LW
from nova.scheduler import filters
from nova.scheduler.filters import utils
LOG = logging.getLogger(__name__)
disk_allocation_ratio_opt = cfg.FloatOpt("disk_allocation_ratio", default=1.0,
help="Virtual disk to physical disk allocation ratio")
CONF = cfg.CONF
CONF.register_opt(disk_allocation_ratio_opt)
class DiskFilter(filters.BaseHostFilter):
"""Disk Filter with over subscription flag."""
def _get_disk_allocation_ratio(self, host_state, filter_properties):
return CONF.disk_allocation_ratio
@filters.compat_legacy_props
def host_passes(self, host_state, filter_properties):
"""Filter based on disk usage."""
instance_type = filter_properties.get('instance_type')
requested_disk = (1024 * (instance_type['root_gb'] +
instance_type['ephemeral_gb']) +
instance_type['swap'])
free_disk_mb = host_state.free_disk_mb
total_usable_disk_mb = host_state.total_usable_disk_gb * 1024
disk_allocation_ratio = self._get_disk_allocation_ratio(
host_state, filter_properties)
disk_mb_limit = total_usable_disk_mb * disk_allocation_ratio
used_disk_mb = total_usable_disk_mb - free_disk_mb
usable_disk_mb = disk_mb_limit - used_disk_mb
if not usable_disk_mb >= requested_disk:
LOG.debug("%(host_state)s does not have %(requested_disk)s MB "
"usable disk, it only has %(usable_disk_mb)s MB usable "
"disk.", {'host_state': host_state,
'requested_disk': requested_disk,
'usable_disk_mb': usable_disk_mb})
return False
disk_gb_limit = disk_mb_limit / 1024
host_state.limits['disk_gb'] = disk_gb_limit
return True
class AggregateDiskFilter(DiskFilter):
"""AggregateDiskFilter with per-aggregate disk allocation ratio flag.
Fall back to global disk_allocation_ratio if no per-aggregate setting
found.
"""
def _get_disk_allocation_ratio(self, host_state, filter_properties):
aggregate_vals = utils.aggregate_values_from_key(
host_state,
'disk_allocation_ratio')
try:
ratio = utils.validate_num_values(
aggregate_vals, CONF.disk_allocation_ratio, cast_to=float)
except ValueError as e:
LOG.warning(_LW("Could not decode disk_allocation_ratio: '%s'"), e)
ratio = CONF.disk_allocation_ratio
return ratio
| {
"content_hash": "0bdc9fd6b357c63707396db831a5a804",
"timestamp": "",
"source": "github",
"line_count": 72,
"max_line_length": 79,
"avg_line_length": 37.06944444444444,
"alnum_prop": 0.6215811165230424,
"repo_name": "devendermishrajio/nova",
"id": "e623616733a0c02aa6c64826b8c12f0aeeb64e6d",
"size": "3309",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "nova/scheduler/filters/disk_filter.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "16836881"
},
{
"name": "Shell",
"bytes": "24210"
},
{
"name": "Smarty",
"bytes": "351433"
}
],
"symlink_target": ""
} |
<?php
declare(strict_types=1);
namespace spec\Sylius\Bundle\ApiBundle\Validator\Constraints;
use PhpSpec\ObjectBehavior;
use Sylius\Bundle\ApiBundle\Command\Checkout\CompleteOrder;
use Sylius\Bundle\ApiBundle\Command\Checkout\UpdateCart;
use Sylius\Bundle\ApiBundle\Validator\Constraints\CorrectOrderAddress;
use Sylius\Component\Addressing\Model\CountryInterface;
use Sylius\Component\Core\Model\AddressInterface;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\Context\ExecutionContextInterface;
final class CorrectOrderAddressValidatorSpec extends ObjectBehavior
{
function let(RepositoryInterface $countryRepository): void
{
$this->beConstructedWith($countryRepository);
}
function it_is_a_constraint_validator(): void
{
$this->shouldImplement(ConstraintValidatorInterface::class);
}
function it_throws_an_exception_if_value_is_not_an_instance_of_address_order_command(): void
{
$this
->shouldThrow(\InvalidArgumentException::class)
->during('validate', [new CompleteOrder(), new CorrectOrderAddress()])
;
}
function it_throws_an_exception_if_constraint_is_not_an_instance_of_adding_eligible_product_variant_to_cart(
AddressInterface $billingAddress,
AddressInterface $shippingAddress,
): void {
$this
->shouldThrow(\InvalidArgumentException::class)
->during('validate', [
new UpdateCart('john@doe.com', $billingAddress->getWrappedObject(), $shippingAddress->getWrappedObject()),
new class() extends Constraint {
},
])
;
}
function it_adds_violation_if_billing_address_has_incorrect_country_code(
ExecutionContextInterface $executionContext,
AddressInterface $billingAddress,
): void {
$this->initialize($executionContext);
$billingAddress->getCountryCode()->willReturn('united_russia');
$executionContext
->addViolation('sylius.country.not_exist', ['%countryCode%' => 'united_russia'])
->shouldBeCalled()
;
$this->validate(
new UpdateCart('john@doe.com', $billingAddress->getWrappedObject()),
new CorrectOrderAddress(),
);
}
function it_adds_violation_if_billing_address_has_not_country_code(
ExecutionContextInterface $executionContext,
AddressInterface $billingAddress,
): void {
$this->initialize($executionContext);
$billingAddress->getCountryCode()->willReturn(null);
$executionContext
->addViolation('sylius.address.without_country')
->shouldBeCalled()
;
$this->validate(
new UpdateCart('john@doe.com', $billingAddress->getWrappedObject()),
new CorrectOrderAddress(),
);
}
function it_adds_violation_if_shipping_address_has_incorrect_country_code(
RepositoryInterface $countryRepository,
ExecutionContextInterface $executionContext,
AddressInterface $billingAddress,
AddressInterface $shippingAddress,
CountryInterface $usa,
): void {
$this->initialize($executionContext);
$billingAddress->getCountryCode()->willReturn('US');
$shippingAddress->getCountryCode()->willReturn('united_russia');
$countryRepository->findOneBy(['code' => 'US'])->willReturn($usa);
$countryRepository->findOneBy(['code' => 'united_russia'])->willReturn(null);
$executionContext
->addViolation('sylius.country.not_exist', ['%countryCode%' => 'united_russia'])
->shouldBeCalled()
;
$this->validate(
new UpdateCart('john@doe.com', $billingAddress->getWrappedObject(), $shippingAddress->getWrappedObject()),
new CorrectOrderAddress(),
);
}
function it_adds_violation_if_shipping_address_and_billing_address_have_incorrect_country_code(
RepositoryInterface $countryRepository,
ExecutionContextInterface $executionContext,
AddressInterface $billingAddress,
AddressInterface $shippingAddress,
): void {
$this->initialize($executionContext);
$billingAddress->getCountryCode()->willReturn('euroland');
$shippingAddress->getCountryCode()->willReturn('united_russia');
$countryRepository->findOneBy(['code' => 'euroland'])->willReturn(null);
$countryRepository->findOneBy(['code' => 'united_russia'])->willReturn(null);
$executionContext
->addViolation('sylius.country.not_exist', ['%countryCode%' => 'euroland'])
->shouldBeCalled()
;
$executionContext
->addViolation('sylius.country.not_exist', ['%countryCode%' => 'united_russia'])
->shouldBeCalled()
;
$this->validate(
new UpdateCart('john@doe.com', $billingAddress->getWrappedObject(), $shippingAddress->getWrappedObject()),
new CorrectOrderAddress(),
);
}
}
| {
"content_hash": "3023f949e65efc60362245257f02fedc",
"timestamp": "",
"source": "github",
"line_count": 147,
"max_line_length": 122,
"avg_line_length": 35.46258503401361,
"alnum_prop": 0.6598887396892384,
"repo_name": "Sylius/Sylius",
"id": "c7451e0d5c158cd50092554d20c48eabf03028c0",
"size": "5424",
"binary": false,
"copies": "2",
"ref": "refs/heads/1.13",
"path": "src/Sylius/Bundle/ApiBundle/spec/Validator/Constraints/CorrectOrderAddressValidatorSpec.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Dockerfile",
"bytes": "674"
},
{
"name": "Gherkin",
"bytes": "1269548"
},
{
"name": "JavaScript",
"bytes": "102771"
},
{
"name": "Makefile",
"bytes": "1478"
},
{
"name": "PHP",
"bytes": "8145147"
},
{
"name": "SCSS",
"bytes": "53880"
},
{
"name": "Shell",
"bytes": "11411"
},
{
"name": "Twig",
"bytes": "446530"
}
],
"symlink_target": ""
} |
[[toc]]
## Core buttons
The `navbar` option is an array which can contain the following elements:
- `autorotate`
- `zoomOut`
- `zoomRange`
- `zoomIn`
- `zoom` = `zoomOut` + `zoomRange` + `zoomIn`
- `moveLeft`
- `moveRight`
- `moveTop`
- `moveDown`
- `move` = `moveLeft` + `moveRight` + `moveTop` + `moveDown`
- `download`
- `description`
- `caption`
- `fullscreen`
## Plugins buttons
Some [plugins](../plugins/) add new buttons to the navbar and will be automatically shown if you don't override the `navbar` option. However if you do, you will have to manually add said buttons in your configuration. The buttons codes are documented on each plugin page.
## Custom buttons
You can also add as many custom buttons you want. A custom button is an object with the following options:
#### `content` (required)
- type : `string`
Content of the button. Preferably a square image or SVG icon.
#### `onClick(viewer)` (required)
- type : `function(Viewer)`
Function called when the button is clicked.
#### `id`
- type : `string`
Unique identifier of the button, usefull when using the `navbar.getButton()` method.
#### `title`
- type : `string`
Tooltip displayed when the mouse is over the button.
#### `className`
- type : `string`
CSS class added to the button.
#### `disabled`
- type : `boolean`
- default : `false`
Initially disable the button.
#### `visible`
- type : `boolean`
- default : `true`
Initially show the button.
The API allows to change the visibility of the button at any time:
```js
viewer.navbar.getButton('my-button').show();
```
## Example
This example uses some core buttons, the caption and a custom button.
```js
new PhotoSphereViewer.Viewer({
navbar: [
'autorotate',
'zoom',
{
id: 'my-button',
content: '<svg...>',
title: 'Hello world',
className: 'custom-button',
onClick: (viewer) => {
alert('Hello from custom button');
},
},
'caption',
'fullscreen',
],
});
```
| {
"content_hash": "50c33d29a539391c09b02e8be88b94a5",
"timestamp": "",
"source": "github",
"line_count": 96,
"max_line_length": 271,
"avg_line_length": 20.9375,
"alnum_prop": 0.6502487562189054,
"repo_name": "mistic100/Photo-Sphere-Viewer",
"id": "47e5a2a153b96ff456d31861ff6665b61d21c9e9",
"size": "2034",
"binary": false,
"copies": "1",
"ref": "refs/heads/dev",
"path": "docs/guide/navbar.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "220"
},
{
"name": "HTML",
"bytes": "72996"
},
{
"name": "JavaScript",
"bytes": "525957"
},
{
"name": "SCSS",
"bytes": "29337"
},
{
"name": "TypeScript",
"bytes": "2341"
}
],
"symlink_target": ""
} |
PRICE = 1000
lastWinnerPrice = 350
local main_window
local tab_panel
local tab = {}
local aGamemodeMapTable = {}
function createNextmapWindow(tabPanel)
tab = {}
tab.mainBuyPanel = guiCreateTab('Maps-Center', tabPanel)
tab_panel = guiCreateTabPanel ( 0.01, 0.05, 0.98, 0.95, true, tab.mainBuyPanel )
tab.maps = guiCreateTab ( "All Maps", tab_panel)
tab.qmaps = guiCreateTab ( "Queued Maps", tab_panel)
tab.MapListSearch = guiCreateEdit ( 0.03, 0.225, 0.31, 0.05, "", true, tab.maps )
guiCreateStaticImage ( 0.34, 0.225, 0.035, 0.05, "nextmap/search.png", true, tab.maps )
tab.MapList = guiCreateGridList ( 0.03, 0.30, 0.94, 0.55, true, tab.maps )
guiGridListSetSortingEnabled(tab.MapList, false)
guiGridListAddColumn( tab.MapList, "Map Name", 0.55)
guiGridListAddColumn( tab.MapList, "Author", 0.5)
guiGridListAddColumn( tab.MapList, "Resource Name", 1)
guiGridListAddColumn( tab.MapList, "Gamemode", 0.5)
tab.NextMap = guiCreateButton ( 0.49, 0.91, 0.30, 0.04, "Buy selected map", true, tab.maps )
tab.RefreshList = guiCreateButton ( 0.03, 0.91, 0.35, 0.04, "Refresh list", true, tab.maps )
addEventHandler ("onClientGUIClick", tab.NextMap, guiClickBuy, false)
addEventHandler ("onClientGUIClick", tab.RefreshList, guiClickRefresh, false)
addEventHandler ("onClientGUIChanged", tab.MapListSearch, guiChanged)
tab.QueueList = guiCreateGridList (0.02, 0.04, 0.97, 0.92, true, tab.qmaps )
guiGridListSetSortingEnabled(tab.QueueList, false)
guiGridListAddColumn( tab.QueueList, "Priority", 0.15)
guiGridListAddColumn( tab.QueueList, "Map Name", 2)
tab.label1 = guiCreateLabel(0.40, 0.05, 0.50, 0.11, "This is the Maps-Center. Here you can buy maps.", true, tab.maps)
tab.label2 = guiCreateLabel(0.40, 0.13, 0.50, 0.12, "Select a map you like and click \"Buy selected map\"", true, tab.maps)
tab.label3 = guiCreateLabel(0.40, 0.18, 0.50, 0.17, "The map will be added to the Server Queue, where all bought maps are stored until they're played", true, tab.maps)
guiLabelSetHorizontalAlign(tab.label3, "left", true)
-- tab.label4 = guiCreateLabel(0.40, 0.28, 0.50, 0.13, "The queued maps will have priority against the usual server map cycler!", true, tab.maps)
-- guiLabelSetHorizontalAlign(tab.label4, "left", true)
tab.label5 = guiCreateLabel(0.125, 0.1, 0.50, 0.12, "Price: " .. PRICE .. " GC", true, tab.maps)
tab.label6 = guiCreateLabel(0.125, 0.14, 0.50, 0.08, "Price will be " .. lastWinnerPrice .. " GC \nafter you win a map", true, tab.maps)
guiLabelSetColor( tab.label5, 0, 255, 0 )
guiLabelSetColor( tab.label6, 255, 0, 0 )
guiSetFont( tab.label5, "default-bold-small" )
guiSetFont( tab.label6, "default-bold-small" )
triggerServerEvent('refreshServerMaps', localPlayer)
end
addEventHandler('onShopInit', getResourceRootElement(), createNextmapWindow )
function loadMaps(gamemodeMapTable, queuedList)
if gamemodeMapTable then
aGamemodeMapTable = gamemodeMapTable
for id,gamemode in pairs (gamemodeMapTable) do
guiGridListSetItemText ( tab.MapList, guiGridListAddRow ( tab.MapList ), 1, gamemode.name, true, false )
if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then
local row = guiGridListAddRow ( tab.MapList )
guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, true, false )
guiGridListSetItemText ( tab.MapList, row, 2, gamemode.resname, true, false )
guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, true, false )
else
for id,map in ipairs (gamemode.maps) do
local row = guiGridListAddRow ( tab.MapList )
if map.author then
guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false )
end
guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false )
guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false )
guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false )
end
end
end
for priority, mapName in ipairs(queuedList) do
local row_ = guiGridListAddRow ( tab.QueueList )
guiGridListSetItemText ( tab.QueueList, row_, 1, priority, false, false )
guiGridListSetItemText ( tab.QueueList, row_, 2, queuedList[priority][1], false, false )
end
end
end
addEvent("sendMapsToBuy", true)
addEventHandler("sendMapsToBuy", getLocalPlayer(), loadMaps)
addEvent('onTellClientPlayerBoughtMap', true)
addEventHandler('onTellClientPlayerBoughtMap', root,
function(mapName, priority)
local row_ = guiGridListAddRow ( tab.QueueList )
guiGridListSetItemText ( tab.QueueList, row_, 1, priority, false, false )
guiGridListSetItemText ( tab.QueueList, row_, 2, mapName, false, false )
end)
addEventHandler('onClientMapStarting', root,
function(mapinfo)
local name = mapinfo.name
local firstQueue = guiGridListGetItemText( tab.QueueList, 0, 2)
if name == firstQueue then
local rows = guiGridListGetRowCount(tab.QueueList)
guiGridListRemoveRow(tab.QueueList, 0)
guiGridListSetItemText(tab.QueueList, 0, 1, "1", false, false)
local i
for i = 1, rows-1 do
--local oldPriority = tonumber(guiGridListGetItemText(tab.QueueList, i, 1))
--oldPriority = tostring(oldPriority - 1)
guiGridListSetItemText(tab.QueueList, i, 1, tostring(i+1), false, false)
end
end
end)
function guiClickBuy(button)
if button == "left" then
if not guiGridListGetSelectedItem ( tab.MapList ) == -1 then
return
end
local mapName = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 1 )
local mapResName = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 3 )
local gamemode = guiGridListGetItemText ( tab.MapList, guiGridListGetSelectedItem( tab.MapList ), 4 )
triggerServerEvent("sendPlayerNextmapChoice", getLocalPlayer(), { mapName, mapResName, gamemode, getPlayerName(localPlayer) })
end
end
function guiClickRefresh(button)
if button == "left" then
guiGridListClear(tab.MapList)
guiGridListClear(tab.QueueList)
triggerServerEvent('refreshServerMaps', localPlayer)
end
end
function guiChanged()
guiGridListClear(tab.MapList)
local text = string.lower(guiGetText(source))
if ( text == "" ) then
for id,gamemode in pairs (aGamemodeMapTable) do
guiGridListSetItemText ( tab.MapList, guiGridListAddRow ( tab.MapList ), 1, gamemode.name, true, false )
if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then
local row = guiGridListAddRow ( tab.MapList )
guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, false, false )
if map.author then
guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false )
end
guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, false, false )
guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false )
else
for id,map in ipairs (gamemode.maps) do
local row = guiGridListAddRow ( tab.MapList )
guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false )
if map.author then
guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false )
end
guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false )
guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false )
end
end
end
else
for id,gamemode in pairs (aGamemodeMapTable) do
local gameModeRow = guiGridListAddRow ( tab.MapList )
local noMaps = true
guiGridListSetItemText ( tab.MapList, gameModeRow, 1, gamemode.name, true, false )
if #gamemode.maps == 0 and gamemode.name ~= "no gamemode" and gamemode.name ~= "deleted maps" then
if string.find(string.lower(gamemode.name.." "..gamemode.resname), text, 1, true) then
local row = guiGridListAddRow ( tab.MapList )
guiGridListSetItemText ( tab.MapList, row, 1, gamemode.name, false, false )
if map.author then
guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false )
end
guiGridListSetItemText ( tab.MapList, row, 3, gamemode.resname, false, false )
guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false )
noMaps = false
end
else
for id,map in ipairs (gamemode.maps) do
if not map.author then
compareTo = string.lower(map.name.." "..map.resname)
else
compareTo = string.lower(map.name.." "..map.resname.." "..map.author)
end
if string.find(compareTo, text, 1, true) then
local row = guiGridListAddRow ( tab.MapList )
guiGridListSetItemText ( tab.MapList, row, 1, map.name, false, false )
if map.author then
guiGridListSetItemText ( tab.MapList, row, 2, map.author, false, false )
end
guiGridListSetItemText ( tab.MapList, row, 3, map.resname, false, false )
guiGridListSetItemText ( tab.MapList, row, 4, gamemode.resname, false, false )
noMaps = false
end
end
end
if noMaps then
guiGridListRemoveRow(tab.MapList, gameModeRow)
end
end
end
end
addEvent('onGCShopWinnerDiscount', true)
addEventHandler('onGCShopWinnerDiscount', root, function()
if source == localPlayer then
guiLabelSetColor( tab.label5, 255, 0, 0 )
guiSetText(tab.label5, "Winner Discount Price: " .. lastWinnerPrice .. " GC" )
else
guiLabelSetColor( tab.label5, 0, 255, 0 )
guiSetText(tab.label5, "Price: " .. PRICE .. " GC" )
end
end)
function var_dump(...)
-- default options
local verbose = false
local firstLevel = true
local outputDirectly = true
local noNames = false
local indentation = "\t\t\t\t\t\t"
local depth = nil
local name = nil
local output = {}
for k,v in ipairs(arg) do
-- check for modifiers
if type(v) == "string" and k < #arg and v:sub(1,1) == "-" then
local modifiers = v:sub(2)
if modifiers:find("v") ~= nil then
verbose = true
end
if modifiers:find("s") ~= nil then
outputDirectly = false
end
if modifiers:find("n") ~= nil then
verbose = false
end
if modifiers:find("u") ~= nil then
noNames = true
end
local s,e = modifiers:find("d%d+")
if s ~= nil then
depth = tonumber(string.sub(modifiers,s+1,e))
end
-- set name if appropriate
elseif type(v) == "string" and k < #arg and name == nil and not noNames then
name = v
else
if name ~= nil then
name = ""..name..": "
else
name = ""
end
local o = ""
if type(v) == "string" then
table.insert(output,name..type(v).."("..v:len()..") \""..v.."\"")
elseif type(v) == "userdata" then
local elementType = "no valid MTA element"
if isElement(v) then
elementType = getElementType(v)
end
table.insert(output,name..type(v).."("..elementType..") \""..tostring(v).."\"")
elseif type(v) == "table" then
local count = 0
for key,value in pairs(v) do
count = count + 1
end
table.insert(output,name..type(v).."("..count..") \""..tostring(v).."\"")
if verbose and count > 0 and (depth == nil or depth > 0) then
table.insert(output,"\t{")
for key,value in pairs(v) do
-- calls itself, so be careful when you change anything
local newModifiers = "-s"
if depth == nil then
newModifiers = "-sv"
elseif depth > 1 then
local newDepth = depth - 1
newModifiers = "-svd"..newDepth
end
local keyString, keyTable = var_dump(newModifiers,key)
local valueString, valueTable = var_dump(newModifiers,value)
if #keyTable == 1 and #valueTable == 1 then
table.insert(output,indentation.."["..keyString.."]\t=>\t"..valueString)
elseif #keyTable == 1 then
table.insert(output,indentation.."["..keyString.."]\t=>")
for k,v in ipairs(valueTable) do
table.insert(output,indentation..v)
end
elseif #valueTable == 1 then
for k,v in ipairs(keyTable) do
if k == 1 then
table.insert(output,indentation.."["..v)
elseif k == #keyTable then
table.insert(output,indentation..v.."]")
else
table.insert(output,indentation..v)
end
end
table.insert(output,indentation.."\t=>\t"..valueString)
else
for k,v in ipairs(keyTable) do
if k == 1 then
table.insert(output,indentation.."["..v)
elseif k == #keyTable then
table.insert(output,indentation..v.."]")
else
table.insert(output,indentation..v)
end
end
for k,v in ipairs(valueTable) do
if k == 1 then
table.insert(output,indentation.." => "..v)
else
table.insert(output,indentation..v)
end
end
end
end
table.insert(output,"\t}")
end
else
table.insert(output,name..type(v).." \""..tostring(v).."\"")
end
name = nil
end
end
local string = ""
for k,v in ipairs(output) do
if outputDirectly then
outputConsole(v)
end
string = string..v
end
return string, output
end
-- [number "85"] =>
-- table(3) "table: 2805A560"
-- {
-- [string(7) "resname"] => string(15) "shooter-stadium"
-- [string(6) "author"] => string(11) "salvadorc17"
-- [string(4) "name"] => string(15) "Shooter-Stadiu | {
"content_hash": "80815d655df53b1d950753868557c291",
"timestamp": "",
"source": "github",
"line_count": 345,
"max_line_length": 175,
"avg_line_length": 39.13913043478261,
"alnum_prop": 0.6598533659186847,
"repo_name": "AfuSensi/Mr.Green-MTA-Resources",
"id": "cedaba07afb2314daa3950160c650c2a313bec93",
"size": "13505",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "resources/[gameplay]/gcshop/maps/maps_client.lua",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "18851"
},
{
"name": "FLUX",
"bytes": "314021"
},
{
"name": "HTML",
"bytes": "82986"
},
{
"name": "JavaScript",
"bytes": "149009"
},
{
"name": "Lua",
"bytes": "3206669"
},
{
"name": "PHP",
"bytes": "50115"
},
{
"name": "PLpgSQL",
"bytes": "13660"
}
],
"symlink_target": ""
} |
rdio-playlist-generator
=======================
Create an Rdio playlist from a list of albums
| {
"content_hash": "37c5593098369f620a8e41ac551f3636",
"timestamp": "",
"source": "github",
"line_count": 4,
"max_line_length": 45,
"avg_line_length": 23.75,
"alnum_prop": 0.6105263157894737,
"repo_name": "sico/rdio-playlist-generator",
"id": "81442754b6be568351d45aad14057315f1cab030",
"size": "95",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "README.md",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
The MIT License (MIT)
Copyright (c) 2013 Appirio
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
| {
"content_hash": "f4317430027ebf72e7177188a36278f2",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 80,
"avg_line_length": 53.7,
"alnum_prop": 0.8035381750465549,
"repo_name": "Appirio/mock-json",
"id": "575d7ef0bbe9036bedcb561d1e99fb9bf8e8c363",
"size": "1074",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "LICENSE.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "468"
},
{
"name": "JavaScript",
"bytes": "181409"
},
{
"name": "PHP",
"bytes": "16"
}
],
"symlink_target": ""
} |
import os
import sys
#import feedparser
#from bs4 import BeautifulStoneSoup
from bs4 import BeautifulSoup
#from nltk import clean_html
import urllib
import re
import json
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from scrapy.item import Item, Field
from NGOcrawler.items import NgocrawlerItem
class NGOSpider(scrapy.Spider):
name = "ngo"
#allowed_domains = ['achildshopefoundation.org']
#start_urls = ['https://achildshopefoundation.org']
#allowed_domains = ['afcfoundation.org']
start_urls = ['http://www.afcfoundation.org']
def parse(self, response):
page = response.url.split("/")[-2]
filename = 'ngo-%s.html' % page
with open(filename, 'wb') as f:
f.write(response.body)
self.log('Saved file %s' % filename)
print('_______________________________________________________________')
print('SCRAPED DATA:')
print('_______________________________________________________________')
print('_______________________________________________________________')
title = response.xpath('//title/text()').extract_first()
print title
contact = response.css("div.contact")
print contact
parsedHTML = []
i = 0
for x in NGOSpider.start_urls:
parsedHTML.append(self.getHTMLtext(x))
i += 1
phoneNumber = []
email =[]
streetAddress = []
for x in parsedHTML:
phoneNumber.append(self.getPhoneNumber(x))
email.append(self.getEmail(x))
streetAddress.append(self.getAddress(x))
projectProp = 'PROJECTPROPOSAL'
print(self.formatJSON(title,phoneNumber,email,streetAddress,projectProp))
print('_______________________________________________________________')
print('_______________________________________________________________')
#getting all text on a page
def getHTMLtext (self, url):
page = urllib.urlopen(url)
soup = BeautifulSoup(page, 'html.parser')
HTMLtext = soup.get_text()
return HTMLtext
#get the phone number on webpage with regex
def getPhoneNumber (self, webText):
phoneNumber = ""
phoneNumberCombinations = r'\(?\d?-?\d{,3}?\)?\s?\.?-?/?\(?\d{3}\)??\s?\.?-?/?\d{3}\s?\.?-?\d{4}'
#catch index out of range error
phoneNumber = re.findall(phoneNumberCombinations, webText)
#print(re.findall(r'\(?\d{3}\)? \d{3}-\d{4}',webText))
#basic case
"""
phoneNumberCombos = [r'\(?\d{3}\)? \d{3}-\d{4}', r'\(?\d{3}\)?.?\d{3}.?\d{4}']
for numbers in phoneNumberCombos:
phoneNumber = re.findall(numbers, webText)
print(phoneNumber)
"""
print(phoneNumber)
return phoneNumber
#get email
def getEmail (self, webText):
email = ""
#basic case
emailCombinations = r'[-\w\d+.]+@[-\w\d.]+'
#catch index out of range error
email = re.findall(emailCombinations, webText)[0]
print(email)
return email
#using alg
def getAddress(self, webText):
streetNumber = r'\d+'
state = r'(AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT \
|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY \
Alabama|Alaska|Arizona|Arkansas|California|Colorado|Connecticut|Delaware|Florida|Georgia|Hawaii| \
Idaho|Illinois|Indiana|Iowa|Kansas|Kentucky|Louisiana|Maine|Maryland|Massachusetts|Michigan|\
Minnesota|Mississippi|Missouri|Montana|Nebraska|Nevada|New[ ]Hampshire|New[ ]Jersey|New[ ]Mexico|\
New[ ]York|North[ ]Carolina|North[ ]Dakota|Ohio|Oklahoma|Oregon|Pennsylvania|Rhode[ ]Island|\
South[ ]Carolina|South[ ]Dakota|Tennessee|Texas|Utah|Vermont|Virginia|Washington|West[ ]Virginia|Wisconsin|Wyoming)'
zipCode = r'[ ]+(\b\d{5}(?:-\d{4})?\b)'
addressAnchor = state + zipCode
#find address
address = re.findall(addressAnchor, webText)
#print address
stringReform = ''
index = 0
addressList = []
#append string
for (a,b) in address:
stringReform = a + ' ' + b
addressList.append(re.sub("^u'(.*)'$",r'\1',stringReform))
index += 1
#print addresses
#print addressList
addressFinal = []
#find position of zipcode
for x in addressList:
numberEndLoc = webText.find(x) + len(x) + 1
#print (webText.find(streetNum))
#assign starting point for looking for street number
startSearch = numberEndLoc - 45
neededText = webText[startSearch:numberEndLoc]
street_match = re.search(streetNumber,neededText)
if street_match:
addressStart = street_match.start()
else:
print neededText
return neededText
#print addressStart
#print neededText[addressStart:-1]
addressFinal.append(neededText[addressStart:])
print addressFinal
return addressFinal
def formatJSON (self,title,phoneNumber,emailAddress,streetAddress,projectProposal):
data = {
'Organization Title' : '',
'Phone Number' : '',
'Email' : '',
'Street Address' : [],
'Project Proposal': ''
}
data['Organization Title'] = title
data['Phone Number'] = phoneNumber
data['Email'] = emailAddress
data['Street Address'] = streetAddress
data['Project Proposal'] = projectProposal
json_data = json.dumps(data)
return json_data
print json_data
| {
"content_hash": "40348f138441e6fd9f1f875f2991fa66",
"timestamp": "",
"source": "github",
"line_count": 186,
"max_line_length": 132,
"avg_line_length": 31.892473118279568,
"alnum_prop": 0.5505731625084289,
"repo_name": "koneman/NGOpycrawl",
"id": "d71dff45ba005c6545445edad67ac3330e9f5a53",
"size": "5932",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "NGOcrawler/spiders/spider_base.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "7065"
},
{
"name": "Python",
"bytes": "20487"
}
],
"symlink_target": ""
} |
<?php
/**
* you can find x-forms here
* https://github.com/ludwig-gramberg/wp-lib-x-forms
*
* in wp-folder add like so:
* git submodule add -b master --name "wp-includes/x-forms" git@github.com:ludwig-gramberg/wp-lib-x-forms.git wp-includes/x-forms
* */
require_once ABSPATH.'/wp-includes/x-forms/x-forms.php';
// form
$form_name = 'demo-form'; // name of the form, each form on a page must have a unique name
$form_read = &$_POST; // where to read from usually $_POST or $_GET depends on your form
$form_write = array(); // where to write the resulting data
$form_errors = array(); // where to write form errors
// email address
$field_email = x_form_render_text(
$form_name,
'email',
$form_read,
true,
'class="form-control" id="'.$form_name.'_email"', // custom html you want in the resulting element
$form_write,
$form_errors,
'',
'Your E-Mail Address', // place holder
'trim', // sanitization of value
'email' // validatoin
);
// name/address fields
$field_gender = x_form_render_select(
$form_name,
'gender',
$form_read,
array(
'f' => __('Female'),
'm' => __('Male'),
),
null,
'class="form-control" id="'.$form_name.'_gender"',
$form_write,
'f'
);
$field_firstname = x_form_render_text(
$form_name,
'firstname',
$form_read,
true,
'class="form-control" id="'.$form_name.'_firstname"',
$form_write,
$form_errors,
'',
'',
'trim',
'not_empty'
);
$field_lastname = x_form_render_text(
$form_name,
'lastname',
$form_read,
true,
'class="form-control" id="'.$form_name.'_lastname"',
$form_write,
$form_errors,
'',
'',
'trim',
'not_empty'
); | {
"content_hash": "91e476e500c4fd5be8038a0ab0c28e66",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 129,
"avg_line_length": 23.41891891891892,
"alnum_prop": 0.5874206578188114,
"repo_name": "ludwig-gramberg/wp-theme-scaffold",
"id": "c672b611d0e622c18bdfd2ac7db146794a89e980",
"size": "1733",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "form/demo-form/fields.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "120"
},
{
"name": "CSS",
"bytes": "297"
},
{
"name": "JavaScript",
"bytes": "84"
},
{
"name": "PHP",
"bytes": "14429"
}
],
"symlink_target": ""
} |
package com.example.lighthousecontroller.view;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/* adaptado de: https://developer.android.com/guide/topics/ui/dialogs.html#DialogFragment*/
public class SimpleDialogFragment extends DialogFragment {
public interface DialogResponseListener{
public void onResponse(boolean positive);
}
private String dialogMessage;
private String okMessage, cancelMessage;
private DialogResponseListener dialogResponseListener;
private int layoutId;
private boolean isModal;
private String title;
public SimpleDialogFragment() {
super();
this.dialogMessage = "";
this.okMessage = null;
this.cancelMessage = null;
this.dialogResponseListener = null;
this.layoutId = 0;
this.isModal = false;
this.title = null;
}
public String getDialogMessage() { return dialogMessage; }
public String getOkMessage() { return okMessage; }
public String getCancelMessage() { return cancelMessage;}
public DialogResponseListener getDialogResponseListener() { return dialogResponseListener;}
public void setDialogMessage(String dialogMessage) {
this.dialogMessage = dialogMessage;
}
public void setOkMessage(String okMessage) {
this.okMessage = okMessage;
}
public void hideOkButton() {
this.okMessage = null;
}
public void setCancelMessage(String cancelMessage) {
this.cancelMessage = cancelMessage;
}
public void hideCancelButton() {
this.cancelMessage = null;
}
public void setDialogResponseListener(DialogResponseListener dialogResponseListener) {
this.dialogResponseListener = dialogResponseListener;
}
public int getLayoutId() {
return layoutId;
}
public void setLayoutId(int layoutId) {
this.layoutId = layoutId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
if(layoutId > 0 && !isModal){
return createView(layoutId, inflater, container);
}
return super.onCreateView(inflater, container, savedInstanceState);
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
isModal = true;
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
if(layoutId > 0 && isModal){
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = createView(layoutId, inflater, null);
builder.setView(view);
}
builder.setMessage(this.getDialogMessage());
if(this.getTitle() != null){
builder.setTitle(getTitle());
}
if(isValidMessage(getOkMessage())){
builder.setPositiveButton(getOkMessage(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
notifyResponse(true);
}
});
};
if(isValidMessage(getCancelMessage())){
builder.setNegativeButton(getCancelMessage(), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
notifyResponse(false);
}
})
.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
notifyResponse(false);
}
});
};
return builder.create();
}
protected View createView(int layoutId, LayoutInflater inflater, ViewGroup container) {
return inflater.inflate(layoutId, container, false);
}
private boolean isValidMessage(String message) {
return message != null && message.length() != 0;
}
private void notifyResponse(boolean response) {
if(dialogResponseListener != null){
dialogResponseListener.onResponse(response);
}
}
}
| {
"content_hash": "0f7e4ee01914c38ab0d2a4cc9dfb53bb",
"timestamp": "",
"source": "github",
"line_count": 136,
"max_line_length": 94,
"avg_line_length": 30.375,
"alnum_prop": 0.7061244250786735,
"repo_name": "souzabrizolara/LightHouseController",
"id": "f3dc7900d52d593f928c11a93d1fe7bccb910557",
"size": "4131",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/com/example/lighthousecontroller/view/SimpleDialogFragment.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "346961"
}
],
"symlink_target": ""
} |
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using NUnit.ProjectEditor.ViewElements;
namespace NUnit.ProjectEditor
{
/// <summary>
/// Displays a dialog for creation of a new configuration.
/// The dialog collects and validates the name and the
/// name of a configuration to be copied and then adds the
/// new configuration to the doc.
///
/// A DialogResult of DialogResult.OK indicates that the
/// configuration was added successfully.
/// </summary>
public partial class AddConfigurationDialog : System.Windows.Forms.Form, IAddConfigurationDialog
{
private static readonly string NONE_SELECTED = "<none>";
#region Constructor
public AddConfigurationDialog()
{
InitializeComponent();
okButtonWrapper = new ButtonElement(okButton);
}
#endregion
#region Properties
private MessageDisplay mbox = new MessageDisplay("Add Configuration");
public IMessageDisplay MessageDisplay { get { return mbox; } }
private string[] configList;
public string[] ConfigList
{
get { return configList; }
set
{
configList = value;
configurationComboBox.Items.Clear();
configurationComboBox.Items.Add(NONE_SELECTED);
configurationComboBox.SelectedIndex = 0;
foreach (string config in configList)
configurationComboBox.Items.Add(config);
}
}
public string ConfigToCreate
{
get { return configurationNameTextBox.Text; }
}
public string ConfigToCopy
{
get
{
string config = (string)configurationComboBox.SelectedItem;
return config == NONE_SELECTED ? null : config;
}
set
{
string config = string.IsNullOrEmpty(value) ? NONE_SELECTED : value;
configurationComboBox.SelectedItem = config;
}
}
private ICommand okButtonWrapper;
public ICommand OkButton
{
get { return okButtonWrapper; }
}
#endregion
}
public interface IAddConfigurationDialog : IDialog
{
string[] ConfigList { get; set; }
string ConfigToCreate { get; }
string ConfigToCopy { get; }
ICommand OkButton { get; }
}
}
| {
"content_hash": "c29d79d541e7dcd8019520376d0a2db3",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 97,
"avg_line_length": 27.70212765957447,
"alnum_prop": 0.5798771121351767,
"repo_name": "acken/AutoTest.Net",
"id": "71b1ac5da950a553238d05374b02d632e54a9efa",
"size": "2897",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "lib/NUnit/src/NUnit-2.6.0.12051/src/ProjectEditor/editor/ConfigurationEditor/AddConfigurationDialog.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "150"
},
{
"name": "C#",
"bytes": "9855924"
},
{
"name": "C++",
"bytes": "57796"
},
{
"name": "CSS",
"bytes": "22906"
},
{
"name": "JavaScript",
"bytes": "10141"
},
{
"name": "Pascal",
"bytes": "215"
},
{
"name": "PowerShell",
"bytes": "156"
},
{
"name": "Ruby",
"bytes": "3593661"
},
{
"name": "Shell",
"bytes": "21129"
},
{
"name": "Visual Basic",
"bytes": "97606"
},
{
"name": "XSLT",
"bytes": "164747"
}
],
"symlink_target": ""
} |
#include "tensorflow/core/framework/common_shape_fns.h"
#include "tensorflow/core/framework/op.h"
#include "tensorflow/core/framework/rng_alg.h"
namespace tensorflow {
using shape_inference::DimensionHandle;
using shape_inference::InferenceContext;
using shape_inference::ShapeHandle;
static Status StatelessShapeV2(InferenceContext* c) {
// Check key and counter shapes
ShapeHandle key;
ShapeHandle counter;
TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &key));
TF_RETURN_IF_ERROR(c->WithRank(c->input(2), 1, &counter));
shape_inference::ShapeHandle unused_shape;
TF_RETURN_IF_ERROR(c->WithRank(c->input(3), 0, &unused_shape));
DimensionHandle unused;
TF_RETURN_IF_ERROR(c->WithValue(c->Dim(key, 0), RNG_KEY_SIZE, &unused));
// Set output shape
ShapeHandle out;
TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(0, &out));
c->set_output(0, out);
return Status::OK();
}
#define REGISTER_STATELESS_OP(name) \
REGISTER_OP(name) \
.Input("shape: Tshape") \
.Input("key: uint64") \
.Input("counter: uint64") \
.Input("alg: int32") \
.Output("output: dtype") \
.Attr("dtype: {half,bfloat16,float,double} = DT_FLOAT") \
.Attr("Tshape: {int32, int64} = DT_INT32") \
.SetShapeFn(StatelessShapeV2)
REGISTER_STATELESS_OP("StatelessRandomUniformV2");
REGISTER_STATELESS_OP("StatelessRandomNormalV2");
REGISTER_STATELESS_OP("StatelessTruncatedNormalV2");
#undef REGISTER_STATELESS_OP
REGISTER_OP("StatelessRandomUniformIntV2")
.Input("shape: Tshape")
.Input("key: uint64")
.Input("counter: uint64")
.Input("alg: int32")
.Input("minval: dtype")
.Input("maxval: dtype")
.Output("output: dtype")
.Attr("dtype: {int32, int64, uint32, uint64}")
.Attr("Tshape: {int32, int64} = DT_INT32")
.SetShapeFn([](InferenceContext* c) {
ShapeHandle unused;
Status s = c->WithRank(c->input(4), 0, &unused);
if (!s.ok()) {
return errors::InvalidArgument(
"minval must be a scalar; got a tensor of shape ",
c->DebugString(c->input(4)));
}
s = c->WithRank(c->input(5), 0, &unused);
if (!s.ok()) {
return errors::InvalidArgument(
"maxval must be a scalar; got a tensor of shape ",
c->DebugString(c->input(5)));
}
return StatelessShapeV2(c);
});
REGISTER_OP("StatelessRandomUniformFullIntV2")
.Input("shape: Tshape")
.Input("key: uint64")
.Input("counter: uint64")
.Input("alg: int32")
.Output("output: dtype")
.Attr("dtype: {int32, int64, uint32, uint64} = DT_UINT64")
.Attr("Tshape: {int32, int64} = DT_INT32")
.SetShapeFn(StatelessShapeV2);
REGISTER_OP("StatelessRandomGetKeyCounterAlg")
.Input("seed: Tseed")
.Output("key: uint64")
.Output("counter: uint64")
.Output("alg: int32")
.Attr("Tseed: {int32, int64} = DT_INT64")
.SetIsStateful() // because outputs depend on device
.SetShapeFn([](InferenceContext* c) {
// Check seed shape
ShapeHandle seed;
TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 1, &seed));
DimensionHandle unused;
TF_RETURN_IF_ERROR(c->WithValue(c->Dim(seed, 0), 2, &unused));
// Set output shapes
c->set_output(0, c->MakeShape({RNG_KEY_SIZE}));
c->set_output(1, c->MakeShape({RNG_MAX_COUNTER_SIZE}));
c->set_output(2, c->MakeShape({}));
return Status::OK();
});
} // namespace tensorflow
| {
"content_hash": "c0787815be1f45d3360a17adf638c003",
"timestamp": "",
"source": "github",
"line_count": 106,
"max_line_length": 74,
"avg_line_length": 34.83018867924528,
"alnum_prop": 0.5950704225352113,
"repo_name": "davidzchen/tensorflow",
"id": "e6f87674174833f11f647da2d7c2af5cb60fad4d",
"size": "4360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tensorflow/core/ops/stateless_random_ops_v2.cc",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "32240"
},
{
"name": "Batchfile",
"bytes": "55269"
},
{
"name": "C",
"bytes": "887514"
},
{
"name": "C#",
"bytes": "8562"
},
{
"name": "C++",
"bytes": "81865221"
},
{
"name": "CMake",
"bytes": "6500"
},
{
"name": "Dockerfile",
"bytes": "112853"
},
{
"name": "Go",
"bytes": "1867241"
},
{
"name": "HTML",
"bytes": "4686483"
},
{
"name": "Java",
"bytes": "971474"
},
{
"name": "Jupyter Notebook",
"bytes": "549437"
},
{
"name": "LLVM",
"bytes": "6536"
},
{
"name": "MLIR",
"bytes": "1921657"
},
{
"name": "Makefile",
"bytes": "65901"
},
{
"name": "Objective-C",
"bytes": "116558"
},
{
"name": "Objective-C++",
"bytes": "316967"
},
{
"name": "PHP",
"bytes": "4236"
},
{
"name": "Pascal",
"bytes": "318"
},
{
"name": "Pawn",
"bytes": "19963"
},
{
"name": "Perl",
"bytes": "7536"
},
{
"name": "Python",
"bytes": "37285698"
},
{
"name": "RobotFramework",
"bytes": "1779"
},
{
"name": "Roff",
"bytes": "2705"
},
{
"name": "Ruby",
"bytes": "7464"
},
{
"name": "SWIG",
"bytes": "8992"
},
{
"name": "Shell",
"bytes": "700629"
},
{
"name": "Smarty",
"bytes": "35540"
},
{
"name": "Starlark",
"bytes": "3604653"
},
{
"name": "Swift",
"bytes": "62814"
},
{
"name": "Vim Snippet",
"bytes": "58"
}
],
"symlink_target": ""
} |
;(function() {
if (typeof define === 'function' && define.amd) {
define('GLoadMore', ['require', 'jquery', 'G', 'iscroll'], function(require) {
return factory(require('jquery'), require('G'), require('iscroll'));
});
} else if (typeof module === "object" && typeof module.exports === "object") {
module.exports = factory(require('jquery'), require('G'), require('iscroll'))
} else {
window.GLoadmore = factory(window.jQuery, window.G, window.iscroll);
}
function factory($, G, iScroll) {
var cssObj = {};
var defaultConfig = {
pageContent: {
perpage: '5',
page: '1'
},
conditions: {
'perpage': 5,
'page': 1
},
pullDownState: {
'0': {
status: 0,
className: 'success',
text: '刷新成功'
},
'1': {
status: 1,
className: '',
text: '下拉刷新...'
},
'2': {
status: 2,
className: '',
text: '继续下拉刷新...'
},
'3': {
status: 3,
className: 'flip',
text: '松手开始更新...'
},
'4': {
status: 4,
className: 'loading',
text: '加载中...'
}
},
pullUpState: {
'0': {
status: 0,
className: 'success',
text: '加载成功'
},
'1': {
status: 1,
className: '',
text: '上拉加载更多...'
},
'2': {
status: 2,
className: '',
text: '继续上拉加载更多...'
},
'3': {
status: 3,
className: 'flip',
text: '松手加载更多...'
},
'4': {
status: 4,
className: 'loading',
text: '加载中...'
}
},
getBlockData: function(el) {
var innerScroll = '';
var innerScroll = '<div id="scroller">';
innerScroll += '<div id="pullDown">';
innerScroll += '<span class="pullDownIcon"></span>';
innerScroll += '<span class="pullDownLabel">下拉刷新...</span>';
innerScroll += '</div>';
innerScroll += '<div class="init-data"></div>';
innerScroll += '<div id="pullUp">';
innerScroll += '<span class="pullUpIcon"></span>';
innerScroll += '<span class="pullUpLabel">上拉加载更多...</span>';
innerScroll += '</div>'
innerScroll += '</div>';
$(el).html(innerScroll);
},
getInitData: function(){
var innerContent = '';
return innerContent;
},
};
var LoadMore = function(el, conf) {
this.el = el;
this.conf = $.extend({}, defaultConfig, conf);
this.conf.getBlockData(this.el);
this.init();
return this;
}
LoadMore.prototype = {
init: function() {
var conf = this.conf;
this.page = conf.pageContent.page;
this.perpage = conf.pageContent.perpage;
this.pullDownOffset = $('#pullDown').get(0).offsetHeight;
this.pullUpOffset = $('#pullUp').get(0).offsetHeight;
this.myScroll = new iScroll('#wrapper', {
probeType: 3
});
this.pullDownStatus = 1;
this.pullUpStatus = 1;
var self = this;
this.myScroll.on('scroll', function(){ self._onScrollEvent(this); });
this.myScroll.on('scrollEnd', function(){ self._onscrollEndEvent(this); });
conf.getInitData($('.init-data'), function(){
self.myScroll.refresh();
});
document.addEventListener('touchmove', function(e) {
e.preventDefault();
}, false);
},
_onScrollEvent: function(scroll){
var self = this;
if (scroll.y < 1 && self.pullDownStatus <= 2) {
self._setStatus('pullDown', 1);
} else if (scroll.y > 1 && self.pullDownStatus === 1) {
self._setStatus('pullDown', 2);
} else if (scroll.y > self.pullDownOffset && self.pullDownStatus <= 2) {
self._setStatus('pullDown', 3);
} else if (scroll.startY < self.pullDownOffset && self.pullDownStatus === 3) {
self._setStatus('pullDown', 2);
}
if (scroll.y > (scroll.maxScrollY - 1) && self.pullUpStatus <= 2) {
self._setStatus('pullUp', 1);
} else if (scroll.y < (scroll.maxScrollY - 1) && self.pullUpStatus === 1) {
self._setStatus('pullUp', 2);
} else if (scroll.y < (scroll.maxScrollY - self.pullUpOffset) && self.pullUpStatus <= 2) {
self._setStatus('pullUp', 3);
} else if (scroll.startY < scroll.maxScrollY && scroll.startY > scroll.maxScrollY - self.pullUpOffset && self.pullUpStatus === 3) {
self._setStatus('pullUp', 2);
}
},
_onscrollEndEvent: function(scroll){
var self = this;
var el = self.el;
var conf = self.conf;
if (scroll.y > -1 && scroll.startY > self.pullDownOffset && self.pullDownStatus === 3) {
self._setStatus('pullDown', 4);
self.pullDownStatus = 4;
conf.getPullDownData(el, function(){
self._scrollRefresh();
scroll.refresh();
});
} else if (self.pullDownStatus === 3) {
self._setStatus('pullDown', 1);
self.pullDownStatus = 1;
}
if (scroll.y < (scroll.maxScrollY + 1) && scroll.startY < scroll.maxScrollY - self.pullUpOffset && self.pullUpStatus === 3) {
self._setStatus('pullUp', 4);
self.pullUpStatus = 4;
self._scrollRefresh();
conf.getPullUpData(el, self.page, self.perpage, function(){
self._scrollRefresh();
scroll.refresh();
self.page++;
});
} else if (self.pullUpStatus === 3) {
self._setStatus('pullUp', 1);
self.pullUpStatus = 1;
}
},
_setStatus: function(direction, state) {
var conf = this.conf;
var result = null;
if (direction === 'pullDown') {
result = conf.pullDownState[state];
$('#pullDown').attr('class', result.className);
$('.pullDownLabel').html(result.text);
this.pullDownStatus = state;
} else {
result = conf.pullUpState[state];
$('#pullUp').attr('class', result.className);
$('.pullUpLabel').html(result.text);
this.pullUpStatus = state;
}
},
_scrollRefresh: function(){
if (this.pullDownStatus === 4) {
this._setStatus('pullDown', 0);
this.pullDownStatus = 0;
} else if (this.pullUpStatus === 4) {
this._setStatus('pullUp', 0);
this.pullUpStatus = 0;
}
}
}
return LoadMore;
}
})() | {
"content_hash": "b10eb9a21d0336741f9ba5dbb26ae088",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 147,
"avg_line_length": 41.48275862068966,
"alnum_prop": 0.3988837430233939,
"repo_name": "daixianfeng/lancer",
"id": "383b3c16f5d67fb9bfaadc08e162fad7a676b1f6",
"size": "8541",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/load-more/load-more.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "22569"
},
{
"name": "HTML",
"bytes": "60192"
},
{
"name": "JavaScript",
"bytes": "3271104"
}
],
"symlink_target": ""
} |
class Vector2;
#endif
class Angle
{
private:
float curAngle;
public:
Angle();
Angle( float Degrees );
void Add( float Degrees );
void Set( float Degrees );
float ToDegrees();
float ToRadians();
Vector2* ToVector();
float ShortestAngleTo( Angle* DestinationAngle );
float ShortestAngleTo( float DestinationAngle );
bool ClockwiseShortestTo( Angle* DestinationAngle );
bool ClockwiseShortestTo( float DestinationAngle );
void RotateShortestBy( Angle* DestinationAngle, float ByDegrees );
void RotateShortestBy( float DestinationAngle, float ByDegrees );
float Sine();
float Cosine();
float Tan();
}; | {
"content_hash": "d03d3737de0f4027581a8942b728a6f2",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 68,
"avg_line_length": 21.3,
"alnum_prop": 0.7261345852895149,
"repo_name": "pmprog/deathsnow",
"id": "2503e1cb1706dc1a77dae31a6cec809c77b7df45",
"size": "690",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/angle.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "828"
},
{
"name": "C++",
"bytes": "180484"
}
],
"symlink_target": ""
} |
'use strict';
var game = require('./game-4b284c1b.js');
/**
* Base class that bots can extend.
*/
var Bot =
/*#__PURE__*/
function () {
function Bot(_ref) {
var _this = this;
var enumerate = _ref.enumerate,
seed = _ref.seed;
game._classCallCheck(this, Bot);
game._defineProperty(this, "enumerate", function (G, ctx, playerID) {
var actions = _this.enumerateFn(G, ctx, playerID);
return actions.map(function (a) {
if (a.payload !== undefined) {
return a;
}
if (a.move !== undefined) {
return game.makeMove(a.move, a.args, playerID);
}
if (a.event !== undefined) {
return game.gameEvent(a.event, a.args, playerID);
}
});
});
this.enumerateFn = enumerate;
this.seed = seed;
this.iterationCounter = 0;
this._opts = {};
}
game._createClass(Bot, [{
key: "addOpt",
value: function addOpt(_ref2) {
var key = _ref2.key,
range = _ref2.range,
initial = _ref2.initial;
this._opts[key] = {
range: range,
value: initial
};
}
}, {
key: "getOpt",
value: function getOpt(key) {
return this._opts[key].value;
}
}, {
key: "setOpt",
value: function setOpt(key, value) {
if (key in this._opts) {
this._opts[key].value = value;
}
}
}, {
key: "opts",
value: function opts() {
return this._opts;
}
}, {
key: "random",
value: function random(arg) {
var number;
if (this.seed !== undefined) {
var r = null;
if (this.prngstate) {
r = new game.alea('', {
state: this.prngstate
});
} else {
r = new game.alea(this.seed, {
state: true
});
}
number = r();
this.prngstate = r.state();
} else {
number = Math.random();
}
if (arg) {
// eslint-disable-next-line unicorn/explicit-length-check
if (arg.length) {
var id = Math.floor(number * arg.length);
return arg[id];
} else {
return Math.floor(number * arg);
}
}
return number;
}
}]);
return Bot;
}();
/**
* The number of iterations to run before yielding to
* the JS event loop (in async mode).
*/
var CHUNK_SIZE = 25;
/**
* Bot that uses Monte-Carlo Tree Search to find promising moves.
*/
var MCTSBot =
/*#__PURE__*/
function (_Bot) {
game._inherits(MCTSBot, _Bot);
function MCTSBot(_ref) {
var _this;
var enumerate = _ref.enumerate,
seed = _ref.seed,
objectives = _ref.objectives,
game$1 = _ref.game,
iterations = _ref.iterations,
playoutDepth = _ref.playoutDepth,
iterationCallback = _ref.iterationCallback;
game._classCallCheck(this, MCTSBot);
_this = game._possibleConstructorReturn(this, game._getPrototypeOf(MCTSBot).call(this, {
enumerate: enumerate,
seed: seed
}));
if (objectives === undefined) {
objectives = function objectives() {
return {};
};
}
_this.objectives = objectives;
_this.iterationCallback = iterationCallback || function () {};
_this.reducer = game.CreateGameReducer({
game: game$1
});
_this.iterations = iterations;
_this.playoutDepth = playoutDepth;
_this.addOpt({
key: 'async',
initial: false
});
_this.addOpt({
key: 'iterations',
initial: typeof iterations === 'number' ? iterations : 1000,
range: {
min: 1,
max: 2000
}
});
_this.addOpt({
key: 'playoutDepth',
initial: typeof playoutDepth === 'number' ? playoutDepth : 50,
range: {
min: 1,
max: 100
}
});
return _this;
}
game._createClass(MCTSBot, [{
key: "createNode",
value: function createNode(_ref2) {
var state = _ref2.state,
parentAction = _ref2.parentAction,
parent = _ref2.parent,
playerID = _ref2.playerID;
var G = state.G,
ctx = state.ctx;
var actions = [];
var objectives = [];
if (playerID !== undefined) {
actions = this.enumerate(G, ctx, playerID);
objectives = this.objectives(G, ctx, playerID);
} else if (ctx.activePlayers) {
for (var _playerID in ctx.activePlayers) {
actions = actions.concat(this.enumerate(G, ctx, _playerID));
objectives = objectives.concat(this.objectives(G, ctx, _playerID));
}
} else {
actions = actions.concat(this.enumerate(G, ctx, ctx.currentPlayer));
objectives = objectives.concat(this.objectives(G, ctx, ctx.currentPlayer));
}
return {
// Game state at this node.
state: state,
// Parent of the node.
parent: parent,
// Move used to get to this node.
parentAction: parentAction,
// Unexplored actions.
actions: actions,
// Current objectives.
objectives: objectives,
// Children of the node.
children: [],
// Number of simulations that pass through this node.
visits: 0,
// Number of wins for this node.
value: 0
};
}
}, {
key: "select",
value: function select(node) {
// This node has unvisited children.
if (node.actions.length > 0) {
return node;
} // This is a terminal node.
if (node.children.length == 0) {
return node;
}
var selectedChild = null;
var best = 0.0;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = node.children[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
var child = _step.value;
var childVisits = child.visits + Number.EPSILON;
var uct = child.value / childVisits + Math.sqrt(2 * Math.log(node.visits) / childVisits);
if (selectedChild == null || uct > best) {
best = uct;
selectedChild = child;
}
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator["return"] != null) {
_iterator["return"]();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return this.select(selectedChild);
}
}, {
key: "expand",
value: function expand(node) {
var actions = node.actions;
if (actions.length == 0 || node.state.ctx.gameover !== undefined) {
return node;
}
var id = this.random(actions.length);
var action = actions[id];
node.actions.splice(id, 1);
var childState = this.reducer(node.state, action);
var childNode = this.createNode({
state: childState,
parentAction: action,
parent: node
});
node.children.push(childNode);
return childNode;
}
}, {
key: "playout",
value: function playout(node) {
var _this2 = this;
var state = node.state;
var playoutDepth = this.getOpt('playoutDepth');
if (typeof this.playoutDepth === 'function') {
playoutDepth = this.playoutDepth(state.G, state.ctx);
}
var _loop = function _loop(i) {
var _state = state,
G = _state.G,
ctx = _state.ctx;
var playerID = ctx.currentPlayer;
if (ctx.activePlayers) {
playerID = Object.keys(ctx.activePlayers)[0];
}
var moves = _this2.enumerate(G, ctx, playerID); // Check if any objectives are met.
var objectives = _this2.objectives(G, ctx);
var score = Object.keys(objectives).reduce(function (score, key) {
var objective = objectives[key];
if (objective.checker(G, ctx)) {
return score + objective.weight;
}
return score;
}, 0.0); // If so, stop and return the score.
if (score > 0) {
return {
v: {
score: score
}
};
}
if (!moves || moves.length == 0) {
return {
v: undefined
};
}
var id = _this2.random(moves.length);
var childState = _this2.reducer(state, moves[id]);
state = childState;
};
for (var i = 0; i < playoutDepth && state.ctx.gameover === undefined; i++) {
var _ret = _loop();
if (game._typeof(_ret) === "object") return _ret.v;
}
return state.ctx.gameover;
}
}, {
key: "backpropagate",
value: function backpropagate(node) {
var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
node.visits++;
if (result.score !== undefined) {
node.value += result.score;
}
if (result.draw === true) {
node.value += 0.5;
}
if (node.parentAction && result.winner === node.parentAction.payload.playerID) {
node.value++;
}
if (node.parent) {
this.backpropagate(node.parent, result);
}
}
}, {
key: "play",
value: function play(state, playerID) {
var _this3 = this;
var root = this.createNode({
state: state,
playerID: playerID
});
var numIterations = this.getOpt('iterations');
if (typeof this.iterations === 'function') {
numIterations = this.iterations(state.G, state.ctx);
}
var getResult = function getResult() {
var selectedChild = null;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = root.children[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
var child = _step2.value;
if (selectedChild == null || child.visits > selectedChild.visits) {
selectedChild = child;
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
_iterator2["return"]();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
var action = selectedChild && selectedChild.parentAction;
var metadata = root;
return {
action: action,
metadata: metadata
};
};
return new Promise(function (resolve) {
var iteration = function iteration() {
for (var i = 0; i < CHUNK_SIZE && _this3.iterationCounter < numIterations; i++) {
var leaf = _this3.select(root);
var child = _this3.expand(leaf);
var result = _this3.playout(child);
_this3.backpropagate(child, result);
_this3.iterationCounter++;
}
_this3.iterationCallback({
iterationCounter: _this3.iterationCounter,
numIterations: numIterations,
metadata: root
});
};
_this3.iterationCounter = 0;
if (_this3.getOpt('async')) {
var asyncIteration = function asyncIteration() {
if (_this3.iterationCounter < numIterations) {
iteration();
setTimeout(asyncIteration, 0);
} else {
resolve(getResult());
}
};
asyncIteration();
} else {
while (_this3.iterationCounter < numIterations) {
iteration();
}
resolve(getResult());
}
});
}
}]);
return MCTSBot;
}(Bot);
/**
* Bot that picks a move at random.
*/
var RandomBot =
/*#__PURE__*/
function (_Bot) {
game._inherits(RandomBot, _Bot);
function RandomBot() {
game._classCallCheck(this, RandomBot);
return game._possibleConstructorReturn(this, game._getPrototypeOf(RandomBot).apply(this, arguments));
}
game._createClass(RandomBot, [{
key: "play",
value: function play(_ref, playerID) {
var G = _ref.G,
ctx = _ref.ctx;
var moves = this.enumerate(G, ctx, playerID);
return Promise.resolve({
action: this.random(moves)
});
}
}]);
return RandomBot;
}(Bot);
/*
* Copyright 2018 The boardgame.io Authors
*
* Use of this source code is governed by a MIT-style
* license that can be found in the LICENSE file or at
* https://opensource.org/licenses/MIT.
*/
/**
* Make a single move on the client with a bot.
*
* @param {...object} client - The game client.
* @param {...object} bot - The bot.
*/
async function Step(client, bot) {
var state = client.store.getState();
var playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
var _ref = await bot.play(state, playerID),
action = _ref.action,
metadata = _ref.metadata;
if (action) {
action.payload.metadata = metadata;
client.store.dispatch(action);
}
return action;
}
/**
* Simulates the game till the end or a max depth.
*
* @param {...object} game - The game object.
* @param {...object} bots - An array of bots.
* @param {...object} state - The game state to start from.
*/
async function Simulate(_ref2) {
var game$1 = _ref2.game,
bots = _ref2.bots,
state = _ref2.state,
depth = _ref2.depth;
if (depth === undefined) depth = 10000;
var reducer = game.CreateGameReducer({
game: game$1,
numPlayers: state.ctx.numPlayers
});
var metadata = null;
var iter = 0;
while (state.ctx.gameover === undefined && iter < depth) {
var playerID = state.ctx.currentPlayer;
if (state.ctx.activePlayers) {
playerID = Object.keys(state.ctx.activePlayers)[0];
}
var bot = bots instanceof Bot ? bots : bots[playerID];
var t = await bot.play(state, playerID);
if (!t.action) {
break;
}
metadata = t.metadata;
state = reducer(state, t.action);
iter++;
}
return {
state: state,
metadata: metadata
};
}
exports.Bot = Bot;
exports.MCTSBot = MCTSBot;
exports.RandomBot = RandomBot;
exports.Simulate = Simulate;
exports.Step = Step;
| {
"content_hash": "3314d9db0f76e07ed055375e209970b6",
"timestamp": "",
"source": "github",
"line_count": 601,
"max_line_length": 177,
"avg_line_length": 24.42595673876872,
"alnum_prop": 0.5450272479564032,
"repo_name": "cdnjs/cdnjs",
"id": "06886d8f561a03502c6c582ef17f99af3567f984",
"size": "14680",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/boardgame-io/0.39.11/cjs/ai-8490fdc5.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
'''
Project: Geothon (https://github.com/MBoustani/Geothon)
File: Vector/create_shp_line.py
Description: This code create a line shapefile from multi-points.
Author: Maziyar Boustani (github.com/MBoustani)
'''
import os
try:
import ogr
except ImportError:
from osgeo import ogr
try:
import osr
except ImportError:
from osgeo import osr
latitudes = [30, 10, 40]
longitudes = [10, 20, 30]
shapefile = 'line.shp'
layer_name = 'line_layer'
#create ESRI shapefile dirver
driver = ogr.GetDriverByName('ESRI Shapefile')
#create shapefile data_source(file)
if os.path.exists(shapefile):
driver.DeleteDataSource(shapefile)
data_source = driver.CreateDataSource(shapefile)
#create spatial reference
srs = osr.SpatialReference()
#in this case wgs84
srs.ImportFromEPSG(4326)
#create shapefile layer as line data with wgs84 as spatial reference
layer = data_source.CreateLayer(layer_name, srs, ogr.wkbLineString)
#create "Name" column for attribute table and set type as string
field_name = ogr.FieldDefn("Name", ogr.OFTString)
field_name.SetWidth(24)
layer.CreateField(field_name)
#define line geometry
line = ogr.Geometry(ogr.wkbLineString)
#add points into line geometry
line.AddPoint(longitudes[0], latitudes[0])
line.AddPoint(longitudes[1], latitudes[1])
line.AddPoint(longitudes[2], latitudes[1])
#create a feature
feature = ogr.Feature(layer.GetLayerDefn())
#set feature geometry
feature.SetGeometry(line)
#add field "Name" to feature
feature.SetField("Name", 'line_one')
#create feature in layer
layer.CreateFeature(feature)
| {
"content_hash": "7b51b16876dccbd2815f85b2ae50ee4c",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 68,
"avg_line_length": 25.047619047619047,
"alnum_prop": 0.7547528517110266,
"repo_name": "MBoustani/Geothon",
"id": "bdcb0e3295939319db751a6a45413270f9fd5019",
"size": "1601",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Create Spatial File/Vector/create_shp_line.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "51458"
},
{
"name": "Python",
"bytes": "96626"
}
],
"symlink_target": ""
} |
/*
Cube System definition file
David Mays
3/17/2009
Structs used to define the shape of the cube
Arrays to define the pins on the Arduino board
*/
#define CUBESIZE 4
#define PLANESIZE CUBESIZE*CUBESIZE
#define PLANETIME 3333 // time each plane is displayed in us -> 100 Hz refresh
#define TIMECONST 100 // multiplies DisplayTime to get ms - why not =100?
//Defines a structure for a layer of LEDs in a cube Really, just a simple 2D array
typedef struct {
prog_uint8_t PROGMEM Grid[CUBESIZE][CUBESIZE];
} PlaneDef;
//Defines a structure for an event on the Cube
//Duration is in milliseconds
//Array of Planes that represent the stacked layers of the cube
typedef struct{
prog_int8_t PROGMEM Duration;
PlaneDef PROGMEM Plane[CUBESIZE];
} CubeEventDef;
int LEDPin[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int PlanePin[] = {16,17,18,19};
| {
"content_hash": "419ac34d848204a440c3aae0949086d5",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 87,
"avg_line_length": 25.676470588235293,
"alnum_prop": 0.7250859106529209,
"repo_name": "davidmays/arduino-led-controls",
"id": "442bf2d6c7eef84e576b9e71eeb12c6352168c8b",
"size": "873",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "LED_Cube_System/CubeSystem.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "6242"
},
{
"name": "Processing",
"bytes": "15225"
}
],
"symlink_target": ""
} |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div id="appMasthead" class="ui inverted vertical center aligned segment">
<div class="ui text container appCenterVertical">
<h1 class="ui inverted header">
Roster Manager
</h1>
<h2>Start Managing Your Roster Now!</h2>
<a href="/team/page">
<div class="ui huge primary button">View Team<i class="right arrow icon"></i></div>
</a>
</div>
</div>
<div class="ui container stripe segment">
<div id="appRosterCards" class="ui link cards">
{roster}
<div class="card" onclick="window.location.href='/SinglePlayer/index/{PlayerID}'">
<div class="image">
<img src="img/players/{Image}">
</div>
<div class="content">
<div class="header">{PlayerName}</div>
<div class="meta">
<a>Number {Num}</a>
<a>Position {Pos}</a>
</div>
</div>
<div class="extra content">
<span class="right floated">
{College}
</span>
</div>
</div>
{/roster}
</div>
</div> | {
"content_hash": "cac120d71e2eae43effb3645215d0ea2",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 90,
"avg_line_length": 27.05128205128205,
"alnum_prop": 0.590521327014218,
"repo_name": "duy159/Comp4711",
"id": "86e760a65cf8f3f3d05cdfeddd66bf40c5e70b9a",
"size": "1055",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "application/views/welcome_message.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "412"
},
{
"name": "CSS",
"bytes": "1437501"
},
{
"name": "HTML",
"bytes": "1965"
},
{
"name": "JavaScript",
"bytes": "1379222"
},
{
"name": "PHP",
"bytes": "125219"
}
],
"symlink_target": ""
} |
package org.openkilda.wfm.topology.flowhs.fsm.yflow.update;
import org.openkilda.floodlight.api.request.rulemanager.DeleteSpeakerCommandsRequest;
import org.openkilda.messaging.command.yflow.YFlowRequest;
import org.openkilda.pce.PathComputer;
import org.openkilda.persistence.PersistenceManager;
import org.openkilda.rulemanager.RuleManager;
import org.openkilda.wfm.CommandContext;
import org.openkilda.wfm.share.flow.resources.FlowResourcesManager;
import org.openkilda.wfm.share.logger.FlowOperationsDashboardLogger;
import org.openkilda.wfm.share.metrics.MeterRegistryHolder;
import org.openkilda.wfm.topology.flowhs.fsm.common.YFlowProcessingFsm;
import org.openkilda.wfm.topology.flowhs.fsm.common.actions.AllocateYFlowResourcesAction;
import org.openkilda.wfm.topology.flowhs.fsm.common.actions.RevertYFlowStatusAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.YFlowUpdateFsm.Event;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.YFlowUpdateFsm.State;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.CompleteYFlowUpdatingAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.DeallocateNewYFlowResourcesAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.DeallocateOldYFlowResourcesAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.HandleNotCompletedCommandsAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.HandleNotDeallocatedResourcesAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.HandleNotRevertedSubFlowAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.HandleNotUpdatedSubFlowAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.InstallNewMetersAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.InstallReallocatedMetersAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnFinishedAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnFinishedWithErrorAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnReceivedInstallResponseAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnReceivedRemoveResponseAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnReceivedResponseAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnReceivedValidateResponseAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnRevertSubFlowAllocatedAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnSubFlowAllocatedAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnSubFlowRevertedAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnSubFlowUpdatedAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.OnTimeoutOperationAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.RemoveNewMetersAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.RemoveOldMetersAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.RevertSubFlowsAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.RevertYFlowAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.UpdateSubFlowsAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.UpdateYFlowAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.ValidateNewMetersAction;
import org.openkilda.wfm.topology.flowhs.fsm.yflow.update.actions.ValidateYFlowAction;
import org.openkilda.wfm.topology.flowhs.model.RequestedFlow;
import org.openkilda.wfm.topology.flowhs.model.yflow.YFlowResources;
import org.openkilda.wfm.topology.flowhs.service.FlowGenericCarrier;
import org.openkilda.wfm.topology.flowhs.service.FlowUpdateService;
import org.openkilda.wfm.topology.flowhs.service.yflow.YFlowEventListener;
import io.micrometer.core.instrument.LongTaskTimer;
import io.micrometer.core.instrument.LongTaskTimer.Sample;
import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.squirrelframework.foundation.fsm.StateMachineBuilder;
import org.squirrelframework.foundation.fsm.StateMachineBuilderFactory;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@Getter
@Setter
@Slf4j
public final class YFlowUpdateFsm extends YFlowProcessingFsm<YFlowUpdateFsm, State, Event, YFlowUpdateContext,
FlowGenericCarrier, YFlowEventListener> {
private YFlowRequest originalFlow;
private YFlowRequest targetFlow;
private YFlowResources oldResources;
private final Set<String> subFlows = new HashSet<>();
private final Set<String> updatingSubFlows = new HashSet<>();
private final Set<String> failedSubFlows = new HashSet<>();
private final Set<String> allocatedSubFlows = new HashSet<>();
private String mainAffinityFlowId;
private Collection<RequestedFlow> requestedFlows;
private String diverseFlowId;
private Collection<DeleteSpeakerCommandsRequest> deleteOldYFlowCommands;
private YFlowUpdateFsm(@NonNull CommandContext commandContext, @NonNull FlowGenericCarrier carrier,
@NonNull String yFlowId, @NonNull Collection<YFlowEventListener> eventListeners) {
super(Event.NEXT, Event.ERROR, commandContext, carrier, yFlowId, eventListeners);
}
public void addSubFlow(String flowId) {
subFlows.add(flowId);
}
public boolean isUpdatingSubFlow(String flowId) {
return updatingSubFlows.contains(flowId);
}
public void addUpdatingSubFlow(String flowId) {
updatingSubFlows.add(flowId);
}
public void removeUpdatingSubFlow(String flowId) {
updatingSubFlows.remove(flowId);
}
public void clearUpdatingSubFlows() {
updatingSubFlows.clear();
}
public void addFailedSubFlow(String flowId) {
failedSubFlows.add(flowId);
}
public void clearFailedSubFlows() {
failedSubFlows.clear();
}
public boolean isFailedSubFlow(String flowId) {
return failedSubFlows.contains(flowId);
}
public void addAllocatedSubFlow(String flowId) {
allocatedSubFlows.add(flowId);
}
public void clearAllocatedSubFlows() {
allocatedSubFlows.clear();
}
@Override
protected String getCrudActionName() {
return "update";
}
public static class Factory {
private final StateMachineBuilder<YFlowUpdateFsm, State, Event, YFlowUpdateContext> builder;
private final FlowGenericCarrier carrier;
public Factory(@NonNull FlowGenericCarrier carrier, @NonNull PersistenceManager persistenceManager,
@NonNull PathComputer pathComputer, @NonNull FlowResourcesManager resourcesManager,
@NonNull RuleManager ruleManager, @NonNull FlowUpdateService flowUpdateService,
int resourceAllocationRetriesLimit, int speakerCommandRetriesLimit) {
this.carrier = carrier;
builder = StateMachineBuilderFactory.create(YFlowUpdateFsm.class, State.class, Event.class,
YFlowUpdateContext.class, CommandContext.class, FlowGenericCarrier.class, String.class,
Collection.class);
FlowOperationsDashboardLogger dashboardLogger = new FlowOperationsDashboardLogger(log);
builder.transition()
.from(State.INITIALIZED)
.to(State.YFLOW_VALIDATED)
.on(Event.NEXT)
.perform(new ValidateYFlowAction(persistenceManager, dashboardLogger));
builder.transition()
.from(State.INITIALIZED)
.to(State.FINISHED_WITH_ERROR)
.on(Event.TIMEOUT);
builder.transition()
.from(State.YFLOW_VALIDATED)
.to(State.YFLOW_UPDATED)
.on(Event.NEXT)
.perform(new UpdateYFlowAction(persistenceManager, ruleManager));
builder.transitions()
.from(State.YFLOW_VALIDATED)
.toAmong(State.REVERTING_YFLOW_STATUS, State.REVERTING_YFLOW_STATUS)
.onEach(Event.TIMEOUT, Event.ERROR);
builder.transitions()
.from(State.YFLOW_UPDATED)
.toAmong(State.UPDATING_SUB_FLOWS, State.REVERTING_YFLOW_UPDATE, State.REVERTING_YFLOW_UPDATE)
.onEach(Event.NEXT, Event.TIMEOUT, Event.ERROR);
builder.defineParallelStatesOn(State.UPDATING_SUB_FLOWS, State.SUB_FLOW_UPDATING_STARTED);
builder.defineState(State.SUB_FLOW_UPDATING_STARTED)
.addEntryAction(new UpdateSubFlowsAction(flowUpdateService));
builder.internalTransition()
.within(State.UPDATING_SUB_FLOWS)
.on(Event.SUB_FLOW_ALLOCATED)
.perform(new OnSubFlowAllocatedAction(persistenceManager));
builder.internalTransition()
.within(State.UPDATING_SUB_FLOWS)
.on(Event.SUB_FLOW_UPDATED)
.perform(new OnSubFlowUpdatedAction(flowUpdateService));
builder.internalTransition()
.within(State.UPDATING_SUB_FLOWS)
.on(Event.SUB_FLOW_FAILED)
.perform(new HandleNotUpdatedSubFlowAction(persistenceManager));
builder.transitions()
.from(State.UPDATING_SUB_FLOWS)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW, State.ALL_PENDING_OPERATIONS_COMPLETED)
.onEach(Event.FAILED_TO_UPDATE_SUB_FLOWS, Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.UPDATING_SUB_FLOWS)
.to(State.ALL_SUB_FLOWS_UPDATED)
.on(Event.ALL_SUB_FLOWS_UPDATED);
builder.transitions()
.from(State.ALL_SUB_FLOWS_UPDATED)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.ALL_SUB_FLOWS_UPDATED)
.to(State.REMOVING_OLD_YFLOW_METERS)
.on(Event.NEXT)
.perform(new RemoveOldMetersAction(persistenceManager, ruleManager));
builder.internalTransition()
.within(State.REMOVING_OLD_YFLOW_METERS)
.on(Event.RESPONSE_RECEIVED)
.perform(new OnReceivedRemoveResponseAction(speakerCommandRetriesLimit));
builder.transition()
.from(State.REMOVING_OLD_YFLOW_METERS)
.to(State.OLD_YFLOW_METERS_REMOVED)
.on(Event.YFLOW_METERS_REMOVED);
builder.transitions()
.from(State.REMOVING_OLD_YFLOW_METERS)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.OLD_YFLOW_METERS_REMOVED)
.to(State.NEW_YFLOW_RESOURCES_ALLOCATED)
.on(Event.NEXT)
.perform(new AllocateYFlowResourcesAction<>(persistenceManager, resourceAllocationRetriesLimit,
pathComputer, resourcesManager));
builder.transition()
.from(State.NEW_YFLOW_RESOURCES_ALLOCATED)
.to(State.INSTALLING_NEW_YFLOW_METERS)
.on(Event.NEXT)
.perform(new InstallNewMetersAction(persistenceManager, ruleManager));
builder.transitions()
.from(State.NEW_YFLOW_RESOURCES_ALLOCATED)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.internalTransition()
.within(State.INSTALLING_NEW_YFLOW_METERS)
.on(Event.RESPONSE_RECEIVED)
.perform(new OnReceivedInstallResponseAction(speakerCommandRetriesLimit));
builder.transition()
.from(State.INSTALLING_NEW_YFLOW_METERS)
.to(State.NEW_YFLOW_METERS_INSTALLED)
.on(Event.ALL_YFLOW_METERS_INSTALLED);
builder.transitions()
.from(State.INSTALLING_NEW_YFLOW_METERS)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.NEW_YFLOW_METERS_INSTALLED)
.to(State.VALIDATING_NEW_YFLOW_METERS)
.on(Event.NEXT)
.perform(new ValidateNewMetersAction(persistenceManager));
builder.transitions()
.from(State.NEW_YFLOW_METERS_INSTALLED)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.internalTransition()
.within(State.VALIDATING_NEW_YFLOW_METERS)
.on(Event.RESPONSE_RECEIVED)
.perform(new OnReceivedValidateResponseAction(speakerCommandRetriesLimit));
builder.transition()
.from(State.VALIDATING_NEW_YFLOW_METERS)
.to(State.NEW_YFLOW_METERS_VALIDATED)
.on(Event.YFLOW_METERS_VALIDATED);
builder.transitions()
.from(State.VALIDATING_NEW_YFLOW_METERS)
.toAmong(State.REVERTING_YFLOW, State.REVERTING_YFLOW)
.onEach(Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.NEW_YFLOW_METERS_VALIDATED)
.to(State.YFLOW_INSTALLATION_COMPLETED)
.on(Event.NEXT)
.perform(new CompleteYFlowUpdatingAction(persistenceManager, dashboardLogger));
builder.transitions()
.from(State.YFLOW_INSTALLATION_COMPLETED)
.toAmong(State.DEALLOCATING_OLD_YFLOW_RESOURCES, State.FINISHED_WITH_ERROR,
State.FINISHED_WITH_ERROR)
.onEach(Event.NEXT, Event.ERROR, Event.TIMEOUT);
builder.transition()
.from(State.DEALLOCATING_OLD_YFLOW_RESOURCES)
.to(State.OLD_YFLOW_RESOURCES_DEALLOCATED)
.on(Event.NEXT)
.perform(new DeallocateOldYFlowResourcesAction(persistenceManager, resourcesManager));
builder.transition()
.from(State.OLD_YFLOW_RESOURCES_DEALLOCATED)
.to(State.FINISHED)
.on(Event.NEXT);
builder.transition()
.from(State.OLD_YFLOW_RESOURCES_DEALLOCATED)
.to(State.FINISHED_WITH_ERROR)
.on(Event.ERROR)
.perform(new HandleNotDeallocatedResourcesAction());
builder.onEntry(State.ALL_PENDING_OPERATIONS_COMPLETED)
.perform(new OnTimeoutOperationAction());
builder.internalTransition()
.within(State.ALL_PENDING_OPERATIONS_COMPLETED)
.on(Event.SUB_FLOW_UPDATED)
.perform(new OnReceivedResponseAction(persistenceManager));
builder.internalTransition()
.within(State.ALL_PENDING_OPERATIONS_COMPLETED)
.on(Event.SUB_FLOW_FAILED)
.perform(new OnReceivedResponseAction(persistenceManager));
builder.transition()
.from(State.ALL_PENDING_OPERATIONS_COMPLETED)
.to(State.REVERTING_YFLOW)
.on(Event.REVERT_YFLOW);
builder.transition()
.from(State.REVERTING_YFLOW)
.to(State.REMOVING_YFLOW_METERS)
.on(Event.NEXT)
.perform(new RemoveNewMetersAction(persistenceManager, ruleManager));
builder.internalTransition()
.within(State.REMOVING_YFLOW_METERS)
.on(Event.RESPONSE_RECEIVED)
.perform(new OnReceivedRemoveResponseAction(speakerCommandRetriesLimit));
builder.transition()
.from(State.REMOVING_YFLOW_METERS)
.to(State.YFLOW_METERS_REMOVED)
.on(Event.YFLOW_METERS_REMOVED);
builder.transition()
.from(State.REMOVING_YFLOW_METERS)
.to(State.YFLOW_METERS_REMOVED)
.on(Event.ERROR)
.perform(new HandleNotCompletedCommandsAction());
builder.transition()
.from(State.YFLOW_METERS_REMOVED)
.to(State.DEALLOCATING_NEW_YFLOW_RESOURCES)
.on(Event.NEXT);
builder.transition()
.from(State.DEALLOCATING_NEW_YFLOW_RESOURCES)
.to(State.NEW_YFLOW_RESOURCES_DEALLOCATED)
.on(Event.NEXT)
.perform(new DeallocateNewYFlowResourcesAction(persistenceManager, resourcesManager));
builder.transition()
.from(State.NEW_YFLOW_RESOURCES_DEALLOCATED)
.to(State.REVERTING_SUB_FLOWS)
.on(Event.NEXT);
builder.transition()
.from(State.NEW_YFLOW_RESOURCES_DEALLOCATED)
.to(State.REVERTING_SUB_FLOWS)
.on(Event.ERROR)
.perform(new HandleNotDeallocatedResourcesAction());
builder.defineParallelStatesOn(State.REVERTING_SUB_FLOWS, State.SUB_FLOW_REVERTING_STARTED);
builder.defineState(State.SUB_FLOW_REVERTING_STARTED)
.addEntryAction(new RevertSubFlowsAction(flowUpdateService));
builder.internalTransition()
.within(State.REVERTING_SUB_FLOWS)
.on(Event.SUB_FLOW_ALLOCATED)
.perform(new OnRevertSubFlowAllocatedAction(persistenceManager));
builder.internalTransition()
.within(State.REVERTING_SUB_FLOWS)
.on(Event.SUB_FLOW_UPDATED)
.perform(new OnSubFlowRevertedAction(flowUpdateService));
builder.internalTransition()
.within(State.REVERTING_SUB_FLOWS)
.on(Event.SUB_FLOW_FAILED)
.perform(new HandleNotRevertedSubFlowAction());
builder.transitions()
.from(State.REVERTING_SUB_FLOWS)
.toAmong(State.ALL_SUB_FLOWS_REVERTED, State.ALL_SUB_FLOWS_REVERTED)
.onEach(Event.FAILED_TO_UPDATE_SUB_FLOWS, Event.ERROR);
builder.transition()
.from(State.REVERTING_SUB_FLOWS)
.to(State.ALL_SUB_FLOWS_REVERTED)
.on(Event.ALL_SUB_FLOWS_REVERTED);
builder.transition()
.from(State.ALL_SUB_FLOWS_REVERTED)
.to(State.REVERTING_YFLOW_UPDATE)
.on(Event.NEXT);
builder.transition()
.from(State.REVERTING_YFLOW_UPDATE)
.to(State.YFLOW_UPDATE_REVERTED)
.on(Event.NEXT)
.perform(new RevertYFlowAction(persistenceManager));
builder.transition()
.from(State.YFLOW_UPDATE_REVERTED)
.to(State.INSTALLING_OLD_YFLOW_METERS)
.on(Event.NEXT)
.perform(new InstallReallocatedMetersAction(persistenceManager, ruleManager));
builder.internalTransition()
.within(State.INSTALLING_OLD_YFLOW_METERS)
.on(Event.RESPONSE_RECEIVED)
.perform(new OnReceivedInstallResponseAction(speakerCommandRetriesLimit));
builder.transition()
.from(State.INSTALLING_OLD_YFLOW_METERS)
.to(State.OLD_YFLOW_METERS_INSTALLED)
.on(Event.ALL_YFLOW_METERS_INSTALLED);
builder.transitions()
.from(State.INSTALLING_OLD_YFLOW_METERS)
.toAmong(State.OLD_YFLOW_METERS_INSTALLED, State.OLD_YFLOW_METERS_INSTALLED)
.onEach(Event.ERROR, Event.TIMEOUT)
.perform(new HandleNotCompletedCommandsAction());
builder.transition()
.from(State.OLD_YFLOW_METERS_INSTALLED)
.to(State.YFLOW_REVERTED)
.on(Event.NEXT)
.perform(new CompleteYFlowUpdatingAction(persistenceManager, dashboardLogger));
builder.transition()
.from(State.YFLOW_REVERTED)
.to(State.FINISHED_WITH_ERROR)
.on(Event.NEXT);
builder.transition()
.from(State.REVERTING_YFLOW_STATUS)
.to(State.FINISHED_WITH_ERROR)
.on(Event.NEXT)
.perform(new RevertYFlowStatusAction<>(persistenceManager, dashboardLogger));
builder.defineFinalState(State.FINISHED)
.addEntryAction(new OnFinishedAction(dashboardLogger));
builder.defineFinalState(State.FINISHED_WITH_ERROR)
.addEntryAction(new OnFinishedWithErrorAction(dashboardLogger));
}
public YFlowUpdateFsm newInstance(@NonNull CommandContext commandContext, @NonNull String flowId,
@NonNull Collection<YFlowEventListener> eventListeners) {
YFlowUpdateFsm fsm = builder.newStateMachine(State.INITIALIZED, commandContext, carrier, flowId,
eventListeners);
fsm.addTransitionCompleteListener(event ->
log.debug("YFlowUpdateFsm, transition to {} on {}", event.getTargetState(), event.getCause()));
MeterRegistryHolder.getRegistry().ifPresent(registry -> {
Sample sample = LongTaskTimer.builder("fsm.active_execution")
.register(registry)
.start();
fsm.addTerminateListener(e -> {
long duration = sample.stop();
if (fsm.getCurrentState() == State.FINISHED) {
registry.timer("fsm.execution.success")
.record(duration, TimeUnit.NANOSECONDS);
} else if (fsm.getCurrentState() == State.FINISHED_WITH_ERROR) {
registry.timer("fsm.execution.failed")
.record(duration, TimeUnit.NANOSECONDS);
}
});
});
return fsm;
}
}
public enum State {
INITIALIZED,
YFLOW_VALIDATED,
YFLOW_UPDATED,
UPDATING_SUB_FLOWS,
SUB_FLOW_UPDATING_STARTED,
ALL_SUB_FLOWS_UPDATED,
NEW_YFLOW_RESOURCES_ALLOCATED,
INSTALLING_NEW_YFLOW_METERS,
NEW_YFLOW_METERS_INSTALLED,
VALIDATING_NEW_YFLOW_METERS,
NEW_YFLOW_METERS_VALIDATED,
REMOVING_OLD_YFLOW_METERS,
OLD_YFLOW_METERS_REMOVED,
DEALLOCATING_OLD_YFLOW_RESOURCES,
OLD_YFLOW_RESOURCES_DEALLOCATED,
COMPLETE_YFLOW_INSTALLATION,
YFLOW_INSTALLATION_COMPLETED,
FINISHED,
ALL_PENDING_OPERATIONS_COMPLETED,
REVERTING_YFLOW,
YFLOW_REVERTED,
REMOVING_YFLOW_METERS,
YFLOW_METERS_REMOVED,
DEALLOCATING_NEW_YFLOW_RESOURCES,
NEW_YFLOW_RESOURCES_DEALLOCATED,
REVERTING_YFLOW_UPDATE,
YFLOW_UPDATE_REVERTED,
REVERTING_SUB_FLOWS,
SUB_FLOW_REVERTING_STARTED,
ALL_SUB_FLOWS_REVERTED,
YFLOW_RESOURCES_REALLOCATED,
INSTALLING_OLD_YFLOW_METERS,
OLD_YFLOW_METERS_INSTALLED,
REVERTING_YFLOW_STATUS,
FINISHED_WITH_ERROR;
}
public enum Event {
NEXT,
RESPONSE_RECEIVED,
SUB_FLOW_ALLOCATED,
SUB_FLOW_UPDATED,
SUB_FLOW_FAILED,
ALL_SUB_FLOWS_UPDATED,
FAILED_TO_UPDATE_SUB_FLOWS,
ALL_YFLOW_METERS_INSTALLED,
YFLOW_METERS_VALIDATED,
YFLOW_METERS_REMOVED,
SUB_FLOW_REVERTED,
ALL_SUB_FLOWS_REVERTED,
TIMEOUT,
REVERT_YFLOW,
ERROR
}
}
| {
"content_hash": "11a572847dcacac1c65f6decc55e4f58",
"timestamp": "",
"source": "github",
"line_count": 540,
"max_line_length": 115,
"avg_line_length": 46.105555555555554,
"alnum_prop": 0.6274249909627666,
"repo_name": "telstra/open-kilda",
"id": "5b66e4ac3fa1d849fd2cba0378c7a9466102d60a",
"size": "25514",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src-java/flowhs-topology/flowhs-storm-topology/src/main/java/org/openkilda/wfm/topology/flowhs/fsm/yflow/update/YFlowUpdateFsm.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "89798"
},
{
"name": "CMake",
"bytes": "4314"
},
{
"name": "CSS",
"bytes": "233390"
},
{
"name": "Dockerfile",
"bytes": "30541"
},
{
"name": "Groovy",
"bytes": "2234079"
},
{
"name": "HTML",
"bytes": "362166"
},
{
"name": "Java",
"bytes": "14631453"
},
{
"name": "JavaScript",
"bytes": "369015"
},
{
"name": "Jinja",
"bytes": "937"
},
{
"name": "Makefile",
"bytes": "20500"
},
{
"name": "Python",
"bytes": "367364"
},
{
"name": "Shell",
"bytes": "62664"
},
{
"name": "TypeScript",
"bytes": "867537"
}
],
"symlink_target": ""
} |
CustomModules = new Mongo.Collection("customModules");
Meteor.methods({
}); | {
"content_hash": "5f7c75c639f5f4473de94b3df751e00f",
"timestamp": "",
"source": "github",
"line_count": 5,
"max_line_length": 54,
"avg_line_length": 15.4,
"alnum_prop": 0.7402597402597403,
"repo_name": "eaaajkb/teambuilding-app",
"id": "74b0c0ad44c4c0cd92c9fcfecad41deda615c40f",
"size": "77",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "model/CustomModules.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "122662"
},
{
"name": "HTML",
"bytes": "74113"
},
{
"name": "JavaScript",
"bytes": "2635115"
}
],
"symlink_target": ""
} |
package view.commands.gameplayInput;
import gamecontrollers.Facade;
import view.ViewController;
public class TabDeveloperInputCommand extends GameplayInputCommand {
public TabDeveloperInputCommand(ViewController viewController) {
super(viewController);
}
@Override public void doExecute() {
Facade.getInstance().tabThroughDevelopers();
}
} | {
"content_hash": "4e4692caf941ed81472f93f2a6355521",
"timestamp": "",
"source": "github",
"line_count": 15,
"max_line_length": 68,
"avg_line_length": 24.8,
"alnum_prop": 0.7688172043010753,
"repo_name": "nwcaldwell/Java",
"id": "361ba13fe6eee3ecb1877dc4949e51bc02c19c92",
"size": "417",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/view/commands/gameplayInput/TabDeveloperInputCommand.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "303353"
},
{
"name": "Shell",
"bytes": "335"
}
],
"symlink_target": ""
} |
package finiteStateMachine;
import KeepAway.SoccerTeam.soccerTeamNames;
import players.PlayerInterface;
public class ChaseBall extends State<PlayerInterface> {
boolean debugThis = false;
static ChaseBall instance = null;
static {
instance = new ChaseBall();
}
@Override
public void enter(PlayerInterface player) {
if (debugThis) {
System.out.println("\t\t------ chasing ball on");
}
player.Steering().SetTarget(player.Ball().Pos());
player.Steering().SeekOn();
if (debugThis) {
System.out.println("\t\tPlayer: " + player.ID() + "------ SeekOn");
}
}
@Override
public void execute(PlayerInterface player) {
//if the ball is within kicking range the player changes state to KickBall.
if (player.BallWithinKickingRange()) {
if (player.Team().getTeamName() == soccerTeamNames.takers) {
player.GetFSM().changeState(KickBall.Instance());
} else {
player.GetFSM().changeState(WaitForAgentChoice.Instance());
}
if (debugThis) {
System.out.println("Player: " + player.ID() + " set to " + player.GetFSM().getCurrentState().getClass());
}
return;
}
//if the player is the closest player to the ball then he should keep
//chasing it
if (player.isClosestTeamMemberToBall()) {
player.Steering().SetTarget(player.Ball().Pos());
return;
}
//if the player is not closest to the ball anymore, he should return back
//to his home region and wait for another opportunity
player.GetFSM().changeState(ReturnToHomeSpot.Instance());
if (debugThis) {
System.out.println("Player: " + player.ID() + " set to " + player.GetFSM().getCurrentState().getClass());
}
// player.GetFSM().setState(Wait.Instance());
}
@Override
public void exit(PlayerInterface player) {
player.Steering().SeekOff();
if (debugThis) {
System.out.println("\t\tPlayer: " + player.ID() + "------ SeekOff");
}
}
public static ChaseBall Instance() {
return instance;
}
}
| {
"content_hash": "17beb811eb29081b2edb15de44e29a04",
"timestamp": "",
"source": "github",
"line_count": 74,
"max_line_length": 121,
"avg_line_length": 30.62162162162162,
"alnum_prop": 0.5816416593115622,
"repo_name": "chaostrigger/rl-library",
"id": "9c8ed0f9a901587ca972494452919d727d67268a",
"size": "2266",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "projects/environments/experimental/KeepAway/src/finiteStateMachine/ChaseBall.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "75964"
},
{
"name": "C++",
"bytes": "3154298"
},
{
"name": "CSS",
"bytes": "11927"
},
{
"name": "HTML",
"bytes": "3287272"
},
{
"name": "Java",
"bytes": "1336022"
},
{
"name": "Makefile",
"bytes": "8625"
},
{
"name": "Matlab",
"bytes": "28065"
},
{
"name": "Python",
"bytes": "142408"
},
{
"name": "Shell",
"bytes": "66770"
}
],
"symlink_target": ""
} |
require('./Button.css')
var React = require('react')
var Button = React.createClass({
propTypes: {
onClick: React.PropTypes.func.isRequired,
active: React.PropTypes.bool,
className: React.PropTypes.string,
tabIndex: React.PropTypes.string
},
getDefaultProps() {
return {
active: false,
tabIndex: '0'
}
},
handleClick(e) {
this.props.onClick(e)
},
handleKeyPress(e) {
if (e.key === 'Enter' || e.key === ' ') {
this.props.onClick(e)
}
},
render() {
var {active, className, onClick, tabIndex, ...props} = this.props // eslint-disable-line no-unused-vars
var classNames = ['Button']
if (active) classNames.push('Button--active')
if (className) classNames.push(className)
return <span className={classNames.join(' ')}
onClick={this.handleClick}
onKeyPress={this.handleKeyPress}
role="button"
tabIndex={tabIndex}
{...props}>
{this.props.children}
</span>
}
})
module.exports = Button
| {
"content_hash": "a8fa532404560f3bd8055ea6aa7ae67a",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 107,
"avg_line_length": 24.166666666666668,
"alnum_prop": 0.6167487684729064,
"repo_name": "insin/ideas-md",
"id": "e23220716aad6e5197e91ee58c339b7030816073",
"size": "1015",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/components/Button.js",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "2983"
},
{
"name": "HTML",
"bytes": "265"
},
{
"name": "JavaScript",
"bytes": "18953"
}
],
"symlink_target": ""
} |
@(notification: gitbucket.notifications.model.Watch.Notification,
repository: gitbucket.core.service.RepositoryService.RepositoryInfo)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.view.helpers
@gitbucket.core.helper.html.dropdown(value = notification.name, right = true){
@gitbucket.notifications.model.Watch.Notification.values.map { n =>
<li>
<a href="#" class="watch" data-id="@n.id">
@gitbucket.core.helper.html.checkicon(notification.id == n.id)
<span class="notification-label strong">@n.name</span>
<div class="muted small">@n.description</div>
</a>
</li>
}
}
<script>
$(function(){
$('a.watch').click(function(){
var selected = $(this);
var notification = selected.data('id');
$.post('@helpers.url(repository)/watch',
{ notification : notification },
function(){
$('a.watch i.octicon-check').removeClass('octicon-check');
$('a.watch[data-id=' + notification + '] i').addClass('octicon-check');
// Update button label
var label = selected.find('span.notification-label').text().trim();
selected.parents('div.btn-group').find('button>span.strong').text(label);
}
);
return false;
});
});
</script>
| {
"content_hash": "462eeb848a89fcdd0d5bce4bbfadaebd",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 123,
"avg_line_length": 37.294117647058826,
"alnum_prop": 0.6482649842271293,
"repo_name": "shimamoto/gitbucket-notifications-plugin",
"id": "93b7c44cb85e7c23b611fd72df78f94693084259",
"size": "1268",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/twirl/gitbucket/notifications/watch.scala.html",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "2660"
},
{
"name": "Scala",
"bytes": "16444"
}
],
"symlink_target": ""
} |
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from docusign_esign.client.configuration import Configuration
class SigningGroup(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'created': 'str',
'created_by': 'str',
'error_details': 'ErrorDetails',
'group_email': 'str',
'group_name': 'str',
'group_type': 'str',
'modified': 'str',
'modified_by': 'str',
'signing_group_id': 'str',
'users': 'list[SigningGroupUser]'
}
attribute_map = {
'created': 'created',
'created_by': 'createdBy',
'error_details': 'errorDetails',
'group_email': 'groupEmail',
'group_name': 'groupName',
'group_type': 'groupType',
'modified': 'modified',
'modified_by': 'modifiedBy',
'signing_group_id': 'signingGroupId',
'users': 'users'
}
def __init__(self, _configuration=None, **kwargs): # noqa: E501
"""SigningGroup - a model defined in Swagger""" # noqa: E501
if _configuration is None:
_configuration = Configuration()
self._configuration = _configuration
self._created = None
self._created_by = None
self._error_details = None
self._group_email = None
self._group_name = None
self._group_type = None
self._modified = None
self._modified_by = None
self._signing_group_id = None
self._users = None
self.discriminator = None
setattr(self, "_{}".format('created'), kwargs.get('created', None))
setattr(self, "_{}".format('created_by'), kwargs.get('created_by', None))
setattr(self, "_{}".format('error_details'), kwargs.get('error_details', None))
setattr(self, "_{}".format('group_email'), kwargs.get('group_email', None))
setattr(self, "_{}".format('group_name'), kwargs.get('group_name', None))
setattr(self, "_{}".format('group_type'), kwargs.get('group_type', None))
setattr(self, "_{}".format('modified'), kwargs.get('modified', None))
setattr(self, "_{}".format('modified_by'), kwargs.get('modified_by', None))
setattr(self, "_{}".format('signing_group_id'), kwargs.get('signing_group_id', None))
setattr(self, "_{}".format('users'), kwargs.get('users', None))
@property
def created(self):
"""Gets the created of this SigningGroup. # noqa: E501
# noqa: E501
:return: The created of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._created
@created.setter
def created(self, created):
"""Sets the created of this SigningGroup.
# noqa: E501
:param created: The created of this SigningGroup. # noqa: E501
:type: str
"""
self._created = created
@property
def created_by(self):
"""Gets the created_by of this SigningGroup. # noqa: E501
# noqa: E501
:return: The created_by of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._created_by
@created_by.setter
def created_by(self, created_by):
"""Sets the created_by of this SigningGroup.
# noqa: E501
:param created_by: The created_by of this SigningGroup. # noqa: E501
:type: str
"""
self._created_by = created_by
@property
def error_details(self):
"""Gets the error_details of this SigningGroup. # noqa: E501
:return: The error_details of this SigningGroup. # noqa: E501
:rtype: ErrorDetails
"""
return self._error_details
@error_details.setter
def error_details(self, error_details):
"""Sets the error_details of this SigningGroup.
:param error_details: The error_details of this SigningGroup. # noqa: E501
:type: ErrorDetails
"""
self._error_details = error_details
@property
def group_email(self):
"""Gets the group_email of this SigningGroup. # noqa: E501
# noqa: E501
:return: The group_email of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._group_email
@group_email.setter
def group_email(self, group_email):
"""Sets the group_email of this SigningGroup.
# noqa: E501
:param group_email: The group_email of this SigningGroup. # noqa: E501
:type: str
"""
self._group_email = group_email
@property
def group_name(self):
"""Gets the group_name of this SigningGroup. # noqa: E501
The name of the group. # noqa: E501
:return: The group_name of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._group_name
@group_name.setter
def group_name(self, group_name):
"""Sets the group_name of this SigningGroup.
The name of the group. # noqa: E501
:param group_name: The group_name of this SigningGroup. # noqa: E501
:type: str
"""
self._group_name = group_name
@property
def group_type(self):
"""Gets the group_type of this SigningGroup. # noqa: E501
# noqa: E501
:return: The group_type of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._group_type
@group_type.setter
def group_type(self, group_type):
"""Sets the group_type of this SigningGroup.
# noqa: E501
:param group_type: The group_type of this SigningGroup. # noqa: E501
:type: str
"""
self._group_type = group_type
@property
def modified(self):
"""Gets the modified of this SigningGroup. # noqa: E501
# noqa: E501
:return: The modified of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._modified
@modified.setter
def modified(self, modified):
"""Sets the modified of this SigningGroup.
# noqa: E501
:param modified: The modified of this SigningGroup. # noqa: E501
:type: str
"""
self._modified = modified
@property
def modified_by(self):
"""Gets the modified_by of this SigningGroup. # noqa: E501
# noqa: E501
:return: The modified_by of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._modified_by
@modified_by.setter
def modified_by(self, modified_by):
"""Sets the modified_by of this SigningGroup.
# noqa: E501
:param modified_by: The modified_by of this SigningGroup. # noqa: E501
:type: str
"""
self._modified_by = modified_by
@property
def signing_group_id(self):
"""Gets the signing_group_id of this SigningGroup. # noqa: E501
When set to **true** and the feature is enabled in the sender's account, the signing recipient is required to draw signatures and initials at each signature/initial tab ( instead of adopting a signature/initial style or only drawing a signature/initial once). # noqa: E501
:return: The signing_group_id of this SigningGroup. # noqa: E501
:rtype: str
"""
return self._signing_group_id
@signing_group_id.setter
def signing_group_id(self, signing_group_id):
"""Sets the signing_group_id of this SigningGroup.
When set to **true** and the feature is enabled in the sender's account, the signing recipient is required to draw signatures and initials at each signature/initial tab ( instead of adopting a signature/initial style or only drawing a signature/initial once). # noqa: E501
:param signing_group_id: The signing_group_id of this SigningGroup. # noqa: E501
:type: str
"""
self._signing_group_id = signing_group_id
@property
def users(self):
"""Gets the users of this SigningGroup. # noqa: E501
# noqa: E501
:return: The users of this SigningGroup. # noqa: E501
:rtype: list[SigningGroupUser]
"""
return self._users
@users.setter
def users(self, users):
"""Sets the users of this SigningGroup.
# noqa: E501
:param users: The users of this SigningGroup. # noqa: E501
:type: list[SigningGroupUser]
"""
self._users = users
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
if issubclass(SigningGroup, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SigningGroup):
return False
return self.to_dict() == other.to_dict()
def __ne__(self, other):
"""Returns true if both objects are not equal"""
if not isinstance(other, SigningGroup):
return True
return self.to_dict() != other.to_dict()
| {
"content_hash": "71546a2a06e06b4c1cedefabee628899",
"timestamp": "",
"source": "github",
"line_count": 363,
"max_line_length": 281,
"avg_line_length": 29.542699724517906,
"alnum_prop": 0.5738530399104812,
"repo_name": "docusign/docusign-python-client",
"id": "c85ac1472e8777a1b8b5745ae7cb4e984c3ded22",
"size": "10741",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "docusign_esign/models/signing_group.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Python",
"bytes": "9687716"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Index Fungorum
#### Published in
null
#### Original name
Usnea neocaledonica f. abortiva Räsänen
### Remarks
null | {
"content_hash": "b0713b1308a2ceabaafce7fcc32e28a5",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 39,
"avg_line_length": 11.076923076923077,
"alnum_prop": 0.7222222222222222,
"repo_name": "mdoering/backbone",
"id": "f6085eca7fc620c2b5fd550d39e1aa980782370e",
"size": "208",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Fungi/Ascomycota/Lecanoromycetes/Lecanorales/Parmeliaceae/Usnea/Usnea neocaledonica/Usnea neocaledonica abortiva/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
module Azure::Network::Mgmt::V2018_11_01
module Models
#
# Defines values for ApplicationGatewaySslPolicyType
#
module ApplicationGatewaySslPolicyType
Predefined = "Predefined"
Custom = "Custom"
end
end
end
| {
"content_hash": "c1d929c87600df24cab3a93762b9f9a6",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 56,
"avg_line_length": 22.09090909090909,
"alnum_prop": 0.691358024691358,
"repo_name": "Azure/azure-sdk-for-ruby",
"id": "6785b438312b2dd56d04c09fdc38ded3c70c9785",
"size": "407",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "management/azure_mgmt_network/lib/2018-11-01/generated/azure_mgmt_network/models/application_gateway_ssl_policy_type.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "345216400"
},
{
"name": "Shell",
"bytes": "305"
}
],
"symlink_target": ""
} |
<HTML><HEAD>
<TITLE>Review for Drive Me Crazy (1999)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">
</HEAD>
<BODY BGCOLOR="#FFFFFF" TEXT="#000000">
<H1 ALIGN="CENTER" CLASS="title"><A HREF="/Title?0164114">Drive Me Crazy (1999)</A></H1><H3 ALIGN=CENTER>reviewed by<BR><A HREF="/ReviewsBy?Steve+Rhodes">Steve Rhodes</A></H3><HR WIDTH="40%" SIZE="4">
<PRE>DRIVE ME CRAZY
A film review by Steve Rhodes
Copyright 1999 Steve Rhodes
RATING (0 TO ****): * 1/2</PRE>
<P>Every other week of late brings another generic teen comedy to our local
movie theaters. With interchangeable plot points and photogenic young
actors, most of them share the same remarkable blandness. This week's
entry is John Schultz's DRIVE ME CRAZY. Lamer than most, it does manage
to rise above the worst of the genre, flicks such as the unbearable
JAWBREAKER.</P>
<P>In my generation it was silly surfer movies that the studios put out by
the dozens in order to attract those lucrative teen audiences, flush
with cash and ready to spring for lots of refreshments at the concession
stand. The latest slew of teen movies is no worse than the old surfer
ones and no better. Think of them all as representative of a class of
movies that are the cinematic equivalent of elevator music. They pass
the time and rarely offend.</P>
<P>DRIVE ME CRAZY takes place at a high school about to celebrate its
centennial year, which means -- are you sitting down? -- the movie will
end in a -- surprise! -- big prom. There have been so many proms this
year that one feels underdressed in the theater without a tux or a prom
dress.</P>
<P>The story concerns two next-door neighbors, Nicole (Melissa Joan Hart)
and Chase (Adrian Grenier), who used to share the same tree house when
they were little. Now seniors, they don't like each other anymore.</P>
<P>When Nicole isn't asked to the prom as planned by the school's hottest
jock, she asks the disheveled Chase to help her out. If he'll go with
her, she suggests she'll treat him to some sex as a reward. To make it
look genuine, he'll have to get cleaned up, and they'll have to act like
they're an item.</P>
<P>Think they'll end up falling in love for real? Well, duh!</P>
<P>And will there be several scenes of underage drinking and binging? Of
course. This movie tries to make it seem more harmless by having one
kid, Dave (Mark Webber) be the school's designated driver. He provides
free taxi service to all of those too drunk to drive. Poor Dave gets
ridiculed for taking such a demeaning job. Being considered a loser,
Dave, you can be sure, will eventually be fixed up by the script with a
gorgeous girl as his compensation.</P>
<P>The completely predictable and uneventful story ends with a small twist
that would have provided a good starting point for a more substantial
comedy. But it might have demanded some intelligence on the part of the
viewers, something Rob Thomas's significantly underdeveloped script
avoids like the plague.</P>
<P>This much can be said. Even if their acting in this movie isn't much,
Hart and Grenier seem to be having a good time. Too bad the same can't
be said of most of the audience.</P>
<P>DRIVE ME CRAZY runs 1:34. It is rated PG-13 for teen alcohol and drug
use and for language. It would be acceptable for most teenagers.</P>
<P>Email: <A HREF="mailto:Steve.Rhodes@InternetReviews.com">Steve.Rhodes@InternetReviews.com</A>
Web: <A HREF="http://www.InternetReviews.com">http://www.InternetReviews.com</A></P>
<HR><P CLASS=flush><SMALL>The review above was posted to the
<A HREF="news:rec.arts.movies.reviews">rec.arts.movies.reviews</A> newsgroup (<A HREF="news:de.rec.film.kritiken">de.rec.film.kritiken</A> for German reviews).<BR>
The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.<BR>
Please direct comments/criticisms of the review to relevant newsgroups.<BR>
Broken URLs inthe reviews are the responsibility of the author.<BR>
The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.
</SMALL></P>
<P ALIGN=CENTER>Related links: <A HREF="/Reviews/">index of all rec.arts.movies.reviews reviews</A></P>
</P></BODY></HTML>
| {
"content_hash": "97575bddc360e6c2c5005f343933dd01",
"timestamp": "",
"source": "github",
"line_count": 71,
"max_line_length": 200,
"avg_line_length": 61.33802816901409,
"alnum_prop": 0.7478760045924225,
"repo_name": "xianjunzhengbackup/code",
"id": "7e73ac888cdf187a06a4f753a750f84ae7ba657f",
"size": "4355",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "data science/machine_learning_for_the_web/chapter_4/movie/20881.html",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "BitBake",
"bytes": "113"
},
{
"name": "BlitzBasic",
"bytes": "256"
},
{
"name": "CSS",
"bytes": "49827"
},
{
"name": "HTML",
"bytes": "157006325"
},
{
"name": "JavaScript",
"bytes": "14029"
},
{
"name": "Jupyter Notebook",
"bytes": "4875399"
},
{
"name": "Mako",
"bytes": "2060"
},
{
"name": "Perl",
"bytes": "716"
},
{
"name": "Python",
"bytes": "874414"
},
{
"name": "R",
"bytes": "454"
},
{
"name": "Shell",
"bytes": "3984"
}
],
"symlink_target": ""
} |
auth_config="-Djava.security.auth.login.config=exchange_config/jaas.config"
auth_policy="-Djava.security.policy=exchange_config/auth.policy"
# Allow overriding of the location of the auth files
for arg in $@
do
if [[ "${arg}" =~ "-Djava.security.auth.login.config=" ]]; then
auth_config=""
fi
if [[ "${arg}" =~ "-Djava.security.policy=" ]]; then
auth_policy=""
fi
done
# Determine if we should configure https support, by whether the key/cert and pw are mounted into the container
if [[ -f "$JETTY_BASE/etc/keystore" && -f "$JETTY_BASE/etc/keypassword" ]]; then
# Add the https and ssl modules to the jetty config
java -jar "$JETTY_HOME/start.jar" --create-startd --add-to-start=https,ssl
# Get the keystore and key pass phrase and set those arguments
echo "Configuring https/ssl support"
pw=$(cat $JETTY_BASE/etc/keypassword)
pw_arg1="-Djetty.sslContext.keyStorePassword=$pw"
pw_arg2="-Djetty.sslContext.keyManagerPassword=$pw"
else
echo "Files keystore and keystore are not in $JETTY_BASE/etc/, so not configuring https/ssl support."
fi
echo java -jar $JETTY_HOME/start.jar $auth_config $auth_policy $pw_arg1 $pw_arg2 $@
java -jar $JETTY_HOME/start.jar $auth_config $auth_policy $pw_arg1 $pw_arg2 $@
| {
"content_hash": "774fa28f825b855b17774c21cd472ff9",
"timestamp": "",
"source": "github",
"line_count": 31,
"max_line_length": 111,
"avg_line_length": 40.483870967741936,
"alnum_prop": 0.7059760956175298,
"repo_name": "cgiroua/exchange-api",
"id": "d2cd1f5fdf92e2634c84b613227ff5ae12f38016",
"size": "1359",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "start_exchange.sh",
"mode": "33261",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "6216"
},
{
"name": "JavaScript",
"bytes": "38125"
},
{
"name": "Makefile",
"bytes": "9570"
},
{
"name": "Scala",
"bytes": "964960"
},
{
"name": "Shell",
"bytes": "116166"
}
],
"symlink_target": ""
} |
name 'blackfire'
maintainer 'Olivier Dolbeau'
maintainer_email 'odolbeau@gmail.com'
license 'Apache 2.0'
description 'Installs blackfire'
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '1.0.5'
recipe 'default', 'Installs blackfire-php & blackfire-agent.'
supports 'debian'
supports 'ubuntu'
supports 'redhat'
supports 'fedora'
supports 'centos'
depends 'apt'
depends 'yum'
| {
"content_hash": "e2774eedd8c5daf3cc7d3b614ee9aacf",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 72,
"avg_line_length": 22.77777777777778,
"alnum_prop": 0.7560975609756098,
"repo_name": "odolbeau/cookbook-blackfire",
"id": "392d434c4e46ab0a41797e96a76620996dd42ddb",
"size": "410",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ruby",
"bytes": "4812"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>bcds-parent</artifactId>
<groupId>gov.va.vba</groupId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../bcds</relativePath>
</parent>
<artifactId>bcds-soap-producer</artifactId>
<name>BCDS - SOAP Publisher</name>
<build>
</build>
</project>
| {
"content_hash": "693446c85f0b8a509923aab0770a3e8e",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 108,
"avg_line_length": 33,
"alnum_prop": 0.631578947368421,
"repo_name": "VHAINNOVATIONS/BCDS",
"id": "1bb9b565e71281df1b0740c4d76dc119c1caa46a",
"size": "627",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Code/bcds-soap-producer/pom.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "24139"
},
{
"name": "Batchfile",
"bytes": "1058"
},
{
"name": "CSS",
"bytes": "15964"
},
{
"name": "HTML",
"bytes": "123734"
},
{
"name": "Java",
"bytes": "547224"
},
{
"name": "JavaScript",
"bytes": "237726"
},
{
"name": "PLSQL",
"bytes": "184526"
},
{
"name": "Python",
"bytes": "146150"
}
],
"symlink_target": ""
} |
#include <linux/device.h>
#include <linux/errno.h>
#include <linux/list.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_irq.h>
#include <linux/string.h>
#include <linux/slab.h>
/**
* irq_of_parse_and_map - Parse and map an interrupt into linux virq space
* @dev: Device node of the device whose interrupt is to be mapped
* @index: Index of the interrupt to map
*
* This function is a wrapper that chains of_irq_parse_one() and
* irq_create_of_mapping() to make things easier to callers
*/
unsigned int irq_of_parse_and_map(struct device_node *dev, int index)
{
struct of_phandle_args oirq;
if (of_irq_parse_one(dev, index, &oirq))
return 0;
return irq_create_of_mapping(&oirq);
}
EXPORT_SYMBOL_GPL(irq_of_parse_and_map);
/**
* of_irq_find_parent - Given a device node, find its interrupt parent node
* @child: pointer to device node
*
* Returns a pointer to the interrupt parent node, or NULL if the interrupt
* parent could not be determined.
*/
struct device_node *of_irq_find_parent(struct device_node *child)
{
struct device_node *p;
const __be32 *parp;
if (!of_node_get(child))
return NULL;
do {
parp = of_get_property(child, "interrupt-parent", NULL);
if (parp == NULL)
p = of_get_parent(child);
else {
if (of_irq_workarounds & OF_IMAP_NO_PHANDLE)
p = of_node_get(of_irq_dflt_pic);
else
p = of_find_node_by_phandle(be32_to_cpup(parp));
}
of_node_put(child);
child = p;
} while (p && of_get_property(p, "#interrupt-cells", NULL) == NULL);
return p;
}
/**
* of_irq_parse_raw - Low level interrupt tree parsing
* @parent: the device interrupt parent
* @addr: address specifier (start of "reg" property of the device) in be32 format
* @out_irq: structure of_irq updated by this function
*
* Returns 0 on success and a negative number on error
*
* This function is a low-level interrupt tree walking function. It
* can be used to do a partial walk with synthetized reg and interrupts
* properties, for example when resolving PCI interrupts when no device
* node exist for the parent. It takes an interrupt specifier structure as
* input, walks the tree looking for any interrupt-map properties, translates
* the specifier for each map, and then returns the translated map.
*/
int of_irq_parse_raw(const __be32 *addr, struct of_phandle_args *out_irq)
{
struct device_node *ipar, *tnode, *old = NULL, *newpar = NULL;
__be32 initial_match_array[MAX_PHANDLE_ARGS];
const __be32 *match_array = initial_match_array;
const __be32 *tmp, *imap, *imask, dummy_imask[] = { [0 ... MAX_PHANDLE_ARGS] = ~0 };
u32 intsize = 1, addrsize, newintsize = 0, newaddrsize = 0;
int imaplen, match, i;
#ifdef DEBUG
of_print_phandle_args("of_irq_parse_raw: ", out_irq);
#endif
ipar = of_node_get(out_irq->np);
/* First get the #interrupt-cells property of the current cursor
* that tells us how to interpret the passed-in intspec. If there
* is none, we are nice and just walk up the tree
*/
do {
tmp = of_get_property(ipar, "#interrupt-cells", NULL);
if (tmp != NULL) {
intsize = be32_to_cpu(*tmp);
break;
}
tnode = ipar;
ipar = of_irq_find_parent(ipar);
of_node_put(tnode);
} while (ipar);
if (ipar == NULL) {
pr_debug(" -> no parent found !\n");
goto fail;
}
pr_debug("of_irq_parse_raw: ipar=%s, size=%d\n", of_node_full_name(ipar), intsize);
if (out_irq->args_count != intsize)
return -EINVAL;
/* Look for this #address-cells. We have to implement the old linux
* trick of looking for the parent here as some device-trees rely on it
*/
old = of_node_get(ipar);
do {
tmp = of_get_property(old, "#address-cells", NULL);
tnode = of_get_parent(old);
of_node_put(old);
old = tnode;
} while (old && tmp == NULL);
of_node_put(old);
old = NULL;
addrsize = (tmp == NULL) ? 2 : be32_to_cpu(*tmp);
pr_debug(" -> addrsize=%d\n", addrsize);
/* Range check so that the temporary buffer doesn't overflow */
if (WARN_ON(addrsize + intsize > MAX_PHANDLE_ARGS))
goto fail;
/* Precalculate the match array - this simplifies match loop */
for (i = 0; i < addrsize; i++)
initial_match_array[i] = addr ? addr[i] : 0;
for (i = 0; i < intsize; i++)
initial_match_array[addrsize + i] = cpu_to_be32(out_irq->args[i]);
/* Now start the actual "proper" walk of the interrupt tree */
while (ipar != NULL) {
/* Now check if cursor is an interrupt-controller and if it is
* then we are done
*/
if (of_get_property(ipar, "interrupt-controller", NULL) !=
NULL) {
pr_debug(" -> got it !\n");
return 0;
}
/*
* interrupt-map parsing does not work without a reg
* property when #address-cells != 0
*/
if (addrsize && !addr) {
pr_debug(" -> no reg passed in when needed !\n");
goto fail;
}
/* Now look for an interrupt-map */
imap = of_get_property(ipar, "interrupt-map", &imaplen);
/* No interrupt map, check for an interrupt parent */
if (imap == NULL) {
pr_debug(" -> no map, getting parent\n");
newpar = of_irq_find_parent(ipar);
goto skiplevel;
}
imaplen /= sizeof(u32);
/* Look for a mask */
imask = of_get_property(ipar, "interrupt-map-mask", NULL);
if (!imask)
imask = dummy_imask;
/* Parse interrupt-map */
match = 0;
while (imaplen > (addrsize + intsize + 1) && !match) {
/* Compare specifiers */
match = 1;
for (i = 0; i < (addrsize + intsize); i++, imaplen--)
match &= !((match_array[i] ^ *imap++) & imask[i]);
pr_debug(" -> match=%d (imaplen=%d)\n", match, imaplen);
/* Get the interrupt parent */
if (of_irq_workarounds & OF_IMAP_NO_PHANDLE)
newpar = of_node_get(of_irq_dflt_pic);
else
newpar = of_find_node_by_phandle(be32_to_cpup(imap));
imap++;
--imaplen;
/* Check if not found */
if (newpar == NULL) {
pr_debug(" -> imap parent not found !\n");
goto fail;
}
if (!of_device_is_available(newpar))
match = 0;
/* Get #interrupt-cells and #address-cells of new
* parent
*/
tmp = of_get_property(newpar, "#interrupt-cells", NULL);
if (tmp == NULL) {
pr_debug(" -> parent lacks #interrupt-cells!\n");
goto fail;
}
newintsize = be32_to_cpu(*tmp);
tmp = of_get_property(newpar, "#address-cells", NULL);
newaddrsize = (tmp == NULL) ? 0 : be32_to_cpu(*tmp);
pr_debug(" -> newintsize=%d, newaddrsize=%d\n",
newintsize, newaddrsize);
/* Check for malformed properties */
if (WARN_ON(newaddrsize + newintsize > MAX_PHANDLE_ARGS))
goto fail;
if (imaplen < (newaddrsize + newintsize))
goto fail;
imap += newaddrsize + newintsize;
imaplen -= newaddrsize + newintsize;
pr_debug(" -> imaplen=%d\n", imaplen);
}
if (!match)
goto fail;
/*
* Successfully parsed an interrrupt-map translation; copy new
* interrupt specifier into the out_irq structure
*/
match_array = imap - newaddrsize - newintsize;
for (i = 0; i < newintsize; i++)
out_irq->args[i] = be32_to_cpup(imap - newintsize + i);
out_irq->args_count = intsize = newintsize;
addrsize = newaddrsize;
skiplevel:
/* Iterate again with new parent */
out_irq->np = newpar;
pr_debug(" -> new parent: %s\n", of_node_full_name(newpar));
of_node_put(ipar);
ipar = newpar;
newpar = NULL;
}
fail:
of_node_put(ipar);
of_node_put(newpar);
return -EINVAL;
}
EXPORT_SYMBOL_GPL(of_irq_parse_raw);
/**
* of_irq_parse_one - Resolve an interrupt for a device
* @device: the device whose interrupt is to be resolved
* @index: index of the interrupt to resolve
* @out_irq: structure of_irq filled by this function
*
* This function resolves an interrupt for a node by walking the interrupt tree,
* finding which interrupt controller node it is attached to, and returning the
* interrupt specifier that can be used to retrieve a Linux IRQ number.
*/
int of_irq_parse_one(struct device_node *device, int index, struct of_phandle_args *out_irq)
{
struct device_node *p;
const __be32 *intspec, *tmp, *addr;
u32 intsize, intlen;
int i, res;
pr_debug("of_irq_parse_one: dev=%s, index=%d\n", of_node_full_name(device), index);
/* OldWorld mac stuff is "special", handle out of line */
if (of_irq_workarounds & OF_IMAP_OLDWORLD_MAC)
return of_irq_parse_oldworld(device, index, out_irq);
/* Get the reg property (if any) */
addr = of_get_property(device, "reg", NULL);
/* Try the new-style interrupts-extended first */
res = of_parse_phandle_with_args(device, "interrupts-extended",
"#interrupt-cells", index, out_irq);
if (!res)
return of_irq_parse_raw(addr, out_irq);
/* Get the interrupts property */
intspec = of_get_property(device, "interrupts", &intlen);
if (intspec == NULL)
return -EINVAL;
intlen /= sizeof(*intspec);
pr_debug(" intspec=%d intlen=%d\n", be32_to_cpup(intspec), intlen);
/* Look for the interrupt parent. */
p = of_irq_find_parent(device);
if (p == NULL)
return -EINVAL;
/* Get size of interrupt specifier */
tmp = of_get_property(p, "#interrupt-cells", NULL);
if (tmp == NULL) {
res = -EINVAL;
goto out;
}
intsize = be32_to_cpu(*tmp);
pr_debug(" intsize=%d intlen=%d\n", intsize, intlen);
/* Check index */
if ((index + 1) * intsize > intlen) {
res = -EINVAL;
goto out;
}
/* Copy intspec into irq structure */
intspec += index * intsize;
out_irq->np = p;
out_irq->args_count = intsize;
for (i = 0; i < intsize; i++)
out_irq->args[i] = be32_to_cpup(intspec++);
/* Check if there are any interrupt-map translations to process */
res = of_irq_parse_raw(addr, out_irq);
out:
of_node_put(p);
return res;
}
EXPORT_SYMBOL_GPL(of_irq_parse_one);
/**
* of_irq_to_resource - Decode a node's IRQ and return it as a resource
* @dev: pointer to device tree node
* @index: zero-based index of the irq
* @r: pointer to resource structure to return result into.
*/
int of_irq_to_resource(struct device_node *dev, int index, struct resource *r)
{
int irq = irq_of_parse_and_map(dev, index);
/* Only dereference the resource if both the
* resource and the irq are valid. */
if (r && irq) {
const char *name = NULL;
memset(r, 0, sizeof(*r));
/*
* Get optional "interrupt-names" property to add a name
* to the resource.
*/
of_property_read_string_index(dev, "interrupt-names", index,
&name);
r->start = r->end = irq;
r->flags = IORESOURCE_IRQ | irqd_get_trigger_type(irq_get_irq_data(irq));
r->name = name ? name : of_node_full_name(dev);
}
return irq;
}
EXPORT_SYMBOL_GPL(of_irq_to_resource);
/**
* of_irq_get - Decode a node's IRQ and return it as a Linux irq number
* @dev: pointer to device tree node
* @index: zero-based index of the irq
*
* Returns Linux irq number on success, or -EPROBE_DEFER if the irq domain
* is not yet created.
*
*/
int of_irq_get(struct device_node *dev, int index)
{
int rc;
struct of_phandle_args oirq;
struct irq_domain *domain;
rc = of_irq_parse_one(dev, index, &oirq);
if (rc)
return rc;
domain = irq_find_host(oirq.np);
if (!domain)
return -EPROBE_DEFER;
return irq_create_of_mapping(&oirq);
}
EXPORT_SYMBOL_GPL(of_irq_get);
/**
* of_irq_get_byname - Decode a node's IRQ and return it as a Linux irq number
* @dev: pointer to device tree node
* @name: irq name
*
* Returns Linux irq number on success, or -EPROBE_DEFER if the irq domain
* is not yet created, or error code in case of any other failure.
*/
int of_irq_get_byname(struct device_node *dev, const char *name)
{
int index;
if (unlikely(!name))
return -EINVAL;
index = of_property_match_string(dev, "interrupt-names", name);
if (index < 0)
return index;
return of_irq_get(dev, index);
}
EXPORT_SYMBOL_GPL(of_irq_get_byname);
/**
* of_irq_count - Count the number of IRQs a node uses
* @dev: pointer to device tree node
*/
int of_irq_count(struct device_node *dev)
{
struct of_phandle_args irq;
int nr = 0;
while (of_irq_parse_one(dev, nr, &irq) == 0)
nr++;
return nr;
}
/**
* of_irq_to_resource_table - Fill in resource table with node's IRQ info
* @dev: pointer to device tree node
* @res: array of resources to fill in
* @nr_irqs: the number of IRQs (and upper bound for num of @res elements)
*
* Returns the size of the filled in table (up to @nr_irqs).
*/
int of_irq_to_resource_table(struct device_node *dev, struct resource *res,
int nr_irqs)
{
int i;
for (i = 0; i < nr_irqs; i++, res++)
if (!of_irq_to_resource(dev, i, res))
break;
return i;
}
EXPORT_SYMBOL_GPL(of_irq_to_resource_table);
struct of_intc_desc {
struct list_head list;
struct device_node *dev;
struct device_node *interrupt_parent;
};
/**
* of_irq_init - Scan and init matching interrupt controllers in DT
* @matches: 0 terminated array of nodes to match and init function to call
*
* This function scans the device tree for matching interrupt controller nodes,
* and calls their initialization functions in order with parents first.
*/
void __init of_irq_init(const struct of_device_id *matches)
{
struct device_node *np, *parent = NULL;
struct of_intc_desc *desc, *temp_desc;
struct list_head intc_desc_list, intc_parent_list;
INIT_LIST_HEAD(&intc_desc_list);
INIT_LIST_HEAD(&intc_parent_list);
for_each_matching_node(np, matches) {
if (!of_find_property(np, "interrupt-controller", NULL) ||
!of_device_is_available(np))
continue;
/*
* Here, we allocate and populate an of_intc_desc with the node
* pointer, interrupt-parent device_node etc.
*/
desc = kzalloc(sizeof(*desc), GFP_KERNEL);
if (WARN_ON(!desc))
goto err;
desc->dev = np;
desc->interrupt_parent = of_irq_find_parent(np);
if (desc->interrupt_parent == np)
desc->interrupt_parent = NULL;
list_add_tail(&desc->list, &intc_desc_list);
}
/*
* The root irq controller is the one without an interrupt-parent.
* That one goes first, followed by the controllers that reference it,
* followed by the ones that reference the 2nd level controllers, etc.
*/
while (!list_empty(&intc_desc_list)) {
/*
* Process all controllers with the current 'parent'.
* First pass will be looking for NULL as the parent.
* The assumption is that NULL parent means a root controller.
*/
list_for_each_entry_safe(desc, temp_desc, &intc_desc_list, list) {
const struct of_device_id *match;
int ret;
of_irq_init_cb_t irq_init_cb;
if (desc->interrupt_parent != parent)
continue;
list_del(&desc->list);
match = of_match_node(matches, desc->dev);
if (WARN(!match->data,
"of_irq_init: no init function for %s\n",
match->compatible)) {
kfree(desc);
continue;
}
pr_debug("of_irq_init: init %s @ %p, parent %p\n",
match->compatible,
desc->dev, desc->interrupt_parent);
irq_init_cb = (of_irq_init_cb_t)match->data;
ret = irq_init_cb(desc->dev, desc->interrupt_parent);
if (ret) {
kfree(desc);
continue;
}
/*
* This one is now set up; add it to the parent list so
* its children can get processed in a subsequent pass.
*/
list_add_tail(&desc->list, &intc_parent_list);
}
/* Get the next pending parent that might have children */
desc = list_first_entry_or_null(&intc_parent_list,
typeof(*desc), list);
if (!desc) {
pr_err("of_irq_init: children remain, but no parents\n");
break;
}
list_del(&desc->list);
parent = desc->dev;
kfree(desc);
}
list_for_each_entry_safe(desc, temp_desc, &intc_parent_list, list) {
list_del(&desc->list);
kfree(desc);
}
err:
list_for_each_entry_safe(desc, temp_desc, &intc_desc_list, list) {
list_del(&desc->list);
kfree(desc);
}
}
/**
* of_msi_configure - Set the msi_domain field of a device
* @dev: device structure to associate with an MSI irq domain
* @np: device node for that device
*/
void of_msi_configure(struct device *dev, struct device_node *np)
{
struct device_node *msi_np;
struct irq_domain *d;
msi_np = of_parse_phandle(np, "msi-parent", 0);
if (!msi_np)
return;
d = irq_find_matching_host(msi_np, DOMAIN_BUS_PLATFORM_MSI);
if (!d)
d = irq_find_host(msi_np);
dev_set_msi_domain(dev, d);
}
| {
"content_hash": "e89e9482d6e96fe0e0a496b208d76d8d",
"timestamp": "",
"source": "github",
"line_count": 582,
"max_line_length": 92,
"avg_line_length": 27.5446735395189,
"alnum_prop": 0.6568523485746366,
"repo_name": "publicloudapp/csrutil",
"id": "55317fa9c9dca32557c40b1735ac2c2bec5d4714",
"size": "16835",
"binary": false,
"copies": "184",
"ref": "refs/heads/master",
"path": "linux-4.3/drivers/of/irq.c",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "3984"
},
{
"name": "Awk",
"bytes": "29136"
},
{
"name": "C",
"bytes": "532969471"
},
{
"name": "C++",
"bytes": "3352303"
},
{
"name": "Clojure",
"bytes": "1489"
},
{
"name": "Cucumber",
"bytes": "4701"
},
{
"name": "Groff",
"bytes": "46775"
},
{
"name": "Lex",
"bytes": "55199"
},
{
"name": "Makefile",
"bytes": "1576284"
},
{
"name": "Objective-C",
"bytes": "521540"
},
{
"name": "Perl",
"bytes": "715196"
},
{
"name": "Perl6",
"bytes": "3783"
},
{
"name": "Python",
"bytes": "273092"
},
{
"name": "Shell",
"bytes": "343618"
},
{
"name": "SourcePawn",
"bytes": "4687"
},
{
"name": "UnrealScript",
"bytes": "12797"
},
{
"name": "XS",
"bytes": "1239"
},
{
"name": "Yacc",
"bytes": "114559"
}
],
"symlink_target": ""
} |
/**
* @license Highstock JS v9.3.1 (2021-11-05)
* @module highcharts/modules/datagrouping
* @requires highcharts
*
* Data grouping module
*
* (c) 2010-2021 Torstein Hønsi
*
* License: www.highcharts.com/license
*/
'use strict';
import dataGrouping from '../../Extensions/DataGrouping.js';
export default dataGrouping;
| {
"content_hash": "58013f75dcb43d2dba85d1b6cfdf773f",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 60,
"avg_line_length": 23.428571428571427,
"alnum_prop": 0.7103658536585366,
"repo_name": "cdnjs/cdnjs",
"id": "da98092124cae0a9f7fac0ba0404b698e74954f5",
"size": "329",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ajax/libs/highcharts/9.3.1/es-modules/masters/modules/datagrouping.src.js",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
module Failsafe
module Backends
autoload :Base, 'failsafe/backends/base'
autoload :Airbrake, 'failsafe/backends/airbrake'
autoload :File, 'failsafe/backends/file'
autoload :Stderr, 'failsafe/backends/stderr'
autoload :Exceptional, 'failsafe/backends/exceptional'
autoload :Honeybadger, 'failsafe/backends/honeybadger'
end
end
| {
"content_hash": "a739926e51b1768baa851186cad964af",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 58,
"avg_line_length": 34.27272727272727,
"alnum_prop": 0.7055702917771883,
"repo_name": "zaarly/failsafe",
"id": "9959048a726dd03cde8e1334c4605ea94204f5da",
"size": "377",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "lib/failsafe/failure.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "8868"
}
],
"symlink_target": ""
} |
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<ipojo
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="org.apache.felix.ipojo"
>
<!-- Service Controller -->
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.ControllerCheckService"
name="PS-Controller-1-default">
<provides specifications="org.apache.felix.ipojo.runtime.core.services.FooService">
<controller field="controller"/>
</provides>
<provides specifications="org.apache.felix.ipojo.runtime.core.services.CheckService">
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.ControllerCheckService"
name="PS-Controller-1-false">
<provides specifications="org.apache.felix.ipojo.runtime.core.services.FooService">
<property name="test2" type="string" value="test2"/>
<controller field="controller" value="false"/>
<property name="test" type="string" value="test"/>
</provides>
<provides specifications="org.apache.felix.ipojo.runtime.core.services.CheckService">
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-truetrue">
<provides specifications="org.apache.felix.ipojo.runtime.core.services.FooService">
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="true"/>
<property name="test" type="string" value="test"/>
</provides>
<provides specifications="org.apache.felix.ipojo.runtime.core.services.CheckService">
<controller field="controllerCS" value="true"/>
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-truefalse">
<provides specifications="org.apache.felix.ipojo.runtime.core.services.FooService">
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="false"/>
<property name="test" type="string" value="test"/>
</provides>
<provides specifications="org.apache.felix.ipojo.runtime.core.services.CheckService">
<controller field="controllerCS" value="true"/>
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-spec1">
<provides>
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="false" specification="org.apache.felix.ipojo.runtime.core.services.FooService"/>
<controller field="controllerCS" value="true" specification="org.apache.felix.ipojo.runtime.core.services.CheckService"/>
<property name="test" type="string" value="test"/>
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-spec2">
<provides>
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="true" specification="org.apache.felix.ipojo.runtime.core.services.FooService"/>
<controller field="controllerCS" value="true" specification="org.apache.felix.ipojo.runtime.core.services.CheckService"/>
<property name="test" type="string" value="test"/>
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-spec3">
<provides>
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="true" specification="org.apache.felix.ipojo.runtime.core.services.FooService"/>
<controller field="controllerCS" value="true"/>
<property name="test" type="string" value="test"/>
</provides>
</component>
<component classname="org.apache.felix.ipojo.runtime.core.components.controller.DoubleControllerCheckService"
name="PS-Controller-2-spec4">
<provides>
<property name="test2" type="string" value="test2"/>
<controller field="controllerFoo" value="false" specification="org.apache.felix.ipojo.runtime.core.services.FooService"/>
<controller field="controllerCS" value="true"/>
<property name="test" type="string" value="test"/>
</provides>
</component>
</ipojo>
| {
"content_hash": "3407bcfabcc9b1f7832f60dfea82234c",
"timestamp": "",
"source": "github",
"line_count": 105,
"max_line_length": 133,
"avg_line_length": 53.58095238095238,
"alnum_prop": 0.6724137931034483,
"repo_name": "apache/felix-dev",
"id": "96a16af4c1843f9e8ce30b2b2983bcd83c3e2ebf",
"size": "5626",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ipojo/runtime/core-it/ipojo-core-service-providing-test/src/main/resources/controller/service-controller.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "53237"
},
{
"name": "Groovy",
"bytes": "9231"
},
{
"name": "HTML",
"bytes": "372812"
},
{
"name": "Java",
"bytes": "28836360"
},
{
"name": "JavaScript",
"bytes": "248796"
},
{
"name": "Scala",
"bytes": "40378"
},
{
"name": "Shell",
"bytes": "12628"
},
{
"name": "XSLT",
"bytes": "151258"
}
],
"symlink_target": ""
} |
/*
* This file is part of the opmsg crypto message framework.
*
* (C) 2015 by Sebastian Krahmer,
* sebastian [dot] krahmer [at] gmail [dot] com
*
* opmsg is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* opmsg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with opmsg. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __keystore_h__
#define __keystore_h__
#include <map>
#include <string>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/stat.h>
#include "misc.h"
extern "C" {
#include <openssl/dh.h>
#include <openssl/evp.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
}
namespace opmsg {
class RSAbox {
public:
RSA *pub, *priv;
std::string pub_pem, priv_pem, hex;
RSAbox(RSA *p, RSA *s)
: pub(p), priv(s), pub_pem(""), priv_pem(""), hex("")
{
}
virtual ~RSAbox()
{
if (pub)
RSA_free(pub);
if (priv)
RSA_free(priv);
}
bool can_sign()
{
return priv != nullptr;
}
bool can_decrypt()
{
return priv != nullptr;
}
bool can_encrypt()
{
return pub != nullptr;
}
};
class DHbox {
public:
DH *pub, *priv;
std::string pub_pem, priv_pem, hex;
DHbox(DH *dh1, DH *dh2) : pub(dh1), priv(dh2), pub_pem(""), priv_pem(""), hex("")
{
}
virtual ~DHbox()
{
if (pub)
DH_free(pub);
if (priv)
DH_free(priv);
}
bool can_decrypt()
{
return priv != nullptr;
}
bool can_encrypt()
{
return pub != nullptr;
}
};
class persona {
std::string id, name;
std::map<std::string, DHbox *> keys;
RSAbox *rsa;
DHbox *dh_params;
std::string cfgbase, err;
template<class T>
T build_error(const std::string &msg, T r)
{
err = "persona::";
err += msg;
if (ERR_get_error()) {
err += ":";
err += ERR_error_string(ERR_get_error(), nullptr);
} else if (errno) {
err += ":";
err += strerror(errno);
}
return r;
}
int load_dh(const std::string &hex);
public:
persona(const std::string &dir, const std::string &hash, const std::string &n = "")
: id(hash), name(n), rsa(nullptr), dh_params(nullptr), cfgbase(dir), err("")
{
if (!is_hex_hash(id))
id = "dead";
}
virtual ~persona()
{
for (auto i = keys.begin(); i != keys.end(); ++i) {
if (i->second)
delete i->second;
}
delete rsa;
delete dh_params;
}
bool can_encrypt()
{
return rsa != nullptr && rsa->pub != nullptr;
}
bool can_sign()
{
return rsa != nullptr && rsa->priv != nullptr;
}
bool can_gen_dh()
{
return dh_params != nullptr && dh_params->pub != nullptr;
}
RSAbox *set_rsa(RSA *, RSA *);
RSAbox *get_rsa()
{
return rsa;
}
std::string get_id()
{
return id;
}
std::string get_name()
{
return name;
}
DHbox *new_dh_params();
DHbox *new_dh_params(const std::string &pem);
DHbox *add_dh_pubkey(const std::string &hash, const std::string &pem);
DHbox *add_dh_pubkey(const EVP_MD *md, const std::string &pem);
DHbox *gen_dh_key(const std::string &hash);
DHbox *gen_dh_key(const EVP_MD *md);
DHbox *find_dh_key(const std::string &hex);
int del_dh_id(const std::string &hex);
int del_dh_pub(const std::string &hex);
int del_dh_priv(const std::string &hex);
void used_key(const std::string &hex, bool);
int load(const std::string &hex = "");
std::map<std::string, DHbox *>::iterator first_key();
std::map<std::string, DHbox *>::iterator end_key();
std::map<std::string, DHbox *>::iterator next_key(const std::map<std::string, DHbox *>::iterator &);
int size()
{
return keys.size();
}
const char *why()
{
return err.c_str();
}
friend class keystore;
};
class keystore {
std::string cfgbase;
std::map<std::string, persona *> personas;
const EVP_MD *md;
std::string err;
template<class T>
T build_error(const std::string &msg, T r)
{
int e = 0;
err = "keystore::";
err += msg;
if ((e = ERR_get_error())) {
ERR_load_crypto_strings();
err += ":";
err += ERR_error_string(e, nullptr);
} else if (errno) {
err += ":";
err += strerror(errno);
}
return r;
}
public:
keystore(const std::string& hash, const std::string &base = ".opmsg")
: cfgbase(base), md(nullptr)
{
md = algo2md(hash);
}
~keystore()
{
for (auto i : personas)
delete i.second;
}
const EVP_MD *md_type()
{
return md;
}
int load(const std::string &);
int load();
int gen_rsa(std::string &pub, std::string &priv);
persona *add_persona(const std::string &name, const std::string &rsa_pub_pem, const std::string &rsa_priv_pem, const std::string &dhparams_pem);
persona *find_persona(const std::string &hex);
int size()
{
return personas.size();
}
std::map<std::string, persona *>::iterator first_pers();
std::map<std::string, persona *>::iterator end_pers();
std::map<std::string, persona *>::iterator next_pers(const std::map<std::string, persona *>::iterator &);
const char *why()
{
return err.c_str();
}
};
} // namespace
#endif
| {
"content_hash": "406e162591efe1ccddb44302089ff1ca",
"timestamp": "",
"source": "github",
"line_count": 321,
"max_line_length": 145,
"avg_line_length": 16.660436137071652,
"alnum_prop": 0.6168661181750187,
"repo_name": "dgomez10/xanon",
"id": "eb28f1510114c11723cd75ec6801bcabc4f973b7",
"size": "5348",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "opmsg/keystore.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "5767"
},
{
"name": "Assembly",
"bytes": "602"
},
{
"name": "C",
"bytes": "1834867"
},
{
"name": "C++",
"bytes": "6956615"
},
{
"name": "CSS",
"bytes": "704096"
},
{
"name": "Go",
"bytes": "228"
},
{
"name": "HTML",
"bytes": "5861682"
},
{
"name": "Haskell",
"bytes": "8060"
},
{
"name": "IDL",
"bytes": "84486"
},
{
"name": "Java",
"bytes": "113453"
},
{
"name": "JavaScript",
"bytes": "328606"
},
{
"name": "Makefile",
"bytes": "9270"
},
{
"name": "PHP",
"bytes": "2262806"
},
{
"name": "Perl",
"bytes": "422783"
},
{
"name": "Python",
"bytes": "5266626"
},
{
"name": "R",
"bytes": "3737"
},
{
"name": "SQLPL",
"bytes": "1764"
},
{
"name": "Shell",
"bytes": "45175"
},
{
"name": "Visual Basic",
"bytes": "3078"
}
],
"symlink_target": ""
} |
package pl.touk.nussknacker.engine.process.util
import com.esotericsoftware.kryo.Kryo
import com.esotericsoftware.kryo.io.{Input, Output}
import org.scalatest.flatspec.AnyFlatSpec
import org.scalatest.matchers.should.Matchers
import pl.touk.nussknacker.engine.process.util.Serializers.CaseClassSerializer
class SerializersSpec extends AnyFlatSpec with Matchers {
it should "serialize case objects" in {
val deserialized = serializeAndDeserialize(None)
deserialized shouldBe None
}
it should "serialize usual case class" in {
val obj = UsualCaseClass("a", 1)
val deserialized = serializeAndDeserialize(obj)
deserialized shouldBe obj
}
it should "serialize case class without params" in {
val obj = NoParams()
val deserialized = serializeAndDeserialize(obj)
deserialized shouldBe obj
}
it should "serialize case class with implicit param" in {
implicit val b: Long = 5L
val obj = WithImplicitVal("a")
val deserialized = serializeAndDeserialize(obj)
deserialized shouldBe obj
}
it should "serialize inner case class" in {
val obj = WrapperObj.createInner("abc")
val deserialized = serializeAndDeserialize(obj.asInstanceOf[Product])
//deserialized shouldBe obj // it explodes here because of deserialized obj.$outer ???
deserialized.getClass shouldBe obj.getClass
deserialized.hashCode() shouldBe obj.hashCode()
}
it should "serialize inner case class 2" in {
import scala.collection.JavaConverters._
// runtime type is scala.collection.convert.Wrappers$MutableBufferWrapper
val obj = scala.collection.mutable.Buffer(1,2,3).asJava
val deserialized = serializeAndDeserialize(obj.asInstanceOf[Product])
deserialized shouldBe obj
}
it should "serialize inner case class 3" in {
import scala.collection.JavaConverters._
// runtime type is scala.collection.convert.Wrappers$MutableMapWrapper
val obj = scala.collection.mutable.Map().asJava
val deserialized = serializeAndDeserialize(obj.asInstanceOf[Product])
deserialized shouldBe obj
}
def serializeAndDeserialize(caseClass: Product): Product = {
val kryo = new Kryo()
val out = new Output(1024)
CaseClassSerializer.write(kryo, out, caseClass)
CaseClassSerializer.read(kryo, new Input(out.toBytes), caseClass.getClass.asInstanceOf[Class[Product]])
}
}
case class WithImplicitVal(a: String)(implicit val b: Long)
case class NoParams()
case class UsualCaseClass(a: String, b: Integer, withDefaultValue: String = "aaa")
trait Wrapper {
case class StaticInner(a: String)
}
object WrapperObj extends Wrapper {
def createInner(arg: String) = StaticInner(arg)
} | {
"content_hash": "b000622e125663140205163be2b2852d",
"timestamp": "",
"source": "github",
"line_count": 89,
"max_line_length": 107,
"avg_line_length": 30.134831460674157,
"alnum_prop": 0.749813571961223,
"repo_name": "TouK/nussknacker",
"id": "445e986021abf99e2924f0d49e611a757e9283ee",
"size": "2682",
"binary": false,
"copies": "1",
"ref": "refs/heads/staging",
"path": "engine/flink/executor/src/test/scala/pl/touk/nussknacker/engine/process/util/SerializersSpec.scala",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3757"
},
{
"name": "Dockerfile",
"bytes": "597"
},
{
"name": "HTML",
"bytes": "3573"
},
{
"name": "Java",
"bytes": "240995"
},
{
"name": "JavaScript",
"bytes": "189903"
},
{
"name": "PLSQL",
"bytes": "269"
},
{
"name": "Scala",
"bytes": "5323010"
},
{
"name": "Shell",
"bytes": "42521"
},
{
"name": "Stylus",
"bytes": "60452"
},
{
"name": "TypeScript",
"bytes": "991644"
}
],
"symlink_target": ""
} |
/*
* This code was generated by
* ___ _ _ _ _ _ _ ____ ____ ____ _ ____ ____ _ _ ____ ____ ____ ___ __ __
* | | | | | | | | | __ | | |__| | __ | __ |___ |\ | |___ |__/ |__| | | | |__/
* | |_|_| | |___ | |__| |__| | | | |__] |___ | \| |___ | \ | | | |__| | \
*
* Twilio - Api
* This is the public Twilio REST API.
*
* NOTE: This class is auto generated by OpenAPI Generator.
* https://openapi-generator.tech
* Do not edit the class manually.
*/
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using Twilio.Base;
using Twilio.Clients;
using Twilio.Converters;
using Twilio.Exceptions;
using Twilio.Http;
namespace Twilio.Rest.Api.V2010.Account
{
public class ShortCodeResource : Resource
{
private static Request BuildFetchRequest(FetchShortCodeOptions options, ITwilioRestClient client)
{
string path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json";
string PathAccountSid = options.PathAccountSid ?? client.AccountSid;
path = path.Replace("{"+"AccountSid"+"}", PathAccountSid);
string PathSid = options.PathSid;
path = path.Replace("{"+"Sid"+"}", PathSid);
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
path,
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary> Fetch an instance of a short code </summary>
/// <param name="options"> Fetch ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ShortCode </returns>
public static ShortCodeResource Fetch(FetchShortCodeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#if !NET35
/// <summary> Fetch an instance of a short code </summary>
/// <param name="options"> Fetch ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
public static async System.Threading.Tasks.Task<ShortCodeResource> FetchAsync(FetchShortCodeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildFetchRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary> Fetch an instance of a short code </summary>
/// <param name="pathSid"> The Twilio-provided string that uniquely identifies the ShortCode resource to fetch </param>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to fetch. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ShortCode </returns>
public static ShortCodeResource Fetch(
string pathSid,
string pathAccountSid = null,
ITwilioRestClient client = null)
{
var options = new FetchShortCodeOptions(pathSid){ PathAccountSid = pathAccountSid };
return Fetch(options, client);
}
#if !NET35
/// <summary> Fetch an instance of a short code </summary>
/// <param name="pathSid"> The Twilio-provided string that uniquely identifies the ShortCode resource to fetch </param>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to fetch. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
public static async System.Threading.Tasks.Task<ShortCodeResource> FetchAsync(string pathSid, string pathAccountSid = null, ITwilioRestClient client = null)
{
var options = new FetchShortCodeOptions(pathSid){ PathAccountSid = pathAccountSid };
return await FetchAsync(options, client);
}
#endif
private static Request BuildReadRequest(ReadShortCodeOptions options, ITwilioRestClient client)
{
string path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes.json";
string PathAccountSid = options.PathAccountSid ?? client.AccountSid;
path = path.Replace("{"+"AccountSid"+"}", PathAccountSid);
return new Request(
HttpMethod.Get,
Rest.Domain.Api,
path,
queryParams: options.GetParams(),
headerParams: null
);
}
/// <summary> Retrieve a list of short-codes belonging to the account used to make the request </summary>
/// <param name="options"> Read ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ShortCode </returns>
public static ResourceSet<ShortCodeResource> Read(ReadShortCodeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildReadRequest(options, client));
var page = Page<ShortCodeResource>.FromJson("short_codes", response.Content);
return new ResourceSet<ShortCodeResource>(page, options, client);
}
#if !NET35
/// <summary> Retrieve a list of short-codes belonging to the account used to make the request </summary>
/// <param name="options"> Read ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ShortCodeResource>> ReadAsync(ReadShortCodeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildReadRequest(options, client));
var page = Page<ShortCodeResource>.FromJson("short_codes", response.Content);
return new ResourceSet<ShortCodeResource>(page, options, client);
}
#endif
/// <summary> Retrieve a list of short-codes belonging to the account used to make the request </summary>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to read. </param>
/// <param name="friendlyName"> The string that identifies the ShortCode resources to read. </param>
/// <param name="shortCode"> Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. </param>
/// <param name="pageSize"> How many resources to return in each list page. The default is 50, and the maximum is 1000. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <param name="limit"> Record limit </param>
/// <returns> A single instance of ShortCode </returns>
public static ResourceSet<ShortCodeResource> Read(
string pathAccountSid = null,
string friendlyName = null,
string shortCode = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadShortCodeOptions(){ PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ShortCode = shortCode, PageSize = pageSize, Limit = limit};
return Read(options, client);
}
#if !NET35
/// <summary> Retrieve a list of short-codes belonging to the account used to make the request </summary>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to read. </param>
/// <param name="friendlyName"> The string that identifies the ShortCode resources to read. </param>
/// <param name="shortCode"> Only show the ShortCode resources that match this pattern. You can specify partial numbers and use '*' as a wildcard for any digit. </param>
/// <param name="pageSize"> How many resources to return in each list page. The default is 50, and the maximum is 1000. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <param name="limit"> Record limit </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
public static async System.Threading.Tasks.Task<ResourceSet<ShortCodeResource>> ReadAsync(
string pathAccountSid = null,
string friendlyName = null,
string shortCode = null,
int? pageSize = null,
long? limit = null,
ITwilioRestClient client = null)
{
var options = new ReadShortCodeOptions(){ PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ShortCode = shortCode, PageSize = pageSize, Limit = limit};
return await ReadAsync(options, client);
}
#endif
/// <summary> Fetch the target page of records </summary>
/// <param name="targetUrl"> API-generated URL for the requested results page </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The target page of records </returns>
public static Page<ShortCodeResource> GetPage(string targetUrl, ITwilioRestClient client)
{
client = client ?? TwilioClient.GetRestClient();
var request = new Request(
HttpMethod.Get,
targetUrl
);
var response = client.Request(request);
return Page<ShortCodeResource>.FromJson("short_codes", response.Content);
}
/// <summary> Fetch the next page of records </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The next page of records </returns>
public static Page<ShortCodeResource> NextPage(Page<ShortCodeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetNextPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<ShortCodeResource>.FromJson("short_codes", response.Content);
}
/// <summary> Fetch the previous page of records </summary>
/// <param name="page"> current page of records </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> The previous page of records </returns>
public static Page<ShortCodeResource> PreviousPage(Page<ShortCodeResource> page, ITwilioRestClient client)
{
var request = new Request(
HttpMethod.Get,
page.GetPreviousPageUrl(Rest.Domain.Api)
);
var response = client.Request(request);
return Page<ShortCodeResource>.FromJson("short_codes", response.Content);
}
private static Request BuildUpdateRequest(UpdateShortCodeOptions options, ITwilioRestClient client)
{
string path = "/2010-04-01/Accounts/{AccountSid}/SMS/ShortCodes/{Sid}.json";
string PathAccountSid = options.PathAccountSid ?? client.AccountSid;
path = path.Replace("{"+"AccountSid"+"}", PathAccountSid);
string PathSid = options.PathSid;
path = path.Replace("{"+"Sid"+"}", PathSid);
return new Request(
HttpMethod.Post,
Rest.Domain.Api,
path,
postParams: options.GetParams(),
headerParams: null
);
}
/// <summary> Update a short code with the following parameters </summary>
/// <param name="options"> Update ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ShortCode </returns>
public static ShortCodeResource Update(UpdateShortCodeOptions options, ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = client.Request(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
/// <summary> Update a short code with the following parameters </summary>
/// <param name="options"> Update ShortCode parameters </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
#if !NET35
public static async System.Threading.Tasks.Task<ShortCodeResource> UpdateAsync(UpdateShortCodeOptions options,
ITwilioRestClient client = null)
{
client = client ?? TwilioClient.GetRestClient();
var response = await client.RequestAsync(BuildUpdateRequest(options, client));
return FromJson(response.Content);
}
#endif
/// <summary> Update a short code with the following parameters </summary>
/// <param name="pathSid"> The Twilio-provided string that uniquely identifies the ShortCode resource to update </param>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to update. </param>
/// <param name="friendlyName"> A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. </param>
/// <param name="apiVersion"> The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. </param>
/// <param name="smsUrl"> The URL we should call when receiving an incoming SMS message to this short code. </param>
/// <param name="smsMethod"> The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. </param>
/// <param name="smsFallbackUrl"> The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. </param>
/// <param name="smsFallbackMethod"> The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> A single instance of ShortCode </returns>
public static ShortCodeResource Update(
string pathSid,
string pathAccountSid = null,
string friendlyName = null,
string apiVersion = null,
Uri smsUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
ITwilioRestClient client = null)
{
var options = new UpdateShortCodeOptions(pathSid){ PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ApiVersion = apiVersion, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod };
return Update(options, client);
}
#if !NET35
/// <summary> Update a short code with the following parameters </summary>
/// <param name="pathSid"> The Twilio-provided string that uniquely identifies the ShortCode resource to update </param>
/// <param name="pathAccountSid"> The SID of the [Account](https://www.twilio.com/docs/iam/api/account) that created the ShortCode resource(s) to update. </param>
/// <param name="friendlyName"> A descriptive string that you created to describe this resource. It can be up to 64 characters long. By default, the `FriendlyName` is the short code. </param>
/// <param name="apiVersion"> The API version to use to start a new TwiML session. Can be: `2010-04-01` or `2008-08-01`. </param>
/// <param name="smsUrl"> The URL we should call when receiving an incoming SMS message to this short code. </param>
/// <param name="smsMethod"> The HTTP method we should use when calling the `sms_url`. Can be: `GET` or `POST`. </param>
/// <param name="smsFallbackUrl"> The URL that we should call if an error occurs while retrieving or executing the TwiML from `sms_url`. </param>
/// <param name="smsFallbackMethod"> The HTTP method that we should use to call the `sms_fallback_url`. Can be: `GET` or `POST`. </param>
/// <param name="client"> Client to make requests to Twilio </param>
/// <returns> Task that resolves to A single instance of ShortCode </returns>
public static async System.Threading.Tasks.Task<ShortCodeResource> UpdateAsync(
string pathSid,
string pathAccountSid = null,
string friendlyName = null,
string apiVersion = null,
Uri smsUrl = null,
Twilio.Http.HttpMethod smsMethod = null,
Uri smsFallbackUrl = null,
Twilio.Http.HttpMethod smsFallbackMethod = null,
ITwilioRestClient client = null)
{
var options = new UpdateShortCodeOptions(pathSid){ PathAccountSid = pathAccountSid, FriendlyName = friendlyName, ApiVersion = apiVersion, SmsUrl = smsUrl, SmsMethod = smsMethod, SmsFallbackUrl = smsFallbackUrl, SmsFallbackMethod = smsFallbackMethod };
return await UpdateAsync(options, client);
}
#endif
/// <summary>
/// Converts a JSON string into a ShortCodeResource object
/// </summary>
/// <param name="json"> Raw JSON string </param>
/// <returns> ShortCodeResource object represented by the provided JSON </returns>
public static ShortCodeResource FromJson(string json)
{
try
{
return JsonConvert.DeserializeObject<ShortCodeResource>(json);
}
catch (JsonException e)
{
throw new ApiException(e.Message, e);
}
}
///<summary> The SID of the Account that created this resource </summary>
[JsonProperty("account_sid")]
public string AccountSid { get; private set; }
///<summary> The API version used to start a new TwiML session </summary>
[JsonProperty("api_version")]
public string ApiVersion { get; private set; }
///<summary> The RFC 2822 date and time in GMT that this resource was created </summary>
[JsonProperty("date_created")]
public DateTime? DateCreated { get; private set; }
///<summary> The RFC 2822 date and time in GMT that this resource was last updated </summary>
[JsonProperty("date_updated")]
public DateTime? DateUpdated { get; private set; }
///<summary> A string that you assigned to describe this resource </summary>
[JsonProperty("friendly_name")]
public string FriendlyName { get; private set; }
///<summary> The short code. e.g., 894546. </summary>
[JsonProperty("short_code")]
public string ShortCode { get; private set; }
///<summary> The unique string that identifies this resource </summary>
[JsonProperty("sid")]
public string Sid { get; private set; }
///<summary> HTTP method we use to call the sms_fallback_url </summary>
[JsonProperty("sms_fallback_method")]
public Twilio.Http.HttpMethod SmsFallbackMethod { get; private set; }
///<summary> URL Twilio will request if an error occurs in executing TwiML </summary>
[JsonProperty("sms_fallback_url")]
public Uri SmsFallbackUrl { get; private set; }
///<summary> HTTP method to use when requesting the sms url </summary>
[JsonProperty("sms_method")]
public Twilio.Http.HttpMethod SmsMethod { get; private set; }
///<summary> URL we call when receiving an incoming SMS message to this short code </summary>
[JsonProperty("sms_url")]
public Uri SmsUrl { get; private set; }
///<summary> The URI of this resource, relative to `https://api.twilio.com` </summary>
[JsonProperty("uri")]
public string Uri { get; private set; }
private ShortCodeResource() {
}
}
}
| {
"content_hash": "adf5391609dac62364b72aecc9863f99",
"timestamp": "",
"source": "github",
"line_count": 409,
"max_line_length": 263,
"avg_line_length": 56.67970660146699,
"alnum_prop": 0.5736347165904581,
"repo_name": "twilio/twilio-csharp",
"id": "a70bc39a5d5b218dff02615881a5d165d08ae9b3",
"size": "23182",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Twilio/Rest/Api/V2010/Account/ShortCodeResource.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "13879265"
},
{
"name": "Dockerfile",
"bytes": "1137"
},
{
"name": "Makefile",
"bytes": "1970"
}
],
"symlink_target": ""
} |
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.android.sunshine.app.DetailActivity">
<item
android:id="@+id/action_settings"
android:orderInCategory="100"
android:title="@string/action_settings"
app:showAsAction="never"/>
</menu>
| {
"content_hash": "ee233929e8cf6293090ae84a191050e7",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 70,
"avg_line_length": 39,
"alnum_prop": 0.6736596736596736,
"repo_name": "fechidal89/udacity",
"id": "46883df65b0b071265a435c3fc849f0c0f7a186d",
"size": "429",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "developing-android-apps/create-project-sunchine/app/src/main/res/menu/detail.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "23270"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using ZptSharp.Dom;
namespace ZptSharp.Expressions
{
/// <summary>
/// An object which provides contextual values for the rendering of TALES expressions.
/// </summary>
/// <remarks>
/// <para>
/// This class encapsulates the state for every ZPT operation performed upon a DOM node.
/// That state is contextual, related to the current position in the DOM document and other operations which have occured previously.
/// </para>
/// <para>
/// Some ZPT operations, such as <c>tal:define</c>, will make alterations to the current context. Others might
/// just read it.
/// </para>
/// <para>
/// Apart from the root context (see <see cref="IsRootContext"/>), every context is created by cloning its
/// parent context and substituting a different 'current' DOM node.
/// The structure of parent-to-child expression contexts follows the structure of the DOM.
/// </para>
/// </remarks>
public class ExpressionContext
{
INode currentNode;
/// <summary>
/// Gets or sets a value indicating whether this <see cref="ExpressionContext"/> is the root context.
/// </summary>
/// <remarks>
/// <para>
/// The root context is typically synonymous with the root DOM node in the document.
/// The root context is one which was not created from a parent context.
/// </para>
/// </remarks>
/// <value><c>true</c> if this is the root context; otherwise, <c>false</c>.</value>
public bool IsRootContext { get; set; }
/// <summary>
/// Gets or sets an object representing an error which was encountered whilst rendering or
/// evaluating an expression.
/// </summary>
/// <remarks>
/// <para>
/// The error object will almost always derive from <see cref="Exception"/>.
/// If it is <see langword="null"/> then no error has occurred when rendering; if not then it will describe the error which is currently being handled.
/// </para>
/// </remarks>
/// <value>The error (usually an exception).</value>
public object Error { get; set; }
/// <summary>
/// Gets or sets the model object from which this context was created.
/// </summary>
/// <remarks>
/// <para>
/// This is typically the model which was initially passed to the rendering process.
/// It may be of any object (and could legitimately be <see langword="null"/>).
/// Its precise semantics depend upon the application/current usage of ZptSharp.
/// </para>
/// </remarks>
/// <value>The model.</value>
public object Model { get; set; }
/// <summary>
/// Gets or sets the current DOM node being rendered by this context.
/// </summary>
/// <remarks>
/// <para>
/// Every ZPT operation has a current DOM node, because the ZPT operations are declared within the attributes of element nodes.
/// It would be very unusual for this node object not to be a DOM element node.
/// </para>
/// </remarks>
/// <value>The DOM node (typically an element node).</value>
public INode CurrentNode
{
get => currentNode;
set => currentNode = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets the DOM document being used as a template to render the current rendering request.
/// </summary>
/// <remarks>
/// <para>
/// This is the document currently being rendered.
/// In scenarios where a rendering request touches and draws source from many documents (METAL macro usage),
/// this document is the primary/initial document which was selected as the template.
/// </para>
/// </remarks>
/// <value>The template document.</value>
public IDocument TemplateDocument { get; set; }
/// <summary>
/// Gets the local variable definitions for the current context.
/// </summary>
/// <remarks>
/// <para>
/// Definitions are the variables which are available to ZPT operations using this context.
/// There are three types of definitions.
/// </para>
/// <list type="bullet">
/// <item>
/// <description><c>LocalDefinitions</c> (this property)</description>
/// </item>
/// <item>
/// <description><see cref="GlobalDefinitions"/></description>
/// </item>
/// <item>
/// <description><see cref="Repetitions"/></description>
/// </item>
/// </list>
/// <para>
/// Local definitions are scoped to the DOM element upon which they are created (via the
/// <c>tal:define</c> keyword) and that DOM element's descendents.
/// A locally-defined variable is not visible 'outside' of the element where it was defined.
/// </para>
/// <para>
/// Global definitions are in-scope from the document position at which they were defined and
/// onwards in the document (in source code order).
/// Globally-defined variables do not use the DOM structure; global variables are usable outside of
/// the element & descendents where they were defined, as long as it is after the point of
/// definition in the document source code.
/// </para>
/// <para>
/// Repetitions are a special type of variable which are created only by the <c>tal:repeat</c>
/// operation.
/// They behave identically to locally-defined variables except that they have a standard set of
/// properties, defined by the <see cref="RepetitionInfo"/> class.
/// </para>
/// </remarks>
/// <value>The local definitions.</value>
public IDictionary<string, object> LocalDefinitions { get; }
/// <summary>
/// Gets the global variable definitions for the current context.
/// </summary>
/// <remarks>
/// <para>
/// Definitions are the variables which are available to ZPT operations using this context.
/// There are three types of definitions.
/// </para>
/// <list type="bullet">
/// <item>
/// <description><see cref="LocalDefinitions"/></description>
/// </item>
/// <item>
/// <description><c>GlobalDefinitions</c> (this property)</description>
/// </item>
/// <item>
/// <description><see cref="Repetitions"/></description>
/// </item>
/// </list>
/// <para>
/// Local definitions are scoped to the DOM element upon which they are created (via the
/// <c>tal:define</c> keyword) and that DOM element's descendents.
/// A locally-defined variable is not visible 'outside' of the element where it was defined.
/// </para>
/// <para>
/// Global definitions are in-scope from the document position at which they were defined and
/// onwards in the document (in source code order).
/// Globally-defined variables do not use the DOM structure; global variables are usable outside of
/// the element & descendents where they were defined, as long as it is after the point of
/// definition in the document source code.
/// </para>
/// <para>
/// Repetitions are a special type of variable which are created only by the <c>tal:repeat</c>
/// operation.
/// They behave identically to locally-defined variables except that they have a standard set of
/// properties, defined by the <see cref="RepetitionInfo"/> class.
/// </para>
/// </remarks>
/// <value>The global definitions.</value>
public IDictionary<string, object> GlobalDefinitions { get; }
/// <summary>
/// Gets the repetition variable definitions for the current context.
/// </summary>
/// <remarks>
/// <para>
/// Definitions are the variables which are available to ZPT operations using this context.
/// There are three types of definitions.
/// </para>
/// <list type="bullet">
/// <item>
/// <description><see cref="LocalDefinitions"/></description>
/// </item>
/// <item>
/// <description><see cref="GlobalDefinitions"/></description>
/// </item>
/// <item>
/// <description><c>Repetitions</c> (this property)</description>
/// </item>
/// </list>
/// <para>
/// Local definitions are scoped to the DOM element upon which they are created (via the
/// <c>tal:define</c> keyword) and that DOM element's descendents.
/// A locally-defined variable is not visible 'outside' of the element where it was defined.
/// </para>
/// <para>
/// Global definitions are in-scope from the document position at which they were defined and
/// onwards in the document (in source code order).
/// Globally-defined variables do not use the DOM structure; global variables are usable outside of
/// the element & descendents where they were defined, as long as it is after the point of
/// definition in the document source code.
/// </para>
/// <para>
/// Repetitions are a special type of variable which are created only by the <c>tal:repeat</c>
/// operation.
/// They behave identically to locally-defined variables except that they have a standard set of
/// properties, defined by the <see cref="RepetitionInfo"/> class.
/// </para>
/// </remarks>
/// <value>The repetition definitions.</value>
public IDictionary<string, RepetitionInfo> Repetitions { get; }
/// <summary>
/// Gets a collection of the contexts & handlers which might be able to deal
/// with errors encountered whilst processing this context.
/// </summary>
/// <remarks>
/// <para>
/// Error handlers are added to this property by the parent contexts.
/// Much like the C# <c>try</c> & <c>catch</c> keywords, ZPT rendering errors 'propagate upwards' through the DOM.
/// This occurs until either they are handled by a <c>tal:on-error</c> attribute or until they 'escape' the root of the DOM.
/// In the second case, this will lead to an exception being raised for the overall rendering operation.
/// A rendering error upon an element might be handled by a <c>tal:on-error</c> attribute defined upon that same
/// element, its parent element, grandparent or more disatant ancestor.
/// </para>
/// </remarks>
/// <value>The error handlers.</value>
public Stack<ErrorHandlingContext> ErrorHandlers { get; }
/// <summary>
/// Gets a clone of the current expression context, using a specified node as the current node for the created context.
/// </summary>
/// <remarks>
/// <para>
/// This method is provided for the creation of child expression contexts. The <paramref name="node"/>
/// is intended to be a child of the <see cref="CurrentNode"/>.
/// </para>
/// <para>
/// Because this is intended to be a child context, the local definitions, repetitions & error handlers
/// are cloned by this method, such that modifications to these collections upon the child context do not
/// affect the parent.
/// </para>
/// <para>
/// The exception to this, is the <see cref="GlobalDefinitions"/>.
/// Global definitions are intentionally not cloned, because a child's changes to global definitions may indeed affect parent contexts.
/// A global definition is in-scope from the moment it is defined, for the remainder of the document, regardless of the DOM hierarchy.
/// </para>
/// </remarks>
/// <returns>The cloned expression context.</returns>
/// <param name="node">The node for the cloned context.</param>
public ExpressionContext CreateChild(INode node)
{
return new ExpressionContext(node, LocalDefinitions, GlobalDefinitions, Repetitions, ErrorHandlers)
{
Error = Error,
Model = Model,
TemplateDocument = TemplateDocument,
};
}
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionContext"/> class.
/// </summary>
/// <remarks>
/// <para>
/// This constructor is typically used for the root expression context.
/// All of the other state of the context (apart from the current node) will be initialized with default/empty values.
/// Even if this is for a root context, <see cref="IsRootContext"/> must still be set manually.
/// </para>
/// </remarks>
/// <param name="node">The DOM node for this context.</param>
public ExpressionContext(INode node) : this(node, null, null, null, null) { }
/// <summary>
/// Initializes a new instance of the <see cref="ExpressionContext"/> class; this is (to a degree)
/// a copy-constructor.
/// </summary>
/// <remarks>
/// <para>
/// The <paramref name="localDefinitions"/>, <paramref name="repetitions"/> & <paramref name="errorHandlers"/>
/// are shallow-copied by this constructor. This is because changes to these collections which are made
/// inside of a context should not affect any other context
/// </para>
/// <para>
/// On the other hand, <paramref name="globalDefinitions"/> is used directly without copying, because changes to the global
/// definitions should affect other contexts, including those 'outside' of this one.
/// </para>
/// </remarks>
/// <param name="node">The DOM node for this context.</param>
/// <param name="localDefinitions">Local definitions.</param>
/// <param name="globalDefinitions">Global definitions.</param>
/// <param name="repetitions">Repetitions.</param>
/// <param name="errorHandlers">Error handlers</param>
public ExpressionContext(INode node,
IDictionary<string, object> localDefinitions,
IDictionary<string, object> globalDefinitions,
IDictionary<string, RepetitionInfo> repetitions,
Stack<ErrorHandlingContext> errorHandlers)
{
CurrentNode = node;
LocalDefinitions = new Dictionary<string, object>(localDefinitions ?? new Dictionary<string, object>());
GlobalDefinitions = globalDefinitions ?? new Dictionary<string, object>();
Repetitions = new Dictionary<string, RepetitionInfo>(repetitions ?? new Dictionary<string, RepetitionInfo>());
ErrorHandlers = new Stack<ErrorHandlingContext>(errorHandlers ?? Enumerable.Empty<ErrorHandlingContext>());
}
}
}
| {
"content_hash": "90c6e0fe51fcabf1c433b0b58ccce629",
"timestamp": "",
"source": "github",
"line_count": 314,
"max_line_length": 159,
"avg_line_length": 49.20063694267516,
"alnum_prop": 0.6015923360735322,
"repo_name": "csf-dev/ZPT-Sharp",
"id": "c0bef007a1f7a4c6b25b8d895cd791027276a7d7",
"size": "15451",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "ZptSharp.Abstractions/Expressions/ExpressionContext.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "AMPL",
"bytes": "4949"
},
{
"name": "Batchfile",
"bytes": "3142"
},
{
"name": "C#",
"bytes": "1670750"
},
{
"name": "HTML",
"bytes": "146448"
},
{
"name": "PowerShell",
"bytes": "2416"
}
],
"symlink_target": ""
} |
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE InstanceSigs #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
--------------------------------------------------------------------
-- |
-- Module : XMonad.Util.Parser
-- Description : A parser combinator library for xmonad
-- Copyright : (c) 2021 Tony Zorman
-- License : BSD3
-- Maintainer : Tony Zorman <soliditsallgood@mailbox.org>
-- Stability : experimental
-- Portability : non-portable
--
-- A small wrapper around the 'ReadP' parser combinator in @base@,
-- providing a more intuitive behaviour. While it's theoretically nice
-- that 'ReadP' is actually commutative, this makes a lot of parsing
-- operations rather awkward—more often than not, one only wants the
-- argument that's parsed "first".
--
-- Due to the left-biased nature of the chosen semigroup implementation,
-- using functions like 'many' or 'optional' from "Control.Applicative"
-- now yields more consistent behaviour with other parser combinator
-- libraries.
--
--------------------------------------------------------------------
module XMonad.Util.Parser (
-- * Usage
-- $usage
-- * Running
Parser,
runParser,
-- * Primitive Parsers
pfail,
eof,
num,
char,
string,
skipSpaces,
get,
look,
gather,
-- * Combining Parsers
satisfy,
choice,
count,
between,
option,
optionally,
skipMany,
skipMany1,
many1,
sepBy,
sepBy1,
endBy,
endBy1,
munch,
munch1,
chainr,
chainr1,
chainl,
chainl1,
manyTill,
) where
import XMonad.Prelude
import qualified Text.ParserCombinators.ReadP as ReadP
import Data.Coerce (coerce)
import Data.String (IsString (fromString))
import Text.ParserCombinators.ReadP (ReadP, (<++))
{- $usage
NOTE: This module is mostly intended for developing of other modules.
If you are a users, you probably won't find much use here—you have been
warned.
The high-level API tries to stay as close to 'ReadP' as possible. If
you are familiar with that then no functions here should surprise you.
One notable usability difference when forcing left-biasedness is /when/
one wants to disambiguate a parse. For normal 'ReadP' usage this
happens after the actual parsing stage by going through the list of
successful parses. For 'Parser' it does when constructing the relevant
combinators, leading to only one successful parse. As an example,
consider the 'ReadP'-based parser
> pLangle = ReadP.string "<"
> pLongerSequence = ReadP.char '<' *> ReadP.string "f" <* ReadP.char '>'
> pCombination = pLangle ReadP.+++ pLongerSequence
Parsing the string @"\<f\>"@ will return
>>> ReadP.readP_to_S pCombination "<f>"
[("<","f>"),("f","")]
One would now need to, for example, filter for the second (leftover)
string being empty and take the head of the resulting list (which may
still have more than one element).
With 'Parser', the same situation would look like the following
> pLangle' = string "<"
> pLongerSequence' = char '<' *> string "f" <* char '>'
> pCombination' = pLongerSequence' <> pLangle'
Notice how @pLangle'@ and @pLongerSequence'@ have traded places—since we
are not forcing @pLangle'@ to consume the entire string and @(<>)@ is
left-biased, @pLongerSequence'@ parses a superset of @pLangle'@!
Running @runParser pCombination'@ now yields the expected result:
>>> runParser pCombination' "<f>"
Just "f"
One might also define @pLangle'@ as @string "<" <* eof@, which would
enable a definition of @pCombination' = pLangle' <> pLongerSequence'@.
For example uses, see "XMonad.Util.EZConfig" or "XMonad.Prompt.OrgMode".
-}
-- Parser :: Type -> Type
newtype Parser a = Parser (ReadP a)
deriving newtype (Functor, Applicative, Monad)
instance Semigroup (Parser a) where
-- | Local, exclusive, left-biased choice: If left parser locally
-- produces any result at all, then right parser is not used.
(<>) :: Parser a -> Parser a -> Parser a
(<>) = coerce ((<++) @a)
{-# INLINE (<>) #-}
instance Monoid (Parser a) where
-- | A parser that always fails.
mempty :: Parser a
mempty = Parser empty
{-# INLINE mempty #-}
instance Alternative Parser where
empty :: Parser a
empty = mempty
{-# INLINE empty #-}
(<|>) :: Parser a -> Parser a -> Parser a
(<|>) = (<>)
{-# INLINE (<|>) #-}
-- | When @-XOverloadedStrings@ is on, treat a string @s@ as the parser
-- @'string' s@, when appropriate. This allows one to write things like
-- @"a" *> otherParser@ instead of @'string' "a" *> otherParser@.
instance a ~ String => IsString (Parser a) where
fromString :: String -> Parser a
fromString = string
{-# INLINE fromString #-}
-- | Run a parser on a given string.
runParser :: Parser a -> String -> Maybe a
runParser (Parser p) = fmap fst . listToMaybe . ReadP.readP_to_S p
{-# INLINE runParser #-}
-- | Always fails
pfail :: Parser a
pfail = empty
{-# INLINE pfail #-}
-- | Consume and return the next character. Fails if there is no input
-- left.
get :: Parser Char
get = coerce ReadP.get
{-# INLINE get #-}
-- | Look-ahead: return the part of the input that is left, without
-- consuming it.
look :: Parser String
look = coerce ReadP.look
{-# INLINE look #-}
-- | Transform a parser into one that does the same, but in addition
-- returns the exact characters read.
--
-- >>> runParser ( string "* " $> True) "* hi"
-- Just True
-- >>> runParser (gather $ string "* " $> True) "* hi"
-- Just ("* ",True)
gather :: forall a. Parser a -> Parser (String, a)
gather = coerce (ReadP.gather @a)
{-# INLINE gather #-}
-- | Succeeds if and only if we are at the end of input.
eof :: Parser ()
eof = coerce ReadP.eof
{-# INLINE eof #-}
-- | Parse an integral number.
num :: (Read a, Integral a) => Parser a
num = read <$> munch1 isDigit
{-# INLINE num #-}
-- | Parse and return the specified character.
char :: Char -> Parser Char
char = coerce ReadP.char
{-# INLINE char #-}
-- | Parse and return the specified string.
string :: String -> Parser String
string = coerce ReadP.string
{-# INLINE string #-}
-- | Skip all whitespace.
skipSpaces :: Parser ()
skipSpaces = coerce ReadP.skipSpaces
{-# INLINE skipSpaces #-}
-- | Consume and return the next character if it satisfies the specified
-- predicate.
satisfy :: (Char -> Bool) -> Parser Char
satisfy = coerce ReadP.satisfy
{-# INLINE satisfy #-}
-- | Combine all parsers in the given list in a left-biased way.
choice :: [Parser a] -> Parser a
choice = foldl' (<>) mempty
{-# INLINE choice #-}
-- | @count n p@ parses @n@ occurrences of @p@ in sequence and returns a
-- list of results.
count :: Int -> Parser a -> Parser [a]
count = replicateM
{-# INLINE count #-}
-- | @between open close p@ parses @open@, followed by @p@ and finally
-- @close@. Only the value of @p@ is returned.
between :: Parser open -> Parser close -> Parser a -> Parser a
between open close p = open *> p <* close
{-# INLINE between #-}
-- | @option def p@ will try to parse @p@ and, if it fails, simply
-- return @def@ without consuming any input.
option :: a -> Parser a -> Parser a
option def p = p <|> pure def
{-# INLINE option #-}
-- | @optionally p@ optionally parses @p@ and always returns @()@.
optionally :: Parser a -> Parser ()
optionally p = void p <|> pure ()
{-# INLINE optionally #-}
-- | Like 'many', but discard the result.
skipMany :: Parser a -> Parser ()
skipMany = void . many
{-# INLINE skipMany #-}
-- | Like 'many1', but discard the result.
skipMany1 :: Parser a -> Parser ()
skipMany1 p = p *> skipMany p
{-# INLINE skipMany1 #-}
-- | Parse the first zero or more characters satisfying the predicate.
-- Always succeeds; returns an empty string if the predicate returns
-- @False@ on the first character of input.
munch :: (Char -> Bool) -> Parser String
munch = coerce ReadP.munch
{-# INLINE munch #-}
-- | Parse the first one or more characters satisfying the predicate.
-- Fails if none, else succeeds exactly once having consumed all the
-- characters.
munch1 :: (Char -> Bool) -> Parser String
munch1 = coerce ReadP.munch1
{-# INLINE munch1 #-}
-- | @endBy p sep@ parses zero or more occurrences of @p@, separated and
-- ended by @sep@.
endBy :: Parser a -> Parser sep -> Parser [a]
endBy p sep = many (p <* sep)
{-# INLINE endBy #-}
-- | @endBy p sep@ parses one or more occurrences of @p@, separated and
-- ended by @sep@.
endBy1 :: Parser a -> Parser sep -> Parser [a]
endBy1 p sep = many1 (p <* sep)
{-# INLINE endBy1 #-}
-- | Parse one or more occurrences of the given parser.
many1 :: Parser a -> Parser [a]
many1 = some
{-# INLINE many1 #-}
-- | @sepBy p sep@ parses zero or more occurrences of @p@, separated by
-- @sep@. Returns a list of values returned by @p@.
sepBy :: Parser a -> Parser sep -> Parser [a]
sepBy p sep = sepBy1 p sep <> pure []
{-# INLINE sepBy #-}
-- | @sepBy1 p sep@ parses one or more occurrences of @p@, separated by
-- @sep@. Returns a list of values returned by @p@.
sepBy1 :: Parser a -> Parser sep -> Parser [a]
sepBy1 p sep = liftA2 (:) p (many (sep *> p))
{-# INLINE sepBy1 #-}
-- | @chainr p op x@ parses zero or more occurrences of @p@, separated
-- by @op@. Returns a value produced by a /right/ associative
-- application of all functions returned by @op@. If there are no
-- occurrences of @p@, @x@ is returned.
chainr :: Parser a -> Parser (a -> a -> a) -> a -> Parser a
chainr p op x = option x (chainr1 p op)
{-# INLINE chainr #-}
-- | Like 'chainr', but parses one or more occurrences of @p@.
chainr1 :: forall a. Parser a -> Parser (a -> a -> a) -> Parser a
chainr1 p op = scan
where
scan :: Parser a
scan = p >>= rest
rest :: a -> Parser a
rest x = option x $ do f <- op
f x <$> scan
{-# INLINE chainr1 #-}
-- | @chainl p op x@ parses zero or more occurrences of @p@, separated
-- by @op@. Returns a value produced by a /left/ associative
-- application of all functions returned by @op@. If there are no
-- occurrences of @p@, @x@ is returned.
chainl :: Parser a -> Parser (a -> a -> a) -> a -> Parser a
chainl p op x = option x (chainl1 p op)
{-# INLINE chainl #-}
-- | Like 'chainl', but parses one or more occurrences of @p@.
chainl1 :: forall a. Parser a -> Parser (a -> a -> a) -> Parser a
chainl1 p op = scan
where
scan :: Parser a
scan = p >>= rest
rest :: a -> Parser a
rest x = option x $ do f <- op
y <- p
rest (f x y)
{-# INLINE chainl1 #-}
-- | @manyTill p end@ parses zero or more occurrences of @p@, until
-- @end@ succeeds. Returns a list of values returned by @p@.
manyTill :: forall a end. Parser a -> Parser end -> Parser [a]
manyTill p end = scan
where
scan :: Parser [a]
scan = end $> [] <|> liftA2 (:) p scan
{-# INLINE manyTill #-}
| {
"content_hash": "7a0d5ae19b0aa6b09edbbc3b6cbd409f",
"timestamp": "",
"source": "github",
"line_count": 357,
"max_line_length": 72,
"avg_line_length": 30.593837535014007,
"alnum_prop": 0.6477751327595679,
"repo_name": "xmonad/xmonad-contrib",
"id": "8dff1c0bc18c1674c2097b0fc13c138ce6d6854b",
"size": "10928",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "XMonad/Util/Parser.hs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "4413"
},
{
"name": "Haskell",
"bytes": "2328613"
},
{
"name": "Nix",
"bytes": "1757"
},
{
"name": "Shell",
"bytes": "3754"
}
],
"symlink_target": ""
} |
package org.kuali.kfs.module.purap.document;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.kuali.kfs.module.purap.businessobject.Carrier;
import org.kuali.kfs.module.purap.businessobject.CorrectionReceivingItem;
import org.kuali.kfs.module.purap.businessobject.DeliveryRequiredDateReason;
import org.kuali.kfs.module.purap.businessobject.LineItemReceivingItem;
import org.kuali.kfs.module.purap.businessobject.ReceivingItem;
import org.kuali.kfs.module.purap.document.service.ReceivingService;
import org.kuali.kfs.sys.KFSPropertyConstants;
import org.kuali.kfs.sys.context.SpringContext;
import org.kuali.kfs.vnd.businessobject.CampusParameter;
import org.kuali.kfs.vnd.businessobject.VendorDetail;
import org.kuali.rice.kew.framework.postprocessor.DocumentRouteStatusChange;
import org.kuali.rice.krad.util.ObjectUtils;
import org.kuali.rice.location.framework.country.CountryEbo;
/**
* @author Kuali Nervous System Team (kualidev@oncourse.iu.edu)
*/
public class CorrectionReceivingDocument extends ReceivingDocumentBase {
protected String lineItemReceivingDocumentNumber;
//Collections
protected List<CorrectionReceivingItem> items;
protected LineItemReceivingDocument lineItemReceivingDocument;
/**
* Default constructor.
*/
public CorrectionReceivingDocument() {
super();
items = new ArrayList<CorrectionReceivingItem>();
}
public void populateCorrectionReceivingFromReceivingLine(LineItemReceivingDocument rlDoc){
//populate receiving line document from purchase order
this.setPurchaseOrderIdentifier( rlDoc.getPurchaseOrderIdentifier() );
this.getDocumentHeader().setDocumentDescription( rlDoc.getDocumentHeader().getDocumentDescription());
this.getDocumentHeader().setOrganizationDocumentNumber( rlDoc.getDocumentHeader().getOrganizationDocumentNumber() );
this.setAccountsPayablePurchasingDocumentLinkIdentifier( rlDoc.getAccountsPayablePurchasingDocumentLinkIdentifier() );
this.setLineItemReceivingDocumentNumber(rlDoc.getDocumentNumber());
//copy receiving line items
for (LineItemReceivingItem rli : (List<LineItemReceivingItem>) rlDoc.getItems()) {
this.getItems().add(new CorrectionReceivingItem(rli, this));
}
}
@Override
public void doRouteStatusChange(DocumentRouteStatusChange statusChangeEvent) {
if(this.getFinancialSystemDocumentHeader().getWorkflowDocument().isProcessed()) {
SpringContext.getBean(ReceivingService.class).completeCorrectionReceivingDocument(this);
}
super.doRouteStatusChange(statusChangeEvent);
}
/**
* Gets the lineItemReceivingDocumentNumber attribute.
*
* @return Returns the lineItemReceivingDocumentNumber
*
*/
public String getLineItemReceivingDocumentNumber() {
return lineItemReceivingDocumentNumber;
}
/**
* Sets the lineItemReceivingDocumentNumber attribute.
*
* @param lineItemReceivingDocumentNumber The lineItemReceivingDocumentNumber to set.
*
*/
public void setLineItemReceivingDocumentNumber(String lineItemReceivingDocumentNumber) {
this.lineItemReceivingDocumentNumber = lineItemReceivingDocumentNumber;
}
/**
* Gets the lineItemReceivingDocument attribute.
* @return Returns the lineItemReceivingDocument.
*/
public LineItemReceivingDocument getLineItemReceivingDocument() {
refreshLineReceivingDocument();
return lineItemReceivingDocument;
}
@Override
public void processAfterRetrieve() {
super.processAfterRetrieve();
refreshLineReceivingDocument();
}
protected void refreshLineReceivingDocument(){
if(ObjectUtils.isNull(lineItemReceivingDocument) || lineItemReceivingDocument.getDocumentNumber() == null){
this.refreshReferenceObject("lineItemReceivingDocument");
if (ObjectUtils.isNull(lineItemReceivingDocument.getDocumentHeader().getDocumentNumber())) {
lineItemReceivingDocument.refreshReferenceObject(KFSPropertyConstants.DOCUMENT_HEADER);
}
}else{
if (ObjectUtils.isNull(lineItemReceivingDocument.getDocumentHeader().getDocumentNumber())) {
lineItemReceivingDocument.refreshReferenceObject(KFSPropertyConstants.DOCUMENT_HEADER);
}
}
}
@Override
public Integer getPurchaseOrderIdentifier() {
if (ObjectUtils.isNull(super.getPurchaseOrderIdentifier())){
refreshLineReceivingDocument();
if (ObjectUtils.isNotNull(lineItemReceivingDocument)){
setPurchaseOrderIdentifier(lineItemReceivingDocument.getPurchaseOrderIdentifier());
}
}
return super.getPurchaseOrderIdentifier();
}
/**
* Sets the lineItemReceivingDocument attribute value.
* @param lineItemReceivingDocument The lineItemReceivingDocument to set.
* @deprecated
*/
public void setLineItemReceivingDocument(LineItemReceivingDocument lineItemReceivingDocument) {
this.lineItemReceivingDocument = lineItemReceivingDocument;
}
@Override
public Class getItemClass() {
return CorrectionReceivingItem.class;
}
@Override
public List getItems() {
return items;
}
@Override
public void setItems(List items) {
this.items = items;
}
@Override
public ReceivingItem getItem(int pos) {
return (ReceivingItem) items.get(pos);
}
public void addItem(ReceivingItem item) {
getItems().add(item);
}
public void deleteItem(int lineNum) {
if (getItems().remove(lineNum) == null) {
// throw error here
}
}
@Override
public Integer getAlternateVendorDetailAssignedIdentifier() {
return getLineItemReceivingDocument().getAlternateVendorDetailAssignedIdentifier();
}
@Override
public Integer getAlternateVendorHeaderGeneratedIdentifier() {
return getLineItemReceivingDocument().getAlternateVendorHeaderGeneratedIdentifier();
}
@Override
public String getAlternateVendorName() {
return getLineItemReceivingDocument().getAlternateVendorName();
}
@Override
public String getAlternateVendorNumber() {
return getLineItemReceivingDocument().getAlternateVendorNumber();
}
@Override
public Carrier getCarrier() {
return getLineItemReceivingDocument().getCarrier();
}
@Override
public String getCarrierCode() {
return getLineItemReceivingDocument().getCarrierCode();
}
@Override
public String getDeliveryBuildingCode() {
return getLineItemReceivingDocument().getDeliveryBuildingCode();
}
@Override
public String getDeliveryBuildingLine1Address() {
return getLineItemReceivingDocument().getDeliveryBuildingLine1Address();
}
@Override
public String getDeliveryBuildingLine2Address() {
return getLineItemReceivingDocument().getDeliveryBuildingLine2Address();
}
@Override
public String getDeliveryBuildingName() {
return getLineItemReceivingDocument().getDeliveryBuildingName();
}
@Override
public String getDeliveryBuildingRoomNumber() {
return getLineItemReceivingDocument().getDeliveryBuildingRoomNumber();
}
@Override
public CampusParameter getDeliveryCampus() {
return getLineItemReceivingDocument().getDeliveryCampus();
}
@Override
public String getDeliveryCampusCode() {
return getLineItemReceivingDocument().getDeliveryCampusCode();
}
@Override
public String getDeliveryCityName() {
return getLineItemReceivingDocument().getDeliveryCityName();
}
@Override
public String getDeliveryCountryCode() {
return getLineItemReceivingDocument().getDeliveryCountryCode();
}
@Override
public String getDeliveryInstructionText() {
return getLineItemReceivingDocument().getDeliveryInstructionText();
}
@Override
public String getDeliveryPostalCode() {
return getLineItemReceivingDocument().getDeliveryPostalCode();
}
@Override
public Date getDeliveryRequiredDate() {
return getLineItemReceivingDocument().getDeliveryRequiredDate();
}
@Override
public DeliveryRequiredDateReason getDeliveryRequiredDateReason() {
return getLineItemReceivingDocument().getDeliveryRequiredDateReason();
}
@Override
public String getDeliveryRequiredDateReasonCode() {
return getLineItemReceivingDocument().getDeliveryRequiredDateReasonCode();
}
@Override
public String getDeliveryStateCode() {
return getLineItemReceivingDocument().getDeliveryStateCode();
}
@Override
public String getDeliveryToEmailAddress() {
return getLineItemReceivingDocument().getDeliveryToEmailAddress();
}
@Override
public String getDeliveryToName() {
return getLineItemReceivingDocument().getDeliveryToName();
}
@Override
public String getDeliveryToPhoneNumber() {
return getLineItemReceivingDocument().getDeliveryToPhoneNumber();
}
@Override
public String getShipmentBillOfLadingNumber() {
return getLineItemReceivingDocument().getShipmentBillOfLadingNumber();
}
@Override
public String getShipmentPackingSlipNumber() {
return getLineItemReceivingDocument().getShipmentPackingSlipNumber();
}
@Override
public Date getShipmentReceivedDate() {
return getLineItemReceivingDocument().getShipmentReceivedDate();
}
@Override
public String getShipmentReferenceNumber() {
return getLineItemReceivingDocument().getShipmentReferenceNumber();
}
@Override
public Integer getVendorAddressGeneratedIdentifier() {
return getLineItemReceivingDocument().getVendorAddressGeneratedIdentifier();
}
@Override
public String getVendorCityName() {
return getLineItemReceivingDocument().getVendorCityName();
}
@Override
public CountryEbo getVendorCountry() {
return getLineItemReceivingDocument().getVendorCountry();
}
@Override
public String getVendorCountryCode() {
return getLineItemReceivingDocument().getVendorCountryCode();
}
@Override
public VendorDetail getVendorDetail() {
return getLineItemReceivingDocument().getVendorDetail();
}
@Override
public Integer getVendorDetailAssignedIdentifier() {
return getLineItemReceivingDocument().getVendorDetailAssignedIdentifier();
}
@Override
public Integer getVendorHeaderGeneratedIdentifier() {
return getLineItemReceivingDocument().getVendorHeaderGeneratedIdentifier();
}
@Override
public String getVendorLine1Address() {
return getLineItemReceivingDocument().getVendorLine1Address();
}
@Override
public String getVendorLine2Address() {
return getLineItemReceivingDocument().getVendorLine2Address();
}
@Override
public String getVendorName() {
return getLineItemReceivingDocument().getVendorName();
}
@Override
public String getVendorNumber() {
return getLineItemReceivingDocument().getVendorNumber();
}
@Override
public String getVendorPostalCode() {
return getLineItemReceivingDocument().getVendorPostalCode();
}
@Override
public String getVendorStateCode() {
return getLineItemReceivingDocument().getVendorStateCode();
}
@Override
public List buildListOfDeletionAwareLists() {
List managedLists = super.buildListOfDeletionAwareLists();
managedLists.add(this.getItems());
return managedLists;
}
}
| {
"content_hash": "93298f132c60b7be3459bd04b004d0b6",
"timestamp": "",
"source": "github",
"line_count": 377,
"max_line_length": 126,
"avg_line_length": 31.47214854111406,
"alnum_prop": 0.7227138643067846,
"repo_name": "Ariah-Group/Finance",
"id": "a2ee2e400c3cb073397fe87cc8868a10c096a28b",
"size": "12485",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "af_webapp/src/main/java/org/kuali/kfs/module/purap/document/CorrectionReceivingDocument.java",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
if test -z "$MONGODB_PASSWORD"; then
echo "MONGODB_PASSWORD not defined"
exit 1
fi
auth="-u user -p $MONGODB_PASSWORD"
# MONGODB USER CREATION
(
echo "setup mongodb auth"
create_user="if (!db.getUser('user')) { db.createUser({ user: 'user', pwd: '$MONGODB_PASSWORD', roles: [ {role:'readWrite', db:'rental'} ]}) }"
until mongo rental --eval "$create_user" || mongo rental $auth --eval "$create_user"; do sleep 5; done
killall mongod
sleep 1
killall -9 mongod
) &
# INIT DUMP EXECUTION
(
if test -n "$INIT_DUMP"; then
echo "execute dump file"
until mongo rental $auth $INIT_DUMP; do sleep 5; done
fi
) &
echo "start mongodb without auth"
chown -R mongodb /data/db
gosu mongodb mongod "$@"
echo "restarting with auth on"
sleep 5
exec gosu mongodb mongod --auth "$@"
| {
"content_hash": "2c86d19084b89ddee242216b1d311e3a",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 143,
"avg_line_length": 24.4375,
"alnum_prop": 0.6828644501278772,
"repo_name": "MarcinU2K/media-rental-microservices",
"id": "5bb06eac00c72544fe686fcd9c73adfc2faf16b0",
"size": "794",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "mongodb/init.sh",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "684"
},
{
"name": "Java",
"bytes": "78226"
},
{
"name": "JavaScript",
"bytes": "2630887"
},
{
"name": "Shell",
"bytes": "1820"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.