text
stringlengths 20
812k
| id
stringlengths 40
40
| metadata
dict |
---|---|---|
use std::fmt::Display;
use std::fmt::Formatter;
use std::fmt::Result as FmtResult;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Object {
Comment {
id: String,
alternate: String,
},
File {
id: String,
title: String,
alternate: String,
},
Person {
name: String,
email: String,
uri: String,
photo: String,
username: String,
},
Changeset {
id: String,
title: String,
alternate: String,
},
Issue {
id: String,
title: String,
summary: String,
alternate: String,
},
Repository {
id: String,
title: String,
alternate: String,
},
Review {
id: String,
title: String,
summary: String,
alternate: String,
},
Page {
id: String,
title: String,
alternate: String,
},
Space {
id: String,
title: String,
alternate: String,
},
}
impl Object {
pub fn comment(id: &str, alternate: &str) -> Object {
Object::Comment {
id: id.into(),
alternate: alternate.into(),
}
}
pub fn file(id: &str, title: &str, alternate: &str) -> Object {
Object::File {
id: id.into(),
title: title.into(),
alternate: alternate.into(),
}
}
pub fn person(name: &str, email: &str, uri: &str, photo: &str, username: &str) -> Object {
Object::Person {
name: name.into(),
email: email.into(),
uri: uri.into(),
photo: photo.into(),
username: username.into(),
}
}
pub fn changeset(id: &str, title: &str, alternate: &str) -> Object {
Object::Changeset {
id: id.into(),
title: title.into(),
alternate: alternate.into(),
}
}
pub fn issue(id: &str, title: &str, summary: &str, alternate: &str) -> Object {
Object::Issue {
id: id.into(),
title: title.into(),
summary: summary.into(),
alternate: alternate.into(),
}
}
pub fn repository(id: &str, title: &str, alternate: &str) -> Object {
Object::Repository {
id: id.into(),
title: title.into(),
alternate: alternate.into(),
}
}
pub fn review(id: &str, title: &str, summary: &str, alternate: &str) -> Object {
Object::Review {
id: id.into(),
title: title.into(),
summary: summary.into(),
alternate: alternate.into(),
}
}
pub fn page(id: &str, title: &str, alternate: &str) -> Object {
Object::Page {
id: id.into(),
title: title.into(),
alternate: alternate.into(),
}
}
pub fn space(id: &str, title: &str, alternate: &str) -> Object {
Object::Space {
id: id.into(),
title: title.into(),
alternate: alternate.into(),
}
}
}
impl Display for Object {
fn fmt(&self, f: &mut Formatter) -> FmtResult {
match self {
Object::Comment { .. } => write!(f, "comment"),
Object::File { ref title, .. } => write!(f, "{}", title),
Object::Person { ref name, .. } => write!(f, "{}", name),
Object::Changeset { ref title, .. } => write!(f, "{}", title),
Object::Issue { ref title, .. } => write!(f, "{}", title),
Object::Repository { ref title, .. } => write!(f, "{}", title),
Object::Review { ref title, .. } => write!(f, "{}", title),
Object::Page { ref title, .. } => write!(f, "{}", title),
Object::Space { ref title, .. } => write!(f, "{}", title),
}
}
}
|
6af0fed0b1709fdad24c8bf346c5cc9f2f1c3d8c
|
{
"blob_id": "6af0fed0b1709fdad24c8bf346c5cc9f2f1c3d8c",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-02T18:02:36",
"content_id": "daed836b9329077cf2cfcc6fd91491c7f5633150",
"detected_licenses": [
"MIT"
],
"directory_id": "dd6453ebb6547897ae5d77a93a01bb8300c4c2b3",
"extension": "rs",
"filename": "object.rs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 231434117,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 3873,
"license": "MIT",
"license_type": "permissive",
"path": "/src/entity/object.rs",
"provenance": "stack-edu-0068.json.gz:359467",
"repo_name": "SnakeSolid/rust-team-activity",
"revision_date": "2018-09-02T18:02:36",
"revision_id": "cec7ed70db62fabf746e69fa7e0bd21021d27102",
"snapshot_id": "f1f3c338caa5b7e3f56b9ee54812ea300f043374",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SnakeSolid/rust-team-activity/cec7ed70db62fabf746e69fa7e0bd21021d27102/src/entity/object.rs",
"visit_date": "2020-12-03T18:41:10.479747",
"added": "2024-11-19T01:02:57.370006+00:00",
"created": "2018-09-02T18:02:36",
"int_score": 3,
"score": 2.609375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
package courier
import (
"context"
"encoding/json"
)
type AutomationStep struct {
Action string `json:"action"`
Brand string `json:"brand,omitempty"`
CancelationToken string `json:"cancelation_token,omitempty"`
Data interface{} `json:"data,omitempty"`
Duration string `json:"duration,omitempty"`
If string `json:"if,omitempty"`
List string `json:"list,omitempty"`
Override interface{} `json:"override,omitempty"`
Profile interface{} `json:"profile,omitempty"`
Recipient string `json:"recipient,omitempty"`
Ref string `json:"ref,omitempty"`
Template string `json:"template,omitempty"`
Until string `json:"until,omitempty"`
}
type Automation struct {
CancelationToken string `json:"cancelation_token,omitempty"`
Steps []AutomationStep `json:"steps"`
}
type AutomationInvokeBody struct {
Automation Automation `json:"automation"`
Brand string `json:"brand,omitempty"`
Data interface{} `json:"data,omitempty"`
Profile interface{} `json:"profile,omitempty"`
Recipient string `json:"recipient,omitempty"`
Template string `json:"template,omitempty"`
}
type AutomationTemplateInvokeBody struct {
Brand string `json:"brand,omitempty"`
Data interface{} `json:"data,omitempty"`
Profile interface{} `json:"profile,omitempty"`
Recipient string `json:"recipient,omitempty"`
Template string `json:"template,omitempty"`
}
// Calls the POST /automations/invoke endpoint of the Courier API
func (c *Client) InvokeAutomation(ctx context.Context, body interface{}) (string, error) {
bodyMap, err := toJSONMap(body)
if err != nil {
return "", err
}
response, err := c.API.SendRequestWithMaps(ctx, "POST", "/automations/invoke", bodyMap)
if err != nil {
return "", err
}
var runID string
err = json.Unmarshal(response["runId"], &runID)
if err != nil {
return "", err
}
return runID, nil
}
// Calls the POST /automations/:templateId/invoke endpoint of the Courier API
func (c *Client) InvokeAutomationTemplate(ctx context.Context, templateId string, body interface{}) (string, error) {
bodyMap, err := toJSONMap(body)
if err != nil {
return "", err
}
response, err := c.API.SendRequestWithMaps(ctx, "POST", "/automations/"+templateId+"/invoke", bodyMap)
if err != nil {
return "", err
}
var runID string
err = json.Unmarshal(response["runId"], &runID)
if err != nil {
return "", err
}
return runID, nil
}
|
19b1f1aae58f610d7a0dd7c009d57c73bb723ba4
|
{
"blob_id": "19b1f1aae58f610d7a0dd7c009d57c73bb723ba4",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-09T21:15:33",
"content_id": "7d666d8396d00b6c2a873a1dfad869a2070df126",
"detected_licenses": [
"MIT"
],
"directory_id": "268affaa89451e77df020dd96ac3784b7b347606",
"extension": "go",
"filename": "automations.go",
"fork_events_count": 14,
"gha_created_at": "2020-03-06T18:47:49",
"gha_event_created_at": "2023-08-09T21:15:35",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 245493940,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2609,
"license": "MIT",
"license_type": "permissive",
"path": "/v2/automations.go",
"provenance": "stack-edu-0016.json.gz:199260",
"repo_name": "trycourier/courier-go",
"revision_date": "2023-08-09T21:15:33",
"revision_id": "b4487b62895ef79b11b18c8e15fc4456b20563fa",
"snapshot_id": "a461613e076ad3d2154c44a36641cd8c84dc9a50",
"src_encoding": "UTF-8",
"star_events_count": 34,
"url": "https://raw.githubusercontent.com/trycourier/courier-go/b4487b62895ef79b11b18c8e15fc4456b20563fa/v2/automations.go",
"visit_date": "2023-08-28T03:53:06.856485",
"added": "2024-11-18T22:40:48.660595+00:00",
"created": "2023-08-09T21:15:33",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
package org.commcare.cases.query.queryset;
import org.javarosa.core.model.instance.TreeReference;
import org.javarosa.xpath.expr.XPathExpression;
/**
* A ModelQuerySetMatcher identifies from a provided XPathExpression or TreeReference that the
* expression/reference pattern is referring to a semantic concept that can be evaluated with
* a query set lookup, and provides the relevant lookup object which can be used to potentially
* match and perform that lookup.
*
* For Example:
* in the caseb
*
* the predicate:
* [@case_id = 'hardcoded']
*
* could be semantically encoded as a QuerySetLookup which returns a case's internal model id,
* entirely bypassing the process of performing XPath Evalutions.
*
* Similarly, the predicate
* [index/parent = current()/@case_id]
*
* could be interpreted semantically by knowing that current()/@case_id will be an ID that can
* be matched to a set of cases's index/parent. A matcher could return a lookup which will take
* in a context and identify the case to be matched and return the model ID of cases that index it
* without having to have the engine perform that iteratively.
*
* //TODO: currently these matchers only have the ability to reason within the current model,
* but we may need to reach between models to match complex query lookps
*
* Created by ctsims on 2/6/2017.
*/
public interface ModelQuerySetMatcher {
/**
* Given a predicate expression, identify whether or not it can be expressed as a query set
* lookup, regardless of the current context.
*/
QuerySetLookup getQueryLookupFromPredicate(XPathExpression expr);
/**
* Given an explicit tree reference, identify a direct query set lookup (if any) that can be
* used to look up model id's that match that reference.
*
* example:
* instance('casedb')/casedb/case[4]/@case_id
* and
* instance('casedb')/casedb/case[4]/index/parent
*
* both could produce QuerySetLookup objects with the "case" query model id since they both
* refer to specific cases in the case model.
*/
QuerySetLookup getQuerySetLookup(TreeReference ref);
}
|
4b1d5a88ac5151e813c03a3e7d75ff857d513403
|
{
"blob_id": "4b1d5a88ac5151e813c03a3e7d75ff857d513403",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-22T20:30:22",
"content_id": "2b1d2669ffec5aab46f99a32f12e116c7033f6c5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "229112ef4284870fa0e269ae3dcc2299ff4a6519",
"extension": "java",
"filename": "ModelQuerySetMatcher.java",
"fork_events_count": 12,
"gha_created_at": "2014-06-17T21:13:25",
"gha_event_created_at": "2023-09-14T11:06:53",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 20939782,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2155,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/org/commcare/cases/query/queryset/ModelQuerySetMatcher.java",
"provenance": "stack-edu-0023.json.gz:256608",
"repo_name": "dimagi/commcare-core",
"revision_date": "2023-08-22T20:30:22",
"revision_id": "a60179119656f3b3e6932f7f40fe76b8937cfc47",
"snapshot_id": "aaeed115021da42365c281824c07f692cf23d89d",
"src_encoding": "UTF-8",
"star_events_count": 11,
"url": "https://raw.githubusercontent.com/dimagi/commcare-core/a60179119656f3b3e6932f7f40fe76b8937cfc47/src/main/java/org/commcare/cases/query/queryset/ModelQuerySetMatcher.java",
"visit_date": "2023-09-03T15:28:00.252044",
"added": "2024-11-19T01:30:02.372416+00:00",
"created": "2023-08-22T20:30:22",
"int_score": 3,
"score": 2.75,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
---
title: Reflections on Malick's *Knight of Cups*
layout: post
header:
image: http://www.keithbuhler.com/images/banner-buhler-report.svg
share: true
comments: true
tags: [culture, malick]
categories: [Culture]
excerpt_separator: <!--more-->
permalink:
---

The *Knight of Cups* is, I daresay, a great and beautiful film. Merely watching it challenges me the way that "conversing" with Socrates challenges.
The content is not family friendly, so review the [Ted Baehr Movieguide information first.](https://www.movieguide.org/reviews/knight-of-cups.html) There is far too much nudity and other content, though Malick somehow manages to convey Rick's depravity and still respect natural human beauty.
The film is a must see for die-hard Malick fans and for Hollywood actors who need this kind of Socratic challenge.
The surest way to hate this film is to [compare it to *Tree of Life*.](https://www.theatlantic.com/entertainment/archive/2016/03/knight-of-cups-malick-review/472050/) It's just not *Tree of Life.* If one compares them, of course *Knight of Cups* doesn't "do" as much for me as even *New World* -- but don't compare! If you want to watch *Tree of Life*, go re-watch it. Malick is moving on, moving on; he is not stuck in the past.
<!--more-->
This movie is about the moment. One character (at the Huntington Gardens!) says: "stay in the moment. Everything is there." Just because a sentiment about being in the moment been repeated ad nauseum doesn't mean it is false.
The movie takes you into the moment. Even the ugly moments have beauty.
The movie takes the actors into the moment. Case in point: [Christian Bale had no lines:](http://www.indiewire.com/2015/02/berlin-christian-bale-and-natalie-portman-on-making-knight-of-cups-with-terrence-malick-65313/)
>“The nice and very interesting thing in Terry’s approach was that he didn’t tell us what it was about."
I wonder if "nice and very interesting" are adjectives uttered through clenched teeth.
Malick literally told his lead actor, [“We don’t need to talk that much.”](http://www.denofgeek.com/us/movies/knight-of-cups/252993/knight-of-cups-review)
### An Incomplete Film

The *Knight of Cups* thematizes incompleteness. How can you construct a speech *about* incompleteness? You can make a complete speech about the topic or you can write an *incomplete speech.* Malick takes the latter approach.
[One critic (David Sims) said:](https://www.theatlantic.com/entertainment/archive/2016/03/knight-of-cups-malick-review/472050/)
>while it’s fascinating to see Malick take steps into uncharted territory—Knight of Cups is his first fully contemporary, urban film—it’s unsettling to see a filmmaker who’s known for thoroughness work with such underdeveloped material.
Sims misses the point. "Underdeveloped" might be a synonym for the Tarot character, the Knight of Cups. It's a movie about being underdeveloped, about being about to begin.
### Beginning
The last line is "begin", recalling T.S. Eliot's proclamation that "The end is where we start from."
>What we call the beginning is often the end. And to make an end is to make a beginning.
Just before this line, though, Rick says, "How shall I begin?" That is his redemption, or the closest we get to it. Rick is awake again. He was looking for the pearl while sleepwalking. Now, awake, he can seek in earnest. The heart is restless until it rests in Him, so restlessness is a precursor to redemption.
### Socratic Accounting

Socrates called himself and his friends to account. He famously turned esoteric, ethereal, scientific, metaphysical, or technical conversations into ethical ones: how am I living? Am I caring more for the body and wealth than for the soul? Socrates was never above his own laws, though, and held himself to the same exacting standards he used to make Athenians squirm.
This film is a Socratic call to account, for the audience, for Christian Bale even, and for Hollywood. But it's not a sermon, for it's also Malick's call to account to himself. One critic (Wendy Ide) worried that Malick's formula is [nudging into self-parody.](https://www.theguardian.com/film/2016/may/08/knight-of-cups-review-terrence-malick-christian-bale) Again, this rather misses the point. *Knight of Cups* is a self-critique. It's a critic of Los Angeles, Hollywood, screenwriting, sexual indulgence, hedonism, infidelity, aloofness, Prufrockian indecision, and incompleteness, and therefore a critique of Malick himself, whose career in LA and Hollywood screenwriting (we can only assume) follows even more plot points than his Wikipedia page confirms it does.
|
e50d60a97ce7e95cd27c2180ab774273ff119e62
|
{
"blob_id": "e50d60a97ce7e95cd27c2180ab774273ff119e62",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-23T03:48:50",
"content_id": "8bcf20f80796bba1f0f059ab53726143ce22de0f",
"detected_licenses": [
"MIT"
],
"directory_id": "6f1e13e87a1fcf29b525d3e53fe4bf03e7d44c0d",
"extension": "md",
"filename": "2017-05-17-knight-of-cups.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115288838,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 5068,
"license": "MIT",
"license_type": "permissive",
"path": "/_posts/2017-05-17-knight-of-cups.md",
"provenance": "stack-edu-markdown-0001.json.gz:188465",
"repo_name": "keithbuhler/jasper",
"revision_date": "2022-02-23T03:48:50",
"revision_id": "76580308287660cc263143b0c8db77532a74d2e6",
"snapshot_id": "7ad544ef4573431411c4de6b8e5b3009349de15c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/keithbuhler/jasper/76580308287660cc263143b0c8db77532a74d2e6/_posts/2017-05-17-knight-of-cups.md",
"visit_date": "2022-03-08T18:07:37.419019",
"added": "2024-11-19T00:32:45.822177+00:00",
"created": "2022-02-23T03:48:50",
"int_score": 3,
"score": 3.03125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0001.json.gz"
}
|
// Package commands provides the set of CLI commands used to communicate with the AIS cluster.
// This file handles commands that control running jobs in the cluster.
/*
* Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
*/
package commands
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"github.com/NVIDIA/aistore/api"
"github.com/NVIDIA/aistore/cmd/cli/templates"
"github.com/NVIDIA/aistore/cmn"
"github.com/urfave/cli"
)
var (
etlCmds = []cli.Command{
{
Name: commandETL,
Usage: "use ETLs",
Subcommands: []cli.Command{
{
Name: subcmdInit,
Usage: "initialize ETL with yaml spec",
ArgsUsage: "SPEC_FILE",
Action: etlInitHandler,
},
{
Name: subcmdList,
Usage: "list all ETLs",
Action: etlListHandler,
},
{
Name: subcmdStop,
Usage: "stop ETL with given id",
ArgsUsage: "ETL_ID",
Action: etlStopHandler,
},
{
Name: subcmdObject,
Usage: "transform object with given ETL",
ArgsUsage: "ETL_ID BUCKET_NAME/OBJECT_NAME OUTPUT",
Action: etlObjectHandler,
},
},
},
}
)
func etlInitHandler(c *cli.Context) (err error) {
if c.NArg() == 0 {
return missingArgumentsError(c, "SPEC_FILE")
}
specPath := c.Args()[0]
f, err := os.Open(specPath)
if err != nil {
return err
}
spec, err := ioutil.ReadAll(f)
f.Close()
if err != nil {
return err
}
id, err := api.TransformInit(defaultAPIParams, spec)
if err != nil {
return err
}
fmt.Fprintf(c.App.Writer, "%s\n", id)
return nil
}
func etlListHandler(c *cli.Context) (err error) {
list, err := api.TransformList(defaultAPIParams)
if err != nil {
return err
}
return templates.DisplayOutput(list, c.App.Writer, templates.TransformListTmpl)
}
func etlStopHandler(c *cli.Context) (err error) {
if c.NArg() == 0 {
return missingArgumentsError(c, "ETL_ID")
}
id := c.Args()[0]
if err := api.TransformStop(defaultAPIParams, id); err != nil {
return err
}
fmt.Fprintln(c.App.Writer, "ETL containers stopped successfully.")
return nil
}
func etlObjectHandler(c *cli.Context) (err error) {
if c.NArg() == 0 {
return missingArgumentsError(c, "ETL_ID")
} else if c.NArg() == 1 {
return missingArgumentsError(c, "BUCKET/OBJECT_NAME")
} else if c.NArg() == 2 {
return missingArgumentsError(c, "OUTPUT")
}
var (
id = c.Args()[0]
objName = c.Args()[1]
outputDest = c.Args()[2]
)
bck, objName, err := cmn.ParseBckObjectURI(objName)
if err != nil {
return err
}
var w io.Writer
if outputDest == "-" {
w = os.Stdout
} else {
f, err := os.Create(outputDest)
if err != nil {
return err
}
w = f
defer f.Close()
}
err = api.TransformObject(defaultAPIParams, id, bck, objName, w)
if httpErr, ok := err.(*cmn.HTTPError); ok {
// TODO: How to find out if it's transformation not found, and not object not found?
if httpErr.Status == http.StatusNotFound && strings.Contains(httpErr.Error(), id) {
return fmt.Errorf("ETL %q not found; try starting new ETL with:\nais %s %s <spec>", id, commandETL, subcmdInit)
}
}
return err
}
|
d56087c5dadd7e7df90bbdae6aa71274e70a0827
|
{
"blob_id": "d56087c5dadd7e7df90bbdae6aa71274e70a0827",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-05T01:15:33",
"content_id": "c3833ab43e03e1813bd880666dab148394ee6cd7",
"detected_licenses": [
"MIT"
],
"directory_id": "74ab1851683a233deb2e81a40d5c22cbb39455bc",
"extension": "go",
"filename": "etl.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3152,
"license": "MIT",
"license_type": "permissive",
"path": "/cmd/cli/commands/etl.go",
"provenance": "stack-edu-0016.json.gz:75249",
"repo_name": "cxz/aistore",
"revision_date": "2020-09-05T01:15:11",
"revision_id": "059a0c1775d759ea709d2bb06b3250eee3708343",
"snapshot_id": "5f0a6caa9d3777b56ae3b4c9de85a94afc953101",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/cxz/aistore/059a0c1775d759ea709d2bb06b3250eee3708343/cmd/cli/commands/etl.go",
"visit_date": "2022-12-13T18:50:39.303509",
"added": "2024-11-18T23:22:56.823472+00:00",
"created": "2020-09-05T01:15:11",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
#Imports
import json
import sys
import torch
import numpy as np
from torch import nn
from torch import optim
import torch.nn.functional as F
from torchvision import datasets, transforms, models
from PIL import Image
import argparse
#Create argparse for easy user entry
parser = parser = argparse.ArgumentParser()
parser.add_argument('--img_path', type = str, default = 'flowers/test/52/image_04200.jpg', help = 'Directory of Dataset')
parser.add_argument('--load_chkpt', type = str, default = 'checkpoint.pth', help='Load the trained model from a file')
parser.add_argument('--gpu', type = bool, default = 'True', help='True for GPU, False for CPU')
parser.add_argument('--category_names', type = str, default = 'cat_to_name.json', help='File containing classifier categories')
parser.add_argument('--top_k', type = int, default = 5, help = 'Number of Top Categories to return')
args = parser.parse_args()
# Set variables based on user entry
if args.img_path is not None:
img_path = args.img_path
if args.gpu is not None:
gpu = args.gpu
if args.load_chkpt is not None:
load_chkpt = args.load_chkpt
if args.category_names is not None:
category_names = args.category_names
if args.top_k is not None:
top_k = args.top_k
# Load checkpoint Function
def load_checkpoint(filepath):
checkpoint= torch.load(filepath)
model = getattr(models, checkpoint['architecture'])(pretrained=True)
model.class_to_idx = checkpoint['class_to_idx']
model.classifier = checkpoint['classifier']
model.load_state_dict(checkpoint['state_dict'])
return model
# Process Image Function
def process_image(image):
''' Scales, crops, and normalizes a PIL image for a PyTorch model,
returns an Numpy array
'''
# TODO: Process a PIL image for use in a PyTorch model
# Set Variables
means = [0.485, 0.456, 0.406]
std_devs = [0.229, 0.224, 0.225]
# Processing Steps
process_img = transforms.Compose([transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(means, std_devs)])
# Process image through Processing Steps
pil_img = Image.open(image)
pil_img = process_img(pil_img).float()
np_img = np.array(pil_img)
return np_img
# Display Image Function
def imshow(image, ax=None, title=None):
if ax is None:
fig, ax = plt.subplots()
# PyTorch tensors assume the color channel is the first dimension
# but matplotlib assumes is the third dimension
image = image.transpose((1, 2, 0))
# Undo preprocessing
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
image = std * image + mean
# Image needs to be clipped between 0 and 1 or it looks like noise when displayed
image = np.clip(image, 0, 1)
ax.imshow(image)
return ax
# Prediction function
def predict(image_path, model, topk=5):
# Process image
sample_img = process_image(image_path)
# Convert Numpy to Tensor
img_tensor = torch.from_numpy(sample_img).type(torch.FloatTensor)
# Add batch of size 1 to image
sample_input = img_tensor.unsqueeze(0)
# Get Probabilities
ps = torch.exp(model.forward(sample_input))
ps, labels = torch.topk(ps, topk)
# Seperate Probabilities (ps), Numeric Labels (labels) into individual lists
top_ps = ps.detach().numpy().tolist()[0]
top_labels = labels.detach().numpy().tolist()[0]
# Gather Flower Labels and convert Numeric Label to Flower Label
with open('cat_to_name.json', 'r') as f:
cat_to_name = json.load(f)
idx_to_class = {val: key for key, val in
model.class_to_idx.items()}
top_flowers = [cat_to_name[idx_to_class[label]] for label in top_labels]
# Return Probabilities (ps), Numeric Labels (Labels), Flower Labels
return top_ps, top_labels, top_flowers
# Test Loading Checkpoint
#Load model from checkpoint saved in train.py
model = load_checkpoint(load_chkpt)
#Switch to CPU and Evaluation
model.to('cpu')
model.eval()
# Set Test Image
image_path = img_path
# Make prediction
ps, labels, flowers = predict(image_path, model, top_k)
# Print Prediction
print("Image: ", img_path)
print("\nTop ", top_k, " Predictions")
print("Percentage: ", ps)
print("Numeric Label: ", labels)
print("Flower Label: ", flowers)
print("\nTop Prediction")
print("Percentage: ", round(ps[0] * 100, 2), "%")
print("Numeric Label: ", labels[0])
print("Flower Label: ", flowers[0])
|
6babe6dd4e73dcc973740c910591acd8414284b7
|
{
"blob_id": "6babe6dd4e73dcc973740c910591acd8414284b7",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-27T00:56:12",
"content_id": "3c6440a92fece24fc4a60c48e8919197fa9a1ab2",
"detected_licenses": [
"MIT"
],
"directory_id": "5ce7a760cee5abdcedc329048e0c4063874010d2",
"extension": "py",
"filename": "predict.py",
"fork_events_count": 0,
"gha_created_at": "2019-02-10T18:38:43",
"gha_event_created_at": "2019-02-10T18:38:43",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 170012218,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4603,
"license": "MIT",
"license_type": "permissive",
"path": "/predict.py",
"provenance": "stack-edu-0057.json.gz:197150",
"repo_name": "dcurl/aipnd-project",
"revision_date": "2019-02-27T00:56:12",
"revision_id": "7d5376b81b8701a506034a2752793b70cc48066e",
"snapshot_id": "02d526faf6308332c696334fdb6762aad6e87ae0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dcurl/aipnd-project/7d5376b81b8701a506034a2752793b70cc48066e/predict.py",
"visit_date": "2020-04-22T01:22:04.099072",
"added": "2024-11-18T21:00:26.535118+00:00",
"created": "2019-02-27T00:56:12",
"int_score": 3,
"score": 2.734375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz"
}
|
<?php
namespace Ephp\Bundle\WsInvokerBundle\Form\Config;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
class ServiceType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name')
->add('method', 'choice', array('choices' => array('GET' => 'GET', 'POST' => 'POST', 'PUT' => 'PUT', 'SOAP' => 'SOAP')))
->add('uri')
->add('query_string')
->add('data_type', null, array('label' => 'Data Type/Soap Method'))
->add('header')
->add('data_body')
->add('host')
;
}
public function getName()
{
return 'ephp_bundle_siliconbundle_config_servicetype';
}
}
|
4935f09c370b9070993c867db641467ef852fe40
|
{
"blob_id": "4935f09c370b9070993c867db641467ef852fe40",
"branch_name": "refs/heads/master",
"committer_date": "2013-10-09T10:35:16",
"content_id": "e94472b97b2b00c5f25197e66429f88aef67c3b8",
"detected_licenses": [
"MIT"
],
"directory_id": "e056fa319fbd3b61e2764892751d5411cb4b3090",
"extension": "php",
"filename": "ServiceType.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 798,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Ephp/Bundle/WsInvokerBundle/Form/Config/ServiceType.php",
"provenance": "stack-edu-0051.json.gz:423077",
"repo_name": "ephp/Sinistri",
"revision_date": "2013-10-09T10:35:16",
"revision_id": "2ab344337ccab98c3ffc38f769a1efa9ff130e0c",
"snapshot_id": "793d84e11349621b64f8b6e72ea34b97f85dd977",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/ephp/Sinistri/2ab344337ccab98c3ffc38f769a1efa9ff130e0c/src/Ephp/Bundle/WsInvokerBundle/Form/Config/ServiceType.php",
"visit_date": "2020-03-29T16:00:44.479124",
"added": "2024-11-19T01:38:46.896595+00:00",
"created": "2013-10-09T10:35:16",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
#include "ros_time.h"
#include <ros/ros.h>
double time_now_toSec() {
return ros::Time::now().toSec();
}
uint64_t time_now_toNSec() {
return ros::Time::now().toNSec();
}
void time_init() {
ros::Time::init();
}
void time_shutdown() {
ros::Time::shutdown();
}
void time_useSystemTime() {
ros::Time::useSystemTime();
}
bool time_isSimTime() {
return ros::Time::isSimTime();
}
bool time_isSystemTime() {
return ros::Time::isSystemTime();
}
bool time_isValid() {
return ros::Time::isValid();
}
void time_waitForValid() {
ros::Time::waitForValid();
}
/*
* WallTime
*/
double walltime_now_toSec() {
return ros::WallTime::now().toSec();
}
uint64_t walltime_now_toNSec() {
return ros::WallTime::now().toNSec();
}
bool walltime_isSystemTime() {
return ros::WallTime::isSystemTime();
}
|
579a2e71a25317dc3bcacd6035fbf079f227a6e4
|
{
"blob_id": "579a2e71a25317dc3bcacd6035fbf079f227a6e4",
"branch_name": "refs/heads/main",
"committer_date": "2021-04-16T18:16:43",
"content_id": "b5fac4071c9831dc60b4eaf0bbbc09f6cf8aeccb",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "4712f442c1a045b757c69620d7bef95bb2cd4a42",
"extension": "cc",
"filename": "ros_time.cc",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 813,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/ros-native/src/ros-native/src/ros_time.cc",
"provenance": "stack-edu-0006.json.gz:301074",
"repo_name": "yuancaimaiyi/leogate",
"revision_date": "2021-04-16T18:16:43",
"revision_id": "4d82bd8d8e3f657d1e00d0a1904d0b9940e1fcf4",
"snapshot_id": "08451e37fe9d30609d247b80d08c99ef86849304",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yuancaimaiyi/leogate/4d82bd8d8e3f657d1e00d0a1904d0b9940e1fcf4/ros-native/src/ros-native/src/ros_time.cc",
"visit_date": "2023-08-31T22:33:51.554566",
"added": "2024-11-18T21:12:14.312636+00:00",
"created": "2021-04-16T18:16:43",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0024.json.gz"
}
|
// @flow
import * as mobx from 'mobx';
import axios from 'axios';
class PostStore {
@mobx.observable posts: Array<PostType>;
@mobx.observable post: ?PostType;
@mobx.observable page: number;
@mobx.observable total: number;
@mobx.observable totalPage: number;
rootStore: RootStoreType;
constructor(rootStore: RootStoreType, initialState: Object) {
this.posts = initialState.posts || [];
this.post = initialState.post || null;
this.page = initialState.page || 1;
this.total = initialState.total || 0;
this.totalPage = initialState.totalPage || 1;
this.rootStore = rootStore;
}
syncPosts(): Array<PostType> | Promise<any> {
this.rootStore.headStore.title = 'List post';
return axios(`${this.rootStore.domainStore.path}wp/v2/posts`)
.then(res => {
this.total = res.headers ? res.headers['x-wp-total'] : 0;
this.totalPage = res.headers ? res.headers['x-wp-totalpages'] : 1;
this.posts = res.data;
})
.catch(e => {
throw e;
});
}
syncPost(slug: string): PostType | Promise<any> {
return axios(`${this.rootStore.domainStore.path}postlight/v1/post?slug=${slug}`)
.then(res => {
this.post = res.data;
})
.catch(e => {
throw e;
});
}
findPostInPosts(slug: string): ?PostType {
this.posts.find((post: Object) => post.slug === slug);
}
findPost(slug: string): PostType | Promise<any> {
// if same post return
if (this.post && this.post.slug === slug) {
return this.post;
}
return new Promise(async resolve => {
this.post = null;
const post = this.findPostInPosts(slug);
if (post) {
this.post = post;
if (this.post) this.rootStore.headStore.title = this.post.title.rendered;
return resolve();
}
await this.syncPost(slug);
if (this.post) this.rootStore.headStore.title = this.post.title.rendered;
return resolve();
});
}
}
export default PostStore;
|
7ab5e8c4889c3e654f8fd3f3bcd095b50e97451e
|
{
"blob_id": "7ab5e8c4889c3e654f8fd3f3bcd095b50e97451e",
"branch_name": "refs/heads/master",
"committer_date": "2017-12-18T11:04:50",
"content_id": "8b4c8cc2869a117e17d06edaababee6c13062d0b",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "b7343583839004b2ef67cfe647dc457bbe62b509",
"extension": "js",
"filename": "PostStore.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2002,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/stores/PostStore.js",
"provenance": "stack-edu-0032.json.gz:717521",
"repo_name": "music-rec/react-mobx-ssr",
"revision_date": "2017-12-18T11:04:50",
"revision_id": "4c0c49185fecb3eed012247e28a8fa3db6e31452",
"snapshot_id": "66edc60911e9e4ea146fbe31a49269662cbcf083",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/music-rec/react-mobx-ssr/4c0c49185fecb3eed012247e28a8fa3db6e31452/src/stores/PostStore.js",
"visit_date": "2020-06-25T13:15:53.928339",
"added": "2024-11-19T00:50:12.914266+00:00",
"created": "2017-12-18T11:04:50",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0050.json.gz"
}
|
/*
* ----------------------------------------
* Nutrient Usage Tracking System
* ----------------------------------------
* Produced by Dan Grew
* 2017
* ----------------------------------------
*/
package uk.dangrew.nuts.progress.weight;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
/**
* {@link WeightRecording} provides an individual recording of weight properties for a day.
*/
public class WeightRecording {
private final LocalDate date;
private final WeighIn morning;
private final WeighIn evening;
private final WeighInAverage runningAverage;
/**
* Constructs a new {@link WeightRecording}.
* @param date the {@link LocalDate} of the recording.
* @param previousWeighIns the {@link WeightRecording}s before this.
*/
public WeightRecording( LocalDate date, Collection< WeightRecording > previousWeighIns ) {
this( date, new WeighIn( DayTime.Morning ), new WeighIn( DayTime.Evening ), previousWeighIns );
}//End Constructor
/**
* Constructs a new {@link WeightRecording}.
* @param date the {@link LocalDate} of the recording.
* @param morning the {@link WeighIn} for the morning.
* @param evening the {@link WeighIn} for the evening.
* @param previousWeighIns the {@link WeightRecording}s before this.
*/
WeightRecording( LocalDate date, WeighIn morning, WeighIn evening, Collection< WeightRecording > previousWeighIns ) {
this.date = date;
this.morning = morning;
this.evening = evening;
List< WeightRecording > averageWeighIns = new ArrayList<>();
averageWeighIns.addAll( previousWeighIns );
averageWeighIns.add( this );
this.runningAverage = new WeighInAverage( averageWeighIns );
}//End Class
/**
* Access to the date.
* @return the {@link LocalDate}.
*/
public LocalDate date(){
return date;
}//End Method
/**
* Access to the morning {@link WeighIn}.
* @return the {@link WeighIn}.
*/
public WeighIn morningWeighIn() {
return morning;
}//End Method
/**
* Access to the evening {@link WeighIn}.
* @return the {@link WeighIn}.
*/
public WeighIn eveningWeighIn() {
return evening;
}//End Method
/**
* Access to the {@link WeighInAverage}.
* @return the {@link WeighInAverage}.
*/
public WeighInAverage runningAverage() {
return runningAverage;
}//End Method
}//End Class
|
e9f7c75c37453182b8517b3d3c6591340ded32c2
|
{
"blob_id": "e9f7c75c37453182b8517b3d3c6591340ded32c2",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-10T08:04:59",
"content_id": "090a93390be16494bc68b10a99172220b2ea80be",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "60a6a97e33382fd1d19ca74c2c17700122f9d2ff",
"extension": "java",
"filename": "WeightRecording.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97559046,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2532,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/nuts/src/uk/dangrew/nuts/progress/weight/WeightRecording.java",
"provenance": "stack-edu-0022.json.gz:143986",
"repo_name": "DanGrew/Nuts",
"revision_date": "2021-02-10T08:04:59",
"revision_id": "e0f6835f376dc911c630122c2b21c7130c437bfd",
"snapshot_id": "19b946672a00651c1b36b4dc4b99dbedc6c08786",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/DanGrew/Nuts/e0f6835f376dc911c630122c2b21c7130c437bfd/nuts/src/uk/dangrew/nuts/progress/weight/WeightRecording.java",
"visit_date": "2021-06-03T08:23:02.295355",
"added": "2024-11-19T01:37:53.861500+00:00",
"created": "2021-02-10T08:04:59",
"int_score": 3,
"score": 2.859375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
using System;
using System.Collections.Generic;
namespace ReplicaProcess.Kernel {
public class DupKernel : AbstractKernel {
public override IList<IList<string>> execute(IList<string> tuple) {
if (DEBUGGING_HARD) Console.WriteLine("[DupKernel] Got tuple <{0}>", string.Join(", ", tuple));
return new List<IList<string>> {tuple};
}
}
}
|
6eaeb2d432adbcadf1d7faadca954fa0297e2ac6
|
{
"blob_id": "6eaeb2d432adbcadf1d7faadca954fa0297e2ac6",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-19T23:38:20",
"content_id": "71bd953e03fecddd5412fd28ae02aba4882fc22a",
"detected_licenses": [
"MIT"
],
"directory_id": "c330468b410c687a46b2f255f2608e9a29c89c38",
"extension": "cs",
"filename": "DupKernel.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 97770310,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 387,
"license": "MIT",
"license_type": "permissive",
"path": "/OperatorProcess/Kernel/DupKernel.cs",
"provenance": "stack-edu-0010.json.gz:508898",
"repo_name": "Vasco-jofra/dadstorm",
"revision_date": "2017-07-19T23:38:20",
"revision_id": "05bc03d6de85f99295b4ed37cc124ed3235e1e49",
"snapshot_id": "7341eff0996981cbddb95ea2831c646d43572643",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Vasco-jofra/dadstorm/05bc03d6de85f99295b4ed37cc124ed3235e1e49/OperatorProcess/Kernel/DupKernel.cs",
"visit_date": "2021-01-01T16:06:59.294954",
"added": "2024-11-18T23:40:08.414291+00:00",
"created": "2017-07-19T23:38:20",
"int_score": 2,
"score": 2.078125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
import unittest
from services import RoverRunnerService
from tests.test_environment.marses import small_mars_with_one_rover_empty_commands
from tests.test_environment import mocks as m
from data_objects import Rover
class TestRoverRunnerService(unittest.TestCase):
def test_rover_runner_moves_rover_forward(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = small_mars_with_one_rover_empty_commands.rover_setups[0].rover
tss = m.get_mocked_turn_command_selector_turn_left_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
final_pos = rrs.run(['M'])
self.assertEqual(Rover(0, 1, 'N'), final_pos)
def test_rover_runner_turns_rover_left(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = small_mars_with_one_rover_empty_commands.rover_setups[0].rover
tss = m.get_mocked_turn_command_selector_turn_left_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
final_pos = rrs.run(['L'])
self.assertEqual(Rover(0, 0, 'W'), final_pos)
def test_rover_runner_turns_rover_right(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = small_mars_with_one_rover_empty_commands.rover_setups[0].rover
tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
final_pos = rrs.run(['R'])
self.assertEqual(Rover(0, 0, 'E'), final_pos)
def test_rover_runner_goes_off_gird_east(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = Rover(1, 1, "E")
tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only()
mss = m.get_mocked_move_command_selector_east_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
self.assertRaises(ValueError, rrs.run, ['M'])
def test_rover_runner_goes_off_gird_north(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = Rover(1, 1, "N")
tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
self.assertRaises(ValueError, rrs.run, ['M'])
def test_rover_runner_goes_off_gird_west(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = Rover(0, 1, "W")
tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only()
mss = m.get_mocked_move_command_selector_west_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
self.assertRaises(ValueError, rrs.run, ['M'])
def test_rover_runner_goes_off_gird_south(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = Rover(0, 0, "S")
tss = m.get_mocked_turn_command_selector_turn_right_from_north_command_only()
mss = m.get_mocked_move_command_selector_south_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
self.assertRaises(ValueError, rrs.run, ['M'])
def test_rover_runner_does_nothing_empty_command(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = small_mars_with_one_rover_empty_commands.rover_setups[0].rover
tss = m.get_mocked_turn_command_selector_turn_left_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
final_pos = rrs.run([])
self.assertEqual(rover, final_pos)
def test_rover_runner_raises_error_for_None_command(self):
grid = small_mars_with_one_rover_empty_commands.grid
rover = small_mars_with_one_rover_empty_commands.rover_setups[0].rover
tss = m.get_mocked_turn_command_selector_turn_left_from_north_command_only()
mss = m.get_mocked_move_command_selector_north_command_only()
rrs = RoverRunnerService(grid, rover, mss, tss)
self.assertRaises(TypeError, rrs.run, None)
|
677855a6ff301908d57a6f7684fdb87b4b7bc97a
|
{
"blob_id": "677855a6ff301908d57a6f7684fdb87b4b7bc97a",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-28T11:52:35",
"content_id": "0ecfc00a422b2dc3bba9eb71d7782113b804c267",
"detected_licenses": [
"MIT"
],
"directory_id": "dbf7d44245a9fe50148589ffe5f663547b30c832",
"extension": "py",
"filename": "test_rover_runner_service.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 262568699,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4351,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/services/test_rover_runner_service.py",
"provenance": "stack-edu-0060.json.gz:494129",
"repo_name": "dev-11/mars-rover-challenge",
"revision_date": "2021-03-28T11:52:35",
"revision_id": "67569fcc4b93e5ec4cbe466d7a2fd5b3e9a316b0",
"snapshot_id": "73cc8eacde30bfc6f1b290fd43180e27f7e114f7",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dev-11/mars-rover-challenge/67569fcc4b93e5ec4cbe466d7a2fd5b3e9a316b0/tests/services/test_rover_runner_service.py",
"visit_date": "2023-04-01T11:04:52.335185",
"added": "2024-11-18T22:40:32.520493+00:00",
"created": "2021-03-28T11:52:35",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0078.json.gz"
}
|
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views import generic
from .models import Participant
from .forms import ParticipantForm
def index(request):
return HttpResponseRedirect('/participant_info/add_participant')
# This view will return a list of all the participants
# that have been entereed in the UDN database.
def all_participants(request):
return render(request, 'participant_info/all.html', {'participants': Participant.objects.all()})
# This view is the form where a participant's information is entered.
def add_participant(request):
if request.method == 'POST':
form = ParticipantForm(request.POST)
# If the form is valid (no duplicate name or incorrect data)
# then save the data and redirect the user to participant list page.
if form.is_valid():
form.save()
return HttpResponseRedirect('/participant_info/all')
else:
form = ParticipantForm()
return render(request, 'participant_info/add_participant.html', {'form': form})
|
31f97ae284e4c5dbc8cdbe7faaf6888618f0660d
|
{
"blob_id": "31f97ae284e4c5dbc8cdbe7faaf6888618f0660d",
"branch_name": "refs/heads/master",
"committer_date": "2019-12-27T16:36:31",
"content_id": "5eb70620cc02d3e49464e29f5a933c9b191e6878",
"detected_licenses": [
"MIT"
],
"directory_id": "5cccc17489d323a8769d82ac749bb7400893c737",
"extension": "py",
"filename": "views.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 230069321,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1105,
"license": "MIT",
"license_type": "permissive",
"path": "/udn/participant_info/views.py",
"provenance": "stack-edu-0057.json.gz:512991",
"repo_name": "Techno-Hwizrdry/UDN",
"revision_date": "2019-12-27T16:36:31",
"revision_id": "ef52c28c5cdd8ec2cc6669f56c0dcbdccc6e6c47",
"snapshot_id": "6bdd9b4f95be247673e3f7b25cfb429e1e70e260",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Techno-Hwizrdry/UDN/ef52c28c5cdd8ec2cc6669f56c0dcbdccc6e6c47/udn/participant_info/views.py",
"visit_date": "2020-11-29T08:31:25.672603",
"added": "2024-11-19T01:37:40.363385+00:00",
"created": "2019-12-27T16:36:31",
"int_score": 2,
"score": 2.296875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0075.json.gz"
}
|
# doctrine-laminas-hydrator
[](https://github.com/doctrine/doctrine-laminas-hydrator/actions/workflows/continuous-integration.yml?query=branch%3A3.4.x)
[](https://codecov.io/gh/doctrine/doctrine-laminas-hydrator/branch/3.4.x)
[](https://packagist.org/packages/doctrine/doctrine-laminas-hydrator)
[](https://packagist.org/packages/doctrine/doctrine-laminas-hydrator)
This library provides Doctrine hydrators for Laminas.
## Installation
Run the following to install this library using [Composer](https://getcomposer.org/):
```bash
composer require doctrine/doctrine-laminas-hydrator
```
## Documentation
Please check the [documentation on the Doctrine website](https://www.doctrine-project.org/projects/doctrine-laminas-hydrator.html)
for more detailed information on features provided by this component. The source files for the documentation can be
found in the [docs directory](./docs/en).
|
bc8efc4e61101f08f308304ba4d0ac0d50185af5
|
{
"blob_id": "bc8efc4e61101f08f308304ba4d0ac0d50185af5",
"branch_name": "refs/heads/3.4.x",
"committer_date": "2023-02-07T22:14:07",
"content_id": "b7acdf4441c63c83eb1185e76a8272c2712e189f",
"detected_licenses": [
"MIT"
],
"directory_id": "cf1a2ab469cc9776fe7ad1e21f5aa75f45d3ff14",
"extension": "md",
"filename": "README.md",
"fork_events_count": 20,
"gha_created_at": "2020-01-15T20:23:15",
"gha_event_created_at": "2023-02-07T19:58:25",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 234165990,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1315,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0013.json.gz:158129",
"repo_name": "doctrine/doctrine-laminas-hydrator",
"revision_date": "2023-02-07T22:14:07",
"revision_id": "6eebc1f52a48cfdee36eb61192609d5da32bd007",
"snapshot_id": "d28719eba2d98e7880db31be31d95ecfa798095b",
"src_encoding": "UTF-8",
"star_events_count": 27,
"url": "https://raw.githubusercontent.com/doctrine/doctrine-laminas-hydrator/6eebc1f52a48cfdee36eb61192609d5da32bd007/README.md",
"visit_date": "2023-02-09T04:10:40.731410",
"added": "2024-11-18T22:46:16.038917+00:00",
"created": "2023-02-07T22:14:07",
"int_score": 3,
"score": 3.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0013.json.gz"
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.tadspi3null.servletUsuario;
import com.tadspi3null.dao.DaoFuncao;
import com.tadspi3null.dao.DaoUsuario;
import com.tadspi3null.models.Funcao;
import com.tadspi3null.models.Usuario;
import java.io.IOException;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
*
* @author Alexandre
*/
@WebServlet(name = "CadastrarUsuario", urlPatterns = {"/cadastrar-usuario"})
public class CadastrarUsuario extends HttpServlet {
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// valor da funcao é no DOGET
try {
HttpSession sessao = request.getSession();
ArrayList<Funcao> listaFuncao = DaoFuncao.obterListaFuncao();
request.setAttribute("listaFuncao2", listaFuncao);
sessao.setAttribute("listaFuncao", listaFuncao);
} catch (SQLException ex) {
Logger.getLogger(CadastrarUsuario.class.getName()).log(Level.SEVERE, null, ex);
}
RequestDispatcher dispatcher
= request.getRequestDispatcher("WEB-INF/jsp/cadastrar-usuario.jsp");
dispatcher.forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Usuario usuario = new Usuario();
HttpSession sessao = request.getSession();
usuario.setNome(request.getParameter("nome"));
usuario.setSexo(request.getParameter("sexo"));
usuario.setTelefone(request.getParameter("telefone"));
usuario.setSobrenome(request.getParameter("sobrenome"));
usuario.setFuncaoNome(request.getParameter("funcao"));
try {
//criando objeto funcao por nome
Date data = Auxiliar.InputDateToUtilDate(request.getParameter("dt_admissao"));
usuario.setDtAdmissao(data);
Funcao funcao = DaoFuncao.obterFuncaoPorNome(usuario.getFuncaoNome());
usuario.setFuncao(funcao);
DaoUsuario.inserirUsuario(usuario);
// funcao = DaoFuncao.obterFuncaoPOrId(idFuncao);
} catch (SQLException ex) {
System.out.println(ex.getMessage());
} catch (ParseException ex) {
Logger.getLogger(CadastrarUsuario.class.getName()).log(Level.SEVERE, null, ex);
}
RequestDispatcher dispatcher
= request.getRequestDispatcher("WEB-INF/jsp/cadastrar-usuario.jsp");
dispatcher.forward(request, response);
}
}
|
904a311745bc0e8ce32e61adfccac45e658b7d7b
|
{
"blob_id": "904a311745bc0e8ce32e61adfccac45e658b7d7b",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-08T20:59:02",
"content_id": "6501d5f159d86862ae1815b7426c80fd7341593d",
"detected_licenses": [
"MIT"
],
"directory_id": "aace1963eed5bd6e5d1248cd48f7a9f2c6704c37",
"extension": "java",
"filename": "CadastrarUsuario.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 128425455,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3580,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/com/tadspi3null/servletUsuario/CadastrarUsuario.java",
"provenance": "stack-edu-0026.json.gz:667946",
"repo_name": "mrtzdanilo/tads_pi3_null",
"revision_date": "2018-06-08T20:59:02",
"revision_id": "a9ff5f86fa2475f58bead1d5479407230274b454",
"snapshot_id": "e9e3ef1059071711bfe6cc111330b2ee3aa765d0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mrtzdanilo/tads_pi3_null/a9ff5f86fa2475f58bead1d5479407230274b454/src/main/java/com/tadspi3null/servletUsuario/CadastrarUsuario.java",
"visit_date": "2021-06-11T05:06:57.692063",
"added": "2024-11-19T00:24:00.345846+00:00",
"created": "2018-06-08T20:59:02",
"int_score": 2,
"score": 2.328125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0044.json.gz"
}
|
// ┌∩┐(◣_◢)┌∩┐
// \\
// GreenMonster.cs (00/00/0000) \\
// Autor: Antonio Mateo (.\Moon Antonio) [email protected] \\
// Descripcion: \\
// Fecha Mod: 00/00/0000 \\
// Ultima Mod: \\
//******************************************************************************\\
#region Librerias
using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
#endregion
namespace MoonAntonio
{
public class GreenMonster : Monster
{
public int earth;
void Awake()
{
earth = UnityEngine.Random.Range(10, 100);
}
public override Dictionary<string, object> Save()
{
Dictionary<string, object> data = base.Save();
data.Add("Earth", earth);
return data;
}
public override void Load(Dictionary<string, object> data)
{
base.Load(data);
earth = Convert.ToInt32(data["Earth"]);
}
}
}
|
02d83bd39b9c898ed8e833aaeba2880558ec1292
|
{
"blob_id": "02d83bd39b9c898ed8e833aaeba2880558ec1292",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-08T23:25:31",
"content_id": "7959fbdc34ba3068316b534225f118061fc5c289",
"detected_licenses": [
"MIT"
],
"directory_id": "dd7dc91c4cd2a0aad4a4edeb47111d8987ab2c21",
"extension": "cs",
"filename": "GreenMonster.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 145270269,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 976,
"license": "MIT",
"license_type": "permissive",
"path": "/LearnCSharpUnity Project/Assets/09.Guardando datos/GreenMonster.cs",
"provenance": "stack-edu-0012.json.gz:332773",
"repo_name": "CodeBackDoor/LearnCSharpUnity",
"revision_date": "2019-01-08T23:25:31",
"revision_id": "af9a5370c6de3d425362ebaa2ff75596e63c4a6a",
"snapshot_id": "4a0bb6e4b599389493372c8beb87a72f6386200e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/CodeBackDoor/LearnCSharpUnity/af9a5370c6de3d425362ebaa2ff75596e63c4a6a/LearnCSharpUnity Project/Assets/09.Guardando datos/GreenMonster.cs",
"visit_date": "2020-03-26T19:32:18.419917",
"added": "2024-11-19T00:50:28.496559+00:00",
"created": "2019-01-08T23:25:31",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
export interface Link {
label: string;
link: string;
class?: string;
}
|
9afd756b65ca49f5bf5e5f42fd2676353e5ab6b8
|
{
"blob_id": "9afd756b65ca49f5bf5e5f42fd2676353e5ab6b8",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-05T22:59:44",
"content_id": "43ea931ca2b0473c2421ed74a5b1f03077d498f7",
"detected_licenses": [
"MIT"
],
"directory_id": "da4bf918a4ad2110b7eaa05accf4921cc4b8c817",
"extension": "ts",
"filename": "link.ts",
"fork_events_count": 0,
"gha_created_at": "2018-01-24T18:22:12",
"gha_event_created_at": "2023-01-04T03:00:00",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 118804322,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 83,
"license": "MIT",
"license_type": "permissive",
"path": "/src/app/shared/model/link.ts",
"provenance": "stack-edu-0074.json.gz:978256",
"repo_name": "xby2/xby2-website",
"revision_date": "2019-10-05T22:59:44",
"revision_id": "a8ca18e6610d1d15616c0a92d97ac3cb3937fe6c",
"snapshot_id": "709c9d6d2966b6be850cf3d6dc6d12d7846e0af9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/xby2/xby2-website/a8ca18e6610d1d15616c0a92d97ac3cb3937fe6c/src/app/shared/model/link.ts",
"visit_date": "2023-01-14T09:45:27.095999",
"added": "2024-11-18T23:44:06.357633+00:00",
"created": "2019-10-05T22:59:44",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
package advance.datastructureandalgorithm.array;
import java.util.Arrays;
import java.util.Comparator;
/**
* @ClassName PrintMinNumber
* @Descrption 剑指Offer 把数组排成最小的数<p>https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking</p>
* @Author lt
* @Date 2019/6/24 22:13
* @Version 1.0
**/
public class PrintMinNumber {
public static void main(String[] args) {
int[] intArray = new int[]{3, 32, 321};
String minString = sort(intArray);
System.out.println(minString);
}
private static String sort(int[] intArray) {
if (intArray == null || intArray.length == 0) {
return "";
}
int length = intArray.length;
String[] strArr = new String[length];
for (int i = 0; i < length; i++) {
strArr[i] = String.valueOf(intArray[i]);
}
Arrays.sort(strArr, new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
return (s1 + s2).compareTo(s2 + s1);
}
});
StringBuilder sb = new StringBuilder();
for (String str : strArr) {
sb.append(str);
}
return sb.toString();
}
}
|
f64feac9292943aecb26e1362e706c17b6403c4a
|
{
"blob_id": "f64feac9292943aecb26e1362e706c17b6403c4a",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-24T07:27:24",
"content_id": "fc24f12c7c6cd172581c7e5a6f85d5970409fb36",
"detected_licenses": [
"MIT"
],
"directory_id": "d4e5570762c71c783128792e14c738a1020823b8",
"extension": "java",
"filename": "PrintMinNumber.java",
"fork_events_count": 0,
"gha_created_at": "2019-11-09T15:14:48",
"gha_event_created_at": "2021-04-22T19:02:35",
"gha_language": "Java",
"gha_license_id": "MIT",
"github_id": 220660246,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1341,
"license": "MIT",
"license_type": "permissive",
"path": "/src/main/java/advance/datastructureandalgorithm/array/PrintMinNumber.java",
"provenance": "stack-edu-0024.json.gz:39036",
"repo_name": "Pirate5946/techframework",
"revision_date": "2021-06-24T07:07:13",
"revision_id": "ec37b8f4401377805a8b346a657b449cb824d4e2",
"snapshot_id": "bfed6f38243bfdaa14b29850fed3692bcb2cc0f0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Pirate5946/techframework/ec37b8f4401377805a8b346a657b449cb824d4e2/src/main/java/advance/datastructureandalgorithm/array/PrintMinNumber.java",
"visit_date": "2022-02-04T00:37:03.046168",
"added": "2024-11-18T22:53:43.603910+00:00",
"created": "2021-06-24T07:07:13",
"int_score": 4,
"score": 3.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
package plugin
import (
"fmt"
"path/filepath"
"plugin"
"reflect"
"strconv"
"sync"
)
var (
m sync.Mutex
cache = map[string]Plugin{}
newPlugin *openedPlugin
)
// Open opens a Go plugin.
// If a path has already been opened, then the existing *Plugin is returned.
// It is safe for concurrent use by multiple goroutines.
func Open(path string) (Plugin, error) {
if !filepath.IsAbs(path) {
abs, err := filepath.Abs(path)
if err != nil {
return nil, fmt.Errorf("failed to get absolute path: %w", err)
}
path = abs
}
filepath.Clean(path)
m.Lock()
defer m.Unlock()
if p, ok := cache[path]; ok {
return p, nil
}
newPlugin = &openedPlugin{} //nolint:exhaustruct
defer func() { newPlugin = nil }()
p, err := plugin.Open(path)
if err != nil {
return nil, err
}
newPlugin.Plugin = p
cache[path] = newPlugin
return newPlugin, nil
}
// Symbol is a pointer to a variable or function.
type Symbol = plugin.Symbol
// SetupFunc represents a setup function.
// If it returns non-nil teardown, the function will be called later.
type SetupFunc func(ctx *Context) (newCtx *Context, teardown func(*Context))
// Plugin represents a scenarigo plugin.
type Plugin interface {
Lookup(name string) (Symbol, error)
GetSetup() SetupFunc
GetSetupEachScenario() SetupFunc
}
// RegisterSetup registers a function to setup for plugin.
// Plugins must call this function in their init function if it registers the setup process.
func RegisterSetup(setup SetupFunc) {
if newPlugin == nil {
panic("RegisterSetup must be called in init()")
}
newPlugin.m.Lock()
defer newPlugin.m.Unlock()
newPlugin.setups = append(newPlugin.setups, setup)
}
// RegisterSetupEachScenario registers a function to setup for plugin.
// Plugins must call this function in their init function if it registers the setup process.
// The registered function will be called before each scenario.
func RegisterSetupEachScenario(setup SetupFunc) {
if newPlugin == nil {
panic("RegisterSetupEachScenario must be called in init()")
}
newPlugin.m.Lock()
defer newPlugin.m.Unlock()
newPlugin.setupsEachScenario = append(newPlugin.setupsEachScenario, setup)
}
type openedPlugin struct {
*plugin.Plugin
m sync.Mutex
setups []SetupFunc
setupsEachScenario []SetupFunc
}
// GetSetup implements Plugin interface.
func (p *openedPlugin) GetSetup() SetupFunc {
p.m.Lock()
defer p.m.Unlock()
return p.getSetup(p.setups)
}
// GetSetupEachScenario implements Plugin interface.
func (p *openedPlugin) GetSetupEachScenario() SetupFunc {
p.m.Lock()
defer p.m.Unlock()
return p.getSetup(p.setupsEachScenario)
}
func (p *openedPlugin) getSetup(setups []SetupFunc) SetupFunc {
if len(setups) == 0 {
return nil
}
if len(setups) == 1 {
return setups[0]
}
return func(ctx *Context) (*Context, func(*Context)) {
var teardowns []func(*Context)
for i, setup := range setups {
newCtx := ctx
ctx.Run(strconv.Itoa(i+1), func(ctx *Context) {
ctx, teardown := setup(ctx)
if ctx != nil {
newCtx = ctx
}
if teardown != nil {
teardowns = append(teardowns, teardown)
}
})
ctx = newCtx.WithReporter(ctx.Reporter())
}
if len(teardowns) == 0 {
return ctx, nil
}
if len(teardowns) == 1 {
return ctx, teardowns[0]
}
return ctx, func(ctx *Context) {
for i, teardown := range teardowns {
ctx.Run(strconv.Itoa(i+1), func(ctx *Context) {
teardown(ctx)
})
}
}
}
}
// ExtractByKey implements query.KeyExtractor interface.
func (p *openedPlugin) ExtractByKey(key string) (interface{}, bool) {
sym, err := p.Lookup(key)
if err != nil {
return nil, false
}
// If sym is a pointer to a variable, return the actual variable for convenience.
if v := reflect.ValueOf(sym); v.Kind() == reflect.Ptr {
return v.Elem().Interface(), true
}
return sym, true
}
|
dae40252784f58e066eb32eca937ade7673889bc
|
{
"blob_id": "dae40252784f58e066eb32eca937ade7673889bc",
"branch_name": "refs/heads/main",
"committer_date": "2023-07-27T03:58:10",
"content_id": "8b0f960f8e9339033f3762f1f9fe77399a917fd3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c2ecbd92fc39baf34926abcee4de46be9da6a324",
"extension": "go",
"filename": "plugin.go",
"fork_events_count": 19,
"gha_created_at": "2019-02-28T06:21:31",
"gha_event_created_at": "2023-09-14T11:19:21",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 173053663,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3860,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/plugin/plugin.go",
"provenance": "stack-edu-0018.json.gz:713945",
"repo_name": "zoncoen/scenarigo",
"revision_date": "2023-07-27T03:58:10",
"revision_id": "fb954a653905da70cc4d91bf1c284b0981fc8580",
"snapshot_id": "5ee080e6b130fec236503aa979f8f82fb4ed477f",
"src_encoding": "UTF-8",
"star_events_count": 231,
"url": "https://raw.githubusercontent.com/zoncoen/scenarigo/fb954a653905da70cc4d91bf1c284b0981fc8580/plugin/plugin.go",
"visit_date": "2023-08-24T01:07:34.882653",
"added": "2024-11-18T22:00:28.266084+00:00",
"created": "2023-07-27T03:58:10",
"int_score": 3,
"score": 2.796875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
from django.db import models
from authors.apps.profiles.models import Profile
from authors.apps.articles.models import Articles
class Readers(models.Model):
reader = models.ForeignKey(Profile,
related_name='read_by',
on_delete=models.CASCADE,
null=False, blank=False,)
article = models.ForeignKey(Articles,
on_delete=models.CASCADE,
null=False, blank=False,)
last_read = models.DateTimeField(auto_now=True)
class Meta:
app_label = 'read_stats'
def __str__(self):
"""Print out as title."""
return self.article.title
|
7cff02bf440b0f46980269bdc6a6f069e8f32c67
|
{
"blob_id": "7cff02bf440b0f46980269bdc6a6f069e8f32c67",
"branch_name": "refs/heads/develop",
"committer_date": "2019-02-01T08:51:07",
"content_id": "b291f9d775d17831a55058036932f060a6fa513c",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "97a5d3a6355c40e04ba27a40c674897c1fee7506",
"extension": "py",
"filename": "models.py",
"fork_events_count": 2,
"gha_created_at": "2018-11-12T13:15:04",
"gha_event_created_at": "2022-12-08T01:27:32",
"gha_language": "Python",
"gha_license_id": "BSD-3-Clause",
"github_id": 157216057,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 720,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/authors/apps/read_stats/models.py",
"provenance": "stack-edu-0059.json.gz:209687",
"repo_name": "andela/ah-jumanji",
"revision_date": "2019-02-01T08:51:07",
"revision_id": "a304718929936dd4a759d737fb3570d6cc25fb76",
"snapshot_id": "c3969240dafd71cc73a8690e926c2a383f6f600a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/andela/ah-jumanji/a304718929936dd4a759d737fb3570d6cc25fb76/authors/apps/read_stats/models.py",
"visit_date": "2022-12-11T13:46:36.614361",
"added": "2024-11-19T00:06:19.083015+00:00",
"created": "2019-02-01T08:51:07",
"int_score": 2,
"score": 2.140625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0077.json.gz"
}
|
import { CreateMethodImplementForMethodStruct } from './methods/method-implement-for';
import { TraitToClass } from '../../traits/functions/trait-to-class';
import { IMethodStruct } from '../method-struct-definition';
import { IMethod, IMethodConstructor, TMethodClassTypedTraitStruct } from './method-class-definition';
import { TTraitToClassConstructorWithVoidAllowed } from '../../traits/trait-types';
import { TGenericMethodStruct } from '../method-types';
import { CreateMethodIsImplementedByMethodStruct } from './methods/method-is-implemented-by';
import { MethodClassNew } from './method-class-new';
import { CreateMethodCallMethodStruct } from './methods/method-call';
import { TGenericFunction } from '../../../../types/misc-types';
import { CallFunction } from '../../derived-function/call-function';
import { CreateMethodDeriveMethodStruct } from './methods/method-derive';
import { CreateMethodEqualsMethodStruct } from './methods/method-equals';
import { CreateMethodIsDerivedFromMethodStruct } from './methods/method-is-derived-from';
const MethodClassTrait: TMethodClassTypedTraitStruct<TGenericMethodStruct> = {
methods: [
CreateMethodCallMethodStruct(),
CreateMethodDeriveMethodStruct(),
CreateMethodEqualsMethodStruct(),
CreateMethodImplementForMethodStruct(),
CreateMethodIsImplementedByMethodStruct(),
CreateMethodIsDerivedFromMethodStruct(),
],
};
const MethodClassTraitAsClass: TTraitToClassConstructorWithVoidAllowed<typeof MethodClassTrait, void> = CallFunction(TraitToClass, MethodClassTrait, []);
export const Method =
class Method<GPropertyKey extends PropertyKey, GFunction extends TGenericFunction> extends MethodClassTraitAsClass implements IMethod<GPropertyKey, GFunction> {
readonly value: GFunction;
readonly propertyKey: GPropertyKey;
readonly enumerable: boolean;
readonly configurable: boolean;
readonly writable: boolean;
constructor(options: IMethodStruct<GPropertyKey, GFunction>) {
super();
CallFunction(MethodClassNew, this, [options]);
}
} as IMethodConstructor;
|
d82b78c38d0ef64c6a91b1739d4ae611d220e0aa
|
{
"blob_id": "d82b78c38d0ef64c6a91b1739d4ae611d220e0aa",
"branch_name": "refs/heads/master",
"committer_date": "2020-10-18T15:07:04",
"content_id": "c26bc5baed18ab80c7be001b2f0c7496d2652c2b",
"detected_licenses": [
"MIT"
],
"directory_id": "4ba1341558a2f8972713ee4bcc7cb87f443b2cff",
"extension": "ts",
"filename": "method-class.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 254344905,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2087,
"license": "MIT",
"license_type": "permissive",
"path": "/src/core/traits/with-this-method/method/class/method-class.ts",
"provenance": "stack-edu-0075.json.gz:538757",
"repo_name": "lifaon74/class-factory",
"revision_date": "2020-10-18T15:07:04",
"revision_id": "7d3f4ee5ba26c059268b5152953aa7a79c4978b2",
"snapshot_id": "560eee396d7f791ae47d2a94500c5bbf03767705",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lifaon74/class-factory/7d3f4ee5ba26c059268b5152953aa7a79c4978b2/src/core/traits/with-this-method/method/class/method-class.ts",
"visit_date": "2021-06-10T19:24:59.508537",
"added": "2024-11-18T20:59:31.604258+00:00",
"created": "2020-10-18T15:07:04",
"int_score": 2,
"score": 2.421875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
/*
* Copyright 2017 Michael Mackenzie High
*
* 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.
*/
package com.mackenziehigh.sexpr;
import com.mackenziehigh.sexpr.annotations.After;
import com.mackenziehigh.sexpr.annotations.Before;
import com.mackenziehigh.sexpr.annotations.Condition;
import com.mackenziehigh.sexpr.annotations.Pass;
import com.mackenziehigh.sexpr.internal.schema.Schema;
import com.mackenziehigh.sexpr.internal.schema.SchemaParser;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
import org.junit.Test;
/**
* Unit Test.
*/
public final class SexprSchemaTest
{
private boolean parse (final String schema,
final String expression)
{
/**
* Remember, parse(*) adds an implicit pair of parentheses.
* Remove the extra parentheses for the sake of simplicity.
*/
final Sexpr tree = SList.parse(SexprSchemaTest.class.getName(), expression).asList().get(0);
/**
* Parse the schema.
*/
final Schema grammar = SchemaParser.parse(SexprSchemaTest.class.getName(), schema);
/**
* Attempt to match the symbolic-expression using the schema.
*/
final boolean result = grammar.match(tree);
return result;
}
/**
* Test: 20170703031359687941
*
* <p>
* Case: Special Predefined Rules
* </p>
*/
@Test
public void test20170703031359687941 ()
{
System.out.println("Test: 20170703031359687941");
assertTrue(parse(" (root = (ref $BOOLEAN))", "true"));
assertTrue(parse(" (root = (ref $BOOLEAN))", "false"));
assertFalse(parse("(root = (ref $BOOLEAN))", "XYZ"));
assertTrue(parse(" (root = (ref $BYTE))", "100"));
assertTrue(parse(" (root = (ref $BYTE))", "-100"));
assertFalse(parse("(root = (ref $BYTE))", "30.0"));
assertFalse(parse("(root = (ref $BYTE))", "XYZ"));
assertTrue(parse(" (root = (ref $SHORT))", "1000"));
assertTrue(parse(" (root = (ref $SHORT))", "-200"));
assertFalse(parse("(root = (ref $SHORT))", "30.0"));
assertFalse(parse("(root = (ref $SHORT))", "XYZ"));
assertTrue(parse(" (root = (ref $INT))", "1000"));
assertTrue(parse(" (root = (ref $INT))", "-200"));
assertFalse(parse("(root = (ref $INT))", "30.0"));
assertFalse(parse("(root = (ref $INT))", "XYZ"));
assertTrue(parse(" (root = (ref $LONG))", "1000"));
assertTrue(parse(" (root = (ref $LONG))", "-200"));
assertFalse(parse("(root = (ref $LONG))", "30.0"));
assertFalse(parse("(root = (ref $LONG))", "XYZ"));
}
/**
* Test: 20170703020824718850
*
* <p>
* Case: Constant Rules
* </p>
*/
@Test
public void test20170703020824718850 ()
{
System.out.println("Test: 20170703020824718850");
assertTrue(parse("(root = (keyword '123'))", "123"));
assertTrue(parse("(root = (keyword \"123\"))", "123"));
}
/**
* Test: 20170703020824718946
*
* <p>
* Case: Regular-Expression Rules
* </p>
*/
@Test
public void test20170703020824718946 ()
{
System.out.println("Test: 20170703020824718946");
assertTrue(parse("(root = (atom 'X[0-9]*Y'))", "XY"));
assertTrue(parse("(root = (atom 'X[0-9]*Y'))", "X1Y"));
assertTrue(parse("(root = (atom 'X[0-9]*Y'))", "X12Y"));
assertTrue(parse("(root = (atom 'X[0-9]*Y'))", "X123Y"));
assertFalse(parse("(root = (atom 'X[0-9]+Y'))", "XYZ"));
}
/**
* Test: 20170703020824719014
*
* <p>
* Case: And Rules
* </p>
*/
@Test
public void test20170703020824719014 ()
{
System.out.println("Test: 20170703020824719014");
assertTrue(parse("(root = (and (atom 'X[0-9]+.') (atom '.[0-9]+Y')))", "X123Y"));
assertFalse(parse("(root = (and (atom 'X[0-9]+.') (atom '.[0-9]+Y')))", "X123Z"));
}
/**
* Test: 20170703020824719042
*
* <p>
* Case: Or Rules
* </p>
*/
@Test
public void test20170703020824719042 ()
{
System.out.println("Test: 20170703020824719042");
assertTrue(parse("(root = (either (atom '12') (atom '34') (atom '56')))", "12"));
assertTrue(parse("(root = (either (atom '12') (atom '34') (atom '56')))", "34"));
assertTrue(parse("(root = (either (atom '12') (atom '34') (atom '56')))", "56"));
assertFalse(parse("(root = (either (atom '12') (atom '34') (atom '56')))", "78"));
}
/**
* Test: 20170703023207618848
*
* <p>
* Case: Not Rules
* </p>
*/
@Test
public void test20170703023207618848 ()
{
System.out.println("Test: 20170703023207618848");
final String schema = "(root = (and (atom '[0-9]') (not (atom '3')) (not (atom '5')) (not (atom '7'))))";
assertTrue(parse(schema, "0"));
assertTrue(parse(schema, "1"));
assertTrue(parse(schema, "2"));
assertFalse(parse(schema, "3"));
assertTrue(parse(schema, "4"));
assertFalse(parse(schema, "5"));
assertTrue(parse(schema, "6"));
assertFalse(parse(schema, "7"));
assertTrue(parse(schema, "8"));
assertTrue(parse(schema, "9"));
}
/**
* Test: 20170703022350691405
*
* <p>
* Case: Sequence Rules (Basic Functionality)
* </p>
*/
@Test
public void test20170703022350691405 ()
{
System.out.println("Test: 20170703022350691405");
assertTrue(parse("(root = (seq))", "()"));
assertTrue(parse("(root = (seq (atom 12)))", "(12)"));
assertTrue(parse("(root = (seq (atom 12) (atom 34)))", "(12 34)"));
assertTrue(parse("(root = (seq (atom 12) (atom 34) (atom 56)))", "(12 34 56)"));
assertFalse(parse("(root = (seq (atom 12) (atom 34)))", "(12 34 56)"));
}
/**
* Test: 20170703022350691495
*
* <p>
* Case: Sequence Rules (Zero-Or-One Modifiers)
* </p>
*/
@Test
public void test20170703022350691495 ()
{
System.out.println("Test: 20170703022350691495");
assertTrue(parse(" (root = (seq (atom X) (option (atom Y)) (atom Z)))", "(X Z)"));
assertTrue(parse(" (root = (seq (atom X) (option (atom Y)) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (option (atom Y)) (atom Z)))", "(X Y Y Z)"));
}
/**
* Test: 20170703022350691526
*
* <p>
* Case: Sequence Rules (Zero-Or-More Modifiers)
* </p>
*/
@Test
public void test20170703022350691526 ()
{
System.out.println("Test: 20170703022350691526");
assertTrue(parse(" (root = (seq (atom X) (star (atom Y)) (atom Z)))", "(X Z)"));
assertTrue(parse(" (root = (seq (atom X) (star (atom Y)) (atom Z)))", "(X Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (star (atom Y)) (atom Z)))", "(X Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (star (atom Y)) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (star (atom Y)) (atom Z)))", "(X M Z)"));
}
/**
* Test: 20170703022350691558
*
* <p>
* Case: Sequence Rules (One-Or-More Modifiers)
* </p>
*/
@Test
public void test20170703022350691558 ()
{
System.out.println("Test: 20170703022350691558");
assertFalse(parse("(root = (seq (atom X) (plus (atom Y)) (atom Z)))", "(X Z)"));
assertTrue(parse(" (root = (seq (atom X) (plus (atom Y)) (atom Z)))", "(X Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (plus (atom Y)) (atom Z)))", "(X Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (plus (atom Y)) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (plus (atom Y)) (atom Z)))", "(X M Z)"));
}
/**
* Test: 20170703022350691591
*
* <p>
* Case: Sequence Rules (Exact Modifiers)
* </p>
*/
@Test
public void test20170703022350691591 ()
{
System.out.println("Test: 20170703022350691591");
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 0 0) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 0 0) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 0 0) (atom Z)))", "(X Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 0 0) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 0 0) (atom Z)))", "(X M Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X M Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 2 2) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 2 2) (atom Z)))", "(X Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 2 2) (atom Z)))", "(X Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 2 2) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 2 2) (atom Z)))", "(X M Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 3) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 3) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 3) (atom Z)))", "(X Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 3) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 3) (atom Z)))", "(X M Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 4 4) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 4 4) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 4 4) (atom Z)))", "(X Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 4 4) (atom Z)))", "(X Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 4 4) (atom Z)))", "(X M Z)"));
}
/**
* Test: 20170703022350691619
*
* <p>
* Case: Sequence Rules (Min-Max Modifiers)
* </p>
*/
@Test
public void test20170703022350691619 ()
{
System.out.println("Test: 20170703022350691619");
/**
* Zero-width rule.
*/
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 1) (atom Z)))", "(X Y Y Z)"));
/**
* The match must stop at the maximum.
*/
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 1 2) (atom Z)))", "(X Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 1 2) (atom Z)))", "(X Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 1 2) (atom Z)))", "(X Y Y Y Z)"));
/**
* The minimum must be reached.
*/
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 4) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 4) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 4) (atom Z)))", "(X Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 4) (atom Z)))", "(X Y Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 4) (atom Z)))", "(X Y Y Y Y Z)"));
/**
* Wider range.
*/
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Y Y Z)"));
assertTrue(parse(" (root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Y Y Y Y Z)"));
assertFalse(parse("(root = (seq (atom X) (repeat (atom Y) 3 7) (atom Z)))", "(X Y Y Y Y Y Y Y Y Y Z)"));
}
/**
* Test: 20170703022350691646
*
* <p>
* Case: No Root Specified
* </p>
*/
@Test
public void test20170703022350691646 ()
{
System.out.println("Test: 20170703022350691646");
/**
* By default, the rule named 'root' will be treated as the root rule.
*/
assertTrue(parse("(root = (keyword @'X'))", "X"));
}
/**
* Test: 20170703022350691671
*
* <p>
* Case: Duplicate Rules
* </p>
*/
@Test (expected = IllegalStateException.class)
public void test20170703022350691671 ()
{
System.out.println("Test: 20170703022350691671");
parse("(root x) (x = (atom 'X')) (x = (atom 'Y'))", "(X)");
}
/**
* Test: 20170704163111209006
*
* <p>
* Case: Impossible Ranges in Sequence Rules
* </p>
*/
@Test (expected = IllegalStateException.class)
public void test20170704163111209006 ()
{
System.out.println("Test: 20170704163111209006");
parse("(root = (seq (repeat (atom X) 3 2)))", "X");
}
/**
* Test: 20170703022749118428
*
* <p>
* Case: Regular-Expression Rule - Invalid Regular-Expression
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170703022749118428 ()
{
System.out.println("Test: 20170703022749118428");
/**
* An opening-bracket indicates the start of a character-class.
*/
parse("(root = (atom '['))", "X");
}
/**
* Test: 20170711022745123106
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Define Predicate-Rule Condition using Sexpr Parameter.
* </p>
*/
@Test
public void test20170711022745123106 ()
{
System.out.println("Test: 20170711022745123106");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test (final Sexpr arg)
{
return arg.isAtom() && arg.asAtom().toString().equals("X");
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
final SList input1 = SList.parse("N/A", "A X Z");
final SList input2 = SList.parse("N/A", "A Y Z");
assertTrue(schema.match(input1));
assertFalse(schema.match(input2));
}
/**
* Test: 20170711022745123175
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Define Predicate-Rule Condition using SAtom Parameter.
* </p>
*/
@Test
public void test20170711022745123175 ()
{
System.out.println("Test: 20170711022745123175");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test (final SAtom arg)
{
return arg.asAtom().toString().equals("X");
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
final SList input1 = SList.parse("N/A", "A X Z");
final SList input2 = SList.parse("N/A", "A Y Z");
final SList input3 = SList.parse("N/A", "A (X) Z");
assertTrue(schema.match(input1));
assertFalse(schema.match(input2));
assertFalse(schema.match(input3));
}
/**
* Test: 20170711022745123201
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Define Predicate-Rule Condition using SList Parameter.
* </p>
*/
@Test
public void test20170711022745123201 ()
{
System.out.println("Test: 20170711022745123201");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test (final SList arg)
{
return arg.asList().toString().equals("(X)");
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
final SList input1 = SList.parse("N/A", "A X Z");
final SList input2 = SList.parse("N/A", "A Y Z");
final SList input3 = SList.parse("N/A", "A (X) Z");
final SList input4 = SList.parse("N/A", "A (Y) Z");
final SList input5 = SList.parse("N/A", "A () Z");
assertFalse(schema.match(input1));
assertFalse(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertFalse(schema.match(input5));
}
/**
* Test: 20170711022745123225
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Predicate-Rule Condition with Invalid Parameter Count.
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711022745123225 ()
{
System.out.println("Test: 20170711022745123225");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test ()
{
return false;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
}
/**
* Test: 20170711022745123247
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Predicate-Rule Condition with Invalid Parameter Type.
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711022745123247 ()
{
System.out.println("Test: 20170711022745123247");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test (final Object arg)
{
return false;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
}
/**
* Test: 20170711022745123269
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Predicate-Rule Condition with Invalid Return Type.
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711022745123269 ()
{
System.out.println("Test: 20170711022745123269");
final Object object = new Object()
{
@Condition ("TEST1")
public Object test (final SAtom atom)
{
return false;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
}
/**
* Test: 20170711022745123289
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Predicate-Rule Condition with Invalid Throws Clause.
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711022745123289 ()
{
System.out.println("Test: 20170711022745123289");
final Object object = new Object()
{
@Condition ("TEST1")
public boolean test (final SAtom atom)
throws Exception
{
return false;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (predicate TEST1) (atom Z)))")
.defineViaAnnotations(object)
.build();
}
/**
* Test: 20170711022745123310
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with Sexpr Parameter
* </p>
*/
@Test
public void test20170711022745123310 ()
{
System.out.println("Test: 20170711022745123310");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 (final Sexpr<?> atom)
{
list.add("P = " + atom);
}
@Pass ("PASS2")
@Before ("M")
public void execute2 (final Sexpr<?> atom)
{
list.add("Q = " + atom);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (either (atom X) (atom Y)))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A W Z");
final SList input2 = SList.parse("N/A", "A X Z");
final SList input3 = SList.parse("N/A", "A Y Z");
final SList input4 = SList.parse("N/A", "A Z Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = X", list.get(0));
assertEquals("Q = X", list.get(1));
assertEquals("P = Y", list.get(2));
assertEquals("Q = Y", list.get(3));
}
/**
* Test: 20170711022745123330
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with SAtom Parameter
* </p>
*/
@Test
public void test20170711022745123330 ()
{
System.out.println("Test: 20170711022745123330");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 (final SAtom atom)
{
list.add("P = " + atom);
}
@Pass ("PASS2")
@Before ("M")
public void execute2 (final SAtom atom)
{
list.add("Q = " + atom);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (either (atom X) (atom Y)))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A W Z");
final SList input2 = SList.parse("N/A", "A X Z");
final SList input3 = SList.parse("N/A", "A Y Z");
final SList input4 = SList.parse("N/A", "A Z Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = X", list.get(0));
assertEquals("Q = X", list.get(1));
assertEquals("P = Y", list.get(2));
assertEquals("Q = Y", list.get(3));
}
/**
* Test: 20170711022745123349
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with SList Parameter
* </p>
*/
@Test
public void test20170711022745123349 ()
{
System.out.println("Test: 20170711022745123349");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 (final SList node)
{
list.add("P = " + node);
}
@Pass ("PASS2")
@Before ("M")
public void execute2 (final SList node)
{
list.add("Q = " + node);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A (W) Z");
final SList input2 = SList.parse("N/A", "A (X) Z");
final SList input3 = SList.parse("N/A", "A (Y) Z");
final SList input4 = SList.parse("N/A", "A (Z) Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = (X)", list.get(0));
assertEquals("Q = (X)", list.get(1));
assertEquals("P = (Y)", list.get(2));
assertEquals("Q = (Y)", list.get(3));
}
/**
* Test: 20170711023511488273
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with Invalid Parameter Count
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488273 ()
{
System.out.println("Test: 20170711023511488273");
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 ()
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.build();
}
/**
* Test: 20170711023511488349
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with Invalid Parameter Type
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488349 ()
{
System.out.println("Test: 20170711023511488349");
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 (final Object node)
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.build();
}
/**
* Test: 20170711023511488378
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with Invalid Return Type
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488378 ()
{
System.out.println("Test: 20170711023511488378");
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public Object execute1 (final SList node)
{
return null;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.build();
}
/**
* Test: 20170711023511488405
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Before-Action with Invalid Throws Clause
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488405 ()
{
System.out.println("Test: 20170711023511488405");
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute1 (final SList node)
throws Exception
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.build();
}
/**
* Test: 20170711023511488430
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with Sexpr Parameter
* </p>
*/
@Test
public void test20170711023511488430 ()
{
System.out.println("Test: 20170711023511488430");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute1 (final Sexpr<?> atom)
{
list.add("P = " + atom);
}
@Pass ("PASS2")
@After ("M")
public void execute2 (final Sexpr<?> atom)
{
list.add("Q = " + atom);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (either (atom X) (atom Y)))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A W Z");
final SList input2 = SList.parse("N/A", "A X Z");
final SList input3 = SList.parse("N/A", "A Y Z");
final SList input4 = SList.parse("N/A", "A Z Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = X", list.get(0));
assertEquals("Q = X", list.get(1));
assertEquals("P = Y", list.get(2));
assertEquals("Q = Y", list.get(3));
}
/**
* Test: 20170711023511488453
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with SAtom Parameter
* </p>
*/
@Test
public void test20170711023511488453 ()
{
System.out.println("Test: 20170711023511488453");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute1 (final SAtom atom)
{
list.add("P = " + atom);
}
@Pass ("PASS2")
@After ("M")
public void execute2 (final SAtom atom)
{
list.add("Q = " + atom);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (either (atom X) (atom Y)))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A W Z");
final SList input2 = SList.parse("N/A", "A X Z");
final SList input3 = SList.parse("N/A", "A Y Z");
final SList input4 = SList.parse("N/A", "A Z Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = X", list.get(0));
assertEquals("Q = X", list.get(1));
assertEquals("P = Y", list.get(2));
assertEquals("Q = Y", list.get(3));
}
/**
* Test: 20170711023511488474
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with SList Parameter
* </p>
*/
@Test
public void test20170711023511488474 ()
{
System.out.println("Test: 20170711023511488474");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute1 (final SList node)
{
list.add("P = " + node);
}
@Pass ("PASS2")
@After ("M")
public void execute2 (final SList node)
{
list.add("Q = " + node);
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
final SList input1 = SList.parse("N/A", "A (W) Z");
final SList input2 = SList.parse("N/A", "A (X) Z");
final SList input3 = SList.parse("N/A", "A (Y) Z");
final SList input4 = SList.parse("N/A", "A (Z) Z");
assertFalse(schema.match(input1));
assertTrue(schema.match(input2));
assertTrue(schema.match(input3));
assertFalse(schema.match(input4));
assertEquals(4, list.size());
assertEquals("P = (X)", list.get(0));
assertEquals("Q = (X)", list.get(1));
assertEquals("P = (Y)", list.get(2));
assertEquals("Q = (Y)", list.get(3));
}
/**
* Test: 20170711023511488494
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with Invalid Parameter Count
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488494 ()
{
System.out.println("Test: 20170711023511488494");
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute ()
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
}
/**
* Test: 20170711023511488514
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with Invalid Parameter Type
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488514 ()
{
System.out.println("Test: 20170711023511488514");
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute (final Object node)
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
}
/**
* Test: 20170711023511488534
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with Invalid Return Type
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711023511488534 ()
{
System.out.println("Test: 20170711023511488534");
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public Object execute (final SList node)
{
return null;
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
}
/**
* Test: 20170711024605706433
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: After-Action with Invalid Throws Clause
* </p>
*/
@Test (expected = IllegalArgumentException.class)
public void test20170711024605706433 ()
{
System.out.println("Test: 20170711024605706433");
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute (final SList node)
throws Exception
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.build();
}
/**
* Test: 20170711024605706536
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: No Such Translation Pass for Before-Action
* </p>
*/
@Test (expected = IllegalStateException.class)
public void test20170711024605706536 ()
{
System.out.println("Test: 20170711024605706536");
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("M")
public void execute (final SList node)
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.build();
}
/**
* Test: 20170711024605706563
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: No Such Translation Pass for After-Action
* </p>
*/
@Test (expected = IllegalStateException.class)
public void test20170711024605706563 ()
{
System.out.println("Test: 20170711024605706563");
final Object object = new Object()
{
@Pass ("PASS1")
@After ("M")
public void execute (final SList node)
{
// Pass
}
};
SexprSchema.fromString("N/A", "(root = (seq (atom A) (ref M) (atom Z))) (M = (seq (either (atom X) (atom Y))))")
.defineViaAnnotations(object)
.build();
}
@Pass ("PASS1")
private static final class TestClass1
{
public final List<String> calls = new ArrayList<>();
@Pass ("PASS3") // Overrides PASS1 (above)
@Before ("A")
public void execute1 (final Sexpr<?> node)
{
calls.add("A = " + node.toString());
}
@Pass ("PASS2") // Overrides PASS1 (above)
@Before ("B")
public void execute2 (final Sexpr<?> node)
{
calls.add("B = " + node.toString());
}
@Before ("C")
public void execute3 (final Sexpr<?> node)
{
calls.add("C = " + node.toString());
}
};
/**
* Test: 20170711025550465323
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Overridden Translation Pass for Before-Action
* </p>
*/
@Test
public void test20170711025550465323 ()
{
System.out.println("Test: 20170711025550465323");
final TestClass1 object = new TestClass1();
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom X) (ref A) (ref B) (ref C) (atom X))) (A = (atom 13)) (B = (atom 17)) (C = (atom 19))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.pass("PASS3")
.build();
final SList input1 = SList.parse("N/A", "X 13 17 19 X");
assertTrue(schema.match(input1));
assertEquals(3, object.calls.size());
assertEquals("C = 19", object.calls.get(0));
assertEquals("B = 17", object.calls.get(1));
assertEquals("A = 13", object.calls.get(2));
}
@Pass ("PASS1")
private static final class TestClass2
{
public final List<String> calls = new ArrayList<>();
@Pass ("PASS3") // Overrides PASS1 (above)
@After ("A")
public void execute1 (final Sexpr<?> node)
{
calls.add("A = " + node.toString());
}
@Pass ("PASS2") // Overrides PASS1 (above)
@After ("B")
public void execute2 (final Sexpr<?> node)
{
calls.add("B = " + node.toString());
}
@After ("C")
public void execute3 (final Sexpr<?> node)
{
calls.add("C = " + node.toString());
}
};
/**
* Test: 20170711025550465390
*
* <p>
* Method: <code>defineViaAnnotations</code>
* </p>
*
* <p>
* Case: Overridden Translation Pass for After-Action
* </p>
*/
@Test
public void test20170711025550465390 ()
{
System.out.println("Test: 20170711025550465390");
final TestClass2 object = new TestClass2();
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root = (seq (atom X) (ref A) (ref B) (ref C) (atom X))) (A = (atom 13)) (B = (atom 17)) (C = (atom 19))")
.defineViaAnnotations(object)
.pass("PASS1")
.pass("PASS2")
.pass("PASS3")
.build();
final SList input1 = SList.parse("N/A", "X 13 17 19 X");
assertTrue(schema.match(input1));
assertEquals(3, object.calls.size());
assertEquals("C = 19", object.calls.get(0));
assertEquals("B = 17", object.calls.get(1));
assertEquals("A = 13", object.calls.get(2));
}
/**
* Test: 20180902012950783308
*
* <p>
* Case: Order Of Actions.
* </p>
*/
@Test
public void test20180902012950783308 ()
{
System.out.println("Test: 20180902012950783308");
final List<String> list = new ArrayList<>();
final Object object = new Object()
{
@Pass ("PASS1")
@Before ("A")
public void action1 (final Sexpr<?> node)
{
list.add("P1BA");
}
@Pass ("PASS1")
@After ("A")
public void action2 (final Sexpr<?> node)
{
list.add("P1AA");
}
@Pass ("PASS1")
@Before ("B")
public void action3 (final Sexpr<?> node)
{
list.add("P1BB");
}
@Pass ("PASS1")
@After ("B")
public void action4 (final Sexpr<?> node)
{
list.add("P1AB");
}
@Pass ("PASS1")
@Before ("C")
public void action5 (final Sexpr<?> node)
{
list.add("P1BC");
}
@Pass ("PASS1")
@After ("C")
public void action6 (final Sexpr<?> node)
{
list.add("P1AC");
}
@Pass ("PASS2")
@Before ("A")
public void action7 (final Sexpr<?> node)
{
list.add("P2BA");
}
@Pass ("PASS2")
@After ("A")
public void action8 (final Sexpr<?> node)
{
list.add("P2AA");
}
@Pass ("PASS2")
@Before ("B")
public void action9 (final Sexpr<?> node)
{
list.add("P2BB");
}
@Pass ("PASS2")
@After ("B")
public void action10 (final Sexpr<?> node)
{
list.add("P2AB");
}
@Pass ("PASS2")
@Before ("C")
public void action11 (final Sexpr<?> node)
{
list.add("P2BC");
}
@Pass ("PASS2")
@After ("C")
public void action12 (final Sexpr<?> node)
{
list.add("P2AC");
}
};
final SexprSchema schema = SexprSchema
.fromString("N/A", "(root A) (A = (seq (atom X) (ref B) (atom X))) (B = (seq (atom Y) (ref C) (atom Y))) (C = (atom Z))")
.pass("PASS1")
.pass("PASS2")
.defineViaAnnotations(object)
.build();
final SList input = SList.parse("N/A", "X (Y Z Y) X");
assertTrue(schema.match(input));
// Pass #1
assertEquals("P1BA", list.get(0));
assertEquals("P1BB", list.get(1));
assertEquals("P1BC", list.get(2));
assertEquals("P1AC", list.get(3));
assertEquals("P1AB", list.get(4));
assertEquals("P1AA", list.get(5));
// Pass #2
assertEquals("P2BA", list.get(6));
assertEquals("P2BB", list.get(7));
assertEquals("P2BC", list.get(8));
assertEquals("P2AC", list.get(9));
assertEquals("P2AB", list.get(10));
assertEquals("P2AA", list.get(11));
}
}
|
35f79a7590b0dcf619e0d7bcd1ef8019cb48dab3
|
{
"blob_id": "35f79a7590b0dcf619e0d7bcd1ef8019cb48dab3",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-04T03:30:29",
"content_id": "e63622c0fddf935a50b71bf1352fc06a5f02c6c5",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "a4db453998e94b24b7d04e5276d54c1bc62c4374",
"extension": "java",
"filename": "SexprSchemaTest.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 147273118,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 47455,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/test/com/mackenziehigh/sexpr/SexprSchemaTest.java",
"provenance": "stack-edu-0031.json.gz:310555",
"repo_name": "Mackenzie-High/Sexpr",
"revision_date": "2018-09-04T03:30:29",
"revision_id": "bc3078a3d1c28543030fcf18bdda8ef02d5498f9",
"snapshot_id": "1e0dc074685997f8ecd35a8212e236a91a11a20b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Mackenzie-High/Sexpr/bc3078a3d1c28543030fcf18bdda8ef02d5498f9/test/com/mackenziehigh/sexpr/SexprSchemaTest.java",
"visit_date": "2020-03-27T22:55:49.981080",
"added": "2024-11-18T23:10:08.999298+00:00",
"created": "2018-09-04T03:30:29",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0049.json.gz"
}
|
"use strict";
const request = require('request');
const express = require("express");
const bodyParser = require('body-parser');
module.exports = {
name: "command",
settings: {
port: process.env.PORT || 4003,
},
methods: {
initRoutes(app) {
app.get("/cmd", this.getCommands);
//parametri novih komandi ili promene prostojecih..:
app.post("/error", this.postError);
app.post("/notfixed", this.postNotFixed);
app.post("/brokenstation", this.postBrokenStation);
app.put("/full", this.putFULL);
app.put("/empty", this.putEMPTY);
},
getCommands(req, res)
{
// vraca listu komandi i parametara
const commands = [
{
"path": "/error",
"params" : ["stationId", "errorCODE"],
"paramTypes": ["string", "string"],
"description": "sensor reports that a bike is taken/returned from a station that has no bikes/docks (errorCODE: full/empty)"
},
{
"path": "/full",
"params": ["stationId"],
"paramsTypes": ["string"],
"description": "the station is full (cannot take anymore bikes)"
},
{
"path": "/empty",
"params": ["stationId"],
"paramsTypes": ["string"],
"description": "the station is empty (doesn't have any bikes left)"
}
]
return Promise.resolve()
.then(() => {
return res.send(commands);
})
.catch(this.handleErr(res));
},
postError(req, resp)
{
const payload = req.body;
console.log("GRESKA U COMMAND SERVISU");
request.post(process.env.DEVICE_URL + "turnoff", {
json: { stationId: payload.stationId }
}, (err, res, body) => {
if (err) {
return resp.send(err.message);
}
console.log(res.statusCode);
console.log(body);
return resp.send(body);
});
},
postNotFixed(req, resp)
{
const payload = req.body;
console.log("cmd");
request.post(process.env.DEVICE_URL + "notfixed", {
json: { "stationId": payload.stationId }
}, (err, res, body) => {
if (err) {
return resp.send(err.message);
}
console.log(res.statusCode);
console.log(body);
return resp.send(body)
});
},
postBrokenStation(req, resp)
{
const payload = req.body;
console.log("cmd");
request.post(process.env.DEVICE_URL + "turnoff", {
json: { stationId: payload.stationId }
}, (err, res, body) => {
if (err) {
return resp.send(err.message);
}
console.log(res.statusCode);
console.log(body);
return resp.send(body)
});
},
putFULL(req, resp)
{
const payload = req.body;
console.log("command: full");
request.put(process.env.DEVICE_URL + "full", {
json: {stationId: payload.stationId}
}, (err, res, body) => {
if (err) {
console.log(err);
return resp.status(err.code).send(err.message);
}
return resp.status(res.statusCode).send(body);
})
},
putEMPTY(req, resp)
{
// ONO STO DOBIJA OD DEVICE MANAGERA
const payload = req.body;
console.log("command: empty");
request.put(process.env.DEVICE_URL + "empty", {
json: {stationId: payload.stationId}
}, (err, res, body) => {
if (err) {
console.log(err);
return resp.status(err.code).send(err.message);
}
return resp.status(res.statusCode).send(body);
})
},
handleErr(res) {
return err => {
res.status(err.code || 500).send(err.message);
};
}
},
created() {
const app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.listen(this.settings.port);
this.initRoutes(app);
this.app = app;
}
};
|
1b3413f7777cfb0769290ab12d8152fb76035523
|
{
"blob_id": "1b3413f7777cfb0769290ab12d8152fb76035523",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-07T11:59:57",
"content_id": "a5e9ccf9595bab230ab5afb7951bbbff920d6876",
"detected_licenses": [
"ISC"
],
"directory_id": "5a393d011d2cb13ffddaa096dd7809a7bf813669",
"extension": "js",
"filename": "command.service.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 285661666,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 5002,
"license": "ISC",
"license_type": "permissive",
"path": "/services/command.service.js",
"provenance": "stack-edu-0038.json.gz:593575",
"repo_name": "marijadstankovic/SOA",
"revision_date": "2020-09-07T11:59:57",
"revision_id": "27d168c5fbb68614eb0b19eb4a48c969c9c9c35d",
"snapshot_id": "6d3117093c40a11efe2a3f1c87660648724ed4d2",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marijadstankovic/SOA/27d168c5fbb68614eb0b19eb4a48c969c9c9c35d/services/command.service.js",
"visit_date": "2022-12-11T16:36:19.365667",
"added": "2024-11-19T01:09:31.091732+00:00",
"created": "2020-09-07T11:59:57",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz"
}
|
<?php
namespace App\Http\Controllers\Adm\VisitTransfer;
use App\Http\Controllers\Adm\AdmController;
use App\Models\Statistic;
use App\Models\VisitTransfer\Application;
use App\Models\VisitTransfer\Reference;
use Cache;
class Dashboard extends AdmController
{
public function getDashboard()
{
$statisticsRaw = Cache::remember('visittransfer::statistics', 60, function () {
$statistics = [];
$statistics['applications_total'] = Application::all()->count();
$statistics['applications_open'] = Application::status(Application::$APPLICATION_IS_CONSIDERED_OPEN)->count();
$statistics['applications_closed'] = Application::status(Application::$APPLICATION_IS_CONSIDERED_CLOSED)->count();
$statistics['references_pending'] = Reference::statusIn([
Reference::STATUS_DRAFT,
Reference::STATUS_REQUESTED,
])->count();
$statistics['references_approval'] = Reference::status(Reference::STATUS_UNDER_REVIEW)->count();
$statistics['references_accepted'] = Reference::statusIn([
Reference::STATUS_ACCEPTED,
])->count();
return $statistics;
});
$statisticsGraph = Cache::remember('visittransfer::statistics.graph', 60 * 24, function () {
$statistics = [];
$statisticKeys = ['applications.total', 'applications.open', 'applications.closed', 'applications.new'];
$date = \Carbon\Carbon::parse('180 days ago');
while ($date->lt(\Carbon\Carbon::parse('today midnight'))) {
$counts = [];
foreach ($statisticKeys as $key) {
$counts[$key] = Statistic::getStatistic($date->toDateString(), 'visittransfer::'.$key);
}
$statistics[$date->toDateString()] = $counts;
$date->addDay();
}
return $statistics;
});
return $this->viewMake('visit-transfer.admin.dashboard')
->with('statisticsRaw', $statisticsRaw)
->with('statisticsGraph', $statisticsGraph);
}
}
|
24dcbc606bffe618661cdbeca56d123a386587a7
|
{
"blob_id": "24dcbc606bffe618661cdbeca56d123a386587a7",
"branch_name": "refs/heads/develop",
"committer_date": "2018-09-30T21:18:12",
"content_id": "a01650f6b9c9393f11ca42f00b518a4741d90252",
"detected_licenses": [],
"directory_id": "1e69cde34efda71d7c8f7a035a0a05cefbfd087b",
"extension": "php",
"filename": "Dashboard.php",
"fork_events_count": 0,
"gha_created_at": "2018-08-18T18:50:53",
"gha_event_created_at": "2018-09-04T13:54:13",
"gha_language": "HTML",
"gha_license_id": "MIT",
"github_id": 145244883,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2157,
"license": "",
"license_type": "permissive",
"path": "/app/Http/Controllers/Adm/VisitTransfer/Dashboard.php",
"provenance": "stack-edu-0052.json.gz:753649",
"repo_name": "NickMarinov/core",
"revision_date": "2018-09-30T21:18:12",
"revision_id": "21004c20569b231983f66a10461106fd61e8c363",
"snapshot_id": "035f738946d6b0b7c448808652d04cb8976026a8",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/NickMarinov/core/21004c20569b231983f66a10461106fd61e8c363/app/Http/Controllers/Adm/VisitTransfer/Dashboard.php",
"visit_date": "2020-03-26T19:01:50.762198",
"added": "2024-11-19T03:09:50.918170+00:00",
"created": "2018-09-30T21:18:12",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0070.json.gz"
}
|
---
title: Taken for Granted
date: 06/05/2023
---
#### inTro
**Read This Week’s Passage: Revelation 4:11**
**Taken for Granted**
It’s easy to take things for granted, particularly things we have always known or experienced. How easy, for instance, for young children to take their parents for granted, whom they have known all their short lives? How easy for us, too, to take for granted the sun, the sky, the air, and the ground beneath our feet.
However, have you ever stopped to think just how much we take existence itself for granted? How often do we stop and ask the famous philosophical question “Why is there something instead of nothing?”
Why does our universe and all the majesty and grandeur and astonishing things in it exist to begin with? According to the latest scientific theory (they tend to change), our universe once did not exist. In other words, ours is a contingent existence; it’s a miracle that we are here at all. And despite all sorts of myths about the universe arising from absolutely nothing or from some kind of mathematical equation, our universe exists because God, the Creator, has made it and everything in it.
#### inScribe
Write out Revelation 4:11 from the translation of your choice. You may also rewrite the passage in your own words, or outline or mind-map it.
` `
|
cfd3fdae6b8f3838e65abf6121d8d1cdb1932a3b
|
{
"blob_id": "cfd3fdae6b8f3838e65abf6121d8d1cdb1932a3b",
"branch_name": "refs/heads/stage",
"committer_date": "2023-08-22T16:05:42",
"content_id": "8d4274cbf7ee14e56be203b0325cca3d57644952",
"detected_licenses": [
"MIT"
],
"directory_id": "a6f75bcfabb20269d17db81880ef60ba404732b3",
"extension": "md",
"filename": "01.md",
"fork_events_count": 129,
"gha_created_at": "2016-01-06T00:14:24",
"gha_event_created_at": "2023-09-14T15:21:45",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 49100744,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1325,
"license": "MIT",
"license_type": "permissive",
"path": "/src/en/2023-02-cq/07/01.md",
"provenance": "stack-edu-markdown-0012.json.gz:224619",
"repo_name": "Adventech/sabbath-school-lessons",
"revision_date": "2023-08-22T16:05:42",
"revision_id": "b5a21c399cb257e62f0b1e0fa74b00b250b688d1",
"snapshot_id": "6454cc7c10be145db8904e3ef39b9be1a9728613",
"src_encoding": "UTF-8",
"star_events_count": 88,
"url": "https://raw.githubusercontent.com/Adventech/sabbath-school-lessons/b5a21c399cb257e62f0b1e0fa74b00b250b688d1/src/en/2023-02-cq/07/01.md",
"visit_date": "2023-08-22T19:22:02.497580",
"added": "2024-11-19T00:04:14.392322+00:00",
"created": "2023-08-22T16:05:42",
"int_score": 3,
"score": 2.921875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz"
}
|
package at.ameise.moodtracker.backend.models;
import com.google.api.server.spi.config.AnnotationBoolean;
import com.google.api.server.spi.config.ApiResourceProperty;
import com.google.appengine.repackaged.org.joda.time.DateTime;
import com.googlecode.objectify.Ref;
import com.googlecode.objectify.annotation.Entity;
import com.googlecode.objectify.annotation.Id;
import com.googlecode.objectify.annotation.Index;
import com.googlecode.objectify.annotation.Parent;
import javax.servlet.http.HttpServletRequest;
/**
* Representation of a certain mood by a certain user at a certain point in time.
*
* Created by Mario Gastegger <mario DOT gastegger AT gmail DOT com> on 28.11.15.
*/
@Entity
public class Mood {
@Id
private Long key;
@Parent @Index
private Ref<UserAccount> userAccount;
@Index
private float mood;
@Index
private long timestampMs;
@Index
private String scope;
@Index
private long syncTimestampNs;
public long getSyncTimestampNs() {
return syncTimestampNs;
}
public void setSyncTimestampNs(long syncTimestamp) {
this.syncTimestampNs = syncTimestamp;
}
public String getScope() {
return scope;
}
public void setScope(String scope) {
this.scope = scope;
}
public float getMood() {
return mood;
}
public void setMood(float mood) {
this.mood = mood;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public Ref<UserAccount> getUserAccount() {
return userAccount;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public void setUserAccount(Ref<UserAccount> userAccount) {
this.userAccount = userAccount;
}
public Long getKey() {
return key;
}
public void setKey(Long key) {
this.key = key;
}
public final long getTimestamp() {
return this.timestampMs;
}
@ApiResourceProperty(ignored = AnnotationBoolean.TRUE)
public final DateTime getDateTime() {
return new DateTime(this.timestampMs);
}
public final void setTimestamp(final long timestampMs) {
this.timestampMs = timestampMs;
}
@Override
public String toString() {
return "Mood{" +
"key=" + key +
", userAccount=" + userAccount +
", mood=" + mood +
", timestampMs=" + timestampMs +
", scope='" + scope + '\'' +
", syncTimestampNs=" + syncTimestampNs +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mood mood1 = (Mood) o;
if (Float.compare(mood1.mood, mood) != 0) return false;
if (timestampMs != mood1.timestampMs) return false;
if (key != null ? !key.equals(mood1.key) : mood1.key != null) return false;
if (userAccount != null ? !userAccount.equals(mood1.userAccount) : mood1.userAccount != null)
return false;
return !(scope != null ? !scope.equals(mood1.scope) : mood1.scope != null);
}
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (userAccount != null ? userAccount.hashCode() : 0);
result = 31 * result + (mood != +0.0f ? Float.floatToIntBits(mood) : 0);
result = 31 * result + (int) (timestampMs ^ (timestampMs >>> 32));
result = 31 * result + (scope != null ? scope.hashCode() : 0);
return result;
}
public static Mood getFrom(HttpServletRequest request) {
Mood mood = new Mood();
Float moodValue = Float.valueOf(null/*request.getParameter("mood")*/);
Long timestamp = Long.valueOf(request.getParameter("timestampMs"));
String scope = request.getParameter("scope");
mood.setTimestamp(timestamp);
mood.setScope(scope);
return mood;
}
}
|
987d4ec89d61d95fc4e934e21f3243a5dd961af8
|
{
"blob_id": "987d4ec89d61d95fc4e934e21f3243a5dd961af8",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-30T08:44:06",
"content_id": "7d5b5bf695382c96458db9f0b0245f651dcbd94b",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "5fa1ead79d5cde3e9bab6887991da38860d5372a",
"extension": "java",
"filename": "Mood.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 30795023,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3992,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/MoodTracker/backend/src/main/java/at/ameise/moodtracker/backend/models/Mood.java",
"provenance": "stack-edu-0028.json.gz:738325",
"repo_name": "gwario/moodtracker",
"revision_date": "2017-01-30T08:44:06",
"revision_id": "9900a4e58c091afbd6b709ca475efd7df206822a",
"snapshot_id": "04609817dba49d5c456aa2d576999348751347aa",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/gwario/moodtracker/9900a4e58c091afbd6b709ca475efd7df206822a/MoodTracker/backend/src/main/java/at/ameise/moodtracker/backend/models/Mood.java",
"visit_date": "2020-04-06T06:50:53.141061",
"added": "2024-11-18T23:05:34.280263+00:00",
"created": "2017-01-30T08:44:06",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
## PseudoStruct
Originally published: 2012-11-25 03:43:05
Last updated: 2012-11-25 03:43:06
Author: Matthew Zipay
This is a recipe for a Python "data object." It is similar in function to namedtuple (http://code.activestate.com/recipes/500261/) and recordtype (http://code.activestate.com/recipes/576555-records/) in that it is a simple container for data, but is designed to meet three specific goals:
1. Easy to subclass data objects.
2. Get/set speed comparable to a simple class.
3. Minimal memory consumption per instance.
|
00e8429a6cc161553c9f0c70201d9bb0e13d4673
|
{
"blob_id": "00e8429a6cc161553c9f0c70201d9bb0e13d4673",
"branch_name": "refs/heads/master",
"committer_date": "2021-02-24T15:39:59",
"content_id": "1485e5a80d83d9f9098e71b593d81d63046853a5",
"detected_licenses": [
"MIT"
],
"directory_id": "50008b3b7fb7e14f793e92f5b27bf302112a3cb4",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": "2021-02-24T11:31:15",
"gha_event_created_at": "2021-02-24T15:40:00",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 341878663,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 541,
"license": "MIT",
"license_type": "permissive",
"path": "/recipes/Python/578349_PseudoStruct/README.md",
"provenance": "stack-edu-markdown-0003.json.gz:171475",
"repo_name": "betty29/code-1",
"revision_date": "2021-02-24T15:39:59",
"revision_id": "d097ca0ad6a6aee2180d32dce6a3322621f655fd",
"snapshot_id": "db56807e19ac9cfe711b41d475a322c168cfdca6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/betty29/code-1/d097ca0ad6a6aee2180d32dce6a3322621f655fd/recipes/Python/578349_PseudoStruct/README.md",
"visit_date": "2023-03-14T08:15:47.492844",
"added": "2024-11-18T22:55:53.014760+00:00",
"created": "2021-02-24T15:39:59",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0003.json.gz"
}
|
// The MIT License (MIT)
//
// Copyright (c) 2014-2017 Darrell Wright
//
// 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.
#include <boost/asio/error.hpp>
#include <memory>
#include <utility>
#include <vector>
#include <daw/daw_range_algorithm.h>
#include <daw/daw_string_view.h>
#include "base_event_emitter.h"
namespace daw {
namespace nodepp {
namespace base {
namespace impl {
EventEmitterImpl::EventEmitterImpl( size_t max_listeners )
: m_listeners{std::make_shared<listeners_t>( )}
, m_max_listeners{max_listeners}
, m_emit_depth{std::make_shared<std::atomic_int_least8_t>( 0 )}
, m_allow_cb_without_params{true} {}
EventEmitterImpl::listeners_t &EventEmitterImpl::listeners( ) {
return *m_listeners;
}
bool EventEmitterImpl::operator==( EventEmitterImpl const &rhs ) const noexcept {
return this == &rhs; // All we need is a pointer comparison
}
bool EventEmitterImpl::operator!=( EventEmitterImpl const &rhs ) const noexcept {
return this != &rhs;
}
bool EventEmitterImpl::at_max_listeners( daw::string_view event ) {
auto result = 0 != m_max_listeners;
result &= listeners( )[event.to_string( )].size( ) >= m_max_listeners;
return result;
}
void EventEmitterImpl::remove_listener( daw::string_view event, callback_id_t id ) {
daw::algorithm::erase_remove_if( listeners( )[event.to_string( )],
[&]( std::pair<bool, Callback> const &item ) {
if( item.second.id( ) == id ) {
// TODO: verify if this needs to be outside loop
emit_listener_removed( event, item.second );
return true;
}
return false;
} );
}
void EventEmitterImpl::remove_listener( daw::string_view event, Callback listener ) {
return remove_listener( event, listener.id( ) );
}
void EventEmitterImpl::remove_all_listeners( ) {
listeners( ).clear( );
}
void EventEmitterImpl::remove_all_listeners( daw::string_view event ) {
listeners( )[event.to_string( )].clear( );
}
void EventEmitterImpl::set_max_listeners( size_t max_listeners ) {
m_max_listeners = max_listeners;
}
EventEmitterImpl::listener_list_t EventEmitterImpl::listeners( daw::string_view event ) {
return listeners( )[event.to_string( )];
}
size_t EventEmitterImpl::listener_count( daw::string_view event ) {
return listeners( event ).size( );
}
void EventEmitterImpl::emit_listener_added( daw::string_view event, Callback listener ) {
emit( "listener_added", event, std::move( listener ) );
}
void EventEmitterImpl::emit_listener_removed( daw::string_view event, Callback listener ) {
emit( "listener_removed", event, std::move( listener ) );
}
EventEmitterImpl::~EventEmitterImpl( ) = default;
EventEmitter EventEmitterImpl::create( size_t max_listeners ) noexcept {
try {
auto result = new EventEmitterImpl{max_listeners};
return EventEmitter{result};
} catch( ... ) { return EventEmitter{nullptr}; }
}
} // namespace impl
EventEmitter create_event_emitter( size_t max_listeners ) noexcept {
return impl::EventEmitterImpl::create( max_listeners );
}
} // namespace base
} // namespace nodepp
} // namespace daw
|
a4b876d0b0dc5c8f3a6248f6512daef79c0aef61
|
{
"blob_id": "a4b876d0b0dc5c8f3a6248f6512daef79c0aef61",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-20T16:22:16",
"content_id": "5bc1334799eca6e754ddf4cad40a0883a44b627f",
"detected_licenses": [
"MIT"
],
"directory_id": "7d1ff6055c2b1a1de9aa1536f496f3ded5810f92",
"extension": "cpp",
"filename": "base_event_emitter.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4579,
"license": "MIT",
"license_type": "permissive",
"path": "/src/base_event_emitter.cpp",
"provenance": "stack-edu-0002.json.gz:132898",
"repo_name": "skyformat99/lib_nodepp",
"revision_date": "2017-08-20T16:22:16",
"revision_id": "f19152c9713392b6e33e634dd4f6328eec484ed0",
"snapshot_id": "aae2b825f0c90dc24859b17d02ed8f1a145a5505",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skyformat99/lib_nodepp/f19152c9713392b6e33e634dd4f6328eec484ed0/src/base_event_emitter.cpp",
"visit_date": "2021-06-21T16:07:48.808342",
"added": "2024-11-18T23:06:43.544312+00:00",
"created": "2017-08-20T16:22:16",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
/*
By- Krish Jani (KrishJani)
Question: Given an array that is sorted such that some
elements are moved to either of the adjacent positions,
i.e., A[i] may be present at A[i+1] or A[i-1]. Write an
efficient function to search an element in this array.
Basically, the element A[i] can only be swapped with
either A[i+1] or A[i-1].
Approach: Compare the key with middle 3 elements, if
present then return the index. If not present, then
compare the key with middle element to decide whether
to go in left half or right half. Comparing with middle
element is enough as all the elements after mid+2 must be
greater than element mid and all elements before mid-2 must
be smaller than mid element.
*/
import java.util.*;
class HacktoberFest
{
int binarySearch(int A[], int l, int r, int x)
{
if (r >= l)
{
int mid = l + (r - l) / 2;
if (A[mid] == x)
return mid;
if (mid > l && A[mid - 1] == x)
return (mid - 1);
if (mid < r && A[mid + 1] == x)
return (mid + 1);
if (A[mid] > x)
return binarySearch(A);
return binarySearch(A, mid + 2, r, x);
}
return -1;
}
public static void main(String args[])
{
HacktoberFest ob = new HacktoberFest();
int A[] = {31, 21, 101, 41, 401};
int n = arr.length;
int x = 4;
int result = ob.binarySearch(arr, 0, n - 1, x);
if(result == -1)
System.out.println("Element not present");
else
System.out.println("Element present at index " +
result);
}
}
|
1d2c2bcf817270e8a34199ae58db60b521f7d267
|
{
"blob_id": "1d2c2bcf817270e8a34199ae58db60b521f7d267",
"branch_name": "refs/heads/main",
"committer_date": "2023-08-21T14:06:52",
"content_id": "7d0956febfd82c78d3a7ec36e563fb55827137de",
"detected_licenses": [
"MIT"
],
"directory_id": "a39d0684a46ea9eee9dcf36a21c240ab765638b5",
"extension": "java",
"filename": "AlmostSortedArray.java",
"fork_events_count": 0,
"gha_created_at": "2021-10-04T10:47:18",
"gha_event_created_at": "2021-10-04T10:47:18",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 413380202,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1715,
"license": "MIT",
"license_type": "permissive",
"path": "/Array/Java/AlmostSortedArray.java",
"provenance": "stack-edu-0025.json.gz:518139",
"repo_name": "malvika-sinha/DSA-Questions",
"revision_date": "2023-08-21T14:06:52",
"revision_id": "fa5b1105a6bede84068c12a24bd2fbbfc614f8e7",
"snapshot_id": "c4ee4c888820845b1072bef849725a93b02b512a",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/malvika-sinha/DSA-Questions/fa5b1105a6bede84068c12a24bd2fbbfc614f8e7/Array/Java/AlmostSortedArray.java",
"visit_date": "2023-08-31T00:30:23.795097",
"added": "2024-11-19T01:30:58.005894+00:00",
"created": "2023-08-21T14:06:52",
"int_score": 4,
"score": 3.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz"
}
|
using System.Linq;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Attributes;
using DSharpPlus.Entities;
using Silk.Core.Database.Models;
using Silk.Core.Tools;
using Silk.Core.Utilities;
using SilkBot.Extensions;
namespace Silk.Core.Commands.Moderation
{
[Category(Categories.Mod)]
public class UnbanCommand : BaseCommandModule
{
private readonly TimedEventService _eventService;
public UnbanCommand(TimedEventService eventService)
{
_eventService = eventService;
}
[Command("unban")]
[RequireFlag(UserFlag.Staff)]
public async Task UnBan(CommandContext ctx, DiscordUser user, [RemainingText] string reason = "No reason given.")
{
if (!ctx.Member.HasPermission(Permissions.BanMembers))
{
await ctx.RespondAsync("[You] Can't ban, can't unban. Sorry.").ConfigureAwait(false);
return;
}
if ((await ctx.Guild.GetBansAsync()).Select(b => b.User.Id).Contains(user.Id))
{
await user.UnbanAsync(ctx.Guild, reason);
DiscordEmbedBuilder embed =
new DiscordEmbedBuilder(EmbedHelper.CreateEmbed(ctx, "",
$"Unbanned {user.Username}#{user.Discriminator} `({user.Id})`! ")).AddField("Reason:", reason);
var infraction =
(TimedInfraction) _eventService.Events.FirstOrDefault(e => ((TimedInfraction) e).Id == user.Id);
if (infraction is not null) _eventService.Events.TryRemove(infraction);
await ctx.RespondAsync(embed: embed);
}
else
{
DiscordEmbedBuilder embed =
new DiscordEmbedBuilder(EmbedHelper.CreateEmbed(ctx, "", $"{user.Mention} is not banned!"))
.WithColor(new DiscordColor("#d11515"));
await ctx.RespondAsync(embed: embed);
}
}
}
}
|
8ccf60b4ed605135b85844709913cf6672d193ad
|
{
"blob_id": "8ccf60b4ed605135b85844709913cf6672d193ad",
"branch_name": "refs/heads/development",
"committer_date": "2021-01-03T10:44:32",
"content_id": "fbcb0be79361648d8c4621a7a95bd43b3fc26686",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "72fecb3372ebc770197bbe0e3e640aa27c39cd4d",
"extension": "cs",
"filename": "UnbanCommand.cs",
"fork_events_count": 1,
"gha_created_at": "2020-12-25T10:16:56",
"gha_event_created_at": "2021-01-05T10:01:38",
"gha_language": "C#",
"gha_license_id": "Apache-2.0",
"github_id": 324338943,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 2069,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Silk.Core/Commands/Moderation/UnbanCommand.cs",
"provenance": "stack-edu-0009.json.gz:793767",
"repo_name": "TheodoreSnoozevelt/Silk",
"revision_date": "2021-01-03T10:44:32",
"revision_id": "5295d115998be060bda75deade3ea33e3cf05d45",
"snapshot_id": "e39b4ad248d909ec534cc73d835d2c3f7c021a78",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TheodoreSnoozevelt/Silk/5295d115998be060bda75deade3ea33e3cf05d45/Silk.Core/Commands/Moderation/UnbanCommand.cs",
"visit_date": "2023-02-11T02:07:30.518528",
"added": "2024-11-19T02:26:05.273694+00:00",
"created": "2021-01-03T10:44:32",
"int_score": 2,
"score": 2.484375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0027.json.gz"
}
|
# The traditions of Halloween are rooted in Ireland’s Ancient East
Published at: **2019-11-06T12:00:39+00:00**
Author: **Paula Worthington**
Original: [Calgary Herald](https://calgaryherald.com/travel/ski-snowboard/the-traditions-of-halloween-are-rooted-in-irelands-ancient-east)
Animal mask in hand, I could hear the music of the procession get closer, and I eagerly waited with hundreds of others gathered on the historic streets of the town of Trim. Lanterns began to sway as people of all ages parted to make room for the mythical creature Puca, who was leading the procession. With a piercing animal skull face and long black hair, you certainly wouldn’t want to be in her way.
Staring solemnly ahead, Puca made her way past me with a gaggle of creatures bobbing and weaving throughout the crowd. Safely behind her, I stepped off the curb and joined the procession. The mood wasn’t the dark or spooky feeling that we’ve come to associate with modern Halloween, rather one of celebration. Walking slowly to the beat of the music, I made my way along with the ghouls and ghosts towards Trim Castle, and the start of Samhain.
The Puca Festival celebrates Samhain, the ancient roots of Halloween. (Photo: Paula Worthington)
Do you love Halloween? You have the Irish to thank for that.
As most of North America tidies up tiny candy wrappers and lays carved pumpkins to rest in the compost, few consider the ancient roots of its traditions.
Long before echoes of “Trick or Treat”, playful costumes, pumpkins and Hollywood horror flicks, Ireland’s Ancient Celts celebrated the original Halloween.
The Puca Festival celebrates Samhain, the ancient roots of Halloween. (Photo: Paula Worthington)
Samhain (pronounced sow-win), meaning “summer’s end”, was first celebrated more than 2,000 years ago, and marked the end of the harvest season. As the midway point between the fall equinox and winter solstice, it was a time for the Celts to feast on the fruits of their labour as they prepared for the darker days of winter.
Trim Castle is the largest Norman castle in Ireland. (Photo: Paula Worthington)
It also marked the start of a new year (November 1), and it was believed that the end of the year was a time when the veil between the worlds of the living and the dead thinned. Centuries later, we call it Halloween, but its roots are firmly planted here.
If you really want to learn about the history of Ireland firsthand, head north of Dublin to the Ancient East region in County Meath.
Older than the Egyptian Pyramids
At Brύ na Bόinne, meaning “palace” of the Boyne, you’ll find the massive Neolithic mounds of Newgrange, Knowth and Dowth, dating back some 5,000 years, making them older than Stonehenge and the Egyptian pyramids. Beyond their impressive size (Knowth is 95 metres wide), the mounds are much more than what first meets the eye.
The mysterious mounds at Brύ na Bόinne. (Photo: Paula Worthington)
They house carefully carved passage tombs, Neolithic art and, at Newgrange, the entire passageway is mysteriously illuminated from the rays of the sun on the winter solstice.
The reasons why these mounds were created poses more questions than answers about the past. They are undoubtedly sacred and were of great importance to the Neolithic people. Today, it’s a UNESCO World Heritage Site and gives modern-day visitors a chance to contemplate the mystery of our collective past.
Megalithic art at Brύ na Bόinne. (Photo: Paula Worthington)
The Birthplace of Halloween
The area surrounding ancient Brύ na Bόinne is also steeped in powerful history. The nearby Hill of Tara was once the meeting place of the high kings of Ireland, while it is on the Hill of Slane where it is believed that St. Patrick lit the first paschal fire in his quest to bring Christianity to Ireland. The Hill of Ward or Tlachtga was where the Samhain fires were traditionally lit by the druids, from which all fires throughout Ireland were rekindled for a new year. Today, the Hill of Ward is still an important gathering place at Samhain where some of those traditions and fires are recreated.
A Celtic cross in the town of Kells. (Photo: Paula Worthington)
The surrounding towns of Athboy, Trim and Drogheda are perfectly situated to celebrate the traditions of Samhain, which culminated in the first-ever Puca Festival, held Oct. 31 to Nov. 2.
Modern-day Meets Tradition at the Puca Festival
As our procession made its way through the curved, narrow streets of Trim, more people joined the snaking parade. In the background, Trim castle was illuminated with massive projections, its old stone walls coming to life with light and movement. The music grew louder, and the procession itself turned into a street party scene. Just like the connections between the living and the dead, Samhain is as much about the light as the dark.
The Puca Festival celebrates Samhain, the ancient roots of Halloween. (Photo: Paula Worthington)
Trim, with its fortress-like 12th Century castle (which was used in key scenes in Braveheart) set the scene for the kickoff of the Puca Festival.
Puca, the namesake of the Ancient East’s Halloween Festival, is known as a shapeshifter and spirit, with the power to alter the fortunes of all who cross her path – whether they be good or bad.
It’s believed that during ancient Samhain, if people needed to leave their dwellings after dark, they would don a costume to not be recognized by lingering spirits roaming among the living. Some left food and wine for the spirits, laying the roots for modern-day “trick or treating”.
These types of traditions continued to evolve over the centuries, eventually coming to Canada and the U.S. with the mass immigration of the Irish in the 19th century, helping to form our modern-day Halloween traditions.
Trim Castle is aglow during the Puca Festival. (Photo: Paula Worthington)
The History of Ireland Flows through the Boyne
Oscar Wilde’s father William once said of the River Boyne that “The history of Ireland might be written in tracing its banks.” The quiet river meanders past many of the area’s ancient sites, and it bore witness to the famous Battle of the Boyne in 1690. Today, visitors can paddle sections of the Boyne in traditional currachs, which were also used in the filming of Game of Thrones in Ireland.
A traditional currach along the River Boyne. (Photo: Paula Worthington)
Slane Castle also sits on the River Boyne and was popularized in the 1980s as a venue for large-scale rock concerts from the likes of U2, Bruce Springsteen, Thin Lizzy and more. Despite suffering a devastating fire in the 1990s, Slane has since been re-built and was aglow for a Puca Festival feast, sharing tales of ancient Samhain and driving away spirits with lively music and a taste of its latest local treasure, Slane whiskey.
Slane Castle celebrates Samhain with a feast and entertainment. (Photo: Paula Worthington)
A New Year Dawns
While the veil between the living and the dead is once again lowered as Samhain ends, the mystery and folklore of Ireland’s Ancient East is evident all year long. Castles, abbeys, towers and churches that span nearly every century from the past 2,000 years provide an incredible backdrop to get immersed in Ireland’s stories, myths and folklore. While Puca may choose to stay in the shadows when you visit, the celebratory spirit of Samhain lives on in Ireland’s Ancient East.
—
For more information about Puca Festival and the region, visit www.pucafestival.com and www.irelandsancienteast.com.
|
2b78f7cb87ae015da8afa740d28a6b112e51f569
|
{
"blob_id": "2b78f7cb87ae015da8afa740d28a6b112e51f569",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-17T05:07:58",
"content_id": "9790a533c2d05904468e8620271c467d7869eb24",
"detected_licenses": [
"Unlicense"
],
"directory_id": "3552a8ca26e8a9ff76c152189d65cb49586fdc04",
"extension": "md",
"filename": "git-1003909011522578155.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 7859,
"license": "Unlicense",
"license_type": "permissive",
"path": "/DATA_MARKDOWN/git-1003909011522578155.md",
"provenance": "stack-edu-markdown-0010.json.gz:170866",
"repo_name": "dsadlollioygjmzvcxv/tdc-exported",
"revision_date": "2019-11-17T05:07:58",
"revision_id": "48ea3f20419157cf402bf9f9d16733351757255f",
"snapshot_id": "02f0add356d739b64850315294172ecaa088af80",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dsadlollioygjmzvcxv/tdc-exported/48ea3f20419157cf402bf9f9d16733351757255f/DATA_MARKDOWN/git-1003909011522578155.md",
"visit_date": "2022-04-08T05:00:30.228770",
"added": "2024-11-18T23:55:23.599562+00:00",
"created": "2019-11-17T05:07:58",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
// (c) Copyright Cory Plotts.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.
using System.Windows;
using System.Windows.Controls;
namespace Snoop
{
public partial class BoolValueEditor : ValueEditor
{
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var cb = Template.FindName( "PART_CheckBox", this ) as CheckBox;
if ( cb != null )
{
cb.Click += CheckBoxClickedHandler;
}
}
private void CheckBoxClickedHandler( object sender, RoutedEventArgs e )
{
if ( PropertyInfo != null )
{
PropertyInfo.IsValueChangedByUser = true;
}
}
}
}
|
4fe1824f8297684424eba10a35f7043c1d139750
|
{
"blob_id": "4fe1824f8297684424eba10a35f7043c1d139750",
"branch_name": "refs/heads/master",
"committer_date": "2019-01-14T20:56:41",
"content_id": "4cf99df23b5787deb8049fa3d59ad8df22cc4f4e",
"detected_licenses": [
"MS-PL"
],
"directory_id": "9b48a9c324beb33626ce973377000a95a46d4840",
"extension": "cs",
"filename": "BoolValueEditor.cs",
"fork_events_count": 0,
"gha_created_at": "2019-01-28T21:24:05",
"gha_event_created_at": "2019-01-28T21:24:05",
"gha_language": null,
"gha_license_id": "NOASSERTION",
"github_id": 168039871,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 719,
"license": "MS-PL",
"license_type": "permissive",
"path": "/Snoop/ValueEditors/BoolValueEditor.cs",
"provenance": "stack-edu-0014.json.gz:829844",
"repo_name": "poizan42/snoopwpf",
"revision_date": "2019-01-14T20:56:41",
"revision_id": "4e2121b6222a1677abe6477823ba4f5b83cb75d2",
"snapshot_id": "ce6b152bbcc5e6517428ed25d36b69488f1dcf6b",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/poizan42/snoopwpf/4e2121b6222a1677abe6477823ba4f5b83cb75d2/Snoop/ValueEditors/BoolValueEditor.cs",
"visit_date": "2020-04-19T07:10:56.846979",
"added": "2024-11-18T22:50:57.279845+00:00",
"created": "2019-01-14T20:56:41",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0032.json.gz"
}
|
import drawArcPath, { getPositionOnCircle, IPoint } from '../../src';
const canvas = <HTMLCanvasElement>document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const settings = {
innerRadius: { value: 120, min: 10, max: 150 },
outerRadius: { value: 200, min: 160, max: 300 },
numberOfParts: { value: 6, min: 1, max: 20, isInt: true },
spacing: { value: 40, min: 0, max: 100 },
rotateOffset: { value: 0, min: 0, max: 1 },
showPoints: false,
drawFirstOnly: false,
showSpacing: false,
showDrawOrder: false,
};
Object.keys(settings).forEach(key => {
const wrap = document.createElement('div');
const label = document.createElement('label');
label.style.display = 'block';
label.style.fontSize = '10px';
label.innerText = key;
const input = document.createElement('input');
if (typeof settings[key] === 'boolean') {
input.type = 'checkbox';
// listen to change
input.addEventListener('change', () => {
settings[key] = input.checked;
draw();
});
} else {
input.type = 'range';
// listen to change
input.addEventListener('input', () => {
const setting = settings[key];
let value = setting.min + parseInt(input.value, 10) / 100 * (setting.max - setting.min);
if (setting.isInt) {
value = Math.round(value);
}
setting.value = value;
draw();
});
}
wrap.appendChild(label);
wrap.appendChild(input);
document.getElementById('controls').appendChild(wrap);
});
const draw = () => {
if (settings.showSpacing) {
drawParts('white', true, true, true);
drawParts('deepskyblue', false, false, false);
} else {
drawParts();
}
};
const drawParts = (color = 'deepskyblue', noSpacing = false, clear = true, skipPoints = false) => {
if (clear) {
ctx.fillStyle = '#DDD';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
const center = {
x: canvas.width * 0.5,
y: canvas.height * 0.5,
};
const radiansPerPart = Math.PI * 2 / settings.numberOfParts.value;
for (let i = 0; i < settings.numberOfParts.value; i++) {
if (settings.drawFirstOnly && i !== 0) {
continue;
}
const offset = settings.rotateOffset.value * Math.PI * 2;
const startRadians = i * radiansPerPart + offset;
const endRadians = startRadians + radiansPerPart;
const arcData = drawArcPath(
ctx,
center.x,
center.y,
startRadians,
endRadians,
settings.outerRadius.value,
settings.innerRadius.value,
noSpacing ? 0 : settings.spacing.value,
);
ctx.globalAlpha = 0.6;
ctx.fillStyle = color;
ctx.fill();
ctx.globalAlpha = 1;
if (settings.showPoints && !skipPoints) {
drawArcPoints(ctx, arcData);
}
if (settings.showSpacing) {
const dash = [5,5];
const color = 'black';
const startPoints = getInnerOuterPoints(
center,
settings.outerRadius.value,
settings.innerRadius.value,
startRadians,
);
const endPoints = getInnerOuterPoints(
center,
settings.outerRadius.value,
settings.innerRadius.value,
endRadians,
);
drawDottedLine(ctx, startPoints.inner, startPoints.outer, dash, color);
const halfStart = getHalfWay(startPoints.inner, startPoints.outer);
const perpendicularSpacingPointStart:IPoint = {
x: halfStart.x + (Math.cos(startRadians + Math.PI * 0.5) * settings.spacing.value * 0.5),
y: halfStart.y + (Math.sin(startRadians + Math.PI * 0.5) * settings.spacing.value * 0.5),
};
drawDottedLine(ctx, halfStart, perpendicularSpacingPointStart, [], 'magenta', 2);
// when drawing 1 part, also draw the line for the end
if (settings.drawFirstOnly) {
drawDottedLine(ctx, endPoints.inner, endPoints.outer, dash, color);
const halfEnd = getHalfWay(endPoints.inner, endPoints.outer);
const perpendicularSpacingPointEnd:IPoint = {
x: halfEnd.x + (Math.cos(endRadians - Math.PI * 0.5) * settings.spacing.value * 0.5),
y: halfEnd.y + (Math.sin(endRadians - Math.PI * 0.5) * settings.spacing.value * 0.5),
};
drawDottedLine(ctx, halfEnd, perpendicularSpacingPointEnd, [], 'magenta', 2);
}
}
}
};
function getInnerOuterPoints(
center: IPoint,
outer: number,
inner: number,
radians: number,
): {outer:IPoint; inner: IPoint} {
return {
outer: getPositionOnCircle(center.x, center.y, radians, outer),
inner: getPositionOnCircle(center.x, center.y, radians, inner),
}
}
function drawDottedLine(context:CanvasRenderingContext2D, point1:IPoint, point2: IPoint, lineDash:number[], color:string, lineWidth = 1): void {
context.beginPath();
context.moveTo(point1.x, point1.y);
context.lineTo(point2.x, point2.y);
context.setLineDash(lineDash);
context.strokeStyle = color;
context.lineWidth = lineWidth;
context.stroke();
context.closePath();
context.setLineDash([]);
}
const orderedProps = ['outerStart', 'outerEnd', 'innerStart', 'innerEnd'];
function drawArcPoints(context: CanvasRenderingContext2D, arcData: any): void {
Object.keys(arcData).forEach(key => {
if (typeof arcData[key] !== 'object') {
// only draw points
return;
}
const label = settings.showDrawOrder ? `${key} (${orderedProps.indexOf(key) + 1})` : key;
drawPoint(context, arcData[key].x, arcData[key].y, 'red');
context.font = '9px monospace';
context.fillStyle = 'black';
const space = 5;
context.fillText(label, arcData[key].x + space, arcData[key].y - space);
});
}
function drawPoint(context, x: number, y: number, color = 'black', radius: number = 3): void {
context.beginPath();
context.arc(x, y, radius, 0, Math.PI * 2);
context.fillStyle = color;
context.fill();
}
function getHalfWay(point1: IPoint, point2: IPoint): IPoint {
return {
x: point1.x + 0.5 * (point2.x - point1.x),
y: point1.y + 0.5 * (point2.y - point1.y),
}
}
draw();
|
49c7ebec11be09b66b4901251b938cbc5909c89b
|
{
"blob_id": "49c7ebec11be09b66b4901251b938cbc5909c89b",
"branch_name": "refs/heads/master",
"committer_date": "2018-06-26T09:45:38",
"content_id": "9cbff4955c6c1ed0176f9f52e079ccf0e58699c9",
"detected_licenses": [
"MIT"
],
"directory_id": "bb09beff5347ba9b3b2580d538828055fd32ce33",
"extension": "ts",
"filename": "index.ts",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 127290212,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 5992,
"license": "MIT",
"license_type": "permissive",
"path": "/example/src/index.ts",
"provenance": "stack-edu-0075.json.gz:181784",
"repo_name": "petervdn/arc-path",
"revision_date": "2018-06-26T09:45:38",
"revision_id": "65a51184f189b661c76f8755de083d94756031f5",
"snapshot_id": "4c0dd8d997c97dcc13acb918b315f1a2687013f8",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/petervdn/arc-path/65a51184f189b661c76f8755de083d94756031f5/example/src/index.ts",
"visit_date": "2020-03-07T05:14:17.899033",
"added": "2024-11-18T22:24:08.792326+00:00",
"created": "2018-06-26T09:45:38",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0093.json.gz"
}
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
//strlen, strcpy, stricmp/strcmp
//char cadena[20]={'h','o','l','a'};
char cadena[20]="perro";
char cadena2[20]="gato";
strcpy (cadena2, "gato");
/*int cantidad;
cantidad = strlen (cadena);*/
printf("%s \n", cadena);
printf("%s \n", cadena2);
/*
int estado;
estado=stricmp (cadena2, "gato");
printf("%d", estado);
*/
//puts(); - Muestra una varialbe por consola.-
//pedir 3 nombres, 20 caracteres cada uno. (y apellido).
/*guardar el nombre y el apellido en una variable con una coma y un espacio entre el nombre y el apellido por ejemplo "juan, perez"
y que cada letra delantera este en mayuscula.- */
return 0;
}
/*
printf("Ingrese nombre: ");
fflush(stdin);
//scanf("%s", &cadena);
gets(cadena);
printf("Su nombre es: %s", cadena);
*/
|
8fd157d489bbc95558b32cb63026319fde44ee3f
|
{
"blob_id": "8fd157d489bbc95558b32cb63026319fde44ee3f",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-07T15:18:25",
"content_id": "23da952fb2079b454bad3558bcd08f9b965127c1",
"detected_licenses": [
"MIT"
],
"directory_id": "6eebe671de10bfd200d02db874bb6345a5f9a649",
"extension": "c",
"filename": "main.c",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 146292621,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 841,
"license": "MIT",
"license_type": "permissive",
"path": "/Cadenas/main.c",
"provenance": "stack-edu-0001.json.gz:110914",
"repo_name": "LucasDLiker/labProgramacionUno",
"revision_date": "2019-05-07T15:18:25",
"revision_id": "95860e016649f0969aa2d03a86d8c59d8359d6b9",
"snapshot_id": "8fd4d6add27ae0c6f522cd91b8b8746e2a866279",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/LucasDLiker/labProgramacionUno/95860e016649f0969aa2d03a86d8c59d8359d6b9/Cadenas/main.c",
"visit_date": "2020-03-27T08:51:15.432754",
"added": "2024-11-18T23:19:59.307013+00:00",
"created": "2019-05-07T15:18:25",
"int_score": 3,
"score": 3.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz"
}
|
/**
* a very simple loop player ...
*/
pub struct LoopPlayer {
index: usize,
loop_buffer: Vec<f32>,
}
impl LoopPlayer {
pub fn new() -> LoopPlayer {
LoopPlayer {
index: 0,
loop_buffer: vec![0.0; 128],
}
}
pub fn get_next_block(&mut self) -> [f32; 128] {
let mut out_buf: [f32; 128] = [0.0; 128];
for i in 0..128 {
out_buf[i] = self.loop_buffer[self.index];
if (self.index + 1) < self.loop_buffer.len() {
self.index = self.index + 1;
} else {
self.index = 0;
}
}
out_buf
}
pub fn set_loop(&mut self, samples:&[f32]) {
self.loop_buffer.resize(samples.len(), 0.0);
self.index = 0;
for i in 0..samples.len() {
self.loop_buffer[i] = samples[i] as f32;
}
}
}
|
3b94c5e098a6ff46d8a8e55774c0841900f6dd47
|
{
"blob_id": "3b94c5e098a6ff46d8a8e55774c0841900f6dd47",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-03T22:44:46",
"content_id": "4c2b6469aab5d9f0cc92430b248f8ef8b62de45c",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "7e5ddc5bc3fd62623cf25ba3942d0d552ea0dde3",
"extension": "rs",
"filename": "loop_player.rs",
"fork_events_count": 0,
"gha_created_at": "2019-06-03T09:57:53",
"gha_event_created_at": "2019-06-08T21:19:06",
"gha_language": "Rust",
"gha_license_id": null,
"github_id": 189979904,
"is_generated": false,
"is_vendor": false,
"language": "Rust",
"length_bytes": 926,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/src/binaural_loop_player/loop_player.rs",
"provenance": "stack-edu-0068.json.gz:315552",
"repo_name": "the-drunk-coder/wasm-loop-player",
"revision_date": "2019-11-03T22:44:46",
"revision_id": "a91da8752fc34e287e63de4d71bc9d9aa025152a",
"snapshot_id": "8b6e11cc4eea722bdfdead506edbf5f6681489a2",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/the-drunk-coder/wasm-loop-player/a91da8752fc34e287e63de4d71bc9d9aa025152a/src/binaural_loop_player/loop_player.rs",
"visit_date": "2020-05-30T21:47:01.909806",
"added": "2024-11-18T22:41:01.263614+00:00",
"created": "2019-11-03T22:44:46",
"int_score": 3,
"score": 3.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0086.json.gz"
}
|
#include <windows.h>
#include <detours.h>
#include <process.h>
#include <shlwapi.h>
#include <swrs.h>
#define WINDOW_HANDLE 0x0089FF90
#define ADDR_AFTER_HEADER 0x42E520
#define ADDR_REPLAY_HEADER_HINT 0x898805
byte *scene_id = (byte *)0x008A0044;
DWORD mountainVaporAddress = 0x008971C0;
char newValue[4];
static wchar_t s_profilePath[1024 + MAX_PATH];
void MemoryWrite(uintptr_t address, char *value, int length) {
DWORD oldProtect;
VirtualProtect((PVOID)address, length, PAGE_EXECUTE_READWRITE, &oldProtect);
memcpy((void *)address, value, length);
VirtualProtect((PVOID)address, length, oldProtect, NULL);
}
class CDetour {
public:
int AfterHeader();
static int (CDetour::*ActualAfterHeader)();
};
int CDetour::AfterHeader() {
int actual = (this->*ActualAfterHeader)();
byte hint = *(byte *)ADDR_REPLAY_HEADER_HINT;
if (hint == 0xCC) { // force no mountain vapor
*newValue = 0;
MemoryWrite(mountainVaporAddress, newValue, sizeof(newValue));
} else if (hint == 0xCD) { // force mountain vapor
*newValue = 11;
MemoryWrite(mountainVaporAddress, newValue, sizeof(newValue));
}
return actual;
}
int (CDetour::*CDetour::ActualAfterHeader)() = union_cast<int (CDetour::*)()>(ADDR_AFTER_HEADER);
void SetMountainVapor(void *unused) {
int disableAlert = GetPrivateProfileIntW(L"Settings", L"disable_alert", 0, s_profilePath);
int hotkeyMV = GetPrivateProfileIntW(L"Hotkeys", L"mountain_vapor_state", 0, s_profilePath);
int hotkeyNorm = GetPrivateProfileIntW(L"Hotkeys", L"normal_state", 0, s_profilePath);
if (!hotkeyMV && !hotkeyNorm) {
return;
}
while (true) {
if (*scene_id == 2 && (void *)GetForegroundWindow() == *(void **)WINDOW_HANDLE) {
if (hotkeyMV && GetAsyncKeyState(hotkeyMV)) {
if (!disableAlert) {
MessageBoxW(NULL, L"Mountain Vapor state is now set", L"ReplayReSync", MB_SETFOREGROUND);
}
*newValue = 11;
MemoryWrite(mountainVaporAddress, newValue, sizeof(newValue));
}
if (hotkeyNorm && GetAsyncKeyState(hotkeyNorm)) {
if (!disableAlert) {
MessageBoxW(NULL, L"Normal state is now set", L"ReplayReSync", MB_SETFOREGROUND);
}
*newValue = 0;
MemoryWrite(mountainVaporAddress, newValue, sizeof(newValue));
}
}
Sleep(60);
}
}
extern "C" {
__declspec(dllexport) bool CheckVersion(const BYTE hash[16]) {
return true;
}
__declspec(dllexport) bool Initialize(HMODULE hMyModule, HMODULE hParentModule) {
GetModuleFileNameW(hMyModule, s_profilePath, 1024);
PathRemoveFileSpecW(s_profilePath);
PathAppendW(s_profilePath, L"ReplayReSync.ini");
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
int (CDetour::*afterHeaderShim)() = &CDetour::AfterHeader;
DetourAttach((void **)&CDetour::ActualAfterHeader, *(PBYTE *)&afterHeaderShim);
DetourTransactionCommit();
_beginthread(SetMountainVapor, 0, NULL);
return true;
}
}
BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) {
return TRUE;
}
|
b123b9bf2af769b8fa3c4f62dfedbe554e40b9de
|
{
"blob_id": "b123b9bf2af769b8fa3c4f62dfedbe554e40b9de",
"branch_name": "refs/heads/master",
"committer_date": "2021-03-28T15:29:53",
"content_id": "56e9c845d6a77480cb1508291853bca694756164",
"detected_licenses": [
"Unlicense"
],
"directory_id": "1b5d6877bed5159a02f4ca50b1c0345ebc3b9d27",
"extension": "cpp",
"filename": "ReplayReSync.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2950,
"license": "Unlicense",
"license_type": "permissive",
"path": "/modules/ReplayReSync/ReplayReSync.cpp",
"provenance": "stack-edu-0002.json.gz:326601",
"repo_name": "lionminhu/SokuMods",
"revision_date": "2021-03-28T15:29:53",
"revision_id": "6b71daee2e9c39326d5aaabb8802548b5821a78f",
"snapshot_id": "8e2c9e97d4e54e0b6f5dd87274d6f9b91ec78ff9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/lionminhu/SokuMods/6b71daee2e9c39326d5aaabb8802548b5821a78f/modules/ReplayReSync/ReplayReSync.cpp",
"visit_date": "2023-03-30T02:04:36.993402",
"added": "2024-11-18T21:44:58.503965+00:00",
"created": "2021-03-28T15:29:53",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
package sessions_test
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/buffalo/render"
"github.com/markbates/buffalo-rails/rails/sessions"
"github.com/pkg/errors"
)
const value = `bXF4TUI3RzdkSVlVeElRUk9jZGZ5YkhnTFFHUStzdit6V2k4bnJWVVd5bFF5ZHZWWmQ2T1J0M2NvRkp0ajlWcmFyNnUxVm13TFBNYkdtY29lekJKMk1EdTRYZ2lpSEtvVjgvRjA2RHk0SWZEQis5TUdyL1ZBUUw0Z2hESEhscFdlaFQvOW1uczAzV1ZhNnczWHVUNTBET0loejF1Y0hoWmFmVkorUEpoUGlGYjJHQTFYSkhSSU5LbEFIQ0V4bkJxemp2TmJORjQzOVNTanRrVVFQRDlZSHI0U1pleldHdEhpbXBvMFNEL0JBMEtZTXFZeUoyc2VuZjlQdUphckVMRGFzTC9FLytGamJFOWlrSFhQc3V1QTlqbllnTmFpWHRuR3RTQ0VoaitTU0ZnN0JNZWNuQkZyMWJjTmsrQnBQa1pzaFI0U0d6SFJNWU5sZzJnKzY1QllOcXVYODZhdGl3eGhyUG9vQUlsSm5VaGJ6L1dXTjZQZGNmMzZmUG5FL3E1clFocE5zL0pQU3ZWdHUreGpMRzNQMlFkVWI1NXRvWERGWW5JKzA5MHBuRT0tLWJSUWM5UXFhMkVNSUtqVjNwQnFRaHc9PQ%3D%3D--37989ccb1eb59c4cd7da99eb496a95dd94519f9e`
func Example_Session_Cookie() {
app := buffalo.New(buffalo.Options{})
app.GET("/", func(c buffalo.Context) error {
s := sessions.New("test")
s.SecretKeyBase = "development"
m, err := s.Cookie(c)
if err != nil {
return errors.WithStack(err)
}
// find a value from the rails cookie, in this case a value named "token"
tok, ok := m["token"].(string)
if !ok {
return errors.New("could not find token")
}
return c.Render(200, render.String(tok))
})
res := httptest.NewRecorder()
cook := &http.Cookie{Name: "test", Value: value}
req := httptest.NewRequest("GET", "/", nil)
req.AddCookie(cook)
app.ServeHTTP(res, req)
body := res.Body.String()
fmt.Println(body)
// output: 3b67f127e9a82e5b9b81d68e64d69249
}
|
94a7bb3f61b9da7104936b01247bf22ba59171c6
|
{
"blob_id": "94a7bb3f61b9da7104936b01247bf22ba59171c6",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-24T15:57:52",
"content_id": "e82e554e1b68d8831f050ad82f4835b98ee3e4ce",
"detected_licenses": [
"MIT"
],
"directory_id": "8a971990f9027bde3b671e32ba2da007ac96ed7d",
"extension": "go",
"filename": "example_test.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 142181724,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1641,
"license": "MIT",
"license_type": "permissive",
"path": "/rails/sessions/example_test.go",
"provenance": "stack-edu-0015.json.gz:655862",
"repo_name": "markbates/buffalo-rails",
"revision_date": "2018-07-24T15:57:52",
"revision_id": "d6d299a21bee45a66d5f94f5e1d772b782deca49",
"snapshot_id": "7d5ecdb89195b99e74075c6e9d4eeb2a781ba0d5",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/markbates/buffalo-rails/d6d299a21bee45a66d5f94f5e1d772b782deca49/rails/sessions/example_test.go",
"visit_date": "2023-08-21T02:47:34.426359",
"added": "2024-11-19T00:53:38.291113+00:00",
"created": "2018-07-24T15:57:52",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
//step 1. make sure clicking on a book will actually trigger an action creator
//-define action creator and call it when a book is clicked
//make sure this action creator is wired up to redux
export function selectBook(book) {
//selectBook is an action creator that needs to return an action
//an object with a type property(purpose of action)
return {
type: 'BOOK_SELECTED',
payload: book
}
}
|
7181d4b28bbf049d224b53dca097cacf71fd51b4
|
{
"blob_id": "7181d4b28bbf049d224b53dca097cacf71fd51b4",
"branch_name": "refs/heads/master",
"committer_date": "2018-07-16T21:38:02",
"content_id": "12a2259f6d6b1741e71d1edb5fc4a3740e58b869",
"detected_licenses": [
"MIT"
],
"directory_id": "da1eee1f91d879ad404220536b86e1f969cde721",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": "2018-07-11T15:33:22",
"gha_event_created_at": "2018-07-11T15:33:22",
"gha_language": null,
"gha_license_id": null,
"github_id": 140595533,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 411,
"license": "MIT",
"license_type": "permissive",
"path": "/src/actions/index.js",
"provenance": "stack-edu-0041.json.gz:629809",
"repo_name": "mekowalski/ReduxSimpleStarter-1",
"revision_date": "2018-07-16T21:38:02",
"revision_id": "6244e3d4a7ed68dbb4f61052a1be3a2e84cdc32d",
"snapshot_id": "6a024cf301c27fef252a92809feea1e517aa7e87",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mekowalski/ReduxSimpleStarter-1/6244e3d4a7ed68dbb4f61052a1be3a2e84cdc32d/src/actions/index.js",
"visit_date": "2020-03-22T20:23:22.389577",
"added": "2024-11-19T00:15:16.539237+00:00",
"created": "2018-07-16T21:38:02",
"int_score": 2,
"score": 2.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0059.json.gz"
}
|
# Contribute
## Dev environment
Given you have [anaconda](https://www.continuum.io/downloads) installed, run the following commands to clone the repository into a new folder `sound_field_analysis-py`, install necessary tools into a new conda environment and activate it:
```
git clone https://github.com/AppliedAcousticsChalmers/sound_field_analysis-py.git
cd sound_field_analysis-py/
conda env create --file environment.yml
source activate sfa
```
You can now work on the *sfa* toolbox inside the `sound_field_analysis-py` folder. Using `ipython`, you may use the following magic commands to ensure reload on any changes inside the package:
```
%load_ext autoreload
%autoreload 2
```
## Documentation
If you want to compile the documentation (pdf and/or html), you need to additionally install sphinx and sphinx_rtd_theme and clone the gh-pages branch:
```
conda env update --file environment_gh-pages.yml
git clone --single-branch --branch gh-pages https://github.com/AppliedAcousticsChalmers/sound_field_analysis-py.git sound_field_analysis-docs
```
Now you can compile the pdf readme (given you have latex installed) and html pages by running `make latexpdf` or `make html` from the `sound_field_analysis-py\doc` directory.
If you decide on a different folder structure, you may edit the following line in `doc/Makefile` to decide on where to move the html documentation:
```
HTMLDIR = ../../sound_field_analysis-docs
```
|
1dc0692f21da968246f53e38996e55d19bf0d8fb
|
{
"blob_id": "1dc0692f21da968246f53e38996e55d19bf0d8fb",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-28T19:22:34",
"content_id": "aab4c7b7ebf502c915d894bc552985d59454d56a",
"detected_licenses": [
"MIT"
],
"directory_id": "3b3c2eda4a53d654c6bbe4c6ecdd47bb3a609cc6",
"extension": "md",
"filename": "contribute.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1436,
"license": "MIT",
"license_type": "permissive",
"path": "/contribute.md",
"provenance": "stack-edu-markdown-0004.json.gz:7907",
"repo_name": "abhayap/sound_field_analysis-py",
"revision_date": "2021-01-28T19:22:34",
"revision_id": "838c57e24e780bcc752ad393d41cabcbc7e891df",
"snapshot_id": "194f74b7ada4af55eb8eec77acd1f296129cac6c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/abhayap/sound_field_analysis-py/838c57e24e780bcc752ad393d41cabcbc7e891df/contribute.md",
"visit_date": "2023-02-24T02:42:08.000303",
"added": "2024-11-18T21:28:24.717231+00:00",
"created": "2021-01-28T19:22:34",
"int_score": 3,
"score": 3.375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz"
}
|
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
namespace MMHLco.FluentControls
{
/// <summary>
/// Interaction logic for FluentButton.xaml
/// </summary>
public partial class FluentButton : UserControl
{
private bool nowork = false;
public FluentButton()
{
InitializeComponent();
// rectangle1.MouseDown += Rectangle1_MouseDown1;
}
private Brush myVar;
public Brush Fill
{
//by mmhl
get => myVar;
set
{
myVar = value;
rectangle1.Fill = myVar;
}
}
private HorizontalAlignment Allign;
public HorizontalAlignment TextHorizontalAlignment
{
//by mmhl
get
{
return Allign;
}
set
{
Allign = value;
label1.HorizontalAlignment = Allign;
}
}
private VerticalAlignment Alllign;
public VerticalAlignment TextVerticalAlignment
{
//by mmhl
get
{
return Alllign;
}
set
{
Alllign = value;
label1.VerticalAlignment = Alllign;
}
}
private string text;
public string Text
{
get => text;
set
{
text = value;
label1.Content = text;
}
}
/********************************************************************/
/********************************************************************/
private void Rectangle1_MouseEnter(object sender, MouseEventArgs e)
{
Point pt = e.GetPosition(rectangle1);
RadialGradientBrush gradientBrush = new RadialGradientBrush
{
MappingMode = BrushMappingMode.Absolute,
Center = new Point(pt.X, pt.Y)
};
GradientStop stop = new GradientStop(Color.FromRgb(169, 169, 169), 0);
GradientStop stop2 = new GradientStop(Colors.Transparent, 1.2);
GradientStopCollection gradients = new GradientStopCollection
{
stop,
stop2
};
gradientBrush.GradientStops = gradients;
gradientBrush.RadiusX = 200;
gradientBrush.RadiusY = 200;
gradientBrush.GradientOrigin = new Point(pt.X, pt.Y);
rectangle1.Fill = gradientBrush;
}
private void Rectangle1_MouseMove(object sender, MouseEventArgs e)
{
Point pt = e.GetPosition(rectangle1);
RadialGradientBrush gradientBrush = new RadialGradientBrush
{
MappingMode = BrushMappingMode.Absolute,
Center = new Point(pt.X, pt.Y)
};
GradientStop stop = new GradientStop(Color.FromRgb(169, 169, 169), 0);
GradientStop stop2 = new GradientStop(Colors.Transparent, 1.2);
GradientStopCollection gradients = new GradientStopCollection
{
stop,
stop2
};
gradientBrush.GradientStops = gradients;
gradientBrush.RadiusX = 200;
gradientBrush.RadiusY = 200;
gradientBrush.GradientOrigin = new Point(pt.X, pt.Y);
rectangle1.Fill = gradientBrush;
}
private void Rectangle1_MouseLeave(object sender, MouseEventArgs e)
{
rectangle1.Fill = new SolidColorBrush(Colors.Transparent);
}
private void Rectangle1_MouseDown(object sender, MouseButtonEventArgs e)
{
// e1 = e;
Point pt = e.GetPosition(rectangle1);
RadialGradientBrush gradientBrush = new RadialGradientBrush
{
MappingMode = BrushMappingMode.Absolute,
Center = new Point(pt.X, pt.Y)
};
GradientStop stop = new GradientStop(Color.FromRgb(169, 169, 169), 0);
GradientStop stop2 = new GradientStop(Colors.Transparent, 3);
GradientStopCollection gradients = new GradientStopCollection
{
stop,
stop2
};
gradientBrush.GradientStops = gradients;
gradientBrush.RadiusX = 200;
gradientBrush.RadiusY = 200;
gradientBrush.GradientOrigin = new Point(pt.X, pt.Y);
rectangle1.Fill = gradientBrush;
nowork = true;
}
public void ApplyEffectTo(FluentButton target)
{
Point pt = Mouse.GetPosition(target);
RadialGradientBrush gradientBrush = new RadialGradientBrush
{
MappingMode = BrushMappingMode.Absolute,
Center = new Point(pt.X, pt.Y)
};
GradientStop stop = new GradientStop(Color.FromRgb(169, 169, 169), 0);
GradientStop stop2 = new GradientStop(Colors.Transparent, 3);
GradientStopCollection gradients = new GradientStopCollection
{
stop,
stop2
};
gradientBrush.GradientStops = gradients;
gradientBrush.RadiusX = 200;
gradientBrush.RadiusY = 200;
gradientBrush.GradientOrigin = new Point(pt.X, pt.Y);
target.Fill = gradientBrush;
nowork = true;
}
private void Dealy(int inter)
{
Timer timer = new Timer()
{
Interval = inter,
AutoReset = false
};
timer.Start();
timer.Stop();
}
private void Rectangle1_MouseUp(object sender, MouseButtonEventArgs e)
{
if (nowork == true)
{
Dealy(3000);
}
Point pt = e.GetPosition(rectangle1);
RadialGradientBrush gradientBrush = new RadialGradientBrush
{
MappingMode = BrushMappingMode.Absolute,
Center = new Point(pt.X, pt.Y)
};
GradientStop stop = new GradientStop(Color.FromRgb(169, 169, 169), 0);
GradientStop stop2 = new GradientStop(Colors.Transparent, 1.2);
GradientStopCollection gradients = new GradientStopCollection
{
stop,
stop2
};
gradientBrush.GradientStops = gradients;
gradientBrush.RadiusX = 200;
gradientBrush.RadiusY = 200;
gradientBrush.GradientOrigin = new Point(pt.X, pt.Y);
rectangle1.Fill = gradientBrush;
}
}
}
|
9e9b01ab5e7344172c8142185a4a1ee347219bf6
|
{
"blob_id": "9e9b01ab5e7344172c8142185a4a1ee347219bf6",
"branch_name": "refs/heads/main",
"committer_date": "2021-08-31T07:55:38",
"content_id": "05b7609636c3e6316b2fdbdcb0983b1e7b750eac",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c4c3c627087d8607666ee98b87bfe600a1892e6a",
"extension": "cs",
"filename": "FluentButton.xaml.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 396747344,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 7118,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Project/FluentButton.xaml.cs",
"provenance": "stack-edu-0013.json.gz:655060",
"repo_name": "themmhl/FluentControls",
"revision_date": "2021-08-31T07:55:38",
"revision_id": "d836e999d9450c4ce45b25ddfcad5f1c2de3d0eb",
"snapshot_id": "7a20fb668a1a719cc358d79b48f14d8a8f9c0fd8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/themmhl/FluentControls/d836e999d9450c4ce45b25ddfcad5f1c2de3d0eb/Project/FluentButton.xaml.cs",
"visit_date": "2023-07-15T07:52:27.461442",
"added": "2024-11-19T01:13:14.960267+00:00",
"created": "2021-08-31T07:55:38",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
import { EventDispatcher, Event } from '../src'
import { Mixin } from 'ts-mixer'
import fn = jest.fn
class MouseEvent extends Event {
public timeStamp: number
constructor(type: string) {
super(type)
this.timeStamp = new Date().getTime()
}
}
interface Events {
// [eventType: string]: (event: EventX) => any
click(event: MouseEvent): void
touch(event: MouseEvent): boolean
}
let ed: EventDispatcher<Events>
beforeEach(() => {
ed = new EventDispatcher<Events>({ validEventTypes: ['click', 'touch', 'sentResponse', 'getPostTitle'] })
})
test('register and trigger event', () => {
const args = { arg1: 'foo', arg2: 'bar' }
const callback = jest.fn()
ed.on('click', callback)
ed.on('touch', callback)
ed.one('touch', callback)
ed.trigger('click', args)
expect(callback).nthCalledWith(1, { type: 'click', ...args })
ed.trigger('touch', args)
expect(callback).nthCalledWith(2, { type: 'touch', ...args })
expect(callback).nthCalledWith(3, { type: 'touch', ...args })
expect(callback).toBeCalledTimes(3)
})
test('trigger method return response array', () => {
ed.on('touch', () => {
return true
})
ed.on('touch', () => {
return false
})
const responses = ed.trigger('touch')
expect(responses).toEqual([true, false])
})
test('register event with regular expression', () => {
const callback = jest.fn()
const ed = new EventDispatcher({ validEventTypes: [/click/] })
expect(() => {
ed.on('clickFoo', callback)
}).not.toThrow()
expect(() => {
ed.on('Foo', callback)
}).toThrow()
})
test('register onetime event', () => {
const callback = jest.fn()
ed.one('click', callback)
ed.trigger('click', [])
ed.trigger('click')
expect(callback).toBeCalledTimes(1)
})
describe('remove the callbacks', () => {
test('with callback specified', () => {
const callback1 = jest.fn()
const callback2 = jest.fn()
const callback3 = jest.fn()
ed.on('click', callback1)
const off = ed.on('click', callback2)
ed.on('click', callback3)
ed.off('click', callback1)
off()
ed.trigger('click')
expect(callback1).not.toBeCalled()
expect(callback2).not.toBeCalled()
expect(callback3).toBeCalled()
})
test('with callback not specified, removes all the callbacks of the given event type', () => {
const callback1 = jest.fn()
const callback2 = jest.fn()
ed.on('click', callback1)
ed.on('click', callback2)
ed.off('click')
ed.trigger('click')
expect(callback1).not.toBeCalled()
expect(callback2).not.toBeCalled()
})
})
test('throws if the event type is not valid', () => {
const callback = jest.fn()
expect(() => {
ed.on('foo' as 'click', callback)
}).toThrow()
expect(() => {
ed.one('foo' as 'click', callback)
}).toThrow()
expect(() => {
ed.trigger('foo' as 'click')
}).toThrow()
expect(() => {
ed.off('foo' as 'click')
}).toThrow()
})
test('disable or enable the event dispatcher', () => {
const callback = jest.fn()
ed.on('click', callback)
ed.disable().trigger('click')
expect(callback).not.toBeCalled()
ed.enable().trigger('click')
expect(callback).toBeCalled()
})
test('set callback context', () => {
const context = {}
ed.one('click', function (this: any) {
expect(this).toEqual(ed)
})
ed.trigger('click')
ed.setCallbackContext(context).one('click', function (this: any) {
expect(this).toEqual(context)
})
ed.trigger('click')
})
test('store and trigger last event object', () => {
const mouseEvent = new MouseEvent('click')
const clickEventHandler = jest.fn()
ed.trigger('click', mouseEvent)
expect(ed.getLastEventObjectOf('click')).toEqual(mouseEvent)
ed.on('click', clickEventHandler, { triggerLastEvent: true })
expect(clickEventHandler).toHaveBeenCalledTimes(1)
expect(clickEventHandler).toHaveBeenCalledWith(mouseEvent)
ed.removeLastEventObjectOf('click')
expect(ed.getLastEventObjectOf('click')).toEqual(null)
})
test('clear all callbacks', () => {
const callback = jest.fn()
ed.on('click', callback)
ed.on('touch', callback)
ed.clear()
ed.trigger('click')
ed.trigger('touch')
expect(callback).toHaveBeenCalledTimes(0)
})
test('mixin to another class', () => {
class BaseClass {}
const response = { foo: 'foobar' }
class MixedClass extends Mixin(BaseClass, ed.Api()) {
listenSentResponse() {
this.on('touch', (e) => {
expect(e).toEqual({ ...response, type: 'touch' })
return false
})
}
}
const mixedObj = new MixedClass()
mixedObj.listenSentResponse()
mixedObj.trigger('touch', response)
})
|
cf78c1ffebdf6207ae863fe46b313b2de7af8dbf
|
{
"blob_id": "cf78c1ffebdf6207ae863fe46b313b2de7af8dbf",
"branch_name": "refs/heads/master",
"committer_date": "2021-06-03T11:06:40",
"content_id": "30d84aab7f41bd91d01b1dacc952aeb9a2215991",
"detected_licenses": [
"MIT"
],
"directory_id": "eb6efd6f29f0134088dd62a87643f03a3debda6a",
"extension": "ts",
"filename": "EventDispatcher.spec.ts",
"fork_events_count": 0,
"gha_created_at": "2016-05-23T04:15:27",
"gha_event_created_at": "2023-01-06T12:37:11",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 59451525,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 4645,
"license": "MIT",
"license_type": "permissive",
"path": "/tests/EventDispatcher.spec.ts",
"provenance": "stack-edu-0073.json.gz:370171",
"repo_name": "yaquawa/EventDispatcher",
"revision_date": "2021-06-03T11:06:40",
"revision_id": "1b1b43d780b5a370459c24f0c76e6623d1c19f0c",
"snapshot_id": "5bdcb0a8dc1075ae67c8e27c4457731bc799cde3",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/yaquawa/EventDispatcher/1b1b43d780b5a370459c24f0c76e6623d1c19f0c/tests/EventDispatcher.spec.ts",
"visit_date": "2023-02-01T03:09:56.164180",
"added": "2024-11-18T21:05:35.787648+00:00",
"created": "2021-06-03T11:06:40",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0091.json.gz"
}
|
<?php
declare(strict_types=1);
namespace PHPJava\Packages\java\lang\invoke;
use PHPJava\Exceptions\NotImplementedException;
/**
* The `VolatileCallSite` class was auto generated.
*
* @parent \PHPJava\Packages\java\lang\Object_
* @parent \PHPJava\Packages\java\lang\invoke\CallSite
*/
class VolatileCallSite extends CallSite
{
/**
* Returns the target method of the call site, which behaves like a volatile field of the VolatileCallSite.
*
* @see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/invoke/package-summary.html#getTarget
* @param null|mixed $a
* @throws NotImplementedException
*/
public function getTarget($a = null)
{
throw new NotImplementedException(__METHOD__);
}
/**
* Updates the target method of this call site, as a volatile variable.
*
* @see https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/invoke/package-summary.html#setTarget
* @param null|mixed $a
* @throws NotImplementedException
*/
public function setTarget($a = null)
{
throw new NotImplementedException(__METHOD__);
}
}
|
6ededd12b50afd0bd87f20aeb7d41d74cd82df16
|
{
"blob_id": "6ededd12b50afd0bd87f20aeb7d41d74cd82df16",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-07T11:36:18",
"content_id": "869c87a4dfce3692dcd46d35efbce596e11734a0",
"detected_licenses": [
"MIT"
],
"directory_id": "d7ae3d85bd970ac57d2faf999034fcd3bdeecc01",
"extension": "php",
"filename": "VolatileCallSite.php",
"fork_events_count": 26,
"gha_created_at": "2015-01-30T13:23:35",
"gha_event_created_at": "2023-02-07T11:36:20",
"gha_language": "PHP",
"gha_license_id": "MIT",
"github_id": 30072897,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1162,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Packages/java/lang/invoke/VolatileCallSite.php",
"provenance": "stack-edu-0049.json.gz:723994",
"repo_name": "php-java/php-java",
"revision_date": "2023-02-07T11:36:18",
"revision_id": "5720776bc3b29adb23b79ce3a978a7d1af1d9667",
"snapshot_id": "d80fc5108bca85a34e2c92dc7640128feb27e06e",
"src_encoding": "UTF-8",
"star_events_count": 365,
"url": "https://raw.githubusercontent.com/php-java/php-java/5720776bc3b29adb23b79ce3a978a7d1af1d9667/src/Packages/java/lang/invoke/VolatileCallSite.php",
"visit_date": "2023-09-05T14:09:51.286975",
"added": "2024-11-18T21:32:12.365127+00:00",
"created": "2023-02-07T11:36:18",
"int_score": 3,
"score": 2.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0067.json.gz"
}
|
import { ModelData } from './../../../models/Model.data';
import { Component, OnDestroy, OnInit } from '@angular/core';
import { ApiService } from '../../../services/api-service';
import { ITermCompareReq } from '../../../interfaces/httpInterfaces';
import { Subscription } from 'rxjs';
import { EventService } from './../../../services/event-service';
@Component({
selector: 'app-words-similarity',
templateUrl: './words-similarity.component.html',
styleUrls: ['./words-similarity.component.sass'],
})
export class WordsSimilarityComponent implements OnInit, OnDestroy {
public similarityData: number;
public firstTerm = '';
public secondTerm = '';
public model: ModelData;
private subscription: Subscription[] = [];
constructor(
private apiService: ApiService,
private eventService: EventService,
) {}
ngOnInit(): void {
if (this.eventService.onWord2VecModelChange.value) {
this.model = this.eventService.onWord2VecModelChange.value;
}
this.subscription.push(this.eventService.onWord2VecModelChange.subscribe((model: ModelData) => {
if (model) {
this.model = model;
if (this.firstTerm && this.secondTerm && this.similarityData !== undefined) {
this.getWordsSimilarity();
}
}
}));
}
ngOnDestroy(): void {
if (this.subscription?.length) {
this.subscription.forEach((s => {
s.unsubscribe();
s = undefined;
}));
}
}
public async getWordsSimilarity(): Promise<void> {
if (this.model) {
const reqObj: ITermCompareReq = {
word_1: this.firstTerm.toLocaleLowerCase(),
word_2: this.secondTerm.toLocaleLowerCase()
};
this.similarityData = await this.apiService.getWordsSimilarity(reqObj, this.model.index);
}
}
}
|
6dcad41d5591bf312c300f0c579e0829f5b4c7d5
|
{
"blob_id": "6dcad41d5591bf312c300f0c579e0829f5b4c7d5",
"branch_name": "refs/heads/master",
"committer_date": "2023-07-09T11:36:40",
"content_id": "47e00602170bc1d8d0017aa5ea2098d748d7129b",
"detected_licenses": [],
"directory_id": "f9c4e0be685286cd49ee1d688937b52d27797f22",
"extension": "ts",
"filename": "words-similarity.component.ts",
"fork_events_count": 0,
"gha_created_at": "2020-10-04T07:05:07",
"gha_event_created_at": "2023-07-09T11:36:41",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 301062465,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 1801,
"license": "",
"license_type": "permissive",
"path": "/ui/src/app/components/term-processing/words-similarity/words-similarity.component.ts",
"provenance": "stack-edu-0076.json.gz:83351",
"repo_name": "malakhovks/docsim",
"revision_date": "2023-07-09T11:36:40",
"revision_id": "4e75e9566a9f546bd7798230847c73772b44a4b9",
"snapshot_id": "896f48d99a869c049a6f9b5f9377191289d7d878",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/malakhovks/docsim/4e75e9566a9f546bd7798230847c73772b44a4b9/ui/src/app/components/term-processing/words-similarity/words-similarity.component.ts",
"visit_date": "2023-07-21T23:04:23.255610",
"added": "2024-11-18T23:43:12.341582+00:00",
"created": "2023-07-09T11:36:40",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0094.json.gz"
}
|
/**
* dragToIncDec v1.0.2
* http://demo.idered.pl/jQuery.dragToIncDec
*
* Copyright 2012, Kasper Mikiewicz
* Released under MIT license.
* Date 2012-09-17
*/
(function($) {
$.fn.dragToIncDec = function() {
var cursor = 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAN5JREFUeNrMUjEOgzAMpFWnDAysKEM2Vl7QPiETa/uqdO0WgRjyB37ETGTiiKSBBCTUpZbMyeezZZtcACD7xa4HOWEcNhgbTrDjUNc1hJjSHU2QTdO0wrMrnG4Q7brTYK1bdhF93wNjLNzVxyke9ViHxLPrOqCUWh/H0YltHCIa5p0W625miFfbtpnW2k5UVVW0J+bKsox4rMMGn6ZpHsMwWFIp5QWcc3+DFG/qvjeQUkJRFG7SO35cnOJR727gmywi4Y6V5zmEmNIdvkRCCIT4/y9xa+/l13pMiWYBBgD2gmfsIU/6oAAAAABJRU5ErkJggg%3D%3D), auto',
isTouchDevice = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
return this.each(function() {
var $input = $(this),
$label = $('label[for="' + $input.attr('id') + '"]'),
step = $input.data('step') || 1,
max = $input.data('max'),
min = $input.data('min'),
dragging, start, value, tmp;
$label.on('hover', function(event) {
$(this).css('cursor', event.type == 'mouseenter' ? cursor : '');
}).on(isTouchDevice ? 'touchstart' : 'mousedown', function (event) {
if (event.originalEvent.preventDefault) event.originalEvent.preventDefault();
dragging = true;
start = isTouchDevice ? event.originalEvent.touches[0].pageX : event.pageX;
value = parseInt($input.val(), 10);
});
$(document.body).on(isTouchDevice ? 'touchend' : 'mouseup', function (event) {
dragging = false;
});
$(document.body).on(isTouchDevice ? 'touchmove' : 'mousemove', function(event) {
if (dragging && ! ((isTouchDevice ? event.originalEvent.touches[0].pageX : event.pageX) % 2)) {
tmp = value + Math.ceil(((isTouchDevice ? event.originalEvent.touches[0].pageX : event.pageX) - start) / 2) * step;
tmp = tmp > max ? max : tmp;
tmp = tmp < min ? min : tmp;
$input.val(tmp);
}
});
});
};
})(jQuery);
|
2796b3928ea709b3f94162c7ab81777457e41dbf
|
{
"blob_id": "2796b3928ea709b3f94162c7ab81777457e41dbf",
"branch_name": "refs/heads/master",
"committer_date": "2012-09-18T13:33:57",
"content_id": "cfc705592a523773d46b712ab89c011865d999c3",
"detected_licenses": [
"MIT"
],
"directory_id": "8cc803275e7e49cd039c71e61134f2ed41b5a5e7",
"extension": "js",
"filename": "jQuery.dragToIncDec.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 5843547,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2325,
"license": "MIT",
"license_type": "permissive",
"path": "/jQuery.dragToIncDec.js",
"provenance": "stack-edu-0040.json.gz:578164",
"repo_name": "Idered/dragToIncDec",
"revision_date": "2012-09-18T13:33:57",
"revision_id": "2e5a5bb10d75f8b60d51a16323a1b56edefc02e1",
"snapshot_id": "9069c46334b482c99e7878f6ab2b759636698dc0",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/Idered/dragToIncDec/2e5a5bb10d75f8b60d51a16323a1b56edefc02e1/jQuery.dragToIncDec.js",
"visit_date": "2016-09-15T23:54:16.434273",
"added": "2024-11-19T01:28:14.229099+00:00",
"created": "2012-09-18T13:33:57",
"int_score": 2,
"score": 2.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0058.json.gz"
}
|
package image
import (
"encoding/json"
"errors"
"time"
"github.com/docker/docker/api/types/container"
"github.com/opencontainers/go-digest"
"github.com/wagoodman/dive/dive/filetree"
)
type diffID digest.Digest
// Image is the image's config object
type Image struct {
// ID is a unique 64 character identifier of the image
ID string `json:"id,omitempty"`
// Parent is the ID of the parent image
Parent string `json:"parent,omitempty"`
// Comment is the commit message that was set when committing the image
Comment string `json:"comment,omitempty"`
// Created is the timestamp at which the image was created
Created time.Time `json:"created"`
// Container is the id of the container used to commit
Container string `json:"container,omitempty"`
// ContainerConfig is the configuration of the container that is committed into the image
ContainerConfig container.Config `json:"container_config,omitempty"`
// DockerVersion specifies the version of Docker that was used to build the image
DockerVersion string `json:"docker_version,omitempty"`
History []imageHistory `json:"history,omitempty"`
// Author is the name of the author that was specified when committing the image
Author string `json:"author,omitempty"`
// Config is the configuration of the container received from the client
Config *container.Config `json:"config,omitempty"`
// Architecture is the hardware that the image is built and runs on
Architecture string `json:"architecture,omitempty"`
// OS is the operating system used to build and run the image
OS string `json:"os,omitempty"`
// Size is the total size of the image including all layers it is composed of
Size int64 `json:",omitempty"`
RootFS *imageRootFS `json:"rootfs,omitempty"`
// rawJSON caches the immutable JSON associated with this image.
rawJSON []byte
}
type imageRootFS struct {
Type string `json:"type"`
DiffIDs []diffID `json:"diff_ids,omitempty"`
BaseLayer string `json:"base_layer,omitempty"`
}
type imageHistory struct {
ID string
Size uint64
Created time.Time `json:"created"`
Author string `json:"author,omitempty"`
CreatedBy string `json:"created_by,omitempty"`
Comment string `json:"comment,omitempty"`
EmptyLayer bool `json:"empty_layer,omitempty"`
}
// RawJSON returns the immutable JSON associated with the image.
func (img *Image) RawJSON() []byte {
return img.rawJSON
}
// NewFromJSON creates an Image configuration from json.
func NewFromJSON(src []byte) (*Image, error) {
img := &Image{}
if err := json.Unmarshal(src, &img); err != nil {
return img, err
}
if img.RootFS == nil {
return img, errors.New("invalid image JSON, no RootFS key")
}
img.rawJSON = src
return img, nil
}
// Manifest is the image manifest struct
type Manifest struct {
Config string `json:"Config,omitempty"`
Layers []string `json:"Layers,omitempty"`
RepoTags []string `json:"RepoTags,omitempty"`
}
// Tar is the image's tar object
type Tar struct {
Tag string
DockerVersion string
Created string
Manifest Manifest
Config *Image
Layers []Layer
RefTrees []*filetree.FileTree
SizeBytes uint64
UserSizeByes uint64 // this is all bytes except for the base image
}
|
20406aaf771b34b84e85d88808141ca7b571be2e
|
{
"blob_id": "20406aaf771b34b84e85d88808141ca7b571be2e",
"branch_name": "refs/heads/master",
"committer_date": "2023-02-02T17:44:10",
"content_id": "4784a35a817d92d6d1e38d983a395f2f702c478a",
"detected_licenses": [
"MIT"
],
"directory_id": "d3777b44d775a10458964ac09e18e1d10d8abc41",
"extension": "go",
"filename": "types.go",
"fork_events_count": 12,
"gha_created_at": "2017-08-10T01:00:25",
"gha_event_created_at": "2022-03-03T01:33:31",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 99865695,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 3284,
"license": "MIT",
"license_type": "permissive",
"path": "/pkg/image/types.go",
"provenance": "stack-edu-0016.json.gz:215975",
"repo_name": "blacktop/graboid",
"revision_date": "2023-02-02T17:44:10",
"revision_id": "d5751bf2d9ab51bb1c30e642e2b9adabd95d8116",
"snapshot_id": "f3259b3380339c5c9ca65b429f46ce8a5f2351ff",
"src_encoding": "UTF-8",
"star_events_count": 84,
"url": "https://raw.githubusercontent.com/blacktop/graboid/d5751bf2d9ab51bb1c30e642e2b9adabd95d8116/pkg/image/types.go",
"visit_date": "2023-02-16T15:09:33.152804",
"added": "2024-11-18T21:05:55.278008+00:00",
"created": "2023-02-02T17:44:10",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
/*!
* base-task-prompts (https://github.com/node-base/base-task-prompts)
*
* Copyright (c) 2016, Jon Schlinkert.
* Licensed under the MIT License.
*/
'use strict';
var camelcase = require('camel-case');
var extend = require('extend-shallow');
module.exports = function(app, config) {
var utils = {};
utils.confirm = function(msg, a, b) {
var key = camelcase(msg);
return function(cb) {
app.confirm(key, msg, extend({save: false}, config));
app.ask(key, function(err, answers) {
if (err) return cb(err);
if (answers[key] === true) {
app.build(a, cb);
} else {
if (typeof b === 'undefined') {
return cb();
}
app.build(b, cb);
}
});
};
};
return utils;
};
|
403c8d7972046606896b896f78452d39c2126bb4
|
{
"blob_id": "403c8d7972046606896b896f78452d39c2126bb4",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-07T13:53:43",
"content_id": "ec0b17e76726f1bdc65bbea0ff9db1f7660681d4",
"detected_licenses": [
"MIT"
],
"directory_id": "77cc0a602842f6bad42b07da29ecfe02a867ff6f",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 173147700,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 786,
"license": "MIT",
"license_type": "permissive",
"path": "/node_modules/base-task-prompts/index.js",
"provenance": "stack-edu-0039.json.gz:18935",
"repo_name": "Tirocigno/ShadowASWProject",
"revision_date": "2019-03-07T13:53:43",
"revision_id": "028eb7b23589376b6bc0886c3be1259d0d1cfef2",
"snapshot_id": "60ead63d89ae91ce676b59672c6192d5c3a60326",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tirocigno/ShadowASWProject/028eb7b23589376b6bc0886c3be1259d0d1cfef2/node_modules/base-task-prompts/index.js",
"visit_date": "2020-04-25T23:29:33.761710",
"added": "2024-11-19T00:27:40.790223+00:00",
"created": "2019-03-07T13:53:43",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0057.json.gz"
}
|
<?php
/**
* The template for displaying all single posts
*/
get_header();
$blog_sidebar = 'right';
$post_nav = true;
if ( class_exists('Redux') ) {
$blog_sidebar = codebean_option('sidebar_position');
$post_nav = codebean_option('blog_navigation');
}
$sidebar_position = isset($_GET['sidebar']) ? $_GET['sidebar'] : $blog_sidebar;
$blog_container_classes = array('blog-archive');
if ( $sidebar_position == 'left' || $sidebar_position == 'right' ) {
$blog_container_classes[] = 'has-sidebar';
}
if ( $sidebar_position == 'left' ) {
$blog_container_classes[] = 'sidebar-left';
} elseif ( $sidebar_position == 'right' ) {
$blog_container_classes[] = 'sidebar-right';
}
?>
<div class="main-page-content default-margin" id="content">
<div class="site-content-inner container" role="main">
<div class="<?php echo esc_attr( implode( ' ', $blog_container_classes ) ); ?>">
<div class="blog-main-loop">
<div class="blog-loop-inner post-single">
<?php get_template_part( '/inc/templates/blog/single' ); ?>
</div>
<?php if ( $post_nav ) {
do_action( 'studiare_post_nav' );
} ?>
<?php if ( comments_open() || get_comments_number() ) : ?>
<!-- start #comments -->
<?php comments_template('', true); ?>
<!-- end #comments -->
<?php endif; ?>
</div> <!-- end .blog-main-loop -->
<?php if ( $sidebar_position !== 'none' ) : ?>
<aside class="main-sidebar-holder">
<?php get_sidebar(); ?>
</aside>
<?php endif; ?>
</div>
</div>
</div>
<?php get_footer(); ?>
|
d61b86c0be204b36a0ba62d410fa9e36bac0ba43
|
{
"blob_id": "d61b86c0be204b36a0ba62d410fa9e36bac0ba43",
"branch_name": "refs/heads/master",
"committer_date": "2020-07-07T06:31:26",
"content_id": "d8b22d23fc3d785bffc2787a0155a2c7b64bc547",
"detected_licenses": [
"MIT"
],
"directory_id": "8267202b3573dbae798b115ea46bde2d1cda4eb5",
"extension": "php",
"filename": "single.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 277735389,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1607,
"license": "MIT",
"license_type": "permissive",
"path": "/single.php",
"provenance": "stack-edu-0046.json.gz:256124",
"repo_name": "karimelshimi/AOUGeeks",
"revision_date": "2020-07-07T06:31:26",
"revision_id": "1127fe64d2397fa0eba52335f3036f4d0a2bd0e4",
"snapshot_id": "b1a3688c1db375551a2fd3ebec33cc872d6b612a",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/karimelshimi/AOUGeeks/1127fe64d2397fa0eba52335f3036f4d0a2bd0e4/single.php",
"visit_date": "2022-11-20T01:17:36.544165",
"added": "2024-11-19T00:02:33.287489+00:00",
"created": "2020-07-07T06:31:26",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
// managed includes
#include "vtkDotNetConvert.h"
#include "vtkProgrammableSourceDotNet.h"
// native includes
#include "strstream"
#include "vtkProgrammableSource.h"
#include "vtkObject.h"
#include "vtkPolyData.h"
#include "vtkRectilinearGrid.h"
#include "vtkStructuredGrid.h"
#include "vtkStructuredPoints.h"
#include "vtkUnstructuredGrid.h"
using namespace System;
namespace vtk {
System::String^ vtkProgrammableSource::GetClassName()
{
const char* retVal = vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetClassName();
System::String^ sRetVal = System::Runtime::InteropServices::Marshal::PtrToStringAnsi(IntPtr(const_cast<char*>(retVal)));
return sRetVal;
}
int vtkProgrammableSource::IsA(System::String^ name)
{
char* nameWrap = static_cast<char*>(System::Runtime::InteropServices::Marshal::StringToHGlobalAnsi(name).ToPointer());
int retVal = vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->IsA(nameWrap);
System::Runtime::InteropServices::Marshal::FreeHGlobal(IntPtr(nameWrap));
return retVal;
}
vtkProgrammableSource^ vtkProgrammableSource::NewInstance()
{
::vtkProgrammableSource* retVal = static_cast<::vtkProgrammableSource*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->NewInstance());
return gcnew vtkProgrammableSource(IntPtr(retVal), false);
}
vtkProgrammableSource^ vtkProgrammableSource::SafeDownCast(vtkObject^ o)
{
::vtkObject* oWrap = vtk::ConvertManagedToNative<::vtkObject>(o->GetNativePointer());
::vtkProgrammableSource* retVal = static_cast<::vtkProgrammableSource*>(::vtkProgrammableSource::SafeDownCast(oWrap));
return gcnew vtkProgrammableSource(IntPtr(retVal), false);
}
vtkPolyData^ vtkProgrammableSource::GetPolyDataOutput()
{
::vtkPolyData* retVal = static_cast<::vtkPolyData*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetPolyDataOutput());
return gcnew vtkPolyData(IntPtr(retVal), false);
}
vtkStructuredPoints^ vtkProgrammableSource::GetStructuredPointsOutput()
{
::vtkStructuredPoints* retVal = static_cast<::vtkStructuredPoints*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetStructuredPointsOutput());
return gcnew vtkStructuredPoints(IntPtr(retVal), false);
}
vtkStructuredGrid^ vtkProgrammableSource::GetStructuredGridOutput()
{
::vtkStructuredGrid* retVal = static_cast<::vtkStructuredGrid*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetStructuredGridOutput());
return gcnew vtkStructuredGrid(IntPtr(retVal), false);
}
vtkUnstructuredGrid^ vtkProgrammableSource::GetUnstructuredGridOutput()
{
::vtkUnstructuredGrid* retVal = static_cast<::vtkUnstructuredGrid*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetUnstructuredGridOutput());
return gcnew vtkUnstructuredGrid(IntPtr(retVal), false);
}
vtkRectilinearGrid^ vtkProgrammableSource::GetRectilinearGridOutput()
{
::vtkRectilinearGrid* retVal = static_cast<::vtkRectilinearGrid*>(vtk::ConvertManagedToNative<::vtkProgrammableSource>(m_instance)->GetRectilinearGridOutput());
return gcnew vtkRectilinearGrid(IntPtr(retVal), false);
}
vtkProgrammableSource::vtkProgrammableSource(System::IntPtr native, bool bConst) : vtkDataSetAlgorithm(native, bConst) {}
vtkProgrammableSource::vtkProgrammableSource(bool donothing) : vtkDataSetAlgorithm(donothing) {}
vtkProgrammableSource::vtkProgrammableSource() : vtkDataSetAlgorithm(false) {
this->SetNativePointer(IntPtr(::vtkProgrammableSource::New()));
}
vtkProgrammableSource::~vtkProgrammableSource() { }
} // end namespace vtkGraphics
|
e78de55232f19eaaff78dbc4048e7108c273a1e0
|
{
"blob_id": "e78de55232f19eaaff78dbc4048e7108c273a1e0",
"branch_name": "refs/heads/master",
"committer_date": "2012-03-19T01:24:14",
"content_id": "06fc9729200db9083d62f4c20459c4a8e97630f9",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "e99c20155e9b08c7e7598a3f85ccaedbd127f632",
"extension": "cxx",
"filename": "vtkProgrammableSourceDotNet.cxx",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 38281086,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3741,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ sjtu-project-pipe/thirdparties/VTK.Net/src/Graphics/vtkProgrammableSourceDotNet.cxx",
"provenance": "stack-edu-0008.json.gz:389609",
"repo_name": "unidevop/sjtu-project-pipe",
"revision_date": "2012-03-19T01:24:14",
"revision_id": "5a09f098db834d5276a2921d861ef549961decbe",
"snapshot_id": "38f00462d501d9b1134ce736bdfbfe4f9d075e4a",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/unidevop/sjtu-project-pipe/5a09f098db834d5276a2921d861ef549961decbe/ sjtu-project-pipe/thirdparties/VTK.Net/src/Graphics/vtkProgrammableSourceDotNet.cxx",
"visit_date": "2020-05-16T21:32:47.772410",
"added": "2024-11-18T23:57:46.496338+00:00",
"created": "2012-03-19T01:24:14",
"int_score": 2,
"score": 2.390625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0026.json.gz"
}
|
package main
import (
"fmt"
"io"
"os"
)
func main(){
CopyFile("./Chapter12/output_copy.dat","output.dat")
fmt.Println("Done")
}
func CopyFile(dstName, scrName string) (written int64, err error){
src, err := os.Open(scrName)
if err != nil{
return
}
defer src.Close()
dst, err := os.OpenFile(dstName, os.O_WRONLY | os.O_CREATE, 0664)
if err!=nil{
return
}
defer dst.Close()
return io.Copy(dst, src)
}
|
e7ba2361dccb0e455e44a444809ad0c3f87c6fec
|
{
"blob_id": "e7ba2361dccb0e455e44a444809ad0c3f87c6fec",
"branch_name": "refs/heads/master",
"committer_date": "2018-02-28T11:39:28",
"content_id": "599106cb0c3d10e7e29c33dd544ec2c153725289",
"detected_licenses": [
"MIT"
],
"directory_id": "1fe692e8dcdc68231f35aebbf894696ff3ca5329",
"extension": "go",
"filename": "filecopy.go",
"fork_events_count": 1,
"gha_created_at": "2018-02-28T11:33:58",
"gha_event_created_at": "2021-07-14T05:41:46",
"gha_language": "Jupyter Notebook",
"gha_license_id": "MIT",
"github_id": 123276169,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 421,
"license": "MIT",
"license_type": "permissive",
"path": "/Go-Tutorial/Chapter12/filecopy.go",
"provenance": "stack-edu-0017.json.gz:568157",
"repo_name": "gaufung/CodeBase",
"revision_date": "2018-02-28T11:39:28",
"revision_id": "0292b06cfe002b3ad0299e43bb51192816a02c74",
"snapshot_id": "301ec33197771a937f75ce6ffb04b61443fc8f43",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/gaufung/CodeBase/0292b06cfe002b3ad0299e43bb51192816a02c74/Go-Tutorial/Chapter12/filecopy.go",
"visit_date": "2021-07-19T15:00:47.000077",
"added": "2024-11-19T01:26:07.298321+00:00",
"created": "2018-02-28T11:39:28",
"int_score": 3,
"score": 2.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0035.json.gz"
}
|
"""XSD Tree operations on namespaces
"""
from xml_utils.commons import constants as xml_utils_constants
from xml_utils.xsd_tree.xsd_tree import XSDTree
def get_namespaces(xsd_string):
"""Returns dict of prefix and namespaces
Args:
xsd_string:
Returns:
"""
# events to look for during iterparse
events = "start", "start-ns"
# initialize namespaces dictionary
namespaces = {"xml": xml_utils_constants.XML_NAMESPACE}
# iterate file namespaces
for event, elem in XSDTree.iterparse(xsd_string, events):
if event == "start-ns":
if len(elem[0]) > 0 and len(elem[1]) > 0:
namespaces[elem[0]] = f"{elem[1]}"
elif event == "start":
break
return namespaces
def get_default_prefix(namespaces):
"""Returns the default prefix used in the schema
Args:
namespaces:
Returns:
"""
default_prefix = ""
for prefix, url in list(namespaces.items()):
if url == xml_utils_constants.SCHEMA_NAMESPACE:
default_prefix = prefix
break
return default_prefix
def get_global_namespace(xsd_string):
"""Get global namespace used in schema (defined by xmlns=<namespace>)
Returns:
"""
# events to look for during iterparse
events = "start", "start-ns"
# Initialize global namespace
global_namespace = None
# iterate file namespaces
for event, elem in XSDTree.iterparse(xsd_string, events):
if event == "start-ns":
if len(elem[0]) == 0:
global_namespace = elem[1]
elif event == "start":
break
return global_namespace
def get_target_namespace(xsd_tree, namespaces):
"""Returns the target namespace used in the schema
Args:
xsd_tree:
namespaces:
Returns:
"""
# get attributes of the root element (schema)
root_attributes = xsd_tree.getroot().attrib
# check if a target namespace is present
target_namespace = (
root_attributes["targetNamespace"]
if "targetNamespace" in root_attributes
else None
)
# set default prefix to empty string
target_namespace_prefix = ""
# if a target namespace is present
if target_namespace is not None:
# iterate through namespaces
for prefix, url in list(namespaces.items()):
# if an url matching the target namespace is found
if url == target_namespace:
# set the target namespace prefix with the associated prefix
target_namespace_prefix = prefix
# stop the search
break
# return target namespace and associated prefix
return target_namespace, target_namespace_prefix
|
f07b32dd65cd0f669e893dd1bed88e94244bc71c
|
{
"blob_id": "f07b32dd65cd0f669e893dd1bed88e94244bc71c",
"branch_name": "refs/heads/develop",
"committer_date": "2023-02-23T16:44:48",
"content_id": "fcea76fc25f0ef549ed2937884f5e7cde3810bbf",
"detected_licenses": [
"BSD-3-Clause",
"MIT",
"NIST-Software"
],
"directory_id": "39b4175eec52a881e4374904625707cae588e0ab",
"extension": "py",
"filename": "namespaces.py",
"fork_events_count": 1,
"gha_created_at": "2016-11-23T16:37:01",
"gha_event_created_at": "2022-09-17T01:38:58",
"gha_language": "Python",
"gha_license_id": "NOASSERTION",
"github_id": 74595333,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2759,
"license": "BSD-3-Clause,MIT,NIST-Software",
"license_type": "permissive",
"path": "/xml_utils/xsd_tree/operations/namespaces.py",
"provenance": "stack-edu-0064.json.gz:30900",
"repo_name": "usnistgov/xml_utils",
"revision_date": "2023-02-23T16:37:12",
"revision_id": "3b23d0be563a3294e3da97b90788f456e633d231",
"snapshot_id": "0c9b1264fc8be641436255e2ee2336c1e2265a1b",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/usnistgov/xml_utils/3b23d0be563a3294e3da97b90788f456e633d231/xml_utils/xsd_tree/operations/namespaces.py",
"visit_date": "2023-03-04T15:16:42.807208",
"added": "2024-11-18T21:14:05.180997+00:00",
"created": "2023-02-23T16:37:12",
"int_score": 3,
"score": 2.953125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz"
}
|
package protoc
import "errors"
// ErrUnknownPlugin is the error returned when a plugin is not known.
var ErrUnknownPlugin = errors.New("unknown plugin")
// PluginRegistry represents a library of plugin implementations.
type PluginRegistry interface {
// PluginNames returns a sorted list of plugin names.
PluginNames() []string
// LookupPlugin returns the implementation under the given name. If the
// plugin is not found, ErrUnknownPlugin is returned.
LookupPlugin(name string) (Plugin, error)
// MustRegisterPlugin installs a Plugin implementation under the given name
// in the global plugin registry. Panic will occur if the same plugin is
// registered multiple times.
MustRegisterPlugin(plugin Plugin) PluginRegistry
// RegisterPlugin installs a Plugin implementation under the given name.
// Panic will occur if the same plugin is registered multiple times. The
// original PluginRegistry API had only the `MustRegisterPlugin` function
// that always used the plugin.Name(), the newer `RegisterPlugin` allows one
// to customize the name.
RegisterPlugin(name string, plugin Plugin) PluginRegistry
}
|
75ba21e7eef67ff907d987cbd6f03a75f8948dbc
|
{
"blob_id": "75ba21e7eef67ff907d987cbd6f03a75f8948dbc",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-11T00:13:34",
"content_id": "e2a00d404c9378ab8500591c63a0bf72e46b4840",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c997ff261781a5a4cea1cb7e7220d850cea551e3",
"extension": "go",
"filename": "plugin_registry.go",
"fork_events_count": 146,
"gha_created_at": "2018-10-03T07:00:44",
"gha_event_created_at": "2023-08-30T00:16:03",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 151373344,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1128,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/pkg/protoc/plugin_registry.go",
"provenance": "stack-edu-0018.json.gz:528946",
"repo_name": "stackb/rules_proto",
"revision_date": "2023-08-11T00:13:34",
"revision_id": "a426e0cbb9fb3756ca230887225b00c75b01c209",
"snapshot_id": "4d19845d8475481fc1cded339c22618f1fa88b35",
"src_encoding": "UTF-8",
"star_events_count": 290,
"url": "https://raw.githubusercontent.com/stackb/rules_proto/a426e0cbb9fb3756ca230887225b00c75b01c209/pkg/protoc/plugin_registry.go",
"visit_date": "2023-08-17T01:05:32.838419",
"added": "2024-11-19T01:53:10.112474+00:00",
"created": "2023-08-11T00:13:34",
"int_score": 3,
"score": 2.546875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0036.json.gz"
}
|
import config from 'config';
import axios from 'axios';
export const eventsService = {
getAll,
getEventById,
EventGenres,
getAllGenres,
getAllLocations,
createEvent,
deleteEvent,
getGenresByType
};
let EventGenres;
function getAllGenres () {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
}
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/genres`,
headers: requestOptions.headers
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function getGenresByType (typeId) {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
}
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/typexgenreselect/${typeId}`,
headers: requestOptions.headers
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function getAllLocations () {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
}
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/locations`,
headers: requestOptions.headers
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function getAll() {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
}
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/events`,
headers: requestOptions.headers
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function getEventById(id) {
const requestOptions = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
}
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/events/${id}?eventParentId=${id}`,
headers: requestOptions.headers
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function createEvent(event) {
const requestOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
},
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/events`,
headers: requestOptions.headers,
data: event
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
function deleteEvent(eventId) {
const requestOptions = {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
'authorization': JSON.parse(localStorage.getItem('user')).token
},
};
return axios({
method: requestOptions.method,
url: `${config.apiUrl}/events/${eventId}`,
headers: requestOptions.headers,
}).then((response) => {
return response.data;
}).catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
// always executed
});
}
|
46b537a25f36783cb8d6f1a9bf97a15833891431
|
{
"blob_id": "46b537a25f36783cb8d6f1a9bf97a15833891431",
"branch_name": "refs/heads/master",
"committer_date": "2021-01-12T19:12:27",
"content_id": "b4a52f9a5de79d776afb8269b3b713ffc634d694",
"detected_licenses": [
"MIT"
],
"directory_id": "b7451c9889ddb72d7cb973b4206daec08a59a709",
"extension": "js",
"filename": "events.service.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 329082330,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4084,
"license": "MIT",
"license_type": "permissive",
"path": "/daw-vue/src/_services/events.service.js",
"provenance": "stack-edu-0038.json.gz:486148",
"repo_name": "rebeca27/daw2020",
"revision_date": "2021-01-12T19:12:27",
"revision_id": "7890179c8badd0e96ad7615be8098f3b2621d115",
"snapshot_id": "39352c33113038d0e2385fd525db4b49f0b9d61f",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/rebeca27/daw2020/7890179c8badd0e96ad7615be8098f3b2621d115/daw-vue/src/_services/events.service.js",
"visit_date": "2023-02-10T05:04:34.031522",
"added": "2024-11-19T01:22:06.563214+00:00",
"created": "2021-01-12T19:12:27",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0056.json.gz"
}
|
from string import ascii_letters, digits
import RandomUsers as ru
username = ru.Username()
password = ru.Password(allow=ascii_letters + digits)
user_model = ru.BasicModel(username=username, password=password)
users = user_model.ordered_generate(ordered_fields={"username": "num_"}, csv_file="test.csv")
|
713629c10d6de8cba6aabd701de9db00ae63c333
|
{
"blob_id": "713629c10d6de8cba6aabd701de9db00ae63c333",
"branch_name": "refs/heads/main",
"committer_date": "2021-06-27T07:21:14",
"content_id": "575c065ee2e19d7807c44e4d7850ffde0c730c2a",
"detected_licenses": [
"MIT"
],
"directory_id": "59f5b5d7119b01e0fdbd7bc36f24213f7ef02770",
"extension": "py",
"filename": "ordered_generate.py",
"fork_events_count": 1,
"gha_created_at": "2021-06-15T12:43:28",
"gha_event_created_at": "2021-06-24T13:35:06",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 377159197,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 305,
"license": "MIT",
"license_type": "permissive",
"path": "/examples/ordered_generate.py",
"provenance": "stack-edu-0055.json.gz:211107",
"repo_name": "SiriusKoan/RandomUsers",
"revision_date": "2021-06-27T07:21:14",
"revision_id": "ae23a801a9b7bb80652bcb73d271a8107a69bf9a",
"snapshot_id": "3b438d4fb54e3b2e78e2954301053dc9bda81183",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/SiriusKoan/RandomUsers/ae23a801a9b7bb80652bcb73d271a8107a69bf9a/examples/ordered_generate.py",
"visit_date": "2023-06-03T23:11:03.354490",
"added": "2024-11-19T00:11:40.040735+00:00",
"created": "2021-06-27T07:21:14",
"int_score": 2,
"score": 2.203125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0073.json.gz"
}
|
/*
By Michael Tran
Converts a DOM element to a CountDown timer that ticks every second,
which invokes a function once it hits 0.
Useful for places where it redirects users to another page in X seconds.
Versioning
----------------------------------
| Version | Modified By |
| 1.0 | Michael Tran |
| 1.1 | Aaron O'Donnell |
| 1.2 | Michael Tran |
----------------------------------
Current Version: 1.2
*/
//Main count down timer function used to give a count down effect for an element
//Usage:
// countDown(document.getElementById("timer"), function(){ ...YourCode }, seconds);
// countDown(document.getElementById("timer"), 'Homepage.html', seconds);
//Does not accept JQuery elements, however can be modified to convert JQuery elements to DOM elements.
//seconds are optional integer values.
//Alternatively, you can pass in the element with the value of seconds already inside it.
//baseFunction is optional parameters which is the function that's called once the timer hits 0;
function countDown(element, baseFunctionOrUrl, seconds)
{
if (typeof baseFunctionOrUrl == 'function')
countDownWithFunction(element, baseFunctionOrUrl, seconds);
else if (typeof baseFunctionOrUrl == 'string')
countDownRedirect(element, baseFunctionOrUrl, seconds);
else
console.error("Must pass in a URL string, or a callback function into the second parameter of countDown function.");
}
function countDownWithFunction(element, baseFunction, seconds) {
//default values
baseFunction = baseFunction || function () { };
seconds = seconds || null;
if (seconds === null) {
seconds = parseInt(element.innerHTML);
if (isNaN(seconds))
seconds = 10; //Setting the default seconds to 10
}
decrementElementText(element, baseFunction, seconds + 1);
}
//Convert an element to a count down timer
//Does not do error checking to check whether element has number text, nor set default values.
function decrementElementText(element, baseFunction, seconds) {
//Decrements an element with a number
if (seconds === 1) {
window.setTimeout(baseFunction, 1000);
}
else {
window.setTimeout(function () {
seconds = seconds - 1;
decrementElementText(element, baseFunction, seconds);
}, 1000);
}
element.innerHTML = seconds - 1;
}
//element - The javascript element which contains the timer to decrement (usually a span with a number in it)
//redirectUrl - Where you are redirecting the user to after the timer
//seconds - Optional. Number of seconds to count down from. If your element already has a number.
function countDownRedirect(element, redirectUrl, seconds) {
var callBackFunction = function () {
window.location.href = redirectUrl;
}
countDown(element, callBackFunction, seconds);
}
|
34f6e4aa4fb95264359e29ca34debf815596dda3
|
{
"blob_id": "34f6e4aa4fb95264359e29ca34debf815596dda3",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-10T06:51:54",
"content_id": "f1a71423cb17440d2562d17599bfe6c19fc210a2",
"detected_licenses": [
"MIT"
],
"directory_id": "4ef4658d0d64d5a8da06b9c4a66852e65e4f40ce",
"extension": "js",
"filename": "count-down.js",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 166658618,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2882,
"license": "MIT",
"license_type": "permissive",
"path": "/publishable/public/js/count-down.js",
"provenance": "stack-edu-0042.json.gz:564269",
"repo_name": "deltoss/sentinel-centurion",
"revision_date": "2019-03-10T06:51:54",
"revision_id": "df54bd4e2460cfd625637b1c689c0bc274c7251e",
"snapshot_id": "e7bd2d73bcfc05c2d29f7921d33066381e3146c4",
"src_encoding": "UTF-8",
"star_events_count": 6,
"url": "https://raw.githubusercontent.com/deltoss/sentinel-centurion/df54bd4e2460cfd625637b1c689c0bc274c7251e/publishable/public/js/count-down.js",
"visit_date": "2023-08-11T15:51:57.141333",
"added": "2024-11-19T01:28:17.567274+00:00",
"created": "2019-03-10T06:51:54",
"int_score": 3,
"score": 3.234375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz"
}
|
from unittest import TestCase
import importlib
import pydoautomator
import inspect
class TestPackageBasics(TestCase):
def test_if_package_exists(self):
self.assertIsNotNone(importlib.find_loader(
'pydoautomator'), 'module does not exist!')
def test_if_Droplet_exists_in_package(self):
self.assertTrue(
hasattr(pydoautomator, 'Droplet'),
'Droplet does not exists in package'
)
def test_Droplet_should_be_not_none(self):
self.assertIsNotNone(
pydoautomator.Droplet,
'Droplet has None value!'
)
def test_if_Droplet_is_a_class(self):
self.assertTrue(
inspect.isclass(pydoautomator.Droplet),
'pydoautomator.Droplet is not a class'
)
def test_if_Droplet_is_from_droplet_submodule(self):
self.assertTrue(
pydoautomator.Droplet.__module__ == 'pydoautomator.droplet',
'pydoautomator.Droplet is NOT a module from pydoautomator.droplet'
)
def test_if_Automator_exists_in_package(self):
self.assertTrue(
hasattr(pydoautomator, 'Automator'),
'Automator does not exists in package'
)
def test_Automator_should_be_not_none(self):
self.assertIsNotNone(
pydoautomator.Automator,
'Automator has None value!'
)
def test_if_Automator_is_a_class(self):
self.assertTrue(
inspect.isclass(pydoautomator.Automator),
'pydoautomator.Automator is not a class'
)
def test_if_Automator_is_from_automator_submodule(self):
self.assertTrue(
pydoautomator.Automator.__module__ == 'pydoautomator.automator',
'pydoautomator.Automator is NOT a module from pydoautomator.automator'
)
|
e103c88f5a717e3164b9fc5f7fea4b25fb90c9b6
|
{
"blob_id": "e103c88f5a717e3164b9fc5f7fea4b25fb90c9b6",
"branch_name": "refs/heads/master",
"committer_date": "2020-11-28T14:04:02",
"content_id": "9b5f1dad7296dfc8564cfa3143aed8d1873aa264",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "aa8e322045527d09c149cd6c643741499a715bdb",
"extension": "py",
"filename": "test_package_basics.py",
"fork_events_count": 2,
"gha_created_at": "2020-09-26T11:14:29",
"gha_event_created_at": "2021-07-29T03:51:13",
"gha_language": "Python",
"gha_license_id": "Apache-2.0",
"github_id": 298797495,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1833,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/tests/unit_tdd/test_package_basics.py",
"provenance": "stack-edu-0065.json.gz:270840",
"repo_name": "christian-hawk/pydoautomator",
"revision_date": "2020-11-28T14:04:02",
"revision_id": "433e634c7c1314d9da3207742f2656d2f7279915",
"snapshot_id": "87bec93ceed0c5462f84cc7a04dbd53f6a776eea",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/christian-hawk/pydoautomator/433e634c7c1314d9da3207742f2656d2f7279915/tests/unit_tdd/test_package_basics.py",
"visit_date": "2023-06-30T07:20:43.412847",
"added": "2024-11-18T23:43:34.812278+00:00",
"created": "2020-11-28T14:04:02",
"int_score": 3,
"score": 2.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
# Fossilize
**This repository is discontinued, see [new upstream under ValveSoftware/](https://github.com/ValveSoftware/Fossilize) for further development.**
[](https://travis-ci.org/Themaister/Fossilize)
[](https://ci.appveyor.com/project/Themaister/fossilize)
Fossilize is a simple library for serializing various persistent Vulkan objects which typically end up
in hashmaps. CreateInfo structs for these Vulkan objects can be recorded and replayed.
- VkSampler (immutable samplers in set layouts)
- VkDescriptorSetLayout
- VkPipelineLayout
- VkRenderPass
- VkShaderModule
- VkPipeline (compute/graphics)
The goal for this project is to cover some main use cases:
### High priority
- For internal engine use. Extend the notion of VkPipelineCache to also include these persistent objects,
so they can be automatically created in load time rather than manually declaring everything up front.
Ideally, this serialized cache could be shipped, and applications can assume all persistent objects are already created.
- Create a Vulkan layer which can capture this cache for repro purposes.
A paranoid mode would serialize the cache before every pipeline creation, to deal with crashing drivers.
- Easy way of sending shader compilation repros to conformance. Capture internally or via a Vulkan layer and send it off.
Normally, this is very difficult with normal debuggers because they generally rely on capturing frames or similar,
which doesn't work if compilation segfaults the driver. Shader compilation in Vulkan requires a lot of state,
which requires sending more complete repro applications.
### Mid priority
- Some convenience tools to modify/disassemble/spirv-opt parts of the cache.
### Low priority
- Serialize state in application once, replay on N devices to build up VkPipelineCache objects without having to run application.
- Benchmark a pipeline offline by feeding it fake input.
## Build
### Supported compilers
- GCC 4.8+
- Clang
- MSVC 2013/2015/2017+
If rapidjson is not already bundled in your project, you need to check out the submodules.
```
git submodule update --init
```
otherwise, you can set `FOSSILIZE_RAPIDJSON_INCLUDE_PATH` if building this library as part of your project.
It is also possible to use `FOSSILIZE_VULKAN_INCLUDE_PATH` to override Vulkan header include paths.
Normally, the CLI tools will be built. These require SPIRV-Tools and SPIRV-Cross submodules to be initialized, however, if you're only building Fossilize as a library/layer, you can use CMake options `-DFOSSILIZE_CLI=OFF` and `-DFOSSILIZE_TESTS=OFF` to disable all those requirements for submodules (assuming you have custom include path for rapidjson).
Standalone build:
```
mkdir build
cd build
cmake ..
cmake --build .
```
Link as part of other project:
```
add_subdirectory(fossilize EXCLUDE_FROM_ALL)
target_link_library(your-target fossilize)
```
For Android, you can use the `android_build.sh` script. It builds the layer for armeabi-v7a and arm64-v8a.
See the script for more details.
## Serialization format
Overall, a binary format which combines JSON with varint-encoded SPIR-V (light compression).
- Magic "FOSSILIZE0000001" (16 bytes ASCII)
- Size of entire binary (64-bit LE)
- JSON magic "JSON " (8 bytes ASCII)
- JSON size (64-bit LE)
- JSON data (JSON size bytes)
- SPIR-V magic "SPIR-V " (8 bytes ASCII)
- SPIR-V size (64-bit LE)
- Varint-encoded SPIR-V words (SPIR-V size bytes)
64-bit little-endian values are not necessarily aligned to 8 bytes.
The JSON is a simple format which represents the various `Vk*CreateInfo` structures.
`pNext` is currently not supported.
When referring to other VK handle types like `pImmutableSamplers` in `VkDescriptorSetLayout`, or `VkRenderPass` in `VkPipeline`,
a 1-indexed format is used. 0 represents `VK_NULL_HANDLE` and 1+, represents an array index into the respective array (off-by-one).
Data blobs (specialization constant data, SPIR-V) are encoded in base64, but I'll likely need something smarter to deal with large applications which have half a trillion SPIR-V files.
When recording or replaying, a mapping from and to real Vk object handles must be provided by the application so the offset-based indexing scheme can be resolved to real handles.
`VkShaderModuleCreateInfo` refers to an encoded buffer in the SPIR-V block by codeBinaryOffset and codeBinarySize.
The varint encoding scheme encodes every 32-bit SPIR-V word by encoding 7 bits at a time starting with the LSBs,
the MSB bit in an encoded byte is set if another byte needs to be read (7 bit) for the same SPIR-V word.
Each SPIR-V word takes from 1 to 5 bytes with this scheme.
## Sample API usage
### Recording state
```
// Note that fossilize.hpp will include Vulkan headers, so make sure you include vulkan.h before
// this one if you care about which Vulkan headers you use.
#include "fossilize.hpp"
void create_state()
{
try
{
Fossilize::StateRecorder recorder;
// TODO here: Add way to capture which extensions/physical device features were used to deal with exotic things
// which require extensions when making repro cases.
VkDescriptorSetLayoutCreateInfo info = {
VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO
};
// Fill in stuff.
Fossilize::Hash hash = Fossilize::Hashing::compute_hash_descriptor_set_layout(recorder, info);
// Or use your own hash. This 64-bit hash will be provided back to application when replaying the state.
// The builtin hashing functions are mostly useful for a Vulkan capturing layer, testing or similar.
unsigned set_index = recorder.register_descriptor_set_layout(hash, info);
vkCreateDescriptorSetLayout(..., &layout);
// Register the true handle of the set layout so that the recorder can map
// layout to an internal index when using register_pipeline_layout for example.
// Setting handles are only required when other Vk*CreateInfo calls refer to any other Vulkan handles.
recorder.set_descriptor_set_layout_handle(set_index, layout);
// Do the same for render passes, pipelines, shader modules, samplers (if using immutable samplers) as necessary.
std::vector<uint8_t> serialized = recorder.serialize();
save_to_disk(serialized);
}
catch (const std::exception &e)
{
// Can throw exception on API misuse.
}
}
```
### Replaying state
```
// Note that fossilize.hpp will include Vulkan headers, so make sure you include vulkan.h before
// this one if you care about which Vulkan headers you use.
#include "fossilize.hpp"
struct Device : Fossilize::StateCreatorInterface
{
// See header for other functions.
bool set_num_descriptor_set_layouts(unsigned count) override
{
// Know a-head of time how many set layouts there will be, useful for multi-threading.
return true;
}
bool enqueue_create_descriptor_set_layout(Hash hash, unsigned index,
const VkDescriptorSetLayoutCreateInfo *create_info,
VkDescriptorSetLayout *layout) override
{
// Can queue this up for threaded creation (useful for pipelines).
// create_info persists as long as Fossilize::Replayer exists.
VkDescriptorSetLayout set_layout = populate_internal_hash_map(hash, create_info);
// Let the replayer know how to fill in VkDescriptorSetLayout in upcoming pipeline creation calls.
// Can use dummy values here if we don't care about using the create_info structs verbatim.
*layout = set_layout;
return true;
}
void wait_enqueue() override
{
// If using multi-threaded creation, join all queued tasks here.
}
};
void replay_state(Device &device)
{
try
{
Fossilize::Replayer replayer;
replayer.parse(device, serialized_state, serialized_state_size);
// Now internal hashmaps are warmed up, and all pipelines have been created.
}
catch (const std::exception &e)
{
// Can throw exception on API misuse.
}
}
```
## Vulkan layer capture
Fossilize can also capture Vulkan application through the layer mechanism.
The layer name is `VK_LAYER_fossilize`.
To build, enable `FOSSILIZE_VULKAN_LAYER` CMake option. This is enabled by default.
The layer and JSON is placed in `layer/` in the build folder.
### Linux/Windows
By default the layer will serialize to `fossilize.json` in the working directory on `vkDestroyDevice`.
However, due to the nature of some drivers, there might be crashes in-between. For this, there are two other modes.
#### `export FOSSILIZE_PARANOID_MODE=1`
Before every call to `vkCreateComputePipelines` and `vkCreateGraphicsPipelines`, data is serialized to disk.
This can be quite slow for application with lots of pipelines, so only use it if the method below doesn't work ...
#### `export FOSSILIZE_DUMP_SIGSEGV=1`
This only works on Linux. A SIGSEGV handler is registered, and the state is serialized to disk in the segfault handler.
This is a bit sketchy, but should work well if drivers are crashing on pipeline creation (or just crashing in general).
On Windows, all `vkCreate*Pipelines` calls are always wrapped in SEH-style __try/__except blocks, which will catch access violations
specifically inside those calls. If an access violation is triggered, a safety serialization is performed,
a message box will appear, notifying user about this,
and immediately terminate the process after. This functionality however, is only enabled when building with MSVC,
as MinGW does not readily support the __try/__except extension. Patches welcome!
#### `export FOSSILIZE_DUMP_PATH=/my/custom/path`
Custom file path for capturing state.
### Android
By default the layer will serialize to `/sdcard/fossilize.json` on `vkDestroyDevice`.
However, this path might not be writeable, so you will probably have to override your path to something like
`/sdcard/Android/data/<package.name>/capture.json`.
Make sure your app has external write permissions if using the default path.
Due to the nature of some drivers, there might be crashes in-between. For this, there are two other modes.
Options can be set through `setprop`.
#### Setprop options
- `setprop debug.fossilize.dump_path /custom/path`
- `setprop debug.fossilize.paranoid_mode 1`
- `setprop debug.fossilize.dump_sigsegv 1`
To force layer to be enabled outside application: `setprop debug.vulkan.layers "VK_LAYER_fossilize"`.
The layer .so needs to be part of the APK for the loader to find the layer.
Use `adb logcat -s Fossilize` to isolate log messages coming from Fossilize.
You should see something like:
```
04-18 21:49:41.692 17444 17461 I Fossilize: Overriding serialization path: "/sdcard/fossilize.json".
04-18 21:49:43.741 17444 17461 I Fossilize: Serialized to "/sdcard/fossilize.json".
```
if capturing is working correctly.
## CLI
The CLI currently has 3 tools available. These are found in `cli/` after build.
### `fossilize-replay`
This tool is for taking a capture, and replaying it on any device.
Currently, all basic PhysicalDeviceFeatures (not PhysicalDeviceFeatures2 stuff) and extensions will be enabled
to make sure a capture will validate properly. robustBufferAccess however is forced off.
This tool serves as the main "repro" tool. After you have a capture, you should ideally be able to repro crashes using this tool.
To make replay faster, use `--filter-compute` and `--filter-graphics` to isolate which pipelines are actually compiled.
### `fossilize-disasm`
This tool can disassemble any pipeline into something human readable. Three modes are provided:
- ASM (using SPIRV-Tools)
- Vulkan GLSL (using SPIRV-Cross)
- AMD ISA (using `VK_AMD_shader_info` if available)
TODO is disassembling more of the other state for quick introspection. Currently only SPIR-V disassembly is provided.
### `fossilize-opt`
Runs spirv-opt over all shader modules in the capture and serializes out an optimized version.
Useful to sanity check that an optimized capture can compile on your driver.
### Android
Running the CLI apps on Android is also supported.
Push the binaries generated to `/data/local/tmp`, `chmod +x` them if needed, and use the binaries like regular Linux.
## Submit shader failure repro cases
TBD
## External modules
- [volk](https://github.com/zeux/volk)
- [rapidjson](https://github.com/miloyip/rapidjson)
- [SPIRV-Tools](https://github.com/KhronosGroup/SPIRV-Tools)
- [SPIRV-Cross](https://github.com/KhronosGroup/SPIRV-Cross)
|
3dbf00568153cefdfb96db6cb71d458f11f39d9b
|
{
"blob_id": "3dbf00568153cefdfb96db6cb71d458f11f39d9b",
"branch_name": "refs/heads/master",
"committer_date": "2019-03-18T09:22:16",
"content_id": "b16aa4c8871332dd063ccb54a105635c79b41eeb",
"detected_licenses": [
"MIT"
],
"directory_id": "d0e93c257b37e49e0290d9839aba5e8fad5fbf54",
"extension": "md",
"filename": "README.md",
"fork_events_count": 3,
"gha_created_at": "2018-04-01T11:36:58",
"gha_event_created_at": "2019-03-16T15:16:21",
"gha_language": "C",
"gha_license_id": "MIT",
"github_id": 127623621,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 12792,
"license": "MIT",
"license_type": "permissive",
"path": "/README.md",
"provenance": "stack-edu-markdown-0004.json.gz:3080",
"repo_name": "Themaister/Fossilize",
"revision_date": "2019-03-18T09:22:16",
"revision_id": "32434e89ee8cb963ccceb3ce49aa97d521500144",
"snapshot_id": "bca4ce41af9bf7735239d013411abb3a9cb9eddb",
"src_encoding": "UTF-8",
"star_events_count": 36,
"url": "https://raw.githubusercontent.com/Themaister/Fossilize/32434e89ee8cb963ccceb3ce49aa97d521500144/README.md",
"visit_date": "2020-03-07T17:53:28.439664",
"added": "2024-11-18T21:19:14.254603+00:00",
"created": "2019-03-18T09:22:16",
"int_score": 4,
"score": 3.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0004.json.gz"
}
|
package com.mao.shop.dao;
import java.util.List;
import java.util.Map;
import org.apache.solr.client.solrj.SolrQuery;
import com.mao.shop.po.Product;
import com.mao.shop.po.ProductInfo;
import com.mao.shop.po.SearchResult;
public interface ProductDao {
/**
* 根据上下架状态查询记录数
* @param showStatus
* @return
*/
int selectProductCount(Integer showStatus);
/**
* 根据上下架状态查询记录
* @param begin
* @param pageSize
* @param showStatus
* @return
*/
List<Product> selectBySaleStatusWithPage(int begin, int pageSize, Integer showStatus);
/**
* 保存商品信息
* @param product
*/
void saveProduct(Product product);
/**
* 查询商品信息,包括分类、品牌、图片、属性、销售单元和规格
* @param pid 商品id
* @return
*/
ProductInfo selectProductDetail(Integer pid);
/**
* 改变上下架状态
* @param pid
* @param i 0变为下架,1变为上架
*/
void updateShowStatus(Integer pid, int i);
/**
* 删除商品信息
* @param pId
*/
void deleteByPid(Integer pId);
/**
* 查询符合条件的商品
* @param begin
* @param pageSize
* @param map
* @return
*/
List<Product> selectProductByQuery(int begin, Integer pageSize, Map<String, Object> map);
/**
* 查询符合条件的商品数量
* @param map
* @return
*/
int selectCountByQuery(Map<String, Object> map);
/**
* 更新商品信息
* @param product
*/
void updateProduct(Product product);
/**
* 查询solr
* @param query
* @return
*/
SearchResult queryProduct(SolrQuery query) throws Exception;
/**
* 查询最贵的商品
* @return
*/
List<Product> selectExpensiveProduct();
/**
* 查询最新的商品
* @return
*/
List<Product> selectNewProduct();
/**
* 根据分类查询商品
* @param integer
* @return
*/
List<Product> selectByCsid(Integer integer);
}
|
53d473ee7c071a180ca58008917d76c9ee9bba05
|
{
"blob_id": "53d473ee7c071a180ca58008917d76c9ee9bba05",
"branch_name": "refs/heads/master",
"committer_date": "2016-12-22T08:17:32",
"content_id": "87ee43a77d45d8e95022d3851d6ba0e50e9ac952",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "fa99abaa6bff8037b91ec6e9a8d948cc9149e6e1",
"extension": "java",
"filename": "ProductDao.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 76917383,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1915,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/com/mao/shop/dao/ProductDao.java",
"provenance": "stack-edu-0025.json.gz:822285",
"repo_name": "jinshuilai/maoshop",
"revision_date": "2016-12-22T07:27:54",
"revision_id": "59856197516bf62476b747174ddd0fd078e3ca29",
"snapshot_id": "5f6c3b4a87bbe346eed5d7d7708aba9ce306765c",
"src_encoding": "GB18030",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jinshuilai/maoshop/59856197516bf62476b747174ddd0fd078e3ca29/src/com/mao/shop/dao/ProductDao.java",
"visit_date": "2021-01-12T05:33:05.321922",
"added": "2024-11-18T23:43:03.002566+00:00",
"created": "2016-12-22T07:27:54",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz"
}
|
import React, { Component } from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import logoImgSrc from 'img/home/family.jpg'
import nameScriptSrc from 'img/home/mark-foster-script.png'
import { colors, MAX_CONTENT_WIDTH } from 'Constants'
class Navbar extends Component {
render() {
return (
<Wrapper>
<LogoArea>
{/* <Logo src={logoImgSrc} /> */}
<Link to="/">
<Name src={nameScriptSrc} />
</Link>
</LogoArea>
<NavLinks>
<NavLink to="/">Home</NavLink>
<NavLink activeStyle={{ color: '#fb3640' }} to="/projects">
Projects
</NavLink>
</NavLinks>
</Wrapper>
)
}
}
export default Navbar
const Wrapper = styled.nav`
width: ${MAX_CONTENT_WIDTH};
max-width: 96%;
margin: 0 auto;
padding: 20px 0;
display: flex;
justify-content: space-between;
align-items: center;
`
const LogoArea = styled.div`
display: flex;
align-items: center;
`
const Logo = styled.img`
height: 80px;
width: 80px;
border-radius: 100%;
`
const Title = styled.div`
font-weight: 700;
font-size: 36px;
margin-left: 20px;
`
const Name = styled.img`
margin-left: 10px;
width: 276px;
margin-top: 10px;
`
const NavLinks = styled.ul``
const NavLink = styled(Link)`
margin: 0 10px;
opacity: 0.7;
color: ${colors.richBlack};
`
|
48feadcc6602b35695450a0582dc2f7d1e1198d7
|
{
"blob_id": "48feadcc6602b35695450a0582dc2f7d1e1198d7",
"branch_name": "refs/heads/master",
"committer_date": "2018-11-02T14:26:18",
"content_id": "b24954c60d0286fd21a718e1554a930a9d8d0d3a",
"detected_licenses": [
"MIT"
],
"directory_id": "b2315401608bdb7fe1c2c9e4ecd22c7d0a4493f0",
"extension": "js",
"filename": "Navbar.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 130229634,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1403,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/Navbar.js",
"provenance": "stack-edu-0045.json.gz:86492",
"repo_name": "markadamfoster/maf-gatsby-netlify",
"revision_date": "2018-11-02T14:26:18",
"revision_id": "dbb1272fea324d19bc98c43aa82daae732ca6e63",
"snapshot_id": "d1e6c26238f5e69410460eee06a7f3fa6fe55f29",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/markadamfoster/maf-gatsby-netlify/dbb1272fea324d19bc98c43aa82daae732ca6e63/src/components/Navbar.js",
"visit_date": "2020-03-11T20:10:18.326442",
"added": "2024-11-19T02:06:02.072690+00:00",
"created": "2018-11-02T14:26:18",
"int_score": 2,
"score": 2,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0063.json.gz"
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using Norika.Documentation.Core;
using Norika.Documentation.Core.FileSystem;
using Norika.Documentation.Core.FileSystem.Interfaces;
using Norika.Documentation.Core.Types;
using Norika.MsBuild.Core.Data;
using Norika.MsBuild.Core.Data.Help;
using Norika.MsBuild.DocumentationGenerator.Business.IO.Interfaces;
using Norika.MsBuild.DocumentationGenerator.Business.Logging;
using Norika.MsBuild.Model.Interfaces;
namespace Norika.MsBuild.DocumentationGenerator.Business
{
/// <summary>
/// Generator for format and printable msbuild project documentation
/// </summary>
/// <typeparam name="T">Output type for the generated documentation. Must implement <see cref="IPrintableDocument">IPrintableDocument</see>.</typeparam>
public class ProjectOverviewGenerator<T> where T : IPrintableDocument
{
/// <summary>
/// MsBuild project represented by the documentation generated by this class
/// </summary>
private readonly IMsBuildProject _msBuildProject;
/// <summary>
/// Target output document the generated documentation is written to
/// </summary>
private readonly IPrintableDocument _outputDocument;
/// <summary>
/// Builder for the target output document
/// </summary>
private readonly PrintableDocument<T> _printableDocumentBuilder;
/// <summary>
/// <inheritdoc cref="_outputDocument"/>
/// </summary>
internal IPrintableDocument OutputDocument => _outputDocument;
/// <summary>
/// Constructor
/// </summary>
/// <param name="project">MsBuild-Project file to generate the documentation for</param>
/// <param name="file">File object representing the msbuild project file</param>
public ProjectOverviewGenerator(IMsBuildProject project, IFile file)
{
_msBuildProject = project;
_printableDocumentBuilder = new PrintableDocument<T>(new FileWriter());
_outputDocument = CreateOutputDocument(file, _printableDocumentBuilder);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="project">MsBuild-Project file to generate the documentation for</param>
/// <param name="file">File object representing the msbuild project file</param>
/// <param name="printableDocument">Object representing output documentation file</param>
public ProjectOverviewGenerator(IMsBuildProject project, IFile file, PrintableDocument<T> printableDocument)
{
_msBuildProject = project;
_printableDocumentBuilder = printableDocument;
_outputDocument = CreateOutputDocument(file, _printableDocumentBuilder);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="file">File object representing the msbuild project file</param>
public ProjectOverviewGenerator(IFile file)
{
var formattableDocumentBuilder = new PrintableDocument<T>();
_msBuildProject = LoadMsBuildProject(file);
_outputDocument = CreateOutputDocument(file, formattableDocumentBuilder);
_printableDocumentBuilder = formattableDocumentBuilder;
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="file">File object representing the msbuild project file</param>
/// <param name="documentBuilder">Factory for creating the output documentation file</param>
public ProjectOverviewGenerator(IFile file, IFormattableDocumentBuilder documentBuilder)
{
_printableDocumentBuilder = new PrintableDocument<T>(documentBuilder);
_msBuildProject = LoadMsBuildProject(file);
_outputDocument = CreateOutputDocument(file, _printableDocumentBuilder);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="file">File object representing the msbuild project file</param>
/// <param name="fileWriter">Writer used for creating the output documentation</param>
/// <param name="documentBuilder">Factory for creating the output documentation file</param>
public ProjectOverviewGenerator(IFile file, IFileWriter fileWriter, IFormattableDocumentBuilder documentBuilder)
{
_printableDocumentBuilder = new PrintableDocument<T>(documentBuilder, fileWriter);
_msBuildProject = LoadMsBuildProject(file);
_outputDocument = CreateOutputDocument(file, _printableDocumentBuilder);
}
/// <summary>
/// Constructor
/// </summary>
/// <param name="file">File object representing the msbuild project file</param>
/// <param name="printableDocument">Object representing output documentation file</param>
public ProjectOverviewGenerator(IFile file, PrintableDocument<T> printableDocument)
{
_printableDocumentBuilder = printableDocument;
_msBuildProject = LoadMsBuildProject(file);
_outputDocument = CreateOutputDocument(file, _printableDocumentBuilder);
}
/// <summary>
/// Creates the documentations body content
/// </summary>
/// <returns>True if the documentation has been created successfully</returns>
public bool CreateBody()
{
try
{
var properties = _msBuildProject.GetChildren<IMsBuildProperty>();
var targets = _msBuildProject.GetChildren<IMsBuildTarget>();
AppendGlobalPropertySection(properties);
AppendPropertySection(properties);
AppendTargetSection(targets);
//CreateTargetOverviewFiles(targets);
return true;
}
catch (Exception ex)
{
Log.WriteError(ex);
return false;
}
}
/// <summary>
/// <inheritdoc cref="IPrintableDocument.Print"/>
/// </summary>
/// <returns></returns>
public string Print()
{
return _outputDocument.Print();
}
/// <summary>
/// Loads the content as MSBuild project from the given file
/// </summary>
/// <param name="file">File from which the content should be loaded</param>
/// <returns>MSBuild project representation</returns>
private IMsBuildProject LoadMsBuildProject(IFile file)
{
return MsBuildProjectFile.LoadContent(file.ReadAllText());
}
/// <summary>
/// Creates the output file from the document builder for the given generic type.
/// </summary>
/// <param name="file">The file for which the output documentation file should be created</param>
/// <param name="printableDocument">The document builder which is used for creating the output file</param>
/// <returns>Instance of the requested generic type</returns>
private IPrintableDocument CreateOutputDocument(IFile file, PrintableDocument<T> printableDocument)
{
return printableDocument.Create(file.FileName);
}
/// <summary>
/// Appends a section to the documentation body containing all information about
/// the given targets. Therefore a table is created containing a row per target.
/// </summary>
/// <param name="targets">List of targets that should be represented by the section.</param>
private void AppendTargetSection(IList<IMsBuildTarget> targets)
{
if (targets.Count == 0) return;
IPrintableDocumentChapter targetsChapter = _outputDocument.AddNewChapter("Targets");
IPrintableDocumentChapterStringContent paragraph =
targetsChapter.AddNewContent<IPrintableDocumentChapterStringContent>();
paragraph.Content =
$"Contains all msbuild targets in {_outputDocument.Title}, ordered by name ascending.";
var propertyTable = targetsChapter.AddNewContent<IPrintableParagraphTable>();
propertyTable.WithHeaders("Target", "Description");
foreach (var target in targets.OrderBy(t => t.Name))
{
propertyTable.WithRow(CreateHyperlinkForTargetOverviewFile(target).Print(),
string.Join(" ", GetPropertySynopsisOrDescription(target)?.Content));
}
}
/// <summary>
/// Creates a hyperlink to a dedicated overview file representing the target target located
/// in a sub directory of the destination documentation directory.
/// </summary>
/// <param name="target">Target for which the hyperlink should be created</param>
/// <returns>ParagraphHyperlink linking to the dedicated target documentation site</returns>
private IPrintableDocumentParagraphHyperlink CreateHyperlinkForTargetOverviewFile(IMsBuildTarget target)
{
IPrintableDocumentParagraphHyperlink paragraphHyperLink =
_outputDocument.CreateElement<IPrintableDocumentParagraphHyperlink>();
paragraphHyperLink.DisplayString = target.Name;
paragraphHyperLink.Hyperlink = Path.Combine(".", "Targets",
string.Format(CultureInfo.InvariantCulture, "{0}.{1}", target.Name,
_outputDocument.DefaultFileExtension));
paragraphHyperLink.ToolTip =
string.Format(CultureInfo.CurrentCulture, "See more about the target {0}.", target.Name);
return paragraphHyperLink;
}
/// <summary>
/// Appends a section to the documentation body containing all information about
/// the given properties. Only properties are considered that are not settable from
/// outside the MSBuild target file.
/// </summary>
/// <param name="properties">List of properties that should be represented by the section</param>
private void AppendPropertySection(IList<IMsBuildProperty> properties)
{
if (properties == null || properties.All(p => p.HasPublicSetter)) return;
var propertyChapter = _outputDocument.AddNewChapter("Properties");
IPrintableDocumentChapterStringContent paragraph =
propertyChapter.AddNewContent<IPrintableDocumentChapterStringContent>();
paragraph.Content =
$"Contains all not settable properties in {_outputDocument.Title}.";
var propertyTable = propertyChapter.AddNewContent<IPrintableParagraphTable>();
propertyTable.WithHeaders("Property", "Description", "Condition");
foreach (var property in properties.Where(p => !p.HasPublicSetter))
propertyTable.WithRow(property.Name,
string.Join(" ", GetPropertySynopsisOrDescription(property)?.Content),
property.Condition);
}
/// <summary>
/// Appends a section to the documentation body containing all information about
/// the given properties. Only properties are considered that are settable from
/// outside the MSBuild target file.
/// </summary>
/// <param name="properties">List of properties that should be represented by the section</param>
private void AppendGlobalPropertySection(IList<IMsBuildProperty> properties)
{
if (properties == null || !properties.Any(p => p.HasPublicSetter)) return;
var propertyChapter = _outputDocument.AddNewChapter("Overwriteable Properties");
IPrintableDocumentChapterStringContent paragraph =
propertyChapter.AddNewContent<IPrintableDocumentChapterStringContent>();
paragraph.Content =
$"Contains all properties in {_outputDocument.Title} that could be overwritten from outside the document.";
var propertyTable = propertyChapter.AddNewContent<IPrintableParagraphTable>();
propertyTable.WithHeaders("Property", "Description", "Condition");
foreach (var property in properties.Where(p => p.HasPublicSetter))
propertyTable.WithRow(property.Name,
string.Join(Environment.NewLine, GetPropertySynopsisOrDescription(property)?.Content),
property.Condition);
}
/// <summary>
/// Returns synopsis of the given MsBuild element. When no synopsis is defined it returns the
/// description, shortened to the first description paragraph.
/// </summary>
/// <param name="node">MsBuildNode to get the synopsis or description for.</param>
/// <returns>HelpParagraph object representing the synopsis or description of the MsBuild Node</returns>
/// Todo: Implementing the "shortening" thing addressed by the summary
private static IMsBuildElementHelpParagraph GetPropertySynopsisOrDescription(IMsBuildElement node)
{
if (node.Help.Count == 0) return null;
if (node.Help.ContainsSection(MsBuildHelpSections.Synopsis, StringComparison.OrdinalIgnoreCase))
{
return node.Help.LookUp(MsBuildHelpSections.Synopsis,
StringComparison.OrdinalIgnoreCase).FirstOrDefault();
}
if (node.Help.ContainsSection(MsBuildHelpSections.Description, StringComparison.OrdinalIgnoreCase))
{
return node.Help.LookUp(MsBuildHelpSections.Description,
StringComparison.OrdinalIgnoreCase).FirstOrDefault();
}
return default;
}
}
}
|
a75a21e1dba50472cae1806da165f027502bf1b7
|
{
"blob_id": "a75a21e1dba50472cae1806da165f027502bf1b7",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-11T13:24:21",
"content_id": "99abacc2d4735e2b0b549694dd3065099e95650b",
"detected_licenses": [
"MIT"
],
"directory_id": "2bb91465d40aaf282c476a067800af38decfcca8",
"extension": "cs",
"filename": "ProjectOverviewGenerator.cs",
"fork_events_count": 0,
"gha_created_at": "2019-11-07T07:29:37",
"gha_event_created_at": "2021-01-29T20:37:22",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 220177012,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 13870,
"license": "MIT",
"license_type": "permissive",
"path": "/Source/Norika.MsBuild.DocumentationGenerator.Business/ProjectOverviewGenerator.cs",
"provenance": "stack-edu-0012.json.gz:719857",
"repo_name": "NorikaDE/MsBuild-DocumentationGenerator",
"revision_date": "2020-01-11T13:24:21",
"revision_id": "9efc8fcf527315d301142d8072bfb39d170ee5e1",
"snapshot_id": "48f9cccb07e888a97e9dc1cc530549dd68e5bff0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/NorikaDE/MsBuild-DocumentationGenerator/9efc8fcf527315d301142d8072bfb39d170ee5e1/Source/Norika.MsBuild.DocumentationGenerator.Business/ProjectOverviewGenerator.cs",
"visit_date": "2021-07-03T13:45:46.205364",
"added": "2024-11-18T19:50:47.115696+00:00",
"created": "2020-01-11T13:24:21",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0030.json.gz"
}
|
/***************************************************************************
* Copyright (C) 2005 by *
* Pedro J. Fernandez Ruiz [email protected] *
* Alejandro Perez Mendez [email protected] *
* *
* This software may be modified and distributed under the terms *
* of the Apache license. See the LICENSE file for details. *
***************************************************************************/
#include "logimpltext.h"
#include <stdio.h>
namespace openikev2 {
LogImplText::LogImplText() : LogImplOpenIKE() {}
void LogImplText::writeMessage( string who, string message, uint16_t type, bool main_info ) {
// Check the mask
if ( !( type & this->log_mask ) )
return;
// Gets the current time
time_t t;
time( &t );
// Stores current time into time_str
string time_str = ctime( &t );
// Changes final \n with a \0
time_str.replace( time_str.size() - 1, 1, "\0" );
// Inserts date if desired
if ( main_info ){
message = "[" + time_str + "] [" + Log::LOG_TYPE_STR( type ) + "] " + who + ": " + message + "\n";
fprintf( log_file, "%s", message.c_str() );
}
else if ( this->show_extra_info ) {
message = message + "\n";
fprintf( log_file, "%s", message.c_str() );
}
}
LogImplText::~LogImplText() {}
}
|
27fc1d074e2f406b305dff0fb2628635bad98334
|
{
"blob_id": "27fc1d074e2f406b305dff0fb2628635bad98334",
"branch_name": "refs/heads/master",
"committer_date": "2020-03-20T16:29:37",
"content_id": "218f83cdce1a9e791f78208e49a86454714b843c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9ffe2a39ebbf0338f89a747caa3b4bae84fbdcf9",
"extension": "cpp",
"filename": "logimpltext.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 83554376,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1604,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/logimpltext.cpp",
"provenance": "stack-edu-0007.json.gz:497159",
"repo_name": "OpenIKEv2/libopenikev2_impl",
"revision_date": "2020-03-20T16:29:37",
"revision_id": "3c620ca479b20814fe42325cffcfd1d18dbf041c",
"snapshot_id": "59b1ed2c9cbe3b6e931b14818336eb359db620cf",
"src_encoding": "UTF-8",
"star_events_count": 5,
"url": "https://raw.githubusercontent.com/OpenIKEv2/libopenikev2_impl/3c620ca479b20814fe42325cffcfd1d18dbf041c/src/logimpltext.cpp",
"visit_date": "2021-01-17T16:02:24.374158",
"added": "2024-11-18T22:52:03.150825+00:00",
"created": "2020-03-20T16:29:37",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0025.json.gz"
}
|
package com.skubit.comics.loaders;
import com.skubit.shared.dto.ImageType;
import com.skubit.shared.dto.UrlDto;
import android.content.Context;
import java.io.IOException;
import java.util.ArrayList;
public class ScreenshotsLoader extends BaseComicServiceLoader<ArrayList<UrlDto>> {
private final String mCbid;
public ScreenshotsLoader(Context context, String cbid) {
super(context, null, null, null);
mCbid = cbid;
}
@Override
protected void closeStream() throws IOException {
}
@Override
public ArrayList<UrlDto> loadInBackground() {
try {
return mComicService.getScreenshotsDownload(mCbid, ImageType.WEBP);
} catch (Exception e) {
// e.printStackTrace();
}
return new ArrayList<>();
}
}
|
5058ec4eb8a2272704888d00b7dab6112d204d5c
|
{
"blob_id": "5058ec4eb8a2272704888d00b7dab6112d204d5c",
"branch_name": "refs/heads/master",
"committer_date": "2015-09-21T01:43:54",
"content_id": "acd7285b0d96975e10234ab6f5c1d8936673f50c",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "f3bfc15013a872d103b9f80dca9aa576fb02c653",
"extension": "java",
"filename": "ScreenshotsLoader.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 31020446,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 807,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/com/skubit/comics/loaders/ScreenshotsLoader.java",
"provenance": "stack-edu-0027.json.gz:838474",
"repo_name": "skubit/skubit-comics",
"revision_date": "2015-09-21T01:43:54",
"revision_id": "7b798b741a3f17df303704911f563070f666eec2",
"snapshot_id": "1ec0f9e94dfa19b4aab0da17f77e0948e32fafeb",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/skubit/skubit-comics/7b798b741a3f17df303704911f563070f666eec2/app/src/main/java/com/skubit/comics/loaders/ScreenshotsLoader.java",
"visit_date": "2016-09-07T19:01:48.669148",
"added": "2024-11-19T01:12:32.019406+00:00",
"created": "2015-09-21T01:43:54",
"int_score": 2,
"score": 2.046875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0045.json.gz"
}
|
package corbaserver;
import example.fibonacciPOA;
public class FiboImpl extends fibonacciPOA {
@Override
public String generar(int numero) {
String cadena = "";
for (int i = 1; i <= numero; i++) {
double raiz = Math.sqrt(5);
int rta = (int) ((1 / raiz) * (Math.pow((1 + raiz) / 2, i)) - (1 / raiz) * (Math.pow((1 - raiz) / 2, i)));
cadena += Math.round(rta) + " ";
}
return cadena;
}
}
|
95af8d51490c0c119e912389bd9d8185c58c435e
|
{
"blob_id": "95af8d51490c0c119e912389bd9d8185c58c435e",
"branch_name": "refs/heads/master",
"committer_date": "2019-05-28T06:47:15",
"content_id": "84b5bf10234b5e32d355555ed068d0269db53d34",
"detected_licenses": [
"MIT"
],
"directory_id": "72280f4e6329a89808b68d0aebeb9372f95b37c5",
"extension": "java",
"filename": "FiboImpl.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 188609422,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 474,
"license": "MIT",
"license_type": "permissive",
"path": "/CorbaServer/src/corbaserver/FiboImpl.java",
"provenance": "stack-edu-0024.json.gz:792128",
"repo_name": "parrol/CORBA",
"revision_date": "2019-05-28T06:47:15",
"revision_id": "aa7b3d0aa2fe4923a6a0522f040d7cbda87250c4",
"snapshot_id": "00d8a5b5a1205514ea723a3979dde844d2a44fec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/parrol/CORBA/aa7b3d0aa2fe4923a6a0522f040d7cbda87250c4/CorbaServer/src/corbaserver/FiboImpl.java",
"visit_date": "2020-05-27T11:55:55.810556",
"added": "2024-11-18T22:58:07.664853+00:00",
"created": "2019-05-28T06:47:15",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0042.json.gz"
}
|
<?php
/**
* File: WhereLogic.php
*/
namespace SmartPDO\Parameters;
/**
* Default parameters for a WHERE
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
*/
class WhereLogic
{
/**
* statement logic AND
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @var bool
*/
protected $and = false;
/**
* Column name
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @var string
*/
protected $column;
/**
* Flag for IS NOT
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @var bool
*/
protected $not = false;
/**
* Table name
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @var string
*/
protected $table;
/**
* Get the column name
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @return string
*/
public function getColumn()
{
return $this->column;
}
/**
* Get the table name
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @return string
*/
public function getTable()
{
return $this->table;
}
/**
* Check if ordering ascending or descending
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @return bool
*/
public function isAnd()
{
return $this->and === true;
}
/**
* Check if condition is inverted: IS NOT
*
* @version 1.1
* @author Rick de Man <[email protected]>
*
* @return bool
*/
public function isNot()
{
return $this->not === true;
}
}
|
0834f4434d667d0c21cf3d128f77a0cdd50183ce
|
{
"blob_id": "0834f4434d667d0c21cf3d128f77a0cdd50183ce",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-19T19:11:40",
"content_id": "a5547aab27295706aae1e21a55cb009f4048c9f3",
"detected_licenses": [
"MIT"
],
"directory_id": "e272a9b02aa418e12dab4067d2426936ad4da259",
"extension": "php",
"filename": "WhereLogic.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 87424657,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1626,
"license": "MIT",
"license_type": "permissive",
"path": "/src/SmartPDO/Parameters/WhereLogic.php",
"provenance": "stack-edu-0051.json.gz:112076",
"repo_name": "Rickdeman/smart-pdo",
"revision_date": "2019-06-19T19:11:40",
"revision_id": "7cf7e5101d1618b884da790060d69883c9c7f899",
"snapshot_id": "f4a7d3e46b6f51f20b8e6464191c3f8b2882b2d5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Rickdeman/smart-pdo/7cf7e5101d1618b884da790060d69883c9c7f899/src/SmartPDO/Parameters/WhereLogic.php",
"visit_date": "2023-08-11T02:55:21.631076",
"added": "2024-11-19T02:23:24.365304+00:00",
"created": "2019-06-19T19:11:40",
"int_score": 3,
"score": 3.015625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
package org.nutz.pay.bean.biz;
/**
* 在传分账标记的情况下,若传子商户号,子商户商品金额必传,即goods字段中每个元素中subMerchantId与subOrderAmount不能为空,元素不能超过20个。
* (goods里所有子商户商品总额要与支付总额totalAmount相等)。
* Created by Jianghao on 2018/12/15
*
* @howechiang
*/
public class Good {
/**
* 商品ID
*/
private String goodsId;
public String getGoodsId() {
return goodsId;
}
public void setGoodsId(String goodsId) {
this.goodsId = goodsId;
}
/**
* 商品名称
*/
private String goodsName;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
/**
* 商品数量
*/
private Integer quantity;
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
/**
* 商品单价(分)
*/
private Integer price;
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
/**
* 商品分类
*/
private String goodsCategory;
public String getGoodsCategory() {
return goodsCategory;
}
public void setGoodsCategory(String goodsCategory) {
this.goodsCategory = goodsCategory;
}
/**
* 商品说明
*/
private String body;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
/**
* 子商户号
*/
private String subMerchantId;
public String getSubMerchantId() {
return subMerchantId;
}
public void setSubMerchantId(String subMerchantId) {
this.subMerchantId = subMerchantId;
}
/**
* 子商户商品总额
*/
private Integer subOrderAmount;
public Integer getSubOrderAmount() {
return subOrderAmount;
}
public void setSubOrderAmount(Integer subOrderAmount) {
this.subOrderAmount = subOrderAmount;
}
/**
* 商品折扣
* 单位:分
*/
private Integer discount;
public Integer getDiscount() {
return discount;
}
public void setDiscount(Integer discount) {
this.discount = discount;
}
}
|
b2be9e37b9ef8b190629ae8f9a55abf5eb42adce
|
{
"blob_id": "b2be9e37b9ef8b190629ae8f9a55abf5eb42adce",
"branch_name": "refs/heads/master",
"committer_date": "2020-04-30T04:15:46",
"content_id": "ceafe10bdaab077de75dfa5d23b4fee0ca7ad7f3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "ccd57d61437e673333428f499a20bb8f855141b7",
"extension": "java",
"filename": "Good.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2480,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/org/nutz/pay/bean/biz/Good.java",
"provenance": "stack-edu-0022.json.gz:844762",
"repo_name": "hi-noikiy/nutz-pay",
"revision_date": "2020-04-30T04:15:46",
"revision_id": "68333ec25bc72240a9456b0ff1c0d59900977b8f",
"snapshot_id": "76bc92cf2d2b108f28a796e1a6d0aa25aff9fdb5",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/hi-noikiy/nutz-pay/68333ec25bc72240a9456b0ff1c0d59900977b8f/src/main/java/org/nutz/pay/bean/biz/Good.java",
"visit_date": "2022-12-20T14:40:39.119250",
"added": "2024-11-19T01:36:21.036539+00:00",
"created": "2020-04-30T04:15:46",
"int_score": 2,
"score": 2.5,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
import math
import numpy as np
from ev3sim.objects.base import objectFactory
from ev3sim.simulation.world import World
class InfraredSensorMixin:
device_type = 'lego-sensor'
ALL_VALUES = 'AC-ALL'
DIRECTION = 'AC'
mode = ALL_VALUES
# Left to Right, bearing relative to middle.
SENSOR_BEARINGS = [
np.pi/3,
np.pi/6,
0,
-np.pi/6,
-np.pi/3,
]
SENSOR_BEARING_DROPOFF_MAX = np.pi/4
MAX_SENSOR_RANGE = 120
MAX_STRENGTH = 9
def _sensorStrength(self, relativeBearing, distance):
while relativeBearing > np.pi:
relativeBearing -= 2*np.pi
while relativeBearing < -np.pi:
relativeBearing += 2*np.pi
if distance > self.MAX_SENSOR_RANGE:
return 0
if abs(relativeBearing) > self.SENSOR_BEARING_DROPOFF_MAX:
return 0
# At halfway to the sensor, this value is 1/4.
sq_dist = pow(distance / self.MAX_SENSOR_RANGE, 2)
exclude_bearing = (1 - sq_dist) * 9
bearing_mult = 1 - abs(relativeBearing) / self.SENSOR_BEARING_DROPOFF_MAX
return int(math.floor(exclude_bearing * bearing_mult + 0.5))
def _sensorValues(self, relativeBearing, distance):
return [
self._sensorStrength(relativeBearing-b, distance)
for b in self.SENSOR_BEARINGS
]
def _predict(self, sensorValues):
total = sum(sensorValues)
if total <= 4:
return 0
weighted = sum([
i*v / total
for i, v in enumerate(sensorValues)
])
# weighted is between 0 and len(sensorValues)-1.
return int(max(min(1 + math.floor(weighted / (len(sensorValues)-1) * 9), 9), 1))
def _getObjName(self, port):
return 'sensor' + port
def applyWrite(self, attribute, value):
if attribute == 'mode':
self.mode = value
else:
raise ValueError(f'Unhandled write! {attribute} {value}')
def toObject(self):
data = {
'address': self._interactor.port,
'driver_name': 'ht-nxt-ir-seek-v2',
'mode': self.mode,
}
if self.mode == self.ALL_VALUES:
for x in range(7):
data[f'value{x}'] = self.value(x)
elif self.mode == self.DIRECTION:
data['value0'] = self.value(0)
else:
raise ValueError(f'Unhandled mode {self.mode}')
return data
|
16378235e5b9543739de5c851ed3ca3c44e6821c
|
{
"blob_id": "16378235e5b9543739de5c851ed3ca3c44e6821c",
"branch_name": "refs/heads/main",
"committer_date": "2020-09-04T22:47:22",
"content_id": "f080a1c09dd6bc2d2c52fd741e4036231ae7bb6b",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "9bd6acdcba3fe0eaa414f075a5f7ab987d9395c0",
"extension": "py",
"filename": "base.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2476,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/ev3sim/devices/infrared/base.py",
"provenance": "stack-edu-0063.json.gz:331956",
"repo_name": "atendulkar20/ev3sim",
"revision_date": "2020-09-04T22:47:22",
"revision_id": "b5c46309b9964c3b543e6d563907c8fbfa09e305",
"snapshot_id": "a540e7a873e08748ed844f45ec4c4e8f396d5320",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/atendulkar20/ev3sim/b5c46309b9964c3b543e6d563907c8fbfa09e305/ev3sim/devices/infrared/base.py",
"visit_date": "2022-12-14T14:40:47.258591",
"added": "2024-11-19T00:43:44.646866+00:00",
"created": "2020-09-04T22:47:22",
"int_score": 3,
"score": 2.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0081.json.gz"
}
|
---
title: British Museum object catalog
publisher: British Museum
categories:
- History
size: Huge
size_description: "More than 2 million+ object records. Around 800,000 have images."
licenses:
- "T+C"
licence_description: "Non-commercial and research use only under a [British Museum specific open license](http://collection.britishmuseum.org/licensing.html). Images are under a different license."
media: text
formats:
- RDF
- SPARQL
- JSON
- XML
update_frequency: Daily
contact_information: "Queries about the database, e-mail [collectiondatabase<EMAIL_ADDRESS>Issues to [[email protected]](mailto:[email protected])"
score: 5
link: "http://collection.britishmuseum.org/"
published: true
---
The British Museum was the first national public museum in the world - founded in 1753 - and remains one of the most famous museums in the World. Its collections contain over 8 million objects spanning the history of the world's cultures: from [carvings of reindeer from 13,0000BC](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=808748&partId=1) to [cardboard models of computer monitors from Singapore](http://www.britishmuseum.org/research/collection_online/collection_object_details.aspx?objectId=3028508&partId=1&images=true&from=ad&fromDate=2000&sortBy=fromDateDesc&page=16).
The museum holds over 3 million individual objects in its collection, around 2 million of which are represented within this database. 800,000+ have images - but these are provided under different licenses depending on use.
There is a [web interface to search the collection](http://www.britishmuseum.org/research/collection_online/search.aspx) to get a feel for the content of the data. The collection database also returns HTML representations - for example <http://collection.britishmuseum.org/resource?uri=http://collection.britishmuseum.org/id/object/EOC3130> is the entry for _Hoa Hakananai'a_, a Rapanui (Easter Island) statue.
## Technical Details ##
The data is modelled using the [CIDOC schema](http://www.cidoc-crm.org) in an RDF format, and there is a [SPARQL endpoint](http://collection.britishmuseum.org/sparql) available. This is a REST interfaces, which can provide both JSON and CSV files; there are some pre-defined example queries you can use, a longer example at http://tinyurl.com/ntwm7d6, and a full exemplar AngularJS front end at http://collection.britishmuseum.org/angularsparqldemo/ with the Angular and Django source available at stash.researchspace.org/scm/an/angularsparqldemo.git.
As per the [help page](http://collection.britishmuseum.org/help.html), the SPARQL endpoint can be called to return XML or JSON representations from SELECT queries, and RDF/XML, Turtle and NTriple from CONSTRUCT queries.
<http://collection.britishmuseum.org/sparql.xml?query=> returns xml (in the browser this is a downloadable file)
<http://collection.britishmuseum.org/sparql.json?query=> returns json
The help page also details the URI scheme. Static [data dumps](http://collection.britishmuseum.org/dumps/) are available.
|
3d0f12b4587d1edf520ff1800b1e59007a811b4d
|
{
"blob_id": "3d0f12b4587d1edf520ff1800b1e59007a811b4d",
"branch_name": "refs/heads/master",
"committer_date": "2017-01-21T16:53:39",
"content_id": "0a07ffd9589e2811e43777ec10629e6b782b08b3",
"detected_licenses": [
"MIT"
],
"directory_id": "f36e51f25ec8e91b468b8941dfb29365e89a8448",
"extension": "md",
"filename": "37251018-British-Museum-object-catalog.md",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3149,
"license": "MIT",
"license_type": "permissive",
"path": "/sources/37251018-British-Museum-object-catalog.md",
"provenance": "stack-edu-markdown-0010.json.gz:63690",
"repo_name": "mashtheweb/data-tool",
"revision_date": "2017-01-21T16:53:39",
"revision_id": "799d05988c94615eabcca1138bcf05dd07f769e9",
"snapshot_id": "f3c47c90c7cc98f5551dac6f02ef568607f72dec",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/mashtheweb/data-tool/799d05988c94615eabcca1138bcf05dd07f769e9/sources/37251018-British-Museum-object-catalog.md",
"visit_date": "2021-01-22T05:43:26.155393",
"added": "2024-11-18T22:19:50.999951+00:00",
"created": "2017-01-21T16:53:39",
"int_score": 3,
"score": 2.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0010.json.gz"
}
|
/*
* @(#)FractionalExponentElimination.java
*
* $Date: 2014-11-27 07:55:25 +0100 (Do, 27 Nov 2014) $
*
* Copyright (c) 2013 by Jeremy Wood.
* All rights reserved.
*
* The copyright of this software is owned by Jeremy Wood.
* You may not use, copy or modify this software, except in
* accordance with the license agreement you entered into with
* Jeremy Wood. For details see accompanying license terms.
*
* This software is probably, but not necessarily, discussed here:
* https://javagraphics.java.net/
*
* That site should also contain the most recent official version
* of this software. (See the SVN repository for more details.)
*/
package com.bric.math.symbolic;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/** This is an abstract framework to apply a transform to remove the fractional exponents from a zeroed expression.
*/
public abstract class FractionalExponentElimination implements FEEConstants {
private static void validateVariableNames(Expression e,String... illegalVariableNames) {
Set<String> vars = e.getVariables();
for(String s : illegalVariableNames) {
if(vars.contains(s))
throw new IllegalArgumentException("the variable name \""+s+"\" is reserved");
}
}
/** The original zeroed expression before this transform was applied. */
public final Expression originalExpression;
/** The new zeroed expression after this transform was applied. */
public final Expression resultingExpression;
/** The variable we need to transform. */
public final String variableName;
/** Create a FractionalExponentElimination.
*
* @param degree the degree this transform applies to.
* @param zeroedExpression an expression equal to zero to transform.
* @param variableName the variable to transform.
*/
public FractionalExponentElimination(int degree, Expression zeroedExpression,String variableName) {
if(degree<=1) throw new IllegalArgumentException("degree = "+degree);
validateVariableNames(zeroedExpression, K);
validateVariableNames(zeroedExpression, C);
this.variableName = variableName;
this.originalExpression = zeroedExpression;
zeroedExpression = zeroedExpression.eliminateFractions().quotient;
Map<Fraction, List<Term>> f = zeroedExpression.factor(variableName);
/** Each array element is for k^(index/degree) terms */
Expression[] e = new Expression[degree];
for(int a = 0; a<e.length; a++) {
e[a] = new Expression();
}
Iterator<Fraction> powers = f.keySet().iterator();
while(powers.hasNext()) {
Fraction power = powers.next();
Expression phrase = new Expression(f.get(power));
Fraction z = power.multiply(Fraction.get(degree));
if(!z.isInteger())
throw new IllegalArgumentException("identified a power that is not a factor of degree ("+power+")");
int i = z.intValue();
int mod = i%degree;
int div = i/degree;
if(div>0) {
phrase = phrase.multiply(new Term(variableName, Fraction.get(div)));
}
e[mod] = e[mod].add(phrase);
}
Expression k = new Expression(new Term(variableName));
try {
Expression result = getFormula();
List<Definition> allSubstitutions = new ArrayList<Definition>();
for(int a = 0; a<degree; a++) {
allSubstitutions.add(new Definition(C[a], e[a]));
}
allSubstitutions.add(new Definition(K, k));
resultingExpression = result.substitute(allSubstitutions.toArray(new Definition[allSubstitutions.size()]));
} catch(IllegalSubstitutionException e2) {
throw new IllegalArgumentException("could not transform this expression", e2);
}
}
/** @return the formula this elimination/transformation applies, stated in terms of FEEConstants. */
protected abstract Expression getFormula();
}
|
2b54701d13f160fc1a3d80d5107af347e51c1fab
|
{
"blob_id": "2b54701d13f160fc1a3d80d5107af347e51c1fab",
"branch_name": "refs/heads/master",
"committer_date": "2017-08-05T20:14:32",
"content_id": "9b8db578ec9ec4c0881956032d253d018a63f7cd",
"detected_licenses": [
"BSD-3-Clause"
],
"directory_id": "441b55ee7203f6ab4cb9df2decc085d8cf519351",
"extension": "java",
"filename": "FractionalExponentElimination.java",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 48960911,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3785,
"license": "BSD-3-Clause",
"license_type": "permissive",
"path": "/src/main/java/com/bric/math/symbolic/FractionalExponentElimination.java",
"provenance": "stack-edu-0025.json.gz:576832",
"repo_name": "javagraphics/main",
"revision_date": "2017-08-05T20:14:32",
"revision_id": "582aada63bfe936e0b49a9d105099401c06d6225",
"snapshot_id": "0925234fc84100b499cf5fcbf60fa544f249530d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/javagraphics/main/582aada63bfe936e0b49a9d105099401c06d6225/src/main/java/com/bric/math/symbolic/FractionalExponentElimination.java",
"visit_date": "2021-01-10T08:56:29.915157",
"added": "2024-11-19T01:21:10.728626+00:00",
"created": "2017-08-05T20:14:32",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0043.json.gz"
}
|
/**
* Compares two strings and returns the result.
* @param {*} a The first string.
* @param {*} b The second string.
*/
function stringCompare(a, b) {
if (a > b) {
return 1;
}
if (a < b) {
return -1;
}
return 0;
}
/**
* Sorts an object's keys and returns the result.
* @param {*} obj The object with keys to be sorted.
*/
function sortedKeys(obj) {
return Object.keys(obj).sort(stringCompare);
}
module.exports = {
stringCompare,
sortedKeys
};
|
c863b7da2dd069e9b2857200ffa38c953f619e5d
|
{
"blob_id": "c863b7da2dd069e9b2857200ffa38c953f619e5d",
"branch_name": "refs/heads/master",
"committer_date": "2021-10-26T17:46:34",
"content_id": "c42593b28fb78245165f70a1063c5f74b84d52e5",
"detected_licenses": [
"MIT"
],
"directory_id": "7a7731164ca2a521f246927c39b96c551a48e521",
"extension": "js",
"filename": "sort-utils.js",
"fork_events_count": 6,
"gha_created_at": "2019-01-24T20:11:22",
"gha_event_created_at": "2022-06-04T11:23:15",
"gha_language": "JavaScript",
"gha_license_id": "MIT",
"github_id": 167430270,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 481,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/utils/sort-utils.js",
"provenance": "stack-edu-0046.json.gz:12683",
"repo_name": "blackbaud/skyux-sdk-cli",
"revision_date": "2021-10-26T17:46:34",
"revision_id": "426f6599f40cd3f69bf060ebdf7a71f6ec17c7e7",
"snapshot_id": "28e0dba997b5587ce74df892efbb6223a97b26fb",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/blackbaud/skyux-sdk-cli/426f6599f40cd3f69bf060ebdf7a71f6ec17c7e7/lib/utils/sort-utils.js",
"visit_date": "2022-06-19T06:31:36.059423",
"added": "2024-11-18T22:28:53.993193+00:00",
"created": "2021-10-26T17:46:34",
"int_score": 3,
"score": 3,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0064.json.gz"
}
|
define([
// 使用するライブラリを指定
'jquery',
'underscore_wrap',
], function (jQuery, us_wrap) {
//
var $this_imgbtn;
// Facebook系処理のオブジェクト
var fb = {
// Facebook系処理の初期化
init: function () {
setEvent.getAlbums();
setEvent.getPhotos();
setEvent.uploadPhoto();
setEvent.backAlbums();
},
};
var setEvent = {
// Facebookからアルバム一覧を取得する
getAlbums: function () {
$('body').on('click', '.fb-albums', function (e) {
e.preventDefault();
$('#fb-modal-contents').empty();
$this_imgbtn = $(this);
$.ajax({
type: 'post',
url: '/fb/albums',
dataType: 'json',
success: function (data) {
if(data.result.fb_user_photos_permission) {
if(data.result.albums.length > 0) {
var view_data = {
albums: data.result.albums,
};
var html = us_wrap.template('#template_fb-albums-contents', view_data);
$('#fb-modal-contents').empty().append(html);
} else {
$('#fb-modal-contents').empty().append('Facebookアルバムがありません');
}
} else {
var html = us_wrap.template('#template_fb-no-permission', view_data);
$('#fb-modal-contents').empty().append(html);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
}
});
});
},
// Facebookから写真一覧を取得する
getPhotos: function () {
$('body').on('click', '.fb-photos', function (e) {
e.preventDefault();
$('#fb-modal-contents').empty();
var $this = $(this);
var album_id = $this.data('album_id');
var post_data = {
album_id: album_id,
};
$.ajax({
type: 'post',
url: '/fb/photos',
data: post_data,
dataType: 'json',
success: function (data) {
var view_data = {
photos: data.result.photos,
};
var html = us_wrap.template('#template_fb-photos-contents', view_data);
$('#fb-modal-contents').empty().append(html);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
}
});
});
},
// Facebookから取得した写真を一時ディレクトリへアップロードする
uploadPhoto: function () {
$('body').on('click', '.fb-upload', function (e) {
e.preventDefault();
$('#fb-modal-contents').empty();
var $this = $(this);
var photo_orig_url = $this.data('photo_orig_url');
var photo_name = $this.data('photo_name');
var photo_ext = $this.data('photo_ext');
var tmpimg_path = $('#hidden-tmpimg-path').val();
var post_data = {
photo_orig_url: photo_orig_url,
photo_name: photo_name,
photo_ext: photo_ext,
tmpimg_path: tmpimg_path,
};
$.ajax({
type: 'post',
url: '/fb/uploadPhoto',
data: post_data,
dataType: 'json',
success: function (data) {
$this_imgbtn.siblings('.hidden-tmpimg-url').val(data.result.tmpimg_info.url);
$this_imgbtn.siblings('.hidden-tmpimg-path').val(data.result.tmpimg_info.path);
$this_imgbtn.siblings('.hidden-tmpimg-ext').val(data.result.tmpimg_info.ext);
view_data = {
src: data.result.tmpimg_info.url,
}
var html = us_wrap.template('#template_fb-photos-imgarea', view_data);
$this_imgbtn.siblings('.selected-img').empty().append(html);
var view_data = {};
var html = us_wrap.template('#template_fb-photos-complete', view_data);
$('#fb-modal-contents').empty().append(html);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
}
});
});
},
// アルバム一覧へ戻る
backAlbums: function () {
$('body').on('click', '.fb-img-back', function (e) {
e.preventDefault();
$('#fb-modal-contents').empty();
$this_imgbtn = $(this);
$.ajax({
type: 'post',
url: '/fb/albums',
dataType: 'json',
success: function (data) {
if(data.result.fb_user_photos_permission) {
if(data.result.albums.length > 0) {
var view_data = {
albums: data.result.albums,
};
var html = us_wrap.template('#template_fb-albums-contents', view_data);
$('#fb-modal-contents').empty().append(html);
} else {
$('#fb-modal-contents').empty().append('Facebookアルバムがありません');
}
} else {
var html = us_wrap.template('#template_fb-no-permission', view_data);
$('#fb-modal-contents').empty().append(html);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
}
});
});
},
};
// 外部へエクスポート
return fb;
});
|
cafe28fc1ecac443b0536d919a0cf077234378cc
|
{
"blob_id": "cafe28fc1ecac443b0536d919a0cf077234378cc",
"branch_name": "refs/heads/master",
"committer_date": "2015-01-04T08:40:36",
"content_id": "daee114c87f2862dda5888e389a1f0ede1320aaa",
"detected_licenses": [
"MIT"
],
"directory_id": "a17ccb8051aa7354e4d88028fcccd36a694bde4c",
"extension": "js",
"filename": "facebook.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 28680401,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 4942,
"license": "MIT",
"license_type": "permissive",
"path": "/public/assets/app/js/lib/original/facebook.js",
"provenance": "stack-edu-0043.json.gz:655351",
"repo_name": "marutoto/fblogin",
"revision_date": "2015-01-04T08:40:36",
"revision_id": "b7e4ec2f226aa58e30c5adf84ee6d4c12614483d",
"snapshot_id": "24723738f72f97552ce9d0bdd5494ead39fbbc18",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/marutoto/fblogin/b7e4ec2f226aa58e30c5adf84ee6d4c12614483d/public/assets/app/js/lib/original/facebook.js",
"visit_date": "2021-01-15T13:11:30.097133",
"added": "2024-11-18T23:54:59.659743+00:00",
"created": "2015-01-04T08:40:36",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0061.json.gz"
}
|
import React, { useState } from "react";
import { TabContent, TabPane, Nav, NavItem, NavLink, Row, Col } from "reactstrap";
import classnames from 'classnames'
import Evaluation from './../evaluation'
import VideoAssessment from './../videoAssessment'
import './tabs.css';
const Tabs = () => {
const [activeTab, setActiveTab] = useState('1');
const toggle = tab => {
if(activeTab !== tab) setActiveTab(tab);
}
return (
<>
<Nav tabs>
<NavItem>
<NavLink onClick={() => { toggle('1'); }} className={classnames({ active: activeTab === '1' })} >
Video
</NavLink>
</NavItem>
<NavItem>
<NavLink onClick={() => { toggle('2'); }} className={classnames({ active: activeTab === '2' })} >
Summary
</NavLink>
</NavItem>
<NavItem>
<NavLink onClick={() => { toggle('3'); }} className={classnames({ active: activeTab === '3' })} >
Attachments
</NavLink>
</NavItem>
<NavItem>
<NavLink onClick={() => { toggle('4'); }} className={classnames({ active: activeTab === '4' })} >
Evaluation
</NavLink>
</NavItem>
<NavItem>
<NavLink onClick={() => { toggle('5'); }} className={classnames({ active: activeTab === '5' })} >
Questionnaire
</NavLink>
</NavItem>
<NavItem>
<NavLink onClick={() => { toggle('6'); }} className={classnames({ active: activeTab === '6' })} >
Video Assessment
</NavLink>
</NavItem>
</Nav>
<TabContent activeTab={activeTab}>
<TabPane tabId="1">
<Row>
<Col sm="12">
<div style={{ textAlign: "center" }}>
<h1>Vidoe Tab</h1>
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="2">
<Row>
<Col sm="12">
<div style={{ textAlign: "center" }}>
<h1>Summary Tab</h1>
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="3">
<Row>
<Col sm="12">
<div style={{ textAlign: "center" }}>
<h1>Attachments Tab</h1>
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="4">
<Row>
<Col sm="12">
<Evaluation />
</Col>
</Row>
</TabPane>
<TabPane tabId="5">
<Row>
<Col sm="12">
<div style={{ textAlign: "center" }}>
<h1>Questionnaire Tab</h1>
</div>
</Col>
</Row>
</TabPane>
<TabPane tabId="6">
<Row>
<Col sm="12">
<VideoAssessment />
</Col>
</Row>
</TabPane>
</TabContent>
</>
);
}
export default Tabs;
|
4741443e1a3033e331ca59b03c5c88bcae2a35bc
|
{
"blob_id": "4741443e1a3033e331ca59b03c5c88bcae2a35bc",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-30T15:18:20",
"content_id": "415cd54706416eae39c0598bafbb6fdeff3f25c5",
"detected_licenses": [
"MIT"
],
"directory_id": "6913d0f49e6b1c5829d0fe60b86b5e4c3ae8eec5",
"extension": "js",
"filename": "index.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 299276509,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 3866,
"license": "MIT",
"license_type": "permissive",
"path": "/src/components/modal/tabs/index.js",
"provenance": "stack-edu-0036.json.gz:713289",
"repo_name": "Ahmad-Sawalqeh/elevatus-modal",
"revision_date": "2020-09-30T15:18:20",
"revision_id": "0395cca50fafd0837937979fcbde423c6407bf0f",
"snapshot_id": "c4c78400a6a57d10f567465434b8ecdbf6d1a26d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ahmad-Sawalqeh/elevatus-modal/0395cca50fafd0837937979fcbde423c6407bf0f/src/components/modal/tabs/index.js",
"visit_date": "2022-12-09T07:21:56.220035",
"added": "2024-11-18T23:13:48.779441+00:00",
"created": "2020-09-30T15:18:20",
"int_score": 2,
"score": 2.15625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz"
}
|
package org.mamute.infra;
import com.google.common.base.Objects;
import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
@RequestScoped
public class ClientIp {
@Inject
private HttpServletRequest request;
private String ip;
@PostConstruct
public void setup() {
String header = request.getHeader("X-Real-IP");
String ip = request.getRemoteAddr();
this.ip = Objects.firstNonNull(header, ip);
}
public String get() {
return ip;
}
}
|
7e951a02c5d82bea29ac2af08c86111a3e21279e
|
{
"blob_id": "7e951a02c5d82bea29ac2af08c86111a3e21279e",
"branch_name": "refs/heads/master",
"committer_date": "2019-02-13T04:19:21",
"content_id": "cf4f47b85ecd1a3eb478d6ec1e9294dd8efd42e3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "5b8675c3cced4691280ec8fff730fba92ffc8cdc",
"extension": "java",
"filename": "ClientIp.java",
"fork_events_count": 4,
"gha_created_at": "2018-07-04T09:03:48",
"gha_event_created_at": "2018-09-26T05:55:28",
"gha_language": "Java",
"gha_license_id": "Apache-2.0",
"github_id": 139696941,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 555,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/src/main/java/org/mamute/infra/ClientIp.java",
"provenance": "stack-edu-0028.json.gz:820220",
"repo_name": "mamutehq/mamute",
"revision_date": "2019-02-13T04:19:21",
"revision_id": "914dc5e22671c2e43ccdea55339eea254173b16a",
"snapshot_id": "99dcb2fb383e558c9ded09002267f7646fffa442",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/mamutehq/mamute/914dc5e22671c2e43ccdea55339eea254173b16a/src/main/java/org/mamute/infra/ClientIp.java",
"visit_date": "2020-03-22T07:23:10.865244",
"added": "2024-11-18T22:28:13.085199+00:00",
"created": "2019-02-13T04:19:21",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0046.json.gz"
}
|
using System;
using System.Collections.Generic;
using Unity.Cloud.Authorization;
namespace Unity.Cloud.UserReporting
{
/// <summary>
/// Represents a user report preview or the fly weight version of a user report.
/// </summary>
public class UserReportPreview
{
#region Constructors
/// <summary>
/// Creates a new instance of the <see cref="UserReportPreview"/> class.
/// </summary>
public UserReportPreview()
{
this.Dimensions = new List<UserReportNamedValue>();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the aggregate metrics.
/// </summary>
public List<UserReportMetric> AggregateMetrics { get; set; }
/// <summary>
/// Gets or sets the appearance hint.
/// </summary>
public UserReportAppearanceHint AppearanceHint { get; set; }
/// <summary>
/// Gets or sets the content length. This property will be overwritten by the server if provided.
/// </summary>
public long ContentLength { get; set; }
/// <summary>
/// Gets or sets the dimensions.
/// </summary>
public List<UserReportNamedValue> Dimensions { get; set; }
/// <summary>
/// Gets or sets the time at which the user report expires. This property will be overwritten by the server if provided.
/// </summary>
public DateTime ExpiresOn { get; set; }
/// <summary>
/// Gets or sets the geo country.
/// </summary>
public string GeoCountry { get; set; }
/// <summary>
/// Gets or sets the identifier. This property will be overwritten by the server if provided.
/// </summary>
public string Identifier { get; set; }
/// <summary>
/// Gets or sets the IP address. This property will be overwritten by the server if provided.
/// </summary>
public string IPAddress { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user report is hidden in the UI if a dimension filter is not specified. This is recommended for automated or high volume reports.
/// </summary>
public bool IsHiddenWithoutDimension { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user report is silent. Silent user reports do not send events to integrations. This is recommended for automated or high volume reports.
/// </summary>
public bool IsSilent { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the user report is temporary. Temporary user reports are short lived and not queryable.
/// </summary>
public bool IsTemporary { get; set; }
/// <summary>
/// Gets or sets the license level. This property will be overwritten by the server if provided.
/// </summary>
public LicenseLevel LicenseLevel { get; set; }
/// <summary>
/// Gets or sets the project identifier.
/// </summary>
public string ProjectIdentifier { get; set; }
/// <summary>
/// Gets or sets the time at which the user report was received. This property will be overwritten by the server if provided.
/// </summary>
public DateTime ReceivedOn { get; set; }
/// <summary>
/// Gets or sets the summary.
/// </summary>
public string Summary { get; set; }
/// <summary>
/// Gets or sets the thumbnail. This screenshot will be resized by the server if too large. Keep the last screenshot small in order to reduce report size and increase submission speed.
/// </summary>
public UserReportScreenshot Thumbnail { get; set; }
#endregion
}
}
|
50c105a916ae5566ebe52b7599599aae6f9dcace
|
{
"blob_id": "50c105a916ae5566ebe52b7599599aae6f9dcace",
"branch_name": "refs/heads/master",
"committer_date": "2022-02-01T14:01:21",
"content_id": "67c80b4d57933b6d764317548a1fc3cd2c8cd3ca",
"detected_licenses": [
"MIT"
],
"directory_id": "15d41b043ae587a19c7936048c1bd0e3d81d003d",
"extension": "cs",
"filename": "UserReportPreview.cs",
"fork_events_count": 38,
"gha_created_at": "2020-03-07T20:50:31",
"gha_event_created_at": "2020-10-28T16:01:13",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 245703592,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 3877,
"license": "MIT",
"license_type": "permissive",
"path": "/GameTemplate/Assets/Plugins/UserReporting/Scripts/Client/UserReportPreview.cs",
"provenance": "stack-edu-0013.json.gz:200433",
"repo_name": "Team-on/UnityGameTemplate",
"revision_date": "2022-02-01T14:01:21",
"revision_id": "bfcbac80d4d384c347e4a0ca9ecc68fed4690556",
"snapshot_id": "8758e8635509978c876fc2209e9ee927f07494fe",
"src_encoding": "UTF-8",
"star_events_count": 289,
"url": "https://raw.githubusercontent.com/Team-on/UnityGameTemplate/bfcbac80d4d384c347e4a0ca9ecc68fed4690556/GameTemplate/Assets/Plugins/UserReporting/Scripts/Client/UserReportPreview.cs",
"visit_date": "2023-08-22T20:30:26.464172",
"added": "2024-11-18T23:18:30.736419+00:00",
"created": "2022-02-01T14:01:21",
"int_score": 2,
"score": 2.109375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0031.json.gz"
}
|
# Sphero SPRK+
The Sphero SPRK+ and Sphero Ollie, and Sphero BB-8 all use the same API. However,
they have separate Gobot drivers to accommodate their other differences.
## What you need
- Sphero Ollie, SPRK+, or BB-8
- Personal computer with Go installed, and a Bluetooth 4.0 radio.
- Linux or OS X
## Installation
```
go get -d -u gobot.io/x/gobot/...
```
## Sphero Robot ID
Download the Sphero EDU App
Pair the robot to your phone
Note the ID, should look like `BB-128E` or `SK-4293`
Use this ID in place of `BB-128E` or `SK-1234` in the examples below
## Running the code
When you run any of these examples, you will compile and execute the code on your computer. When you are running the program, you will be communicating with the robot using the Bluetooth Low Energy (LE) interface.
To compile/run the code, substitute the name of your SPRK+, Ollie or BB-8 as needed.
### OS X
To run any of the Gobot BLE code on OS X, you must use the `GODEBUG=cgocheck=0` flag.
For example:
```
$ GODEBUG=cgocheck=0 go run rover/sprkplus/step1/main.go BB-128E
```
#### Common Errors
##### Bad BLE version
```
2018/08/30 16:08:36 Initializing connections...
2018/08/30 16:08:36 Initializing connection BLEClient-34930C2CE9B59A63 ...
2018/08/30 16:08:36 Initializing connection MQTT-2B88DD27CAB182FB ...
2018/08/30 16:08:36 Initializing devices...
2018/08/30 16:08:36 Initializing device SPRKPlus-5ED845F51BA42B5E ...
2018/08/30 16:08:36 Initializing device Keyboard-4BAC6CB69692381C ...
2018/08/30 16:08:36 Robot rover initialized.
2018/08/30 16:08:36 Starting Robot rover ...
2018/08/30 16:08:36 Starting connections...
2018/08/30 16:08:36 Starting connection BLEClient-34930C2CE9B59A63...
panic: interface conversion: interface {} is nil, not int64
goroutine 17 [running, locked to thread]:
github.com/raff/goble/xpc.xpc.Dict.MustGetInt(...)
/Users/slewis/code/go/src/github.com/raff/goble/xpc/xpc.go:55
github.com/go-ble/ble/darwin.msg.attMTU(...)
/Users/slewis/code/go/src/github.com/go-ble/ble/darwin/msg.go:15
github.com/go-ble/ble/darwin.(*Device).conn(0xc420186000, 0xc4201848a0, 0x4323245)
/Users/slewis/code/go/src/github.com/go-ble/ble/darwin/device.go:549 +0x4b9
github.com/go-ble/ble/darwin.(*Device).HandleXpcEvent(0xc420186000, 0xc420184870, 0x0, 0x0)
/Users/slewis/code/go/src/github.com/go-ble/ble/darwin/device.go:492 +0xe40
github.com/raff/goble/xpc.handleXpcEvent(0x6300340, 0xc420054c78)
/Users/slewis/code/go/src/github.com/raff/goble/xpc/xpc.go:229 +0x22e
github.com/raff/goble/xpc._cgoexpwrap_f507673fb4e8_handleXpcEvent(0x6300340, 0xc420054c78)
_cgo_gotypes.go:458 +0x35
exit status 2
```
To fix this do the following:
```
$ cd $GOPATH/src/github.com/go-ble/ble
$ git checkout fe39e478ef1cfc1395b96134e61f825e46e814ba
```
This switches the version of go-ble/ble to a version that works properly with older macOS/OSX versions
### Linux
On Linux the BLE code will need to run as a root user account. The easiest way to accomplish this is probably to use `go build` to build your program, and then to run the requesting executable using `sudo`.
For example:
```
$ go build -o step1 rover/ollie/step1/main.go
$ sudo ./step1 2B-123E
```
## Code
### step1
This tests that the Sphero SPRK+ or Ollie is connected correctly to your computer, by blinking the built-in LED.
No additional hardware needs to be connected.
We will connect to a MQTT machine to machine messaging server that is maintained by the Eclipse Foundation for public testing.
When the heartbeat data is received from the base station, the built-in LED will change color.
Licensed under the MIT license.
|
3e64bd606b6b24bbf3ee079e843df646d5d6b184
|
{
"blob_id": "3e64bd606b6b24bbf3ee079e843df646d5d6b184",
"branch_name": "refs/heads/master",
"committer_date": "2018-08-30T22:13:21",
"content_id": "fce4eabfde786d4352b49071a93864aa4a1e3033",
"detected_licenses": [
"MIT"
],
"directory_id": "8fda6a4e3a68a1f7e68c0dc50e1403b993b7e121",
"extension": "md",
"filename": "README.md",
"fork_events_count": 0,
"gha_created_at": "2018-08-30T19:38:55",
"gha_event_created_at": "2018-08-30T19:38:55",
"gha_language": null,
"gha_license_id": null,
"github_id": 146798229,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6401,
"license": "MIT",
"license_type": "permissive",
"path": "/rover/sprkplus/README.md",
"provenance": "stack-edu-markdown-0011.json.gz:38593",
"repo_name": "SophisticaSean/gophercon-2018",
"revision_date": "2018-08-30T22:13:21",
"revision_id": "616ed46f1d8f9069085061ad961b5d1f5e1fe555",
"snapshot_id": "a3aca76e18b53cc3ff681c9bde01aad4f2c9fab6",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SophisticaSean/gophercon-2018/616ed46f1d8f9069085061ad961b5d1f5e1fe555/rover/sprkplus/README.md",
"visit_date": "2020-03-27T16:39:56.480973",
"added": "2024-11-19T01:39:20.288769+00:00",
"created": "2018-08-30T22:13:21",
"int_score": 4,
"score": 3.515625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0011.json.gz"
}
|
// Copyright The OpenTelemetry Authors
//
// 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.
package baggage // import "go.opentelemetry.io/otel/internal/baggage"
import "context"
type baggageContextKeyType int
const baggageKey baggageContextKeyType = iota
// SetHookFunc is a callback called when storing baggage in the context.
type SetHookFunc func(context.Context, List) context.Context
// GetHookFunc is a callback called when getting baggage from the context.
type GetHookFunc func(context.Context, List) List
type baggageState struct {
list List
setHook SetHookFunc
getHook GetHookFunc
}
// ContextWithSetHook returns a copy of parent with hook configured to be
// invoked every time ContextWithBaggage is called.
//
// Passing nil SetHookFunc creates a context with no set hook to call.
func ContextWithSetHook(parent context.Context, hook SetHookFunc) context.Context {
var s baggageState
if v, ok := parent.Value(baggageKey).(baggageState); ok {
s = v
}
s.setHook = hook
return context.WithValue(parent, baggageKey, s)
}
// ContextWithGetHook returns a copy of parent with hook configured to be
// invoked every time FromContext is called.
//
// Passing nil GetHookFunc creates a context with no get hook to call.
func ContextWithGetHook(parent context.Context, hook GetHookFunc) context.Context {
var s baggageState
if v, ok := parent.Value(baggageKey).(baggageState); ok {
s = v
}
s.getHook = hook
return context.WithValue(parent, baggageKey, s)
}
// ContextWithList returns a copy of parent with baggage. Passing nil list
// returns a context without any baggage.
func ContextWithList(parent context.Context, list List) context.Context {
var s baggageState
if v, ok := parent.Value(baggageKey).(baggageState); ok {
s = v
}
s.list = list
ctx := context.WithValue(parent, baggageKey, s)
if s.setHook != nil {
ctx = s.setHook(ctx, list)
}
return ctx
}
// ListFromContext returns the baggage contained in ctx.
func ListFromContext(ctx context.Context) List {
switch v := ctx.Value(baggageKey).(type) {
case baggageState:
if v.getHook != nil {
return v.getHook(ctx, v.list)
}
return v.list
default:
return nil
}
}
|
809c69b64a1cd8f2f25017d7a3a653c4614f30d3
|
{
"blob_id": "809c69b64a1cd8f2f25017d7a3a653c4614f30d3",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-21T18:09:34",
"content_id": "4469700d9cbb1d7198ab6466dd9f94a72c1a47d9",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "c2e298290aa9d4d0c74482850c0547027d359820",
"extension": "go",
"filename": "context.go",
"fork_events_count": 43154,
"gha_created_at": "2014-06-06T22:56:04",
"gha_event_created_at": "2023-09-14T21:45:02",
"gha_language": "Go",
"gha_license_id": "Apache-2.0",
"github_id": 20580498,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2686,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/vendor/go.opentelemetry.io/otel/internal/baggage/context.go",
"provenance": "stack-edu-0016.json.gz:215122",
"repo_name": "kubernetes/kubernetes",
"revision_date": "2023-08-21T18:09:34",
"revision_id": "55c86d6ad930d437931079318d740bdf8dac34f0",
"snapshot_id": "a3df9e08b5a0d013dcfccfa7cacd6afe39e282df",
"src_encoding": "UTF-8",
"star_events_count": 101271,
"url": "https://raw.githubusercontent.com/kubernetes/kubernetes/55c86d6ad930d437931079318d740bdf8dac34f0/vendor/go.opentelemetry.io/otel/internal/baggage/context.go",
"visit_date": "2023-08-21T18:23:51.296777",
"added": "2024-11-18T19:45:14.525460+00:00",
"created": "2023-08-21T18:09:34",
"int_score": 3,
"score": 2.59375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0034.json.gz"
}
|
#!/bin/bash
# _ __ _
# ((-)).--.((-))
# / '' \
# ( \______/ )
# \ ( ) /
# / /~~~~~~~~\ \
# /~~\/ / \ \/~~\
# ( ( ( ) ) )
# \ \ \ \ / / / /
# _\ \/ \.______./ \/ /_
# ___/ /\__________/\ \___
# *****************************
# Frogg - [email protected]
# http://github.com/FroggDev/zabbix-smb
# *****************************
##########
# PARAMS #
##########
# Action for the script
SMBACTION=$1
# SMB Server IP
SMBSERVER=$2
# SMB formated share list
# ex: action=share share1,share2,share3
# ex: action=right share1|user1:pass1+r,share1|user2:pass2+w
SMBSHARES=$3
##########
# CONSTS #
##########
#Element separator
declare -r SEP=","
#Share separator
declare -r SSEP="|"
#User separator
declare -r USEP=":"
#Right separator
declare -r RSEP="+"
#########
# FUNCS #
#########
# ---
# Check if can check SMB rights
# @param serverIP
# @return 0/1
function canCheckSmbShares()
{
[[ $(smbclient -L $1 -g -N -U zabbix) == "session setup failed: NT_STATUS_ACCESS_DENIED" ]] && return 1 || return 0
}
# ---
# Get the SMB shares of a server
# @param serverIP
# @param shareList
# @return smb shares not found
function checkSmbShares()
{
# Init result (empty by default = ok)
RESULT=""
# get all SMB share for the server
SMBSHARESFOUND=$(getSmbShares "$1")
# get all SMB share sent by user separated by $SEP
SMBSHARES=$(echo $2 | tr "$SEP" "\n")
# For each SMB share test if exist in server SMB share list
while IFS= read -r SHARE; do
#set share as lower case
SHARE="[${SHARE,,}]"
# Check if SMB share does not exist in SMB server shares
if [[ ! " ${SMBSHARESFOUND} " =~ " ${SHARE} " ]]; then
RESULT="${RESULT}${SHARE}"
fi
done <<< ${SMBSHARES}
# Return nothing if all is ok, else the lis of share with trouble
echo $RESULT
}
# ---
# Get the SMB shares of a server
# @param serverIP
# @param shareList
# @return smb shares not found
function checkSmbRights()
{
RESULT=""
# get all SMB share sent by user separated by $SEP
SMBSHARES=$(echo $2 | tr "$SEP" "\n")
# For each SMB share test if exist in server SMB share list
while IFS= read -r SHAREINFO; do
#DATAS = share|user:pass
DATAS=$(getElementAt "$SHAREINFO" "$RSEP" 1)
RIGHT=$(getElementAt "$SHAREINFO" "$RSEP" 2)
#set right as lower case
RIGHT=${RIGHT,,}
SHARE=$(getElementAt "$DATAS" "$SSEP" 1)
#set share as lower case
SHARE=${SHARE,,}
#USERS = user:pass
USERS=$(getElementAt "$DATAS" "$SSEP" 2)
USER=$(getElementAt "$USERS" "$USEP" 1)
PASS=$(getElementAt "$USERS" "$USEP" 2)
#Set USER=anonymous if no user set
[ "$USER" = "" ] && USER="anonymous"
# User as string for the result
USERSTR=$(getUserStr "$USER" "$PASS")
# Debug
#echo "Trying rights ${RIGHT} on ${1}/${SHARE} for $USER $PASS"
case ${RIGHT} in
# should be able to write
("w") [ $(canWriteSmb "${1}" "${SHARE}" "$USER" "$PASS") -eq 0 ] && RESULT="${RESULT}[${SHARE}${USERSTR}${RSEP}${RIGHT}]";;
# should not be able to read
("n") [ $(canReadSmb "${1}" "${SHARE}" "$USER" "$PASS") -eq 1 ] && RESULT="${RESULT}[${SHARE}${USERSTR}${RSEP}${RIGHT}]";;
# by default check read but should not be able to write
(*)
[ $(canReadSmb "${1}" "${SHARE}" "$USER" "$PASS") -eq 0 ] && RESULT="${RESULT}[${SHARE}${USERSTR}${RSEP}r]";
[ $(canWriteSmb "${1}" "${SHARE}" "$USER" "$PASS") -eq 1 ] && RESULT="${RESULT}[${SHARE}${USERSTR}${RSEP}w]";
;;
esac
done <<< $SMBSHARES
# Return nothing if all is ok, else the lis of share with trouble
echo $RESULT
}
##############
# FUNCS UTIL #
##############
# ---
# Get the SMB shares of a server
# @param serverIP
# @return smb shares found
function getSmbShares()
{
echo $(
smbclient -L $1 -g -N -U zabbix 2> /dev/null |
awk -F'|' '$1 == "Disk" {print $2}' |
while IFS= read -r SHARE
do
#set share as lower case
echo "[${SHARE,,}]"
done
)
}
# ---
# Check if user can read in the SMB share
# @param serverIP
# @param share
# @param user
# @param password
# @return true if can read
function canReadSmb()
{
# All before 1st /
SHARE="${2%%/*}"
# All after 1st /
FOLDER="${2#*/}/"
smbclient "//$1/$SHARE" "$4" -U "$3" -c "cd $FOLDER;dir" >/dev/null 2>&1 && echo 1 || echo 0
}
# ---
# Check if user can write in the SMB share
# @param serverIP
# @param share
# @param user
# @param password
# @return true if can write
function canWriteSmb()
{
# All before 1st /
SHARE="${2%%/*}"
# All after 1st /
FOLDER="${2#*/}/"
smbclient "//$1/$SHARE" "$4" -U "$3" -c "cd $FOLDER;md -tmpfolderfroggtest-;rd -tmpfolderfroggtest-" >/dev/null 2>&1 && echo 1 || echo 0
}
# ---
# Get element at position after spliting a string
# @param string
# @param spliting char
# @param array position
# @return string at position splited
function getElementAt()
{
RESULT=""
# spliting the string
ELEMENTS=$(echo $1 | tr "$2" "\n")
i=1
while IFS= read -r ELEMENT; do
# if position match return the string as result
[ $i -eq $3 ] && RESULT=$ELEMENT
((i++))
done <<< $ELEMENTS
echo $RESULT
}
# ---
# Return formated user as string for display the result without useless empty separator
# @param user
# @param pass
# @return formated |user:pass or |user if no pass or nothing if no user
function getUserStr()
{
RESULT=""
[ ! $1 = "" ] && RESULT="${SSEP}${1}" && [ ! $2 = "" ] && RESULT="${RESULT}${USEP}${2}"
echo $RESULT
}
########
# MAIN #
########
# Clean screen
#clear
case ${SMBACTION} in
# command check share
("share")
if canCheckSmbShares "$SMBSERVER";then
echo $(checkSmbShares "$SMBSERVER" "$SMBSHARES")
else
echo "[ SMB rights error : NT_STATUS_ACCESS_DENIED ]"
fi
;;
# command check right
("right")echo $(checkSmbRights "$SMBSERVER" "$SMBSHARES");;
# command not set or invalid
(*)echo "Error : command [${SMBACTION}] not found"
esac
|
fe83048404e8c8e7ea8cf0b3eb5fe6cfe1152016
|
{
"blob_id": "fe83048404e8c8e7ea8cf0b3eb5fe6cfe1152016",
"branch_name": "refs/heads/master",
"committer_date": "2021-08-06T11:47:56",
"content_id": "3432dabc133e2eb8fbe4ce8e53c55082525d4194",
"detected_licenses": [
"MIT"
],
"directory_id": "f9de6d10f6aaafbfc294a7ef96d06035866c5311",
"extension": "sh",
"filename": "frogg_smb_check.sh",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 245831756,
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 5830,
"license": "MIT",
"license_type": "permissive",
"path": "/frogg_smb_check.sh",
"provenance": "stack-edu-0069.json.gz:985122",
"repo_name": "FroggDev/zabbix-smb",
"revision_date": "2021-08-06T11:47:56",
"revision_id": "961798d4426e2b77274b6d3d0e6aa716091e78f5",
"snapshot_id": "e36936df244d71c0e39632bfb3b1817e96d13c17",
"src_encoding": "UTF-8",
"star_events_count": 3,
"url": "https://raw.githubusercontent.com/FroggDev/zabbix-smb/961798d4426e2b77274b6d3d0e6aa716091e78f5/frogg_smb_check.sh",
"visit_date": "2021-08-28T21:05:51.225868",
"added": "2024-11-19T00:42:41.531524+00:00",
"created": "2021-08-06T11:47:56",
"int_score": 4,
"score": 3.6875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0087.json.gz"
}
|
package nachos.vm;
public class CodePage
{
public CodePage(int sectionNum, int offset)
{
this.sectionNum = sectionNum;
this.offset = offset;
}
public int getSectionNum()
{
return sectionNum;
}
public int getOffset()
{
return offset;
}
private int sectionNum;
private int offset;
}
|
0cd81c9fbff3d921e69086d1f58c29667e2e8f04
|
{
"blob_id": "0cd81c9fbff3d921e69086d1f58c29667e2e8f04",
"branch_name": "refs/heads/master",
"committer_date": "2020-12-12T00:54:10",
"content_id": "12d5ccb21250d9f10f90dded48e608cc8a682ae4",
"detected_licenses": [
"MIT-Modern-Variant"
],
"directory_id": "36d11b942656649f3024ed701b4b3fb5edb9ad47",
"extension": "java",
"filename": "CodePage.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 304122691,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 308,
"license": "MIT-Modern-Variant",
"license_type": "permissive",
"path": "/osproject/nachos/vm/CodePage.java",
"provenance": "stack-edu-0022.json.gz:85323",
"repo_name": "Barnes2197/osproj",
"revision_date": "2020-12-12T00:54:10",
"revision_id": "7b5f635cbbd1fc9cdc7bc5be8056a89df5e5756b",
"snapshot_id": "f512c9064c6a4c7bdd868b40a9f9053d5cca0a44",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Barnes2197/osproj/7b5f635cbbd1fc9cdc7bc5be8056a89df5e5756b/osproject/nachos/vm/CodePage.java",
"visit_date": "2023-01-31T19:46:28.776553",
"added": "2024-11-19T03:06:48.302754+00:00",
"created": "2020-12-12T00:54:10",
"int_score": 2,
"score": 2.21875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0040.json.gz"
}
|
# frozen_string_literal: true
require "private_attr"
require "with_advisory_lock"
module ActiveRecord
module PostgresPubSub
class Listener
extend PrivateAttr
private_attr_reader :on_notify_blk, :on_start_blk, :on_timeout_blk,
:channel, :listen_timeout, :exclusive_lock, :notify_only
def self.listen(channel, listen_timeout: nil, exclusive_lock: true, notify_only: true)
listener = new(channel,
listen_timeout: listen_timeout,
exclusive_lock: exclusive_lock,
notify_only: notify_only)
yield(listener) if block_given?
listener.listen
end
def initialize(channel, listen_timeout: nil, exclusive_lock: true, notify_only: true)
@channel = channel
@listen_timeout = listen_timeout
@exclusive_lock = exclusive_lock
@notify_only = notify_only
end
def on_notify(&blk)
@on_notify_blk = blk
end
def on_start(&blk)
@on_start_blk = blk
end
def on_timeout(&blk)
@on_timeout_blk = blk
end
def listen
with_connection do |connection|
on_start_blk&.call
loop do
wait_for_notify(connection) do |payload|
notify_only ? on_notify_blk.call : on_notify_blk.call(payload)
end
end
end
end
private
def with_connection
ActiveRecord::Base.connection_pool.with_connection do |connection|
with_optional_lock do
connection.execute("LISTEN #{channel}")
begin
yield(connection)
ensure
connection.execute("UNLISTEN #{channel}")
end
end
end
end
def with_optional_lock
if exclusive_lock
ActiveRecord::Base.with_advisory_lock(lock_name) { yield }
else
yield
end
end
def lock_name
"#{channel}-listener"
end
def empty_channel(connection)
while connection.wait_for_notify(0)
# call until nil is returned
end
end
def wait_for_notify(connection)
connection_pid = connection.raw_connection.backend_pid
event_result = connection.raw_connection.wait_for_notify(listen_timeout) do |_event, pid, payload|
if pid != connection_pid
empty_channel(connection.raw_connection) if notify_only
yield(payload)
end
end
on_timeout_blk&.call if event_result.nil?
end
end
end
end
|
08d61127cf553f13bcf638a49268616d65eb9675
|
{
"blob_id": "08d61127cf553f13bcf638a49268616d65eb9675",
"branch_name": "refs/heads/master",
"committer_date": "2019-08-18T13:36:15",
"content_id": "fc7d7c1aa31898b6bd2e69ecd47d55dc859d8f39",
"detected_licenses": [
"MIT"
],
"directory_id": "6e666399c4c6ea43f9757e7c468932e77e5decfd",
"extension": "rb",
"filename": "listener.rb",
"fork_events_count": 0,
"gha_created_at": "2019-11-20T10:13:44",
"gha_event_created_at": "2019-11-20T10:13:45",
"gha_language": null,
"gha_license_id": "MIT",
"github_id": 222908903,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 2624,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/activerecord/postgres_pub_sub/listener.rb",
"provenance": "stack-edu-0067.json.gz:549107",
"repo_name": "TimWei/activerecord-postgres_pub_sub",
"revision_date": "2019-08-18T13:36:15",
"revision_id": "d7a46a9dcbaf7606cfcc4cde73dd87fe51d17259",
"snapshot_id": "115fd0dffaed49fc2f8331168d65e566e850b2dd",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/TimWei/activerecord-postgres_pub_sub/d7a46a9dcbaf7606cfcc4cde73dd87fe51d17259/lib/activerecord/postgres_pub_sub/listener.rb",
"visit_date": "2022-06-27T05:23:35.007992",
"added": "2024-11-18T18:00:36.534261+00:00",
"created": "2019-08-18T13:36:15",
"int_score": 3,
"score": 2.53125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
# MagnifyingGlassLocation
```text
fontawesome-6/Solid/MagnifyingGlassLocation
```
```text
include('fontawesome-6/Solid/MagnifyingGlassLocation')
```
| Illustration | MagnifyingGlassLocation |
| :---: | :---: |
|  |  |
## Sprites
The item provides the following sriptes:
- `<$MagnifyingGlassLocationXs>`
- `<$MagnifyingGlassLocationSm>`
- `<$MagnifyingGlassLocationMd>`
- `<$MagnifyingGlassLocationLg>`
## MagnifyingGlassLocation
### Load remotely
```plantuml
@startuml
' configures the library
!global $LIB_BASE_LOCATION="https://raw.githubusercontent.com/tmorin/plantuml-libs/master/distribution"
' loads the library's bootstrap
!include $LIB_BASE_LOCATION/bootstrap.puml
' loads the package bootstrap
include('fontawesome-6/bootstrap')
' loads the Item which embeds the element MagnifyingGlassLocation
include('fontawesome-6/Solid/MagnifyingGlassLocation')
' renders the element
MagnifyingGlassLocation('MagnifyingGlassLocation', 'Magnifying Glass Location', 'an optional tech label', 'an optional description')
@enduml
```
### Load locally
```plantuml
@startuml
' configures the library
!global $INCLUSION_MODE="local"
!global $LIB_BASE_LOCATION="../.."
' loads the library's bootstrap
!include $LIB_BASE_LOCATION/bootstrap.puml
' loads the package bootstrap
include('fontawesome-6/bootstrap')
' loads the Item which embeds the element MagnifyingGlassLocation
include('fontawesome-6/Solid/MagnifyingGlassLocation')
' renders the element
MagnifyingGlassLocation('MagnifyingGlassLocation', 'Magnifying Glass Location', 'an optional tech label', 'an optional description')
@enduml
```
|
80aa5dd4e50e8b1981428e112cee5805e5fb7a50
|
{
"blob_id": "80aa5dd4e50e8b1981428e112cee5805e5fb7a50",
"branch_name": "refs/heads/master",
"committer_date": "2023-05-30T19:04:23",
"content_id": "b556c365949af170dd5b9e273dc024afaefb626f",
"detected_licenses": [
"MIT"
],
"directory_id": "8255480ee8ecef1ad7d65f60b261efce689ba52c",
"extension": "md",
"filename": "MagnifyingGlassLocation.md",
"fork_events_count": 25,
"gha_created_at": "2019-04-16T08:24:49",
"gha_event_created_at": "2023-07-20T10:12:29",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 181646969,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1802,
"license": "MIT",
"license_type": "permissive",
"path": "/distribution/fontawesome-6/Solid/MagnifyingGlassLocation.md",
"provenance": "stack-edu-markdown-0012.json.gz:41891",
"repo_name": "tmorin/plantuml-libs",
"revision_date": "2023-05-30T19:04:23",
"revision_id": "006af18927be7a3f7b4a41950db45b9a8026a534",
"snapshot_id": "26e2eca7afa650a54ee8df4e7300e14e19e43ec0",
"src_encoding": "UTF-8",
"star_events_count": 95,
"url": "https://raw.githubusercontent.com/tmorin/plantuml-libs/006af18927be7a3f7b4a41950db45b9a8026a534/distribution/fontawesome-6/Solid/MagnifyingGlassLocation.md",
"visit_date": "2023-08-09T03:49:04.516794",
"added": "2024-11-19T02:06:11.733417+00:00",
"created": "2023-05-30T19:04:23",
"int_score": 4,
"score": 3.71875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz"
}
|
<?php
/* @var $this yii\web\View */
use yii\helpers\Html;
use yii\helpers\Url;
$this->title = '文件列表';
$this->params['breadcrumbs'][] = $this->title;
$this->registerJsFile('http://libs.baidu.com/jquery/1.10.2/jquery.min.js');
$this->registerJsFile('@web/upload_h5/jQuery.upload.uploadfile.js');
$this->registerJsFile('@web/js/site/showfiles.js');
?>
<link rel="stylesheet" href="<?=Url::to('@web/upload_h5/upload.css');?>">
<style type="text/css">
<!--
.unnamed1 {
padding-top: 1px;
padding-right: 5px;
padding-bottom: 1px;
padding-left: 5px;
}
-->
</style>
<div class="site-about">
<h1>上传文件</h1>
<div class="row">
<div class="col-lg-5">
<div class="case">
<div class="upload" data-num="10" data-type="png,jpg,jpeg,gif" action='<?=Url::to(['site/upload', 'dirname' => \Yii::$app->request->get('dirname', '')]);?>' id='case1'></div>
</div>
</div>
</div>
<h1><?=Html::encode($this->title);?></h1>
<form method="POST" action="<?php echo Url::to(['site/deletefiles', 'dirname' => \Yii::$app->request->get('dirname', '')]); ?>">
<table id="datatable" border="1" cellpadding="10">
<?php foreach ($logs as $key => $log) {?>
<tr>
<td class="unnamed1"><input type="checkbox" name="ids[]" value="<?=$log['id'];?>"></td>
<td class="unnamed1"><?=$log['dirname'];?></td>
<td class="unnamed1"><?=$log['filename'];?></td>
<td class="unnamed1"><?=$log['url'];?></td>
<td class="unnamed1"><?php if ($log['isImage']) {?><img src="<?=$log['url'];?>" width="120px" height="120px"><?php }?></td>
<td class="unnamed1">
<a href="<?=Url::to(['site/deletefile', 'id' => $log['id'], 'dirname' => \Yii::$app->request->get('dirname', '')]);?>" onClick="return confirm('确定要删除吗? 删除后无法恢复');">删除</a>
</td>
</tr>
<?php }?>
</table>
<div class="form-group">
<?=Html::submitButton('批量删除', ['class' => 'btn btn-primary', 'name' => 'createdirform-button']);?>
</div>
</form>
</div>
|
df3517ff8ccb54c9fd74d2321b5dfefbea4ee624
|
{
"blob_id": "df3517ff8ccb54c9fd74d2321b5dfefbea4ee624",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-25T05:32:15",
"content_id": "3772d856b30218dfac8692c46768a4c8f1d2ae02",
"detected_licenses": [],
"directory_id": "37f7e58bdc9610832b7da85aabeedf701a296fd1",
"extension": "php",
"filename": "showfiles.php",
"fork_events_count": 0,
"gha_created_at": "2019-09-10T09:13:53",
"gha_event_created_at": "2023-01-04T10:29:59",
"gha_language": "PHP",
"gha_license_id": "BSD-3-Clause",
"github_id": 207514790,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 2169,
"license": "",
"license_type": "permissive",
"path": "/views/site/showfiles.php",
"provenance": "stack-edu-0051.json.gz:777312",
"repo_name": "yiiapps/yii-aws",
"revision_date": "2019-10-25T05:32:15",
"revision_id": "d9766940def0ca16bdf746b5214400c97dc3f151",
"snapshot_id": "8e850a89738ded65ac5e8c5ef39e1c120078bbe0",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yiiapps/yii-aws/d9766940def0ca16bdf746b5214400c97dc3f151/views/site/showfiles.php",
"visit_date": "2023-01-24T02:49:48.184797",
"added": "2024-11-18T22:38:19.117687+00:00",
"created": "2019-10-25T05:32:15",
"int_score": 2,
"score": 2.1875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0069.json.gz"
}
|
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include "../importgl.h"
#include "Application.h"
#include "Loop.h"
#include "settings.h"
namespace Engine {
Application::Application() {
//init GL
importGLInit();
//init SDL and it's subsystems
__sdl_was_init = __img_was_init = __ttf_was_init = false;
//init SDL main
if(SDL_Init(SDL_INIT_VIDEO)!=0) {
string e = "Unable to init SDL: "; e+=SDL_GetError();
throw e;
}
__sdl_was_init = true;
//init PNG
int need=IMG_INIT_PNG;
int init=IMG_Init(need);
if((init&need) != need) {
string e = "Unable to init required png support: "; e+=IMG_GetError();
throw e;
}
__img_was_init = true;
//init fonts
if(TTF_WasInit()==0) {
if(TTF_Init()<0) {
string e = "Unable to init fonts support: "; e+=TTF_GetError();
throw e;
}
}
__ttf_was_init = true;
}
Application::~Application() {
if(__ttf_was_init) TTF_Quit();
if(__img_was_init) IMG_Quit();
if(__sdl_was_init) SDL_Quit();
importGLDeinit();
}
void Application::load_options(int argc, char** argv) {
options.clear();
//apply default settings
options.displace("width", DEFAULT_WIDTH);
options.displace("height", DEFAULT_HEIGHT);
options.displace("fullscreen", DEFAULT_FULLSCREEN);
options.displace("language", DEFAULT_LANGUAGE);
//TODO: apply arguments settings
//apply config settings
#ifdef CONFIG_FILENAME
options.push_table(CONFIG_FILENAME);
#endif
}
void Application::work(int argc, char** argv) {
Controller controller(&options, &state);
for(Loop_Iteraton i=LOOP_ITERATION_USUAL;;) {
load_options(argc, argv);
Loop loop(&controller);
switch(i) {
default:;
//add cases that influence the game before starting
//all cases that influence the game after previous iteration are in switch down there
}
try {
loop();
break;
} catch (Loop_Iteraton next_iteration) {
i=next_iteration;
switch(next_iteration) {
case LOOP_ITERATION_USUAL: state.clear(); break; //just relaunch
case LOOP_ITERATION_SAVE_STATE: break;
default:
throw next_iteration; //main() is going to crash
}
}
}
}
}
|
b944a5c413b7d0eb0b7800eb09535186a95fa68d
|
{
"blob_id": "b944a5c413b7d0eb0b7800eb09535186a95fa68d",
"branch_name": "refs/heads/master",
"committer_date": "2013-11-17T11:02:09",
"content_id": "99d72cb0c0b2e05cdb1f1799b9f6466105c45e8a",
"detected_licenses": [
"Zlib"
],
"directory_id": "300eebc55b9c779d89fd64035a3278cf4ff795f6",
"extension": "cpp",
"filename": "Application.cpp",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2102,
"license": "Zlib",
"license_type": "permissive",
"path": "/00_engine/00_template/src/Engine/Application.cpp",
"provenance": "stack-edu-0002.json.gz:537584",
"repo_name": "Tkachov/Square",
"revision_date": "2013-11-17T11:02:09",
"revision_id": "6d001c5a2af1b35baba369fbb4f90f86315b64c3",
"snapshot_id": "a02f182b32ea552b3b7f5601dc4e4fb7325e3758",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Tkachov/Square/6d001c5a2af1b35baba369fbb4f90f86315b64c3/00_engine/00_template/src/Engine/Application.cpp",
"visit_date": "2021-01-13T01:58:05.889359",
"added": "2024-11-18T20:40:26.690203+00:00",
"created": "2013-11-17T11:02:09",
"int_score": 3,
"score": 2.671875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0020.json.gz"
}
|
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using MixerLib.Helpers;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
namespace MixerLib
{
internal class JsonRpcWebSocket : IJsonRpcWebSocket, IDisposable
{
const int CONNECT_TIMEOUT = 20000; // In milliseconds
const int READ_BUFFER_SIZE = 1024;
public TimeSpan ReconnectDelay { get; set; } = TimeSpan.FromSeconds(5);
readonly ILogger _logger;
readonly IMixerFactory _factory;
readonly IEventParser _parser;
readonly byte[] _readBuffer;
readonly MemoryStream _receiveStream = new MemoryStream();
IClientWebSocketProxy _ws;
readonly CancellationTokenSource _cancellationToken = new CancellationTokenSource();
bool _disposed;
int _nextPacketId = 0;
readonly ConcurrentDictionary<int, TaskCompletionSource<bool>> _pendingRequests = new ConcurrentDictionary<int, TaskCompletionSource<bool>>();
readonly ConcurrentQueue<Guid> _myLatestMessages = new ConcurrentQueue<Guid>();
Task _receiverTask;
int? _receiverThreadId;
public bool IsAuthenticated { get; private set; }
public string[] Roles { get; private set; }
public TimeSpan ReplyTimeout { get; set; }
#if GENERATE_DUMPS
readonly Random _dumpRandom = new Random();
#endif
/// <summary>
/// Construct a new JsonRpcWebSocket object
/// </summary>
public JsonRpcWebSocket(ILogger logger, IMixerFactory factory, IEventParser parser)
{
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_parser = parser ?? throw new ArgumentNullException(nameof(parser));
_readBuffer = new byte[READ_BUFFER_SIZE];
ReplyTimeout = TimeSpan.FromSeconds(10);
}
/// <summary>
/// Try connecting to the specified websocket url once.
/// If the connection is successful, it will complete the function and you don't have to worry
/// about reconnects
/// </summary>
public async Task<bool> TryConnectAsync(Func<string> resolveUrl, string accessToken, Func<Task> postConnectFunc)
{
if (resolveUrl == null)
throw new ArgumentNullException(nameof(resolveUrl));
if (_disposed)
throw new ObjectDisposedException(nameof(JsonRpcWebSocket));
// Local function that will try to reconnect forever
async Task reconnect()
{
while (true)
{
// Connection lost, wait a little and try again
await Task.Delay(GetReconnectDelay(), _cancellationToken.Token);
await connect();
if (_ws != null)
return;
}
}
// Local function used for connect and re-connects
async Task connect()
{
_ws = null;
var url = resolveUrl();
try
{
var ws = CreateWebSocket(accessToken);
// Connect the websocket
_logger.LogInformation("Connecting to {0}", url);
await ws.ConnectAsync(new Uri(url), _cancellationToken.Token).OrTimeout(CONNECT_TIMEOUT);
_logger.LogInformation("Connected to {0}", url);
_ws = ws;
await EatWelcomeMessageAsync().OrTimeout(10000);
// start receiving data
_receiverTask = Task.Factory.StartNew(() => ReceiverTask(reconnect), TaskCreationOptions.LongRunning);
if (postConnectFunc != null)
await postConnectFunc();
}
catch (Exception e)
{
_ws = null;
_logger.LogWarning("Connection to '{0}' failed: {1}", url, e.Message);
}
}
// Do the first time connect
await connect();
return _ws != null;
}
private TimeSpan GetReconnectDelay()
{
var delay = ReconnectDelay;
if (delay < TimeSpan.FromMilliseconds(10))
delay = TimeSpan.FromMilliseconds(10);
return delay;
}
private IClientWebSocketProxy CreateWebSocket(string accessToken)
{
var ws = _factory.CreateClientWebSocket(_parser.IsChat);
ws.SetRequestHeader("x-is-bot", "true");
if (!string.IsNullOrEmpty(accessToken))
{
ws.SetRequestHeader("Authorization", $"Bearer {accessToken}");
}
return ws;
}
private async Task EatWelcomeMessageAsync()
{
// Wait for next message
var json = await ReceiveNextMessageAsync(_ws);
if (string.IsNullOrEmpty(json))
{
_logger.LogWarning("Received null message EatWelcomeMessageAsync()");
return;
}
_logger.LogTrace("<< " + json);
var doc = JToken.Parse(json);
if (doc["event"]?.Value<string>() == "hello")
{
var hello = doc["data"]?.GetObject<WS.HelloData>();
if (hello != null)
IsAuthenticated = hello.Authenticated;
}
}
/// <summary>
/// Received data from the websocket.
/// This will run for the lifetime of the connection or until cancellation is requested
/// </summary>
private async Task ReceiverTask(Func<Task> reconnect)
{
_receiverThreadId = Thread.CurrentThread.ManagedThreadId;
var ws = _ws;
while (!_cancellationToken.IsCancellationRequested)
{
try
{
// Wait for next message
var json = await ReceiveNextMessageAsync(ws);
if (json == null)
throw new Exception("Connection closed");
_logger.LogTrace("<< " + json);
ProcessReceivedMessage(json);
ws.ProcessingDone(); // Don't remove! Will break tests
}
catch (Exception e) // Maybe filter the exception on HResult == 0x80072eff (WININET_E_CONNECTION_RESET) ?
{
if (_cancellationToken.IsCancellationRequested)
return;
_logger.LogWarning("Error in ReceiverTask() {0}. Will reconnect", e.Message);
reconnect().Forget(); // Will spawn a new receiver task
break;
}
}
}
private void ProcessReceivedMessage(string json)
{
#if GENERATE_DUMPS
if (_parser.IsChat)
File.AppendAllText("ChatDump.json", json + Environment.NewLine, Encoding.UTF8);
else if (json.Length > 120 || !json.Contains("payload\":{\"viewers") || _dumpRandom.Next(100) < 5)
File.AppendAllText("ConstellationDump.json", json + Environment.NewLine, Encoding.UTF8);
#endif
try
{
var doc = JToken.Parse(json);
if (doc.IsNullOrEmpty())
return;
var type = doc["type"];
if (type.IsNullOrEmpty())
return;
switch ((string)type)
{
case "reply":
HandleReply(doc);
break;
case "event":
HandleEvent(doc);
break;
}
}
catch (Exception ex)
{
// Catch any error in parsing the json message, and move on
// NOTE: Maybe I should just catch JsonException here but I like to keep processing messages
// and not trigger a re-connect
_logger.LogWarning("Error in ProcessReceivedMessage: {0}", ex.Message);
}
}
/// <summary>
/// Handle an event message from the websocket
/// </summary>
/// NOITE: CHANGE TO USE STRING INSTEAD OF JToken
private void HandleEvent(JToken doc)
{
if (doc.IsNullOrEmpty())
return;
var data = doc["data"];
if (data.IsNullOrEmpty())
return;
if (data.Type != JTokenType.Object)
return;
// Ignore messages I have send
if (!data["id"].IsNullOrEmpty() && Guid.TryParse((string)data["id"], out var guid))
{
if (_myLatestMessages.Contains(guid))
return;
}
_parser.Process(doc["event"]?.Value<string>(), data);
}
/// <summary>
/// Handle a reply message from the websocket
/// </summary>
private void HandleReply(JToken doc)
{
if (doc.IsNullOrEmpty())
return;
var error = doc["error"];
if (!error.IsNullOrEmpty())
{
_logger.LogError($"Error from server: Code = {(int)error["code"]} Message = '{(string)error["message"]}'");
}
var data = doc["data"];
if (data?.Type != JTokenType.Object)
data = null; // Ignore data which is not an object
if (!data.IsNullOrEmpty() && !data["id"].IsNullOrEmpty())
{
// Remember last 5 messages I have send
_myLatestMessages.Enqueue(Guid.Parse((string)data["id"]));
while (_myLatestMessages.Count > 5)
_myLatestMessages.TryDequeue(out var _);
}
if (!data.IsNullOrEmpty() && !data["authenticated"].IsNullOrEmpty())
{
IsAuthenticated = data["authenticated"].Value<bool>();
Roles = data["roles"]?.Values<string>().ToArray();
}
var id = doc["id"].Value<int>();
if (_pendingRequests.TryGetValue(id, out var task))
{
// Signal waiting task that we have received a reply
if (error?.HasValues == true)
task.SetResult(false);
else
task.SetResult(true);
}
else
{
_logger.LogWarning($"Received reply to unknown pending request (packet id={id}). We currently have {_pendingRequests.Count} pending request");
}
}
/// <summary>
/// Send a command to the server, will wait for reply
/// </summary>
/// <returns>true if success, or false if error</returns>
public async Task<bool> SendAsync(string method, params object[] args)
{
if (_disposed)
throw new ObjectDisposedException(nameof(JsonRpcWebSocket));
if (Thread.CurrentThread.ManagedThreadId == _receiverThreadId)
throw new Exception("Cannot call SendAsync on same thread as websocket receiver thread!");
var ws = _ws;
if (ws == null)
return false;
var id = Interlocked.Increment(ref _nextPacketId);
var json = BuildRequestString(method, args, id);
var buffer = new ArraySegment<byte>(Encoding.UTF8.GetBytes(json));
// Send request and wait for reply (or timeout)
var tcs = new TaskCompletionSource<bool>();
_pendingRequests.TryAdd(id, tcs);
try
{
await ws.SendAsync(buffer, WebSocketMessageType.Text, true, _cancellationToken.Token);
if (Debugger.IsAttached) // no timeout while debugging
await tcs.Task;
else
await tcs.Task.OrTimeout(ReplyTimeout);
return tcs.Task.Result;
}
finally
{
_pendingRequests.TryRemove(id, out var _);
}
}
/// <summary>
/// Builds the json request string for the server.
/// Takes care of masking the authKey out when doing logging
/// </summary>
/// <param name="method">Method name</param>
/// <param name="args">Variable arguments based on method</param>
/// <param name="id">Id to use for the json rpc request</param>
/// <returns>Json string</returns>
private string BuildRequestString(string method, object[] args, int id)
{
var req = new WS.Request {
Id = id,
Type = "method",
Method = method
};
if (_parser.IsChat)
{
if (args != null && args.Length != 0)
req.Arguments = args;
}
else
{
req.Params = new { events = args };
}
var json = MixerSerializer.Serialize(req);
LogRequest(method, args, json);
return json;
}
private void LogRequest(string method, object[] args, string json)
{
if (_logger.IsEnabled(LogLevel.Trace))
{
if (method == "auth" && args.Length >= 3)
{
// hide the authKey from log
_logger.LogTrace(">> " + json.Replace((string)args[2], "************"));
}
else
{
_logger.LogTrace(">> " + json);
}
}
}
/// <summary>
/// Reads the complete next text message from the websocket
/// </summary>
/// <returns>The text message, or null if socket was closed</returns>
private async Task<string> ReceiveNextMessageAsync(IClientWebSocketProxy ws)
{
_receiveStream.Position = 0;
WebSocketReceiveResult result;
do
{
result = await ws.ReceiveAsync(new ArraySegment<byte>(_readBuffer), _cancellationToken.Token);
if (result == null || result.Count == 0 || result.MessageType == WebSocketMessageType.Close)
return null;
if (ws.CloseStatus.HasValue)
return null;
Debug.Assert(result.MessageType == WebSocketMessageType.Text);
if (result.EndOfMessage && _receiveStream.Position == 0)
return Encoding.UTF8.GetString(_readBuffer, 0, result.Count); // No need to use memory stream
_receiveStream.Write(_readBuffer, 0, result.Count);
}
while (!result.EndOfMessage);
return Encoding.UTF8.GetString(_receiveStream.GetBuffer(), 0, (int)_receiveStream.Position);
}
/// <summary>
/// Closes the websocket connection and stops the receiving task
/// </summary>
public void Dispose()
{
if (_disposed)
throw new ObjectDisposedException(nameof(JsonRpcWebSocket));
// Stop receiver task
_cancellationToken.Cancel();
_ws?.Dispose();
// Wait for it to complete
_receiverTask?.Wait();
_receiveStream.Dispose();
_disposed = true;
}
}
}
|
a2c20c1d2ec7372858da3a7845523625f70381e9
|
{
"blob_id": "a2c20c1d2ec7372858da3a7845523625f70381e9",
"branch_name": "refs/heads/dev",
"committer_date": "2018-11-15T04:46:36",
"content_id": "dbc5b39b1dac559846fcadd33ea1bd8650703113",
"detected_licenses": [
"MIT"
],
"directory_id": "9e181453e5ee188a9f456a104db1ca04c0b5e6b6",
"extension": "cs",
"filename": "JsonRpcWebSocket.cs",
"fork_events_count": 0,
"gha_created_at": "2018-03-18T19:47:12",
"gha_event_created_at": "2018-11-15T04:46:37",
"gha_language": "C#",
"gha_license_id": "MIT",
"github_id": 125761565,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 12368,
"license": "MIT",
"license_type": "permissive",
"path": "/MixerLib/JsonRpcWebSocket.cs",
"provenance": "stack-edu-0010.json.gz:546795",
"repo_name": "jbdk/MixerLib",
"revision_date": "2018-11-15T04:46:36",
"revision_id": "212a3846f9a77497e79e0be27e67e49b46aa8f25",
"snapshot_id": "4c0423f47770172e375b44e944860ed15977e1f0",
"src_encoding": "UTF-8",
"star_events_count": 4,
"url": "https://raw.githubusercontent.com/jbdk/MixerLib/212a3846f9a77497e79e0be27e67e49b46aa8f25/MixerLib/JsonRpcWebSocket.cs",
"visit_date": "2021-04-12T04:42:02.502118",
"added": "2024-11-18T22:01:52.129456+00:00",
"created": "2018-11-15T04:46:36",
"int_score": 2,
"score": 2.3125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
/**
* @author [Brendon Sutaj]
* @email [[email protected]]
* @create date 2019-04-01 12:00:00
* @modify date 2019-09-12 23:52:28
* @desc [description]
*/
#region USINGS
using System;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using TMPro;
using UnityEngine;
using static Config;
using System.Collections;
using UnityEngine.Networking;
using System.Xml;
#endregion
public class IPointOfView : MonoBehaviour
{
// Childobjects and Fields, for convinience.
[SerializeField] public string Path;
[SerializeField] public bool TriggeredOnce;
[SerializeField] public GameObject ImageHolder, InfoPanel;
// Private Variables.
private WalkableGraph Graph;
private float Distance;
private bool deserializationIsDone = false;
/**
* Deserializes the .xml file ("Path") and stores the WalkableGraph in "Graph".
*/
void Start()
{
DeserializeXml();
if (Config.URLUSED) {
return;
}
// Compute the right Distances from pov to groupd and from group to their respective nodes.
ComputeDistances();
// Load global value from Config.
Distance = Config.POV_GROUP_DISTANCE;
// Pass the PaperInfo/SciGraph data to the InfoPanel/ImageHolder.
InfoPanel.GetComponent<IInfoPanel>().Paper = Graph.PaperInfo.Paper;
// If the sciGraph file does not exist, or is even null, hide the button.
if (string.IsNullOrEmpty(Graph.PaperInfo.Paper.SciGraph) || !File.Exists(GetFilePath(Graph.PaperInfo.Paper.SciGraph.Trim()))) {
transform.Find("Menu/SciGraph").gameObject.SetActive(false);
} else {
ImageHolder.SetActive(true);
ImageHolder.GetComponent<IImageHolder>().SciGraph = Graph.PaperInfo.Paper.SciGraph;
ImageHolder.GetComponent<IImageHolder>().createContent();
ImageHolder.SetActive(false);
}
InfoPanel.SetActive(true);
InfoPanel.GetComponent<IInfoPanel>().createContent();
InfoPanel.SetActive(false);
deserializationIsDone = true;
}
void Update() {
if (TriggeredOnce) {
return;
}
if (deserializationIsDone && Graph != null) {
TriggeredOnce = true;
GenerateGraph();
}
}
/**
* This function is used to compute the distances from pov to group and from group to their respective nodes.
*/
private void ComputeDistances()
{
var maxNodes = 0;
foreach (var group in Graph.Groups.Group)
{
maxNodes = Math.Max(maxNodes, group.Paper.Count);
}
if (maxNodes == 1) {
Config.GROUP_PAPER_DISTANCE = 1;
} else {
Config.GROUP_PAPER_DISTANCE = Convert.ToSingle(
Math.Max(1, Math.Round(0.6 / Math.Sqrt(2 - 2 * Math.Cos(7 * Math.PI / (4 * (maxNodes - 1)))), 2) + 0.01)
);
}
int m = Graph.Groups.Group.Count;
if (m == 1 || m == 2) {
Config.POV_GROUP_DISTANCE = 1;
}
if (m == 3) {
Config.POV_GROUP_DISTANCE = Convert.ToSingle(
(Config.GROUP_PAPER_DISTANCE + 0.6) * Math.Sin(37.5 * Math.PI / 180) / Math.Sin(2 * Math.PI / 3)
);
}
if (m == 4) {
Config.POV_GROUP_DISTANCE = Convert.ToSingle(
(Config.GROUP_PAPER_DISTANCE + 0.6) * Math.Cos(Math.PI / 8)
);
}
if (m > 4) {
Config.POV_GROUP_DISTANCE = Convert.ToSingle(
Math.Max(1, Math.Round((0.6 + Config.GROUP_PAPER_DISTANCE) / Math.Sin(2 * Math.PI / m), 2) + 0.01)
);
}
}
/**
* Deserializes the xml file ("Path") into the WalkableGraph Object "Graph".
*/
private void DeserializeXml()
{
if (Config.URLUSED)
{
StartCoroutine(DeserializeXmlFromURL());
return;
}
// Load the file from StreamingAssets as a String.
var fileAsStr = GetFileData(Path);
// XML deserialize into the WalkableGraph object "graph".
var memStream = new MemoryStream(Encoding.UTF8.GetBytes(fileAsStr));
var serializer = new XmlSerializer(typeof(WalkableGraph));
Graph = (WalkableGraph)serializer.Deserialize(memStream);
}
/**
* Deserializes the xml file from the URL given in the Config into the WalkableGraph Object "Graph"
*/
private IEnumerator DeserializeXmlFromURL()
{
using(UnityWebRequest www = UnityWebRequest.Get(Config.URL + Config.XMLNAME)) {
yield return www.SendWebRequest();
// XML deserialize into the WalkableGraph object "graph".
var memStream = new MemoryStream(www.downloadHandler.data);
var serializer = new XmlSerializer(typeof(WalkableGraph));
Graph = (WalkableGraph)serializer.Deserialize(memStream);
// Compute the right Distances from pov to groupd and from group to their respective nodes.
ComputeDistances();
// Load global value from Config.
Distance = Config.POV_GROUP_DISTANCE;
// Pass the PaperInfo/SciGraph data to the InfoPanel/ImageHolder.
InfoPanel.GetComponent<IInfoPanel>().Paper = Graph.PaperInfo.Paper;
InfoPanel.SetActive(true);
InfoPanel.GetComponent<IInfoPanel>().createContent();
InfoPanel.SetActive(false);
// If the sciGraph file does not exist, or is even null, hide the button.
if (string.IsNullOrEmpty(Graph.PaperInfo.Paper.SciGraph)) {
transform.Find("Menu/SciGraph").gameObject.SetActive(false);
} else {
ImageHolder.SetActive(true);
ImageHolder.GetComponent<IImageHolder>().SciGraph = Graph.PaperInfo.Paper.SciGraph;
StartCoroutine(ImageHolder.GetComponent<IImageHolder>().createContentFromURL());
}
deserializationIsDone = true;
}
}
/**
* Triggered by Hololens-User walking onto the POV.
*
* Spawns Group Objects in a 360° equidistant manner around the POV and assigns them their "Group" - Data.
* (Euler Function)
*/
private void GenerateGraph()
{
var groupCount = Graph.Groups.Group.Count;
float Scale = transform.localScale.x / 2;
for (int i = 0; i < groupCount; i++)
{
// Calculations, phi = Angle to the new Group. -- exp(i*phi) = cos(phi) + i*sin(phi)
// The Addition "+ Math.PI / 2" makes sure that a Group always spawns in front of the User.
var phi = (Math.PI / 2) + (2 * Math.PI / groupCount) * i;
var sinus = Convert.ToSingle(Math.Sin(phi));
var cosinus = Convert.ToSingle(Math.Cos(phi));
// New Group position and value to rotate the Group Object itself.
var grpDestination = new Vector3(cosinus * Distance, transform.localPosition.y, sinus * Distance);
// Due to the fact that all instantiated Objects face to the North (90°), we only need to rotate them (phi - 90°) further.
// Note - This will not result in a negative angle because phi is alway bigger then 90°.
var grpRotation = (int)(phi * 180 / Math.PI - 90);
/* Line Positions lineFrom and lineTo.
* The POV always starts at (x,z) = (0,0) and has a radius of Scale.
* In order to let the line start at the edge of the POV it has go from (x,z) = (cos * Scale, sin * Scale).
* to the distant point following that direction.
*/
var lineFrom = new Vector3(cosinus * Scale, transform.localPosition.y, sinus * Scale);
var lineTo = new Vector3(cosinus * (Distance - Scale), transform.localPosition.y, sinus * (Distance - Scale));
// Spawn the Group and Line.
SpawnGroup(Graph.Groups.Group[i], grpDestination, grpRotation);
SpawnLine(Graph.Groups.Group[i].GroupName, lineFrom, lineTo);
}
}
/**
* Spawns Group Objects at the given position and rotation.
*/
private void SpawnGroup(Group group, Vector3 position, float rotation)
{
// Spawn a new Group Node, set the position and the new angle.
var groupObj = Instantiate((GameObject) Resources.Load("Prefabs/GroupNode", typeof(GameObject)));
var groupController = groupObj.GetComponent<IGroupNode>();
groupObj.transform.position = position;
groupObj.transform.eulerAngles = new Vector3(0.0f, rotation, 0.0f);
// Pass the Group data to the group.
groupController.Group = group;
// Pass the POV object to the group too.
groupController.pov = this.gameObject;
}
/**
* Spawns a Line Object, from - to.
*/
private void SpawnLine(String groupName, Vector3 from, Vector3 to)
{
// Spawn a new Line at the given from and to positions.
var lineObj = Instantiate((GameObject) Resources.Load("Prefabs/Line", typeof(GameObject)));
var lineRenderer = lineObj.GetComponent<LineRenderer>();
lineRenderer.SetPosition(0, from);
lineRenderer.SetPosition(1, to);
// Little Addition to make it look even cooler!
var lineTop = Instantiate((GameObject) Resources.Load("Prefabs/LineTop", typeof(GameObject)));
var rendererTop = lineTop.GetComponent<LineRenderer>();
var newFrom = new Vector3(from.x, from.y + 0.005f, from.z);
var newTo = new Vector3(to.x, to.y + 0.005f, to.z);
rendererTop.SetPosition(0, newFrom);
rendererTop.SetPosition(1, newTo);
// Spawn the Text onto the line at the half distance of the line.
SpawnTextOnLine(rendererTop, groupName);
}
/**
* Spawns text on the position half of the given lineRenderer.
*/
private void SpawnTextOnLine(LineRenderer lineRenderer, string text)
{
var lineTextobj = Instantiate((GameObject) Resources.Load("Prefabs/LineText", typeof(GameObject)));
var lineStart = lineRenderer.GetPosition(0);
var lineEnd = lineRenderer.GetPosition(1);
lineTextobj.transform.position = new Vector3((lineStart.x + lineEnd.x) / 2, transform.localPosition.y + 0.05f, (lineStart.z + lineEnd.z) / 2);
lineTextobj.transform.Find("Text").GetComponent<TextMeshPro>().text = text;
}
/**
* This function is used to get the FileData returned as a string.
*/
private string GetFileData(string fileName)
{
var filePath = GetFilePath(fileName);
// Open the file in readonly to avoid access exceptions.
var fileStream = File.OpenRead(filePath);
var bytes = ReadStream(fileStream);
return Encoding.UTF8.GetString(bytes);
}
/**
* This function is used to get the filePath from the StreamingAssets Folder on the Device.
*/
private string GetFilePath(string fileName)
{
return System.IO.Path.Combine(Application.streamingAssetsPath, fileName);
}
/**
* This function is used to get all bytes from the given stream.
*/
private byte[] ReadStream(Stream fileStream)
{
using (MemoryStream memStream = new MemoryStream())
{
fileStream.CopyTo(memStream);
var result = memStream.ToArray();
return result;
}
}
/**
* PaperInfo Button EventHandler.
* Activates/Deactivates InfoPanel.
*/
public void PaperInfoHandler()
{ // Resets the InfoPanel to page 1, if it is being currently deactivated.
if (InfoPanel.activeSelf) {
InfoPanel.GetComponent<IInfoPanel>().reset();
}
InfoPanel.SetActive(!InfoPanel.activeSelf);
}
/**
* SciGraph Button EventHandler.
* Activates/Deactivates ImageHolder.
*/
public void ImageHolderHandler()
{
ImageHolder.SetActive(!ImageHolder.activeSelf);
}
}
|
763c0d5f3852ef28af5ac72cad1840d0783e2c60
|
{
"blob_id": "763c0d5f3852ef28af5ac72cad1840d0783e2c60",
"branch_name": "refs/heads/master",
"committer_date": "2019-10-15T23:16:55",
"content_id": "017127614ba9ae88f8c398647d1c24176878e1b3",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "9c74bf9ea50fd5581d84e71d5234c48a79cd752e",
"extension": "cs",
"filename": "IPointOfView.cs",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 196218239,
"is_generated": false,
"is_vendor": false,
"language": "C#",
"length_bytes": 12131,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/Assets/Resources/Scripts/IPointOfView.cs",
"provenance": "stack-edu-0010.json.gz:543090",
"repo_name": "BrendonSutaj/TWG---HoloLens-Application",
"revision_date": "2019-10-15T23:16:55",
"revision_id": "3b2d3a3671975506211e3e0536493e5419f2ebab",
"snapshot_id": "b8505b3f1f6d2a023d24221f18d097444c4542e9",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/BrendonSutaj/TWG---HoloLens-Application/3b2d3a3671975506211e3e0536493e5419f2ebab/Assets/Resources/Scripts/IPointOfView.cs",
"visit_date": "2020-06-18T07:43:16.740053",
"added": "2024-11-18T22:00:32.204516+00:00",
"created": "2019-10-15T23:16:55",
"int_score": 2,
"score": 2.34375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0028.json.gz"
}
|
/* libpgm1.c - pgm utility library part 1
**
** Copyright (C) 1989 by Jef Poskanzer.
**
** Permission to use, copy, modify, and distribute this software and its
** documentation for any purpose and without fee is hereby granted, provided
** that the above copyright notice appear in all copies and that both that
** copyright notice and this permission notice appear in supporting
** documentation. This software is provided "as is" without express or
** implied warranty.
*/
/* See libpbm.c for the complicated explanation of this 32/64 bit file
offset stuff.
*/
#define _FILE_OFFSET_BITS 64
#define _LARGE_FILES
#include <string.h>
#include <stdio.h>
/*#include <errno.h>*/
#include <stdlib.h>
#include <limits.h>
#include "libpgm.h"
int readmagicnumber(FILE * const ifP) {
int ich1, ich2;
ich1 = getc(ifP);
ich2 = getc(ifP);
if (ich1 == EOF || ich2 == EOF){
fprintf(stderr, "Error reading magic number from Netpbm image stream.\nMost often, this means your input file is empty.\n" );
exit(-1);
}
return ich1 * 256 + ich2;
}
inline unsigned int pgm_getuint(FILE * const ifP) {
/*----------------------------------------------------------------------------
Read an unsigned integer in ASCII decimal from the file stream
represented by 'ifP' and return its value.
If there is nothing at the current position in the file stream that
can be interpreted as an unsigned integer, issue an error message
to stderr and abort the program.
If the number at the current position in the file stream is too
great to be represented by an 'int' (Yes, I said 'int', not
'unsigned int'), issue an error message to stderr and abort the
program.
-----------------------------------------------------------------------------*/
char ch,rubish[100000];
unsigned int i;
do {
ch = fgetc(ifP);
if(ch=='#')
fgets(rubish,100000,ifP);
} while (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' || ch == '#');
if (ch < '0' || ch > '9'){
fprintf(stderr,"junk in file where an unsigned integer should be\n");
exit(-1);
}
i = 0;
do {
unsigned int const digitVal = ch - '0';
if (i > INT_MAX/10 - digitVal){
fprintf(stderr,"ASCII decimal integer in file is too large to be processed.\n");
exit(-1);
}
i = i * 10 + digitVal;
ch = fgetc(ifP);
} while (ch >= '0' && ch <= '9');
return i;
}
gray ** pgm_allocarray(int cols,int rows){
gray ** rowIndex;
int row,col;
rowIndex = (gray**) malloc( rows * sizeof(gray*) );
if (rowIndex== NULL){
fprintf(stderr,"out of memory allocating Row %u of an array\n", row);
exit(-1);
}
for (row = 0; row < rows; row++) {
rowIndex[row] = (gray*) malloc(cols * sizeof(gray));
if (rowIndex[row] == NULL){
fprintf(stderr,"out of memory allocating Row %u (%u columns, %u bytes per tuple) of an array\n", row, cols, sizeof(gray));
exit(-1);
}
}
for (row = 0; row < rows; row++)
for (col=0; col < cols; col++)
rowIndex[row][col]=PGM_MAXVAL;
return rowIndex;
}
void pgm_freearray(gray ** const rowIndex, int const rows) {
unsigned int row;
for (row = 0; row < rows; ++row)
free(rowIndex[row]);
free(rowIndex);
}
/*************************************************************/
/* PGM routines */
/*************************************************************/
void pgm_readpgminitrest(FILE * const file,
int * const colsP,
int * const rowsP,
gray * const maxvalP) {
gray maxval;
/* Read size. */
*colsP = (int)pgm_getuint(file);
*rowsP = (int)pgm_getuint(file);
/* Read maxval. */
maxval = pgm_getuint(file);
if (maxval == 0){
fprintf(stderr,"maxval of input image is zero.");
exit(-1);
}
*maxvalP = (gray) maxval;
}
void pgm_readpgminit(FILE * const file, int * const colsP,
int * const rowsP, gray * const maxvalP, int * const formatP) {
/* Check magic number. */
*formatP = readmagicnumber( file );
switch ( PGM_FORMAT_TYPE(*formatP) ) {
case PGM_TYPE:
pgm_readpgminitrest( file, colsP, rowsP, maxvalP );
break;
default:
fprintf(stderr, "bad magic number - not a pgm file\n" );
exit(-1);
}
}
gray pgm_getrawsample(FILE * const file, gray const maxval) {
int iby;
iby = getc(file);
if (iby == EOF){
fprintf(stderr,"EOF / read error reading a one-byte sample\n");
exit(-1);
}
return (unsigned char) iby;
}
void pgm_readpgmrow(FILE* const file, gray* const grayrow,
int const cols, gray const maxval, int const format) {
switch (format) {
case PGM_FORMAT: {
int col;
for (col = 0; col < cols; ++col)
grayrow[col] = pgm_getuint(file);
}
break;
case RPGM_FORMAT: {
int col;
for (col = 0; col < cols; ++col)
grayrow[col] = pgm_getrawsample( file, maxval );
}
break;
default:
fprintf(stderr,"can't happen\n");
}
}
gray** pgm_readpgm(FILE * const file, int * const colsP, int * const rowsP,
gray * const maxvalP) {
gray** grays;
int row;
int format;
pgm_readpgminit( file, colsP, rowsP, maxvalP, &format );
grays = pgm_allocarray( *colsP, *rowsP );
for ( row = 0; row < *rowsP; row++ )
pgm_readpgmrow( file, grays[row], *colsP, *maxvalP, format );
return grays;
}
/********************************************************************/
/* writing routines */
/********************************************************************/
void pgm_writepgminit(FILE * const fileP, int const cols, int const rows, gray const maxval, int const forceplain)
{
fprintf(fileP, "%c%c\n%d %d\n%d\n", PGM_MAGIC1,
forceplain ? PGM_MAGIC2 : RPGM_MAGIC2,
cols, rows, maxval );
}
static void pgm_writepgmrowraw(FILE *file, gray *grayrow, int cols, gray maxval ) {
int col,rc;
for (col = 0; col < cols; col++,grayrow++) {
rc = fputc(*grayrow, file);
if (rc == EOF){
fprintf(stderr,"Error writing single byte sample to file\n");
exit(-1);
}
}
}
inline void pgm_writepgmrowplain(FILE *file, gray *grayrow, int cols, gray maxval ) {
register int col, charcount;
register gray* gP;
charcount = 0;
for ( col = 0, gP = grayrow; col < cols; ++col, ++gP )
{
if ( charcount >= 65 ){
(void) fprintf(file, "\n");
charcount = 0;
} else if ( charcount > 0 )
{
(void) fprintf(file," ");
charcount++;
}
fprintf(file, "%i ", (int) *gP);
charcount += 3;
}
if ( charcount > 0 )
(void) fprintf(file, "\n");
}
void pgm_writepgmrow( FILE* file, gray* grayrow, int cols, gray maxval, int forceplain )
{
if (forceplain )
pgm_writepgmrowplain( file, grayrow, cols, maxval );
else
pgm_writepgmrowraw( file, grayrow, cols, maxval );
}
void pgm_writepgm( FILE* file, gray** grays, int cols, int rows, gray maxval, int forceplain )
{
int row;
pgm_writepgminit( file, cols, rows, maxval, forceplain );
for ( row = 0; row < rows; row++ )
pgm_writepgmrow( file, grays[row], cols, maxval, forceplain );
}
|
27e53ae967860fe873f55ff0263fefcee0783462
|
{
"blob_id": "27e53ae967860fe873f55ff0263fefcee0783462",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-26T16:54:04",
"content_id": "d1556c85a68dd28098c5a6a0d3fdab50c3ea689e",
"detected_licenses": [
"MIT"
],
"directory_id": "dbd844bb6c9e2a2bfa3c1e45486fbe6c9f9f6b1b",
"extension": "c",
"filename": "libpgm.c",
"fork_events_count": 0,
"gha_created_at": "2018-05-13T10:42:50",
"gha_event_created_at": "2022-02-03T18:06:13",
"gha_language": "CMake",
"gha_license_id": "MIT",
"github_id": 133227682,
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 7338,
"license": "MIT",
"license_type": "permissive",
"path": "/FelixiAtros/iatros-v1.0/iatros/htr/offline/src/data_sets/libpgm.c",
"provenance": "stack-edu-0001.json.gz:288398",
"repo_name": "MarioProjects/FelixRobot",
"revision_date": "2020-06-26T16:54:04",
"revision_id": "aeb6eaa329167b75c13d21c2c8de618af182c465",
"snapshot_id": "66ddaf62298de2273138600a7dc8284a3adb68ac",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/MarioProjects/FelixRobot/aeb6eaa329167b75c13d21c2c8de618af182c465/FelixiAtros/iatros-v1.0/iatros/htr/offline/src/data_sets/libpgm.c",
"visit_date": "2022-02-15T23:03:27.438389",
"added": "2024-11-18T19:42:00.481100+00:00",
"created": "2020-06-26T16:54:04",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0019.json.gz"
}
|
---
title: component environment variables
---
## Component environment variable management
The component supports custom environment variables. Users can add the environment variables in the form of Key | Value, and the environment variables will be injected into the component.
### add environment variable
Components -> Environment Variables -> Add Variables.
* variable name:key
* variable value:value
* Description:variable description, will not be injected into the component
### delete environment variable
components -> environment variables -> delete variables
:::danger
note:variable is not recoverable after deletion
:::
### Modify environment variables
Components -> Environment Variables -> Modification
Environment variables only support modifying `variable value`
### transfer environment variables
Convert the environment variable to a dependent environment variable. When the component is dependent, this environment variable will be injected into the dependent component.
> After the transfer, the environment variables will still take effect in the current component.
:::danger
The operations of the above environment variables need to be updated/restarted to take effect.
:::
## Component Profile Management
Configuration file mounting means that we fill in the file content into Rainbond, and Rainbond is mounted to the component in the form of a file.
### Add configuration file
Go to Components -> Environment Configuration -> Configuration File Settings -> Add Configuration File
<img src="https://static.goodrain.com/docs/5.6/use-manual/component-manage/env/configmap.png" width="30%" />
Profile info:
* config file name:custom (not file name)
* The configuration file mount path:needs to fill in the absolute path including the file name, such as:/data/test.conf
* Permissions for files with permissions:, e.g.:777
* Configuration file content:custom
### Edit configuration file
Go to Components -> Environment Configuration -> Configuration File Settings -> Edit Configuration File
`Configuration file mounting path`,`Permissions`,`Configuration file content` can be modified, but the configuration file name cannot be modified.
Rainbond will check whether the content of the configuration file has been modified. If it is not modified, it will not be saved.
### delete profile
Go to Components -> Environment Configuration -> Configuration File Settings -> Delete Configuration File
Note that:will not be recovered after deletion
:::danger
The operations of the above configuration files need to be updated/restarted to take effect.
:::
## shared configuration file
The shared configuration file is to mount the configuration files of other components to the current component, which is suitable for scenarios where the configuration files of multiple components are consistent.
### Mount shared configuration file
Go to Components -> Environment Configuration -> Shared Configuration File Settings -> Mount Shared Configuration File
Fill in the local mount path:
* Check the components that need to mount the configuration file
* Fill in the local mount configuration file path:, you need to write the absolute path including the file name

### Unmount shared configuration file
Go to Components -> Environment Configuration -> Shared Configuration File Settings -> Unmount
:::danger
The above operations of sharing configuration files need to be updated/restarted to take effect.
:::
### Component advanced environment variable configuration
```mdx-code-block
import DocCardList from '@theme/DocCardList';
import {useCurrentSidebarCategory} from '@docusaurus/theme-common';
<DocCardList items={useCurrentSidebarCategory().items}/>
```
|
e5d8f132a71f4dac06652061d1b7717bffb80523
|
{
"blob_id": "e5d8f132a71f4dac06652061d1b7717bffb80523",
"branch_name": "refs/heads/main",
"committer_date": "2023-06-19T04:49:17",
"content_id": "25e26c96ea74e9ee5b06d1684d446c981f535a3b",
"detected_licenses": [],
"directory_id": "bbf7caba12978e5f8cc1872c06f7c3c50244c2c3",
"extension": "md",
"filename": "index.md",
"fork_events_count": 0,
"gha_created_at": "2018-12-26T04:19:37",
"gha_event_created_at": "2019-03-11T09:11:05",
"gha_language": "CSS",
"gha_license_id": "CC-BY-4.0",
"github_id": 163135559,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3838,
"license": "",
"license_type": "permissive",
"path": "/i18n/en/docusaurus-plugin-content-docs/current/use-manual/component-manage/env/index.md",
"provenance": "stack-edu-markdown-0012.json.gz:233322",
"repo_name": "dazuimao1990/rainbond-docs",
"revision_date": "2023-06-19T04:49:17",
"revision_id": "b6c1593330792aba3db9073ddc86cca6639776ed",
"snapshot_id": "843131a47e4dfb814224f1e64c1ec58467b001a8",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dazuimao1990/rainbond-docs/b6c1593330792aba3db9073ddc86cca6639776ed/i18n/en/docusaurus-plugin-content-docs/current/use-manual/component-manage/env/index.md",
"visit_date": "2023-06-25T04:33:15.075735",
"added": "2024-11-18T23:24:37.278169+00:00",
"created": "2023-06-19T04:49:17",
"int_score": 4,
"score": 3.90625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0012.json.gz"
}
|
<?php
namespace App\Repository;
use App\Entity\Freesites;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* FreesitesRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class FreesitesRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, Freesites::class);
}
//obtiene los sitios free.
public function isFreeSite($host)
{
$em = $this->getEntityManager();
//obtengo el listado
$free = $em->getRepository(Freesites::class)->findOneBy(array('patron' => $host));
if (!$free)
return 0;
else
return 1;
}
}
|
f562ab7ede18d1828f45ed3a99bcc3ee427579d0
|
{
"blob_id": "f562ab7ede18d1828f45ed3a99bcc3ee427579d0",
"branch_name": "refs/heads/master",
"committer_date": "2018-09-01T15:19:18",
"content_id": "7846c60b3c271db6e9844be0aff039e183b35b7f",
"detected_licenses": [
"MIT"
],
"directory_id": "d581c3eec7cec9548ccec543d1d633067cbedc8f",
"extension": "php",
"filename": "FreesitesRepository.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 115636382,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 827,
"license": "MIT",
"license_type": "permissive",
"path": "/src/Repository/FreesitesRepository.php",
"provenance": "stack-edu-0054.json.gz:166265",
"repo_name": "pecalleja/squidtrace",
"revision_date": "2018-09-01T15:19:18",
"revision_id": "7803de38a5c05c1062a164251890ea8e6c314a25",
"snapshot_id": "05ce38a4848150b1b14db5ed102259f1e7dea452",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/pecalleja/squidtrace/7803de38a5c05c1062a164251890ea8e6c314a25/src/Repository/FreesitesRepository.php",
"visit_date": "2021-09-21T22:23:46.161514",
"added": "2024-11-19T00:16:17.230998+00:00",
"created": "2018-09-01T15:19:18",
"int_score": 2,
"score": 2.453125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0072.json.gz"
}
|
package com.baidu.disconf.client.common.model;
/**
* 实例指纹
*
* @author liaoqiqi
* @version 2014-6-27
*/
public class InstanceFingerprint {
// 本实例应用名及所在机器的IP
private String appName = "";
// 可以表示本实例的pid
private int pid = 0;
// 一个实例固定的UUID
private String uuid = "";
public InstanceFingerprint(String appName, int pid, String uuid) {
super();
this.appName = appName;
this.pid = pid;
this.uuid = uuid;
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
@Override
public String toString() {
return "InstanceFingerprint [appName=" + appName + ", pid=" + pid + "]";
}
}
|
8faa2456e063529444526cceb5a839e4faa43214
|
{
"blob_id": "8faa2456e063529444526cceb5a839e4faa43214",
"branch_name": "refs/heads/master",
"committer_date": "2016-11-24T03:28:29",
"content_id": "4ec7b5acd5b38206ad86f5b778755694905c02aa",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "03f7735517626ee0400e1aee1b94be7be1e61105",
"extension": "java",
"filename": "InstanceFingerprint.java",
"fork_events_count": 0,
"gha_created_at": "2016-10-20T09:50:16",
"gha_event_created_at": "2016-11-08T07:30:03",
"gha_language": "Java",
"gha_license_id": null,
"github_id": 71448897,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1023,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/disconf-client/src/main/java/com/baidu/disconf/client/common/model/InstanceFingerprint.java",
"provenance": "stack-edu-0019.json.gz:805565",
"repo_name": "ledotcom/disconf",
"revision_date": "2016-11-24T03:28:29",
"revision_id": "b0a39f93798ccb86fa8d2c12867b00a378eb4213",
"snapshot_id": "8d0efc38515f0a6d577623c6d20b4dfa868a27cc",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/ledotcom/disconf/b0a39f93798ccb86fa8d2c12867b00a378eb4213/disconf-client/src/main/java/com/baidu/disconf/client/common/model/InstanceFingerprint.java",
"visit_date": "2021-01-12T16:50:58.913543",
"added": "2024-11-18T21:04:51.251403+00:00",
"created": "2016-11-24T03:28:29",
"int_score": 2,
"score": 2.46875,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0037.json.gz"
}
|
#!/usr/bin/python3
import os
import subprocess
import rpmfile
import re
__tarantool_version = None
basepath = os.path.realpath(
os.path.join(os.path.dirname(__file__), '..', '..')
)
# #######
# Helpers
# #######
def tarantool_version():
global __tarantool_version
if __tarantool_version is None:
__tarantool_version = subprocess.check_output(['tarantool', '-V']).decode('ascii').split('\n')[0]
return __tarantool_version
def tarantool_enterprise_is_used():
return tarantool_version().startswith('Tarantool Enterprise')
def create_project(module_tmpdir, project_name, template):
cmd = [
os.path.join(basepath, "cartridge"), "create",
"--name", project_name,
"--template", template
]
process = subprocess.run(cmd, cwd=module_tmpdir)
assert process.returncode == 0, \
"Error during creating the project"
return os.path.join(module_tmpdir, project_name)
def find_archive(path, project_name, arch_ext):
with os.scandir(path) as it:
for entry in it:
if entry.name.startswith(project_name) and entry.name.endswith('.' + arch_ext) and entry.is_file():
return os.path.join(path, entry.name)
def recursive_listdir(root_dir):
files = set()
for root, directories, filenames in os.walk(root_dir):
rel_dir = os.path.relpath(root, root_dir)
if rel_dir == '.':
rel_dir = ''
for directory in directories:
files.add(os.path.join(rel_dir, directory))
for filename in filenames:
files.add(os.path.join(rel_dir, filename))
return files
def assert_dir_contents(files_list, exp_files_list, exp_rocks_content,
skip_tarantool_binaries=False):
without_rocks = {x for x in files_list if not x.startswith('.rocks')}
if tarantool_enterprise_is_used() and not skip_tarantool_binaries:
assert without_rocks == exp_files_list.union(set(['tarantool', 'tarantoolctl']))
else:
assert without_rocks == exp_files_list
assert all(x in files_list for x in exp_rocks_content)
def assert_filemode(project, filepath, filemode):
filepath = os.path.join('/', filepath)
if filepath == os.path.join('/usr/share/tarantool/', project['name'], 'VERSION'):
assert filemode & 0o777 == 0o644
elif filepath.startswith('/etc/systemd/system/'):
assert filemode & 0o777 == 0o644
elif filepath.startswith('/usr/lib/tmpfiles.d/'):
assert filemode & 0o777 == 0o644
elif filepath.startswith('/usr/share/tarantool/'):
# a+r for files, a+rx for directories
required_bits = 0o555 if os.path.isdir(filepath) else 0o444
assert filemode & required_bits == required_bits
def assert_filemodes(project, basedir):
known_dirs = set([
'etc', 'etc/systemd', 'etc/systemd/system',
'usr', 'usr/share', 'usr/share/tarantool',
'usr/lib', 'usr/lib/tmpfiles.d'
])
filenames = recursive_listdir(basedir) - known_dirs
for filename in filenames:
# we don't check fileowner here because it's set in postinst script
# check filemode
if filename.startswith(os.path.join('usr/share/tarantool/', project['name'], '.rocks')):
continue
# get filestat
file_stat = os.stat(os.path.join(basedir, filename))
filemode = file_stat.st_mode
assert_filemode(project, filename, filemode)
def validate_version_file(project, distribution_dir):
original_keys = [
'TARANTOOL',
project['name'],
# default app dependencies
'luatest',
'cartridge',
# known cartridge dependencies
'membership',
'checks',
'vshard',
'http',
'frontend-core',
]
if tarantool_enterprise_is_used():
original_keys.append('TARANTOOL_SDK')
version_filepath = os.path.join(distribution_dir, 'VERSION')
assert os.path.exists(version_filepath)
version_file_content = {}
with open(version_filepath, 'r') as version_file:
file_lines = version_file.read().strip().split('\n')
for l in file_lines:
m = re.match(r'^([^=]+)=([^=]+)$', l)
assert m is not None
key, version = m.groups()
version_file_content[key] = version
for key in original_keys:
assert key in version_file_content
def assert_files_mode_and_owner_rpm(project, filename):
DIRNAMES_TAG = 1118
DIRINDEXES_TAG = 1116
expected_tags = [
'basenames', DIRNAMES_TAG, DIRINDEXES_TAG, 'filemodes',
'fileusername', 'filegroupname'
]
with rpmfile.open(filename) as rpm:
for key in expected_tags:
assert key in rpm.headers
for i, basename in enumerate(rpm.headers['basenames']):
# get filepath
basename = basename.decode("utf-8")
dirindex = rpm.headers[DIRINDEXES_TAG][i]
dirname = rpm.headers[DIRNAMES_TAG][dirindex].decode("utf-8")
filepath = os.path.join(dirname, basename)
# check fileowner
assert rpm.headers['fileusername'][i].decode("utf-8") == 'root'
assert rpm.headers['filegroupname'][i].decode("utf-8") == 'root'
# check filemodes
if filepath.startswith(os.path.join('/usr/share/tarantool/', project['name'], '.rocks')):
continue
filemode = rpm.headers['filemodes'][i]
assert_filemode(project, filepath, filemode)
def assert_tarantool_dependency_deb(filename):
with open(filename) as control:
control_info = control.read()
depends_str = re.search('Depends: (.*)', control_info)
assert depends_str is not None
min_version = re.findall(r'\d+\.\d+\.\d+', tarantool_version())[0]
max_version = str(int(re.findall(r'\d+', tarantool_version())[0]) + 1)
deps = depends_str.group(1)
assert 'tarantool (>= {})'.format(min_version) in deps
assert 'tarantool (<< {})'.format(max_version) in deps
def assert_tarantool_dependency_rpm(filename):
with rpmfile.open(filename) as rpm:
dependency_keys = ['requirename', 'requireversion', 'requireflags']
for key in dependency_keys:
assert key in rpm.headers
assert len(rpm.headers['requirename']) == 2
assert len(rpm.headers['requireversion']) == 2
assert len(rpm.headers['requireversion']) == 2
min_version = re.findall(r'\d+\.\d+\.\d+', tarantool_version())[0]
max_version = str(int(re.findall(r'\d+', tarantool_version())[0]) + 1)
assert rpm.headers['requirename'][0].decode('ascii') == 'tarantool'
assert rpm.headers['requireversion'][0].decode('ascii') == min_version
assert rpm.headers['requireflags'][0] == 0x08 | 0x04 # >=
assert rpm.headers['requirename'][1].decode('ascii') == 'tarantool'
assert rpm.headers['requireversion'][1].decode('ascii') == max_version
assert rpm.headers['requireflags'][1] == 0x02 # <
def check_systemd_dir(project, basedir):
systemd_dir = (os.path.join(basedir, 'etc/systemd/system'))
assert os.path.exists(systemd_dir)
systemd_files = recursive_listdir(systemd_dir)
assert len(systemd_files) == 2
assert '{}.service'.format(project['name']) in systemd_files
assert '{}@.service'.format(project['name']) in systemd_files
def check_package_files(project, basedir):
# check if only theese files are delivered
for filename in recursive_listdir(basedir):
assert any([
filename.startswith(prefix) or prefix.startswith(filename)
for prefix in [
os.path.join('usr/share/tarantool', project['name']),
'etc/systemd/system',
'usr/lib/tmpfiles.d'
]
])
# check distribution dir content
distribution_dir = os.path.join(basedir, 'usr/share/tarantool', project['name'])
assert os.path.exists(distribution_dir)
assert_dir_contents(
files_list=recursive_listdir(distribution_dir),
exp_files_list=project['distribution_files_list'],
exp_rocks_content=project['rocks_content']
)
# check systemd dir content
check_systemd_dir(project, basedir)
# check tmpfiles conf
project_tmpfiles_conf_file = os.path.join(basedir, 'usr/lib/tmpfiles.d', '%s.conf' % project['name'])
with open(project_tmpfiles_conf_file) as f:
assert f.read().find('d /var/run/tarantool') != -1
# check version file
validate_version_file(project, distribution_dir)
|
b04ae0000186304091fc24f19fa27d118e889764
|
{
"blob_id": "b04ae0000186304091fc24f19fa27d118e889764",
"branch_name": "refs/heads/master",
"committer_date": "2020-01-13T16:16:13",
"content_id": "8f8c81f7c472e79784daa7f10b02ca266a13dabc",
"detected_licenses": [
"BSD-2-Clause"
],
"directory_id": "3d57af093a806457a219d4da4e73c9f8db8b0030",
"extension": "py",
"filename": "utils.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8627,
"license": "BSD-2-Clause",
"license_type": "permissive",
"path": "/test/python/utils.py",
"provenance": "stack-edu-0065.json.gz:202619",
"repo_name": "dimoffon/cartridge-cli",
"revision_date": "2020-01-13T16:16:13",
"revision_id": "a3266989d92e730f9be3bb2d3fc1934f9fb1d0a5",
"snapshot_id": "7b1cea56caf0795891f288da75e36696c68d5a6c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/dimoffon/cartridge-cli/a3266989d92e730f9be3bb2d3fc1934f9fb1d0a5/test/python/utils.py",
"visit_date": "2020-12-11T08:58:27.196181",
"added": "2024-11-18T22:54:25.558025+00:00",
"created": "2020-01-13T16:16:13",
"int_score": 2,
"score": 2.09375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
package be.ugent.vopro1.converter.json.serialization;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.aikodi.lang.funky.behavior.Loop;
import java.io.IOException;
/**
* Serializer for {@link Loop}
*/
public class LoopSerializer extends JsonSerializer<Loop> {
@Override
public void serialize(Loop value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeStartObject();
gen.writeObjectField("data", value.body());
gen.writeObjectField("condition", value.condition().description());
gen.writeEndObject();
}
}
|
123981f6e9b3b0ef556360b4b8410ab4b245d91f
|
{
"blob_id": "123981f6e9b3b0ef556360b4b8410ab4b245d91f",
"branch_name": "refs/heads/master",
"committer_date": "2017-02-19T16:50:42",
"content_id": "bd400460e4cad07d240ded8d30e31c0ffd4ac303",
"detected_licenses": [
"MIT"
],
"directory_id": "4a3fb8c9b965cb2948fe8c3b60e3d73a7ab58a7b",
"extension": "java",
"filename": "LoopSerializer.java",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 712,
"license": "MIT",
"license_type": "permissive",
"path": "/VOP/src/main/java/be/ugent/vopro1/converter/json/serialization/LoopSerializer.java",
"provenance": "stack-edu-0021.json.gz:578341",
"repo_name": "yang123vc/UGentProjects",
"revision_date": "2017-02-19T16:50:42",
"revision_id": "5561ce3bb73d5bc5bf31bcda2be7e038514c7072",
"snapshot_id": "de75c3f13b53a44865db4722dae807a4fb03ce9e",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/yang123vc/UGentProjects/5561ce3bb73d5bc5bf31bcda2be7e038514c7072/VOP/src/main/java/be/ugent/vopro1/converter/json/serialization/LoopSerializer.java",
"visit_date": "2020-06-21T23:04:49.947791",
"added": "2024-11-19T00:05:06.304072+00:00",
"created": "2017-02-19T16:50:42",
"int_score": 2,
"score": 2.25,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0039.json.gz"
}
|
from dataclasses import dataclass
@dataclass
class BBRefGameInfo:
"""Individual game info scraped from brooksbaseball.com."""
url: str = ""
bbref_game_id: str = ""
def as_dict(self):
"""Convert game info to a dictionary."""
return {
"__bbref_game_info__": True,
"url": self.url,
"bbref_game_id": self.bbref_game_id,
}
|
5200900f56a3bd9c22c7c53e793df871225d709c
|
{
"blob_id": "5200900f56a3bd9c22c7c53e793df871225d709c",
"branch_name": "refs/heads/master",
"committer_date": "2022-07-08T14:55:56",
"content_id": "a35890378d47f7e72f07990bceca19c1cf084c89",
"detected_licenses": [
"MIT"
],
"directory_id": "b7500e25551e14fd71694bf7a240eb7c95e38f20",
"extension": "py",
"filename": "game_info.py",
"fork_events_count": 2,
"gha_created_at": "2019-03-06T16:48:22",
"gha_event_created_at": "2023-08-16T02:01:16",
"gha_language": "Python",
"gha_license_id": "MIT",
"github_id": 174183970,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 398,
"license": "MIT",
"license_type": "permissive",
"path": "/src/vigorish/scrape/bbref_games_for_date/models/game_info.py",
"provenance": "stack-edu-0064.json.gz:143486",
"repo_name": "a-luna/vigorish",
"revision_date": "2022-07-08T14:55:56",
"revision_id": "84bd02311b35e2789d741d8cb10a3e4e584f0255",
"snapshot_id": "5f05af1d44745af91a82f84886dd81f8a2cf7489",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/a-luna/vigorish/84bd02311b35e2789d741d8cb10a3e4e584f0255/src/vigorish/scrape/bbref_games_for_date/models/game_info.py",
"visit_date": "2023-08-22T11:51:51.866613",
"added": "2024-11-18T22:29:34.152218+00:00",
"created": "2022-07-08T14:55:56",
"int_score": 3,
"score": 2.625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0082.json.gz"
}
|
package com.nanchen.rxjava2examples.module.rxjava2.usecases.fastNetwork;
import android.util.Log;
import com.nanchen.rxjava2examples.model.MobileAddress;
import com.nanchen.rxjava2examples.model.MobileAddress.ResultBean;
import com.nanchen.rxjava2examples.module.rxjava2.operators.item.RxOperatorBaseActivity;
import com.rx2androidnetworking.Rx2AndroidNetworking;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
* Rx2AndroidNetworking
*
* 仅仅是采用这个框架做 rx2 网络请求
*
* Author: nanchen
* Email: [email protected]
* Date: 2017-06-30 15:41
*/
public class RxNetworkActivity extends RxOperatorBaseActivity {
private static final String TAG = "RxNetworkActivity";
@Override
protected String getSubTitle() {
return "使用Rx2-Networking";
}
@Override
protected void doSomething() {
mRxOperatorsText.append("RxNetworkActivity\n");
Rx2AndroidNetworking.get("http://api.avatardata.cn/MobilePlace/LookUp?key=ec47b85086be4dc8b5d941f5abd37a4e&mobileNumber=13021671512")
.build()
.getObjectObservable(MobileAddress.class)
.observeOn(AndroidSchedulers.mainThread()) // 为doOnNext() 指定在主线程,否则报错
.doOnNext(new Consumer<MobileAddress>() {
@Override
public void accept(@NonNull MobileAddress data) throws Exception {
Log.e(TAG, "doOnNext:"+Thread.currentThread().getName()+"\n" );
mRxOperatorsText.append("\ndoOnNext:"+Thread.currentThread().getName()+"\n" );
Log.e(TAG,"doOnNext:"+data.toString()+"\n");
mRxOperatorsText.append("doOnNext:"+data.toString()+"\n");
}
})
.map(new Function<MobileAddress, ResultBean>() {
@Override
public ResultBean apply(@NonNull MobileAddress mobileAddress) throws Exception {
Log.e(TAG, "\n" );
mRxOperatorsText.append("\n");
Log.e(TAG, "map:"+Thread.currentThread().getName()+"\n" );
mRxOperatorsText.append("map:"+Thread.currentThread().getName()+"\n" );
return mobileAddress.getResult();
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ResultBean>() {
@Override
public void accept(@NonNull ResultBean data) throws Exception {
Log.e(TAG, "subscribe 成功:"+Thread.currentThread().getName()+"\n" );
mRxOperatorsText.append("\nsubscribe 成功:"+Thread.currentThread().getName()+"\n" );
Log.e(TAG, "成功:" + data.toString() + "\n");
mRxOperatorsText.append("成功:" + data.toString() + "\n");
}
}, new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception {
Log.e(TAG, "subscribe 失败:"+Thread.currentThread().getName()+"\n" );
mRxOperatorsText.append("\nsubscribe 失败:"+Thread.currentThread().getName()+"\n" );
Log.e(TAG, "失败:"+ throwable.getMessage()+"\n" );
mRxOperatorsText.append("失败:"+ throwable.getMessage()+"\n");
}
});
}
}
|
804f80e52c001daf6753e646698fe92742220227
|
{
"blob_id": "804f80e52c001daf6753e646698fe92742220227",
"branch_name": "refs/heads/master",
"committer_date": "2017-07-12T06:12:36",
"content_id": "6db1539b3c645172aace4b81d0e0853eb943afb1",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "da5feee275a35c67afb1979ef1cec746d59b7d2f",
"extension": "java",
"filename": "RxNetworkActivity.java",
"fork_events_count": 0,
"gha_created_at": "2017-07-13T09:44:23",
"gha_event_created_at": "2017-07-13T09:44:23",
"gha_language": null,
"gha_license_id": null,
"github_id": 97106690,
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 3808,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/app/src/main/java/com/nanchen/rxjava2examples/module/rxjava2/usecases/fastNetwork/RxNetworkActivity.java",
"provenance": "stack-edu-0023.json.gz:78530",
"repo_name": "cocowobo/RxJava2Examples",
"revision_date": "2017-07-12T06:12:36",
"revision_id": "6188f2f097ef107ab5bfb748eaedf59dc38a45cf",
"snapshot_id": "926e1bab3af8712dc59162e9c17d97e79c90c0c7",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/cocowobo/RxJava2Examples/6188f2f097ef107ab5bfb748eaedf59dc38a45cf/app/src/main/java/com/nanchen/rxjava2examples/module/rxjava2/usecases/fastNetwork/RxNetworkActivity.java",
"visit_date": "2021-01-01T04:02:15.462427",
"added": "2024-11-19T03:23:39.723914+00:00",
"created": "2017-07-12T06:12:36",
"int_score": 2,
"score": 2.4375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0041.json.gz"
}
|
# Releasing
Once your changes are in master, the latest release should be set as a draft at https://github.com/pact-foundation/pact-go/releases/.
Once you've tested that it works as expected:
1. Bump version in `command/version.go`.
1. Run `make release` to generate release notes and release commit.
1. Edit the release notes at https://github.com/pact-foundation/pact-go/releases/edit/v<VERSION>.
|
b19578d86f32a8346ae2a702610b38cf96934ef6
|
{
"blob_id": "b19578d86f32a8346ae2a702610b38cf96934ef6",
"branch_name": "refs/heads/master",
"committer_date": "2023-08-28T22:30:41",
"content_id": "e6b1b2ef65a1d51f42c65152d3b9d2c54d50fe61",
"detected_licenses": [
"MIT"
],
"directory_id": "7652dda7b0f405c6dacfe853fb9f45c0d848c108",
"extension": "md",
"filename": "RELEASING.md",
"fork_events_count": 115,
"gha_created_at": "2016-05-15T12:21:58",
"gha_event_created_at": "2023-09-11T17:19:50",
"gha_language": "Go",
"gha_license_id": "MIT",
"github_id": 58860113,
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 403,
"license": "MIT",
"license_type": "permissive",
"path": "/RELEASING.md",
"provenance": "stack-edu-markdown-0015.json.gz:82210",
"repo_name": "pact-foundation/pact-go",
"revision_date": "2023-08-28T22:30:41",
"revision_id": "b93338ea05d98e89c365c8c4e44067dc1bf0376c",
"snapshot_id": "83cadfdc89a35385ecbed46f1933599c9fb475c6",
"src_encoding": "UTF-8",
"star_events_count": 784,
"url": "https://raw.githubusercontent.com/pact-foundation/pact-go/b93338ea05d98e89c365c8c4e44067dc1bf0376c/RELEASING.md",
"visit_date": "2023-09-02T04:08:58.535247",
"added": "2024-11-19T00:43:55.995417+00:00",
"created": "2023-08-28T22:30:41",
"int_score": 3,
"score": 2.65625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0015.json.gz"
}
|
import {
SET_NOVAPOSHTA_CITIES,
SET_NOVAPOSHTA_WAREHOUSES,
SET_NOVAPOSHTA_PRICES,
SET_FONDY_DATA,
SET_DELIVERY_LOADING,
SET_UKRPOST_REGIONS,
SET_UKRPOST_DISTRICTS,
SET_UKRPOST_CITIES,
SET_UKRPOST_POSTOFFICES
} from './checkout.types';
const initialState = {
deliveryLoading: false,
cities: [],
warehouses: [],
price: {},
ukrPoshtaCities: [],
ukrPoshtaRegions: [],
ukrPoshtaDistricts: [],
ukrPoshtaPostOffices: []
};
export const checkoutReducer = (state = initialState, action = {}) => {
switch (action.type) {
case SET_UKRPOST_REGIONS:
return {
...state,
ukrPoshtaRegions: action.payload
};
case SET_UKRPOST_DISTRICTS:
return {
...state,
ukrPoshtaDistricts: action.payload
};
case SET_UKRPOST_CITIES:
return {
...state,
ukrPoshtaCities: action.payload
};
case SET_UKRPOST_POSTOFFICES:
return {
...state,
ukrPoshtaPostOffices: action.payload
};
case SET_NOVAPOSHTA_CITIES:
return {
...state,
cities: action.payload
};
case SET_FONDY_DATA:
return {
...state,
fondyData: action.payload
};
case SET_NOVAPOSHTA_PRICES:
return {
...state,
price: action.payload
};
case SET_NOVAPOSHTA_WAREHOUSES:
return {
...state,
warehouses: action.payload
};
case SET_DELIVERY_LOADING:
return {
...state,
deliveryLoading: action.payload
};
default:
return state;
}
};
|
9646c8454cfd2a10e4370b29ce98c97981f463a5
|
{
"blob_id": "9646c8454cfd2a10e4370b29ce98c97981f463a5",
"branch_name": "refs/heads/master",
"committer_date": "2021-09-24T13:38:46",
"content_id": "2625b079257b788be2e51882a501ddb521cbce27",
"detected_licenses": [
"MIT"
],
"directory_id": "b5c788d99f53f2c102b313766a4b70bee39e49cb",
"extension": "js",
"filename": "checkout.reducer.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": null,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1590,
"license": "MIT",
"license_type": "permissive",
"path": "/src/redux/checkout/checkout.reducer.js",
"provenance": "stack-edu-0036.json.gz:537822",
"repo_name": "AndriySvitlak/horondi_client_fe",
"revision_date": "2021-09-24T13:38:46",
"revision_id": "3f19d172e078c54ed9a63de562e35e7758579c20",
"snapshot_id": "f627b1375519e39c5b8bed1c515d1f904a72b0ca",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/AndriySvitlak/horondi_client_fe/3f19d172e078c54ed9a63de562e35e7758579c20/src/redux/checkout/checkout.reducer.js",
"visit_date": "2023-08-23T06:21:38.016591",
"added": "2024-11-18T23:06:56.271417+00:00",
"created": "2021-09-24T13:38:46",
"int_score": 2,
"score": 2.125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0054.json.gz"
}
|
-- Name: GetGeometricInfo
-- Schema: posda_files
-- Columns: ['sop_instance_uid', 'image_orientation_patient', 'image_position_patient', 'pixel_spacing', 'i_rows', 'i_columns']
-- Args: ['sop_instance_uid']
-- Tags: ['LinkageChecks', 'BySopInstance']
-- Description: Get Geometric Information by Sop Instance UID from posda
select
distinct sop_instance_uid, iop as image_orientation_patient,
ipp as image_position_patient,
pixel_spacing,
pixel_rows as i_rows,
pixel_columns as i_columns
from
file_sop_common join
file_patient using (file_id) join
file_image using (file_id) join
file_series using (file_id) join
file_study using (file_id) join
image using (image_id) join
file_image_geometry using (file_id) join
image_geometry using (image_geometry_id)
where
sop_instance_uid = ?
|
073a8009b32d74bd14a90445388075cfa36c0ef3
|
{
"blob_id": "073a8009b32d74bd14a90445388075cfa36c0ef3",
"branch_name": "refs/heads/master",
"committer_date": "2023-04-11T18:26:03",
"content_id": "39370a50d29411d54005f42f90fab93a475abb0d",
"detected_licenses": [
"Apache-2.0"
],
"directory_id": "631388273b74bbd24b1e4b632f51d7c35aaf1ff0",
"extension": "sql",
"filename": "GetGeometricInfo.sql",
"fork_events_count": 1,
"gha_created_at": "2016-02-17T23:42:51",
"gha_event_created_at": "2023-04-17T01:24:56",
"gha_language": "Perl",
"gha_license_id": "Apache-2.0",
"github_id": 51964104,
"is_generated": false,
"is_vendor": false,
"language": "SQL",
"length_bytes": 815,
"license": "Apache-2.0",
"license_type": "permissive",
"path": "/posda/posdatools/queries/sql/GetGeometricInfo.sql",
"provenance": "stack-edu-0070.json.gz:410590",
"repo_name": "UAMS-DBMI/PosdaTools",
"revision_date": "2023-04-11T18:26:03",
"revision_id": "815dd46399ed6107d27cc6cfdef8563b36560af7",
"snapshot_id": "d2e4cc0b5ae859a180e841d8feb201d23876499e",
"src_encoding": "UTF-8",
"star_events_count": 13,
"url": "https://raw.githubusercontent.com/UAMS-DBMI/PosdaTools/815dd46399ed6107d27cc6cfdef8563b36560af7/posda/posdatools/queries/sql/GetGeometricInfo.sql",
"visit_date": "2023-04-18T16:33:05.939660",
"added": "2024-11-18T20:15:42.139454+00:00",
"created": "2023-04-11T18:26:03",
"int_score": 3,
"score": 3.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0088.json.gz"
}
|
<?php
namespace Tsukudol;
use Teto\HTTP\AcceptLanguage;
/**
* Abstract class of translated content
*
* @author [email protected]
* @license MIT
*
* @property-read array $family
* @property-read array $given
*/
final class LocaleName extends LocaleValue
{
protected $family = [];
protected $given = [];
public function __construct(array $names)
{
$this->setValues($names);
}
/**
* @param string $lang_str
* @param array $options
* @return array
*/
public function getNameIn($lang_str, array $options = [])
{
$tag = self::parseLang($lang_str);
$family = $this->searchValue('family', $tag);
$given = $this->searchValue('given', $tag);
if (isset($options['format']) ) {
$params = [
'family' => $family,
'given' => $given,
];
return self::renderFormat($options['format'], $params);
}
if ($tag['language'] === 'ja') {
$separator = isset($options['separator']) ? $options['separator'] : '';
return $family . $separator . $given;
}
$separator = isset($options['separator']) ? $options['separator'] : ' ';
return $given . $separator . $family;
}
/**
* @return array[]
*/
public function dumpNames()
{
$retval = [];
for ($n = 0; $n < count($this->family); $n++) {
$retval[] = [$this->family[$n][0], ['family' => $this->family[$n][1], 'given' => $this->given[$n][1]]];
}
return $retval;
}
}
|
4fd690677b2db166b954d334c1b838ef31029ad2
|
{
"blob_id": "4fd690677b2db166b954d334c1b838ef31029ad2",
"branch_name": "refs/heads/master",
"committer_date": "2016-08-27T10:18:46",
"content_id": "a9c9bd98649d0100aab9cea32a8db3c06851ed60",
"detected_licenses": [
"MIT"
],
"directory_id": "3a7b9d08f2fd2a182ef14a578597db5036b1d272",
"extension": "php",
"filename": "LocaleName.php",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 25647945,
"is_generated": false,
"is_vendor": false,
"language": "PHP",
"length_bytes": 1608,
"license": "MIT",
"license_type": "permissive",
"path": "/src/LocaleName.php",
"provenance": "stack-edu-0047.json.gz:41387",
"repo_name": "zonuexe/php-tsukudol-nizicon",
"revision_date": "2016-08-27T10:18:46",
"revision_id": "f3a963ed9669aa76cf88e0a0955f2ca403ed8725",
"snapshot_id": "4ff01d44853a87587a2cabc271e8c11608f06d7d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/zonuexe/php-tsukudol-nizicon/f3a963ed9669aa76cf88e0a0955f2ca403ed8725/src/LocaleName.php",
"visit_date": "2020-05-14T11:21:53.575624",
"added": "2024-11-19T01:14:15.952080+00:00",
"created": "2016-08-27T10:18:46",
"int_score": 3,
"score": 2.859375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0065.json.gz"
}
|
import { IUsersService } from './interfaces/IUsersService';
import { Observable } from 'rxjs';
import { IUser } from 'app/models/interfaces/IUser';
import { Injectable } from '@angular/core';
import { ApiTools } from './data-access/ApiTools';
import { AuthManager } from 'app/config/AuthManager';
import { Router } from '@angular/router';
import { Http } from '@angular/http';
import { NotificationsService } from 'angular2-notifications';
import { map } from 'rxjs/operators';
@Injectable()
export class UsersService implements IUsersService {
private _apiTools: ApiTools;
public constructor(
authManager: AuthManager,
http: Http,
router: Router,
notificationService: NotificationsService
) {
this._apiTools = new ApiTools('api/users', authManager, http, notificationService, router);
}
public createUser(usr: IUser): Observable<IUser> {
const route: string = ``;
return this._apiTools.post(route, usr).pipe(map((body: any) => {
return body || false;
}));
}
public delete(id: number): Observable<boolean> {
const route: string = `${id}`;
return this._apiTools.delete(route).pipe(map((body: any) => {
return body || false;
}));
}
public getAll(): Observable<IUser[]> {
const route: string = ``;
return this._apiTools.get(route).pipe(map((body: any) => {
return body || false;
}));
}
public getAttending(): Observable<IUser[]> {
const route: string = `attending`;
return this._apiTools.get(route).pipe(map((body: any) => {
return body || false;
}));
}
public getById(id: number): Observable<IUser> {
const route: string = `${id}`;
return this._apiTools.get(route).pipe(map((body: any) => {
return body || false;
}));
}
getByName(firstName: string, lastName: string): Observable<IUser[]> {
const route: string = `name/${firstName}/${lastName}`;
return this._apiTools.get(route).pipe(map((body: any) => {
return body || false;
}));
}
public updateBulkUsers(users: IUser[]): Observable<IUser[]> {
const route: string = `bulk`;
const data = {
bulkUpdateUserData: users
}
return this._apiTools.put(route, data).pipe(map((body: any) => {
return body || false;
}));
}
public updateUser(usr: IUser): Observable<IUser> {
const route: string = ``;
return this._apiTools.put(route, usr).pipe(map((body: any) => {
return body || false;
}));
}
}
|
4653c1bb1e62b91b7863205c8b8003a303572520
|
{
"blob_id": "4653c1bb1e62b91b7863205c8b8003a303572520",
"branch_name": "refs/heads/master",
"committer_date": "2019-11-25T14:01:30",
"content_id": "e903a5ea370093560845afc11fdd01d28ccfa2cf",
"detected_licenses": [
"MIT"
],
"directory_id": "406aa1f3e3f6c25150d6c6e2c27622b4c57a86f5",
"extension": "ts",
"filename": "UsersService.ts",
"fork_events_count": 0,
"gha_created_at": "2018-11-01T11:50:55",
"gha_event_created_at": "2022-07-07T23:14:10",
"gha_language": "TypeScript",
"gha_license_id": "MIT",
"github_id": 155707470,
"is_generated": false,
"is_vendor": false,
"language": "TypeScript",
"length_bytes": 2681,
"license": "MIT",
"license_type": "permissive",
"path": "/WeddingInfo.Frontend/src/app/services/UsersService.ts",
"provenance": "stack-edu-0074.json.gz:790699",
"repo_name": "jsonpj3wt/WeddingInfo",
"revision_date": "2019-11-25T14:01:30",
"revision_id": "11d100cb1f406915a419dca98bd392769bf79b8a",
"snapshot_id": "9216a96fc31c364b7a476f33ef58d8dc7a503ec3",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/jsonpj3wt/WeddingInfo/11d100cb1f406915a419dca98bd392769bf79b8a/WeddingInfo.Frontend/src/app/services/UsersService.ts",
"visit_date": "2022-07-24T08:42:17.412417",
"added": "2024-11-19T02:35:41.331027+00:00",
"created": "2019-11-25T14:01:30",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0092.json.gz"
}
|
#!/usr/bin/env python3
"""Problem 15 from Project Euler: Lattice Paths
Determine the number of NE routes in an n x n grid.
Usage:
python3 p015.py [num]
"""
import sys
from math import factorial
def lattice_paths(n: int) -> int:
k = 2 * n
return factorial(k) // (factorial(n) * factorial(k - n))
def euler15(num: int) -> int:
"""Calculates the number of NE routes in an n x n grid."""
return lattice_paths(num)
def main(num: str) -> None:
"""Prints the solution."""
print(f'The number of NE routes in a {num} x {num} grid is {euler15(int(num))}.')
if __name__ == '__main__':
main(sys.argv[1])
|
70feda6aca29886cacd41047065584e3ca3d99d9
|
{
"blob_id": "70feda6aca29886cacd41047065584e3ca3d99d9",
"branch_name": "refs/heads/master",
"committer_date": "2020-06-28T00:06:01",
"content_id": "e14e9ef3b56951229f7492b61860afc2c4b98852",
"detected_licenses": [
"MIT"
],
"directory_id": "3f4fe3be0f63386849ce9c1956039372c37521e6",
"extension": "py",
"filename": "p015.py",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 231834092,
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 635,
"license": "MIT",
"license_type": "permissive",
"path": "/p015.py",
"provenance": "stack-edu-0065.json.gz:290542",
"repo_name": "matthew02/project-euler",
"revision_date": "2020-06-28T00:06:01",
"revision_id": "f4b4905c3e3791619143c83a9427a6bb0c1013d2",
"snapshot_id": "6f9a89cb8d7a5195cb71fa012231e61b43b1b455",
"src_encoding": "UTF-8",
"star_events_count": 1,
"url": "https://raw.githubusercontent.com/matthew02/project-euler/f4b4905c3e3791619143c83a9427a6bb0c1013d2/p015.py",
"visit_date": "2020-12-04T16:19:15.553094",
"added": "2024-11-19T02:17:28.998131+00:00",
"created": "2020-06-28T00:06:01",
"int_score": 4,
"score": 3.9375,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0083.json.gz"
}
|
package main
import (
"flag"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"
)
var stopChan chan os.Signal
func init() {
stopChan = make(chan os.Signal, 1)
go stopServer()
signal.Notify(stopChan, syscall.SIGINT)
flag.IntVar(&port, "port", 8000, "server port")
flag.BoolVar(&noEnd, "noend", false, "remove /end path")
}
var (
port int
noEnd bool
)
func main() {
flag.Parse()
args := flag.Args()
if len(args) == 0 {
fmt.Println("pass some files or directory to serve!")
return
}
if !noEnd {
addServerEndPath("/end")
}
for _, item := range args {
err := serveItem(item)
if err != nil {
fmt.Println()
fmt.Println(err)
return
}
}
startServer(port)
}
func serveItem(item string) (err error) {
item, err = filepath.Abs(item)
if err != nil {
return
}
fi, err := os.Stat(item)
if err != nil {
return err
}
defer func() {
e := recover()
if e != nil {
err = fmt.Errorf("%v", e)
}
}()
var pattern string = "/" + fi.Name()
fmt.Println("item: " + item)
fmt.Printf("path (%s): ", pattern)
fmt.Scanln(&pattern)
if !strings.HasPrefix(pattern, "/") {
pattern = "/" + pattern
}
if fi.IsDir() {
if !strings.HasSuffix(pattern, "/") {
pattern = pattern + "/"
}
serveDir(item, pattern)
} else {
serveFile(item, pattern)
}
return
}
func serveFile(file string, pattern string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, file)
})
}
func serveDir(dir string, pattern string) {
http.Handle(pattern, http.StripPrefix(pattern, http.FileServer(http.Dir(dir))))
}
func startServer(port int) {
fmt.Println("\nStarting Server...")
fmt.Printf("http://%s:%d\n", getIP(), port)
if err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil); err != nil {
fmt.Println(err)
}
}
func stopServer() {
<-stopChan
fmt.Println("\nServer Stopped!")
os.Exit(0)
}
func addServerEndPath(pattern string) {
http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Stopping the Server!"))
stopChan <- syscall.SIGINT
})
}
func getIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "localhost"
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return "localhost"
}
|
263fa0d7b29774cbab57522420e1bfd24308477d
|
{
"blob_id": "263fa0d7b29774cbab57522420e1bfd24308477d",
"branch_name": "refs/heads/master",
"committer_date": "2020-09-27T12:21:43",
"content_id": "7186d89acfea7e03d5986098a43b87415f74af79",
"detected_licenses": [
"MIT"
],
"directory_id": "c3ed8da37ff5f932ed554b78e26cdd20ee865a7f",
"extension": "go",
"filename": "main.go",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 298978782,
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 2403,
"license": "MIT",
"license_type": "permissive",
"path": "/cmd/serve/main.go",
"provenance": "stack-edu-0015.json.gz:769372",
"repo_name": "SharanSharathi/simpl-tools",
"revision_date": "2020-09-27T12:21:43",
"revision_id": "62794dcbac811f1fe4fb5b202619c899a59ed88d",
"snapshot_id": "cba142b0c87e95b8b66b351ce7e44e15c9c0e49d",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/SharanSharathi/simpl-tools/62794dcbac811f1fe4fb5b202619c899a59ed88d/cmd/serve/main.go",
"visit_date": "2022-12-24T05:29:06.555270",
"added": "2024-11-18T19:22:49.907440+00:00",
"created": "2020-09-27T12:21:43",
"int_score": 3,
"score": 2.765625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0033.json.gz"
}
|
const is = require('../../../dist/umd/ispro.js');
const yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
const tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));
describe('time/future', () => {
test('should return true if given date is future', () => {
let date = new Date();
let future = new Date(date.setDate(date.getDate() + 1));
expect(is.future(future)).toBe(true);
});
test('should return false if given date is not future', () => {
let date = new Date();
let past = new Date(date.setDate(date.getDate() - 1));
expect(is.future(date)).toBe(false);
expect(is.future(past)).toBe(false);
});
test('is.not.future(yesterday) => true', () => {
expect(is.not.future(yesterday)).toBe(true);
});
test('is.all.future(tomorrow, yesterday) => true', () => {
expect(is.not.future(yesterday)).toBe(true);
});
test('is.any.future(yesterday, tomorrow) => true', () => {
expect(is.any.future(yesterday, tomorrow)).toBe(true);
});
// 'all' and 'any' interfaces can also take array parameter
test('is.all.future([yesterday, tomorrow]) => false', () => {
let yesterday = new Date(new Date().setDate(new Date().getDate() - 1));
let tomorrow = new Date(new Date().setDate(new Date().getDate() + 1));
expect(is.all.future([yesterday, tomorrow])).toBe(false);
});
});
|
ce0d83642510c37944716e7c4116506158303a92
|
{
"blob_id": "ce0d83642510c37944716e7c4116506158303a92",
"branch_name": "refs/heads/master",
"committer_date": "2019-06-07T14:19:36",
"content_id": "a8a367e7cb2391695d0766250794ea8fcc0e1932",
"detected_licenses": [
"MIT"
],
"directory_id": "b565ae31d2686b71c3d6364b068e130ef3928ea1",
"extension": "js",
"filename": "future.spec.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 174945560,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1379,
"license": "MIT",
"license_type": "permissive",
"path": "/test/types/time/future.spec.js",
"provenance": "stack-edu-0042.json.gz:398875",
"repo_name": "lisniuse/is-pro",
"revision_date": "2019-06-07T14:19:36",
"revision_id": "e29a1842e42060b9a8d0b272496fb55f1c7ef1ae",
"snapshot_id": "940adda7a26577931304fb6b723a7460b27f4e3e",
"src_encoding": "UTF-8",
"star_events_count": 2,
"url": "https://raw.githubusercontent.com/lisniuse/is-pro/e29a1842e42060b9a8d0b272496fb55f1c7ef1ae/test/types/time/future.spec.js",
"visit_date": "2020-04-28T03:39:05.145782",
"added": "2024-11-19T01:11:02.518738+00:00",
"created": "2019-06-07T14:19:36",
"int_score": 3,
"score": 2.578125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0060.json.gz"
}
|
module Canvas
module Workflow
module CLI
class Build < Thor
desc "build", "Build the Canvas Workflow project"
option :with_bundler, :aliases => :b,
:type => :boolean, :default => false,
:desc => "build using bundler?"
option :incremental, :aliases => :i,
:type => :boolean, :default => false,
:desc => "enable jekyll incremental builds?"
def build
config = File.expand_path("../../../../../_config.yml", __FILE__)
cmd = ""
cmd << "bundle exec " if options[:with_bundler]
cmd << "jekyll build --config #{config},_config.yml --verbose"
cmd << " --incremental" if options[:incremental]
#puts "#{cmd}"
ret = system("#{cmd}")
raise Error.new($?.exitstatus) if (ret.nil? || ret == false)
end
default_task :build
end
desc "build", "Manage static site generator"
subcommand "build", Build
end
end
end
# Canvas::Workflow::CLI.desc "build", "Manage static site generator"
# Canvas::Workflow::CLI.subcommand "build", Canvas::Workflow::CLI::Build
|
b72d5ea2f24ff0cfa9a8db11025812414980c09e
|
{
"blob_id": "b72d5ea2f24ff0cfa9a8db11025812414980c09e",
"branch_name": "refs/heads/master",
"committer_date": "2019-09-06T17:49:49",
"content_id": "53960e91b73dcd9a74f4c729648594532fe676da",
"detected_licenses": [
"MIT"
],
"directory_id": "ec6d4453001f7afda4d47871b1a48534440f7db6",
"extension": "rb",
"filename": "build.rb",
"fork_events_count": 1,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 119626699,
"is_generated": false,
"is_vendor": false,
"language": "Ruby",
"length_bytes": 1177,
"license": "MIT",
"license_type": "permissive",
"path": "/lib/canvas/workflow/cli/build.rb",
"provenance": "stack-edu-0067.json.gz:413544",
"repo_name": "jiverson002/canvas-workflow",
"revision_date": "2019-09-06T17:49:49",
"revision_id": "db1b771f83e478f72bb03d913898428b92bb794e",
"snapshot_id": "51dedf8a0cc9cccc8823a8c31b8720ad622b265c",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/jiverson002/canvas-workflow/db1b771f83e478f72bb03d913898428b92bb794e/lib/canvas/workflow/cli/build.rb",
"visit_date": "2021-06-16T12:22:54.289875",
"added": "2024-11-18T19:30:12.199474+00:00",
"created": "2019-09-06T17:49:49",
"int_score": 2,
"score": 2.0625,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0085.json.gz"
}
|
import sgMail from '@sendgrid/mail';
import { config } from 'dotenv';
import logger from '../config';
config();
// Setup this key on your .env
sgMail.setApiKey(process.env.SEND_GRID_API);
/**
* @param {String} to The user's email
* @param {String} subject The email subject
* @param {String} message The mail content
* @returns {object} An email on user's email
*/
async function sendEmail(to, subject = 'Afrilearn', message) {
const msg = {
to,
from: '[email protected]',
subject,
text: message,
html: message,
};
try {
await sgMail.send(msg);
logger.info('Successfully Sent');
} catch (err) {
// logger.error(err);
}
}
export default sendEmail;
|
ffaeb6872b93811b6f9be05c0a7ea5e646518f93
|
{
"blob_id": "ffaeb6872b93811b6f9be05c0a7ea5e646518f93",
"branch_name": "refs/heads/main",
"committer_date": "2021-02-17T06:07:31",
"content_id": "576de53386f18510b159b4687966488c886767aa",
"detected_licenses": [
"MIT"
],
"directory_id": "b4e658d616d5f7933f5894fc3a44a46e4cc43c2d",
"extension": "js",
"filename": "email.utils.js",
"fork_events_count": 0,
"gha_created_at": null,
"gha_event_created_at": null,
"gha_language": null,
"gha_license_id": null,
"github_id": 339367864,
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 701,
"license": "MIT",
"license_type": "permissive",
"path": "/src/utils/email.utils.js",
"provenance": "stack-edu-0034.json.gz:64602",
"repo_name": "Ayobamiu/Upload-to-afrilearn",
"revision_date": "2021-02-17T06:07:31",
"revision_id": "00960ca2908fe1482280c998b9578ad45d21570f",
"snapshot_id": "78aa5ba78290c521ed26c7e518377d3710df2af4",
"src_encoding": "UTF-8",
"star_events_count": 0,
"url": "https://raw.githubusercontent.com/Ayobamiu/Upload-to-afrilearn/00960ca2908fe1482280c998b9578ad45d21570f/src/utils/email.utils.js",
"visit_date": "2023-03-05T08:29:34.474493",
"added": "2024-11-19T00:15:17.514348+00:00",
"created": "2021-02-17T06:07:31",
"int_score": 2,
"score": 2.28125,
"source": "stackv2",
"file_path": "/project/aip-craffel/gsa/data/stack_edu/stack-edu-0052.json.gz"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.