file_name large_stringlengths 4 140 | prefix large_stringlengths 0 12.1k | suffix large_stringlengths 0 12k | middle large_stringlengths 0 7.51k | fim_type large_stringclasses 4
values |
|---|---|---|---|---|
document.py | 0000
SCHEMA = 'Document'
SCHEMA_FOLDER = 'Folder'
SCHEMA_PACKAGE = 'Package'
SCHEMA_WORKBOOK = 'Workbook'
SCHEMA_TEXT = 'PlainText'
SCHEMA_HTML = 'HyperText'
SCHEMA_PDF = 'Pages'
SCHEMA_IMAGE = 'Image'
SCHEMA_AUDIO = 'Audio'
SCHEMA_VIDEO = 'Video'
SCHEMA_TABLE = 'Table'
... | (self):
# Slightly unintuitive naming: this just checks the document type,
# not if there actually are any records.
return self.schema in [self.SCHEMA_PDF, self.SCHEMA_TABLE]
@property
def supports_pages(self):
return self.schema == self.SCHEMA_PDF
@property
def support... | supports_records | identifier_name |
document.py | 0000
SCHEMA = 'Document'
SCHEMA_FOLDER = 'Folder'
SCHEMA_PACKAGE = 'Package'
SCHEMA_WORKBOOK = 'Workbook'
SCHEMA_TEXT = 'PlainText'
SCHEMA_HTML = 'HyperText'
SCHEMA_PDF = 'Pages'
SCHEMA_IMAGE = 'Image'
SCHEMA_AUDIO = 'Audio'
SCHEMA_VIDEO = 'Video'
SCHEMA_TABLE = 'Table'
... |
db.session.add(self)
def update_meta(self):
flag_modified(self, 'meta')
def delete_records(self):
pq = db.session.query(DocumentRecord)
pq = pq.filter(DocumentRecord.document_id == self.id)
pq.delete()
db.session.flush()
def delete_tags(self):
pq =... | value = data.get(prop, self.meta.get(prop))
setattr(self, prop, value) | conditional_block |
document.py | 0000
SCHEMA = 'Document'
SCHEMA_FOLDER = 'Folder'
SCHEMA_PACKAGE = 'Package'
SCHEMA_WORKBOOK = 'Workbook'
SCHEMA_TEXT = 'PlainText'
SCHEMA_HTML = 'HyperText'
SCHEMA_PDF = 'Pages'
SCHEMA_IMAGE = 'Image'
SCHEMA_AUDIO = 'Audio'
SCHEMA_VIDEO = 'Video'
SCHEMA_TABLE = 'Table'
... |
def delete_records(self):
pq = db.session.query(DocumentRecord)
pq = pq.filter(DocumentRecord.document_id == self.id)
pq.delete()
db.session.flush()
def delete_tags(self):
pq = db.session.query(DocumentTag)
pq = pq.filter(DocumentTag.document_id == self.id)
... | flag_modified(self, 'meta') | identifier_body |
document.py | 0000
SCHEMA = 'Document'
SCHEMA_FOLDER = 'Folder'
SCHEMA_PACKAGE = 'Package'
SCHEMA_WORKBOOK = 'Workbook'
SCHEMA_TEXT = 'PlainText'
SCHEMA_HTML = 'HyperText'
SCHEMA_PDF = 'Pages'
SCHEMA_IMAGE = 'Image'
SCHEMA_AUDIO = 'Audio'
SCHEMA_VIDEO = 'Video'
SCHEMA_TABLE = 'Table'
... |
@property
def supports_records(self):
# Slightly unintuitive naming: this just checks the document type,
# not if there actually are any records.
return self.schema in [self.SCHEMA_PDF, self.SCHEMA_TABLE]
@property
def supports_pages(self):
return self.schema == self.SC... | if self.source_url is not None:
return self.source_url | random_line_split |
util.go | /src/client/pps"
ppsclient "github.com/pachyderm/pachyderm/src/client/pps"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
etcd "github.com/coreos/etcd/clientv3"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"k8s.io/api/core/... | jobInput := proto.Clone(pipelineInfo.Input).(*pps.Input)
pps.VisitInput(jobInput, func(input *pps.Input) {
if input.Atom != nil {
if commit, ok := branchToCommit[key(input.Atom.Repo, input.Atom.Branch)]; ok {
input.Atom.Commit = commit.ID
}
}
if input.Cron != nil {
if commit, ok := branchToCommit[k... | branchToCommit := make(map[string]*pfs.Commit)
key := path.Join
for i, provCommit := range outputCommitInfo.Provenance {
branchToCommit[key(provCommit.Repo.Name, outputCommitInfo.BranchProvenance[i].Name)] = provCommit
} | random_line_split |
util.go | /client/pps"
ppsclient "github.com/pachyderm/pachyderm/src/client/pps"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
etcd "github.com/coreos/etcd/clientv3"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"k8s.io/api/core/v1"
... |
// FailPipeline updates the pipeline's state to failed and sets the failure reason
func FailPipeline(ctx context.Context, etcdClient *etcd.Client, pipelinesCollection col.Collection, pipelineName string, reason string) error {
_, err := col.NewSTM(ctx, etcdClient, func(stm col.STM) error {
pipelines := pipelinesCo... | {
buf := bytes.Buffer{}
if err := pachClient.GetFile(ppsconsts.SpecRepo, ptr.SpecCommit.ID, ppsconsts.SpecFile, 0, 0, &buf); err != nil {
return nil, fmt.Errorf("could not read existing PipelineInfo from PFS: %v", err)
}
result := &pps.PipelineInfo{}
if err := result.Unmarshal(buf.Bytes()); err != nil {
return... | identifier_body |
util.go | /client/pps"
ppsclient "github.com/pachyderm/pachyderm/src/client/pps"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
etcd "github.com/coreos/etcd/clientv3"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"k8s.io/api/core/v1"
... |
}
if input.Git != nil {
if commit, ok := branchToCommit[key(input.Git.Name, input.Git.Branch)]; ok {
input.Git.Commit = commit.ID
}
}
})
return jobInput
}
// PipelineReqFromInfo converts a PipelineInfo into a CreatePipelineRequest.
func PipelineReqFromInfo(pipelineInfo *ppsclient.PipelineInfo) *ppsc... | {
input.Cron.Commit = commit.ID
} | conditional_block |
util.go | /client/pps"
ppsclient "github.com/pachyderm/pachyderm/src/client/pps"
col "github.com/pachyderm/pachyderm/src/server/pkg/collection"
"github.com/pachyderm/pachyderm/src/server/pkg/ppsconsts"
etcd "github.com/coreos/etcd/clientv3"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"k8s.io/api/core/v1"
... | (resources *pps.ResourceSpec, cacheSize string) (*v1.ResourceList, error) {
var result v1.ResourceList = make(map[v1.ResourceName]resource.Quantity)
cpuStr := fmt.Sprintf("%f", resources.Cpu)
cpuQuantity, err := resource.ParseQuantity(cpuStr)
if err != nil {
log.Warnf("error parsing cpu string: %s: %+v", cpuStr, ... | getResourceListFromSpec | identifier_name |
condition_strategy_generators.rs | resenativeSeeds {
pub seed_search: SeedSearch,
pub generators: Vec<SharingGenerator>,
}
pub struct SharingGenerator {
pub time_used: Duration,
pub generator: GeneratorKind,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum GeneratorKind {
HillClimb {
steps: usize,
num_verification_seeds: us... |
let mut verification_seeds: Vec<_> = verification_seeds
.into_iter()
.map(|s| HillClimbSeedInfo {
seed: s,
current_score: playout_result(&seed_search.starting_state, s.view(), ¤t).score,
})
.collect();
let mut improvements = 0;
... | {
extra_seeds = (verification_seeds.len()..num_verification_seeds)
.map(|_| SingleSeed::new(rng))
.collect::<Vec<_>>();
verification_seeds.extend(extra_seeds.iter());
} | conditional_block |
condition_strategy_generators.rs | rng);
let duration = start.elapsed();
generator.time_used += duration;
self.seed_search.consider_strategy(
Arc::new(strategy),
generator.generator.min_playouts_before_culling(),
rng,
);
}
}
pub struct HillClimbSeedInfo<'a> {
pub seed: &'a SingleSeed<CombatChoiceLineagesKind>,
p... | .collect();
let mut result = self.clone(); | random_line_split | |
condition_strategy_generators.rs | resenativeSeeds {
pub seed_search: SeedSearch,
pub generators: Vec<SharingGenerator>,
}
pub struct SharingGenerator {
pub time_used: Duration,
pub generator: GeneratorKind,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum GeneratorKind {
HillClimb {
steps: usize,
num_verification_seeds: us... | }
}
}
StrategyGeneratorsWithSharedRepresenativeSeeds {
seed_search: NewFractalRepresentativeSeedSearch::new(
starting_state,
SingleSeedGenerator::new(ChaCha8Rng::from_rng(rng).unwrap()),
Default::default(),
),
generators,
}
}
pub fn step(&mut sel... | {
let mut generators = Vec::new();
for steps in (0..=8).map(|i| 1 << i) {
for num_verification_seeds in (0..=5).map(|i| 1 << i) {
for &start in &[HillClimbStart::NewRandom, HillClimbStart::FromSeedSearch] {
for &kind in &[
HillClimbKind::BunchOfRandomChanges,
Hill... | identifier_body |
condition_strategy_generators.rs | resenativeSeeds {
pub seed_search: SeedSearch,
pub generators: Vec<SharingGenerator>,
}
pub struct SharingGenerator {
pub time_used: Duration,
pub generator: GeneratorKind,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub enum GeneratorKind {
HillClimb {
steps: usize,
num_verification_seeds: us... | <'a> {
pub seed: &'a SingleSeed<CombatChoiceLineagesKind>,
pub current_score: f64,
}
impl GeneratorKind {
pub fn min_playouts_before_culling(&self) -> usize {
match self {
&GeneratorKind::HillClimb { steps, .. } => steps.min(32),
}
}
pub fn gen_strategy(&self, seed_search: &SeedSearch, rng: &mu... | HillClimbSeedInfo | identifier_name |
helicorder.ts | else {
seismograph.shadowRoot?.querySelector("style.selection")?.remove();
}
});
});
}
get heliConfig(): HelicorderConfig {
return this.seismographConfig as HelicorderConfig;
}
set heliConfig(config: HelicorderConfig) {
this.seismographConfig = config;
}
get width(): nu... | {
let selectedStyle = seismograph.shadowRoot?.querySelector("style.selection");
if ( ! selectedStyle) {
selectedStyle = document.createElement('style');
seismograph.shadowRoot?.insertBefore(selectedStyle, seismograph.shadowRoot?.firstChild);
selectedStyle.setAttri... | conditional_block | |
helicorder.ts | .setAttribute("class", "selection");
selectedStyle.textContent = `
svg g.yLabel text {
font-weight: bold;
text-decoration: underline;
}
`;
}
} else {
seismograph.shadowRoot?.querySelector("style.selection")?.... | }
wrapper.appendChild(seismograph);
if (lineNumber === 0) {
const utcDiv = document.createElement('div');
utcDiv.setAttribute("class", "utclabels");
const innerDiv = utcDiv.appendChild(document.createElement('div'));
innerDiv.setAttribute("style", `top: ${lineSeisConfi... | justify-content: space-between;
width: 100%;
z-index: -1;
}
`; | random_line_split |
helicorder.ts | .setAttribute("class", "selection");
selectedStyle.textContent = `
svg g.yLabel text {
font-weight: bold;
text-decoration: underline;
}
`;
}
} else {
seismograph.shadowRoot?.querySelector("style.selection")?.... | (): number {
const wrapper = (this.getShadowRoot().querySelector('div.wrapper') as HTMLDivElement);
const rect = wrapper.getBoundingClientRect();
return rect.height;
}
appendSegment(segment: SeismogramSegment) {
const segMinMax = segment.findMinMax();
const origMinMax = this.heliConfig.fixedAmp... | height | identifier_name |
helicorder.ts | - 1) {
lineSeisConfig.isXAxis = this.heliConfig.isXAxis;
lineSeisConfig.margin.bottom += this.heliConfig.margin.bottom;
height += this.heliConfig.margin.bottom;
}
lineSeisConfig.fixedTimeScale = lineInterval;
lineSeisConfig.yLabel = `${startTime.toFormat("HH:mm")}`;
lin... | {
this.interval = Interval.after(startTime, duration);
this.lineNumber = lineNumber;
} | identifier_body | |
testkeras.py | ss = stack_arrays([root2array(fpath, tree_name, **kwargs).view(np.recarray) for fpath in files])
try:
return pd.DataFrame(ss)
except Exception:
return pd.DataFrame(ss.data)
def flatten(column):
'''
Args:
-----
column: a column of a pandas df whose entries are lists (or regular entr... | files = glob.glob(files_path)
# -- process ntuples into rec arrays | random_line_split | |
testkeras.py | 7']
#w=pd.concat((sigw,bkgw),ignore_index=True).values
w = pd.concat((sig_df['weight_mc'],bkg_df['weight_mc']),ignore_index=True).values
##can run something like b = root2pandas(fiSig,'nominal', selection = 'ejets_2015 >0||ejets_2016>0') for a selection like in http://scikit-hep.org/root_numpy/start.html#a-quick-tu... | plt.text(j, i, format(cm[i, j], fmt),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black") | conditional_block | |
testkeras.py |
try:
return np.array([v for e in column for v in e])
except (TypeError, ValueError):
return column
########################################################################################
fiSig = '/scratch/jbarkelo/20181026Ntuples/user.jbarkelo.410980*/410980.root'
fiBkg = '/... | '''
Args:
-----
column: a column of a pandas df whose entries are lists (or regular entries -- in which case nothing is done)
e.g.: my_df['some_variable']
Returns:
--------
flattened out version of the column.
For example, it will turn:
[1791, 2719... | identifier_body | |
testkeras.py | _df['ph_e']],index=bkg_df.index))
bkg_df = bkg_df.assign(ph_pt0=pd.Series([i[0] for i in bkg_df['ph_pt']],index=bkg_df.index))
bkg_df = bkg_df.assign(ph_eta0=pd.Series([i[0] for i in bkg_df['ph_eta']],index=bkg_df.index))
bkg_df = bkg_df.assign(ph_phi0=pd.Series([i[0] for i in bkg_df['ph_phi']],index=bkg_df.index))
... | plot_confusion_matrix | identifier_name | |
runner.rs | Cell, sync::mpsc::Receiver};
use skulpin_renderer::{ash, LogicalSize, RendererBuilder};
use ash::vk::Result as VkResult;
use crate::skia::{Color, Matrix, Picture, PictureRecorder, Point, Rect, Size};
use super::input::{EventHandleResult, InputState};
use super::time::TimeState;
use super::Game;
use super::{default_... | #[inline]
pub fn with_mut<F, R>(f: F) -> R
where
F: FnOnce(&mut State) -> R,
{
Self::STATE.with(|x| f(x.borrow_mut().as_mut().expect(Self::PANIC_MESSAGE)))
}
pub fn last_update_time() -> Duration {
Self::STATE.with(|x| {
x.borrow()
.as_ref()
... | F: FnOnce(&State) -> R,
{
Self::STATE.with(|x| f(x.borrow().as_ref().expect(Self::PANIC_MESSAGE)))
}
| random_line_split |
runner.rs | , sync::mpsc::Receiver};
use skulpin_renderer::{ash, LogicalSize, RendererBuilder};
use ash::vk::Result as VkResult;
use crate::skia::{Color, Matrix, Picture, PictureRecorder, Point, Rect, Size};
use super::input::{EventHandleResult, InputState};
use super::time::TimeState;
use super::Game;
use super::{default_font... |
}
impl From<VkResult> for Error {
fn from(result: VkResult) -> Self {
Error::RendererError(result)
}
}
#[derive(Debug, PartialEq, Clone, Copy)]
pub struct ID(u64);
impl ID {
pub fn next() -> Self {
Self(State::with_mut(|x| {
let id = x.id_keeper;
x.id_keeper += 1;... | {
match self {
Error::RendererError(e) => Some(e),
}
} | identifier_body |
runner.rs | , sync::mpsc::Receiver};
use skulpin_renderer::{ash, LogicalSize, RendererBuilder};
use ash::vk::Result as VkResult;
use crate::skia::{Color, Matrix, Picture, PictureRecorder, Point, Rect, Size};
use super::input::{EventHandleResult, InputState};
use super::time::TimeState;
use super::Game;
use super::{default_font... | () -> Duration {
Self::STATE.with(|x| {
x.borrow()
.as_ref()
.expect(Self::PANIC_MESSAGE)
.time_state
.elapsed()
})
}
pub fn last_update_time_draw() -> Duration {
Self::STATE.with(|x| {
x.borrow()
... | elapsed | identifier_name |
humantoken.rs | os("1.1 f", 1100);
/// assert_attos("1.0e3 attofil", 1000);
/// ```
///
/// # Known bugs
/// - `1efil` will not parse as an exa (`10^18`), because we'll try and
/// parse it as a exponent in the float. Instead use `1 efil`.
pub fn parse(input: &str) -> anyhow::Result<TokenAmount> {
... | etty { | identifier_name | |
humantoken.rs | }
// units or whole
let (print_me, prefix) = match f.alternate() {
true => (fil_for_printing, None),
false => scale(fil_for_printing),
};
// write the string
match print_me.is_zero() {
true => f.write_str("0 F... | quickcheck! {
fn parser_no_panic(s: String) -> () {
let _ = parse(&s);
}
} | random_line_split | |
humantoken.rs | use crate::shim::econ::TokenAmount;
use anyhow::{anyhow, bail};
use bigdecimal::{BigDecimal, ParseBigDecimalError};
use nom::{
bytes::complete::tag,
character::complete::multispace0,
combinator::{map_res, opt},
error::{FromExternalError, ParseError},
number::compl... | input,
nom::error::ErrorKind::Alt,
)))
}
/// Take a float from the front of `input`
fn bigdecimal<'a, E: ParseError<&'a str>>(input: &'a str) -> IResult<&str, BigDecimal, E>
where
E: FromExternalError<&'a str, ParseBigDecimalError>,
{
map_res(recogniz... | // Try the longest matches first, so we don't e.g match `a` instead of `atto`,
// leaving `tto`.
let mut scales = si::SUPPORTED_PREFIXES
.iter()
.flat_map(|scale| {
std::iter::once(&scale.name)
.chain(scale.units)
.... | identifier_body |
eccrypto.py | 1) // 4, p)
# 1. By factoring out powers of 2, find Q and S such that p - 1 =
# Q * 2 ** S with Q odd
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
# 2. Search for z in Z/pZ which is a quadratic non-residue
z = 1
while legendre(z, p) != -1:
z += 1
m, c, t, ... | (self, backend_factory, params, aes, nid):
self._backend = backend_factory(**params)
self.params = params
self._aes = aes
self.nid = nid
| __init__ | identifier_name |
eccrypto.py | 1) // 4, p)
# 1. By factoring out powers of 2, find Q and S such that p - 1 =
# Q * 2 ** S with Q odd
q = p - 1
s = 0
while q % 2 == 0:
q //= 2
s += 1
# 2. Search for z in Z/pZ which is a quadratic non-residue
z = 1
while legendre(z, p) != -1:
z += 1
m, c, t, ... |
def new_private_key(self):
while True:
private_key = os.urandom(self.public_key_length)
if bytes_to_int(private_key) >= self.n:
continue
return private_key
def private_to_public(self, private_key):
raw = bytes_to_int(private_key)
x, ... | x = bytes_to_int(public_key[1:])
# Calculate Y
y_square = (pow(x, 3, self.p) + self.a * x + self.b) % self.p
try:
y = square_root_mod_prime(y_square, self.p)
except Exception:
raise ValueError("Invalid public key") from None
if y % 2 != public_key[0] - 0x0... | identifier_body |
eccrypto.py | return 0, 0, 0
ysq = (p[1]**2) % self.p
s = (4 * p[0] * ysq) % self.p
m = (3 * p[0]**2 + self.a * p[2]**4) % self.p
nx = (m**2 - 2 * s) % self.p
ny = (m * (s - nx) - 8 * ysq**2) % self.p
nz = (2 * p[1] * p[2]) % self.p
return nx, ny, nz
def jacobian_add(self... |
def new_private_key(self, is_compressed=False):
return self._backend.new_private_key() + (b"\x01"
if is_compressed else b"") | random_line_split | |
eccrypto.py | 1) // 4, p)
# 1. By factoring out powers of 2, find Q and S such that p - 1 =
# Q * 2 ** S with Q odd
q = p - 1
s = 0
while q % 2 == 0:
|
# 2. Search for z in Z/pZ which is a quadratic non-residue
z = 1
while legendre(z, p) != -1:
z += 1
m, c, t, r = s, pow(z, q, p), pow(n, q, p), pow(n, (q + 1) // 2, p)
while True:
if t == 0:
return 0
elif t == 1:
return r
# Use repeated squari... | q //= 2
s += 1 | conditional_block |
github.go | .clientHasSet.L.Unlock()
}
}
}
// AttachToApp ...
func (g *Github) AttachToApp(app core.App) error {
g.m.Lock()
defer g.m.Unlock()
g.init(app)
appConfig := &githubApp{
app: app,
}
app.Config("github", &appConfig.config)
g.apps[app.Name()] = appConfig
g.setupDeployKey(appConfig)
g.setupHooks(appConfig)
... | random_line_split | ||
github.go | ]*githubApp),
trackedPullRequests: make(map[string]pullRequestStatus),
}
http.HandleFunc("/cb/auth/github", g.handleGithubAuth)
http.HandleFunc("/cb/github/hook/", g.handleGithubEvent)
return g
}
// Identifier ...
func (g *Github) Identifier() string { return "github" }
// IsProvider ...
func (g *Github) IsPro... | urn nil
}
func (g *Github) setupHooks(appConfig *githubApp) {
cfg := appConfig.config
_, _, err := g.client.Repositories.Get(cfg.Owner, cfg.Repo)
if err != nil {
logwarnf("(%s) Repository does not exist, owner=%s, repo=%s", appConfig.app.Name(), cfg.Owner, cfg.Repo)
return
}
hookURL := fmt.Sprintf("%s/cb/git... | gcritf("Couldn't create deploy key for %s: %s", appConfig.app.Name(), err)
return err
}
ret | conditional_block |
github.go | [string]*githubApp),
trackedPullRequests: make(map[string]pullRequestStatus),
}
http.HandleFunc("/cb/auth/github", g.handleGithubAuth)
http.HandleFunc("/cb/github/hook/", g.handleGithubEvent)
return g
}
// Identifier ...
func (g *Github) Identifier() string { return "github" }
// IsProvider ...
func (g *Github... | () {
token := core.GetCache("github:token")
if token != "" {
oauth2Token := oauth2.Token{AccessToken: token}
g.setClient(&oauth2Token)
return
}
fmt.Println("")
fmt.Println("This app must be authenticated with github, please visit the following URL to authenticate this app")
fmt.Println(g.getOauthConfig().... | acquireOauthToken | identifier_name |
github.go | [string]*githubApp),
trackedPullRequests: make(map[string]pullRequestStatus),
}
http.HandleFunc("/cb/auth/github", g.handleGithubAuth)
http.HandleFunc("/cb/github/hook/", g.handleGithubEvent)
return g
}
// Identifier ...
func (g *Github) Identifier() string { return "github" }
// IsProvider ...
func (g *Github... | old the g.m.lock when you call this
func (g *Github) untrackBuild(build core.Build) {
buildIndex := -1
for i, trackedBuild := range g.trackedBuilds {
if trackedBuild.Token() == build.Token() {
buildIndex = i
break
}
}
if buildIndex < 0 {
return
}
g.trackedBuilds[buildIndex].Unref()
g.trackedBuilds ... | _, trackedBuild := range g.trackedBuilds {
if trackedBuild.Token() == build.Token() {
return
}
}
build.Ref()
g.trackedBuilds = append(g.trackedBuilds, build)
}
// h | identifier_body |
image_utils.py |
records DataFrame of records from the original CSV file
encoding A string representing the OpenCV encoding of the underlying img ndarray
ships A list of Ship dictionary entries
ship_id - Hash of the RLE string
EncodedPixels - RL... |
# Reshape to 2D
img2 = mask.reshape(shape).T
return img2
def get_contour(self, mask):
"""Return a cv2 contour object from a binary 0/1 mask"""
assert mask.ndim == 2
assert mask.min() == 0
assert mask.max() == 1
contours, hierarchy = cv2.findContours... | start = int(s[2 * i]) - 1
length = int(s[2 * i + 1])
mask[start:start + length] = 1 # Assign this run to ones | conditional_block |
image_utils.py | {} ".format(self.image_id, self.img.shape))
# TODO: (Actually just a note: the .copy() will suppress the SettingWithCopyWarning!
self.records = df.loc[df.index == self.image_id, :].copy()
assert isinstance(self.records, pd.DataFrame)
self.records['ship_id'] = self.records.apply(lambda... | img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
# Encode the in-memory image to .jpg format
retval, buffer = cv2.imencode('.jpg', img)
# Convert to base64 raw bytes
jpg_as_text = base64.b64encode(buffer)
# Decode the bytes to utf
jpg_as_text = jpg_as_text.decode(encoding="utf-8")
logging.info... | identifier_body | |
image_utils.py | EncodedPixels - RLE string
center -
"""
self.image_id = image_id
self.encoding = None
self.records = None
self.img = None
self.contours = None
logging.info("Image id: {}".format(self.image_id))
def __str__(self):
... | img The image as an ndarray
records DataFrame of records from the original CSV file
encoding A string representing the OpenCV encoding of the underlying img ndarray
ships A list of Ship dictionary entries
ship_id - Hash of the ... | random_line_split | |
image_utils.py |
records DataFrame of records from the original CSV file
encoding A string representing the OpenCV encoding of the underlying img ndarray
ships A list of Ship dictionary entries
ship_id - Hash of the RLE string
EncodedPixels - RL... | (self):
logging.info("Fitting and drawing ellipses on a new ndarray canvas.".format())
canvas = self.img
for idx, rec in self.records.iterrows():
# logging.debug("Processing record {} of {}".format(cnt, image_id))
# contour = imutils.get_contour(rec['mask'])
#... | draw_ellipses_img | identifier_name |
reconciler.go | util.KubeCheck(r.SecretAdmin)
util.SecretResetStringDataFromData(r.SecretServer)
util.SecretResetStringDataFromData(r.SecretOp)
util.SecretResetStringDataFromData(r.SecretAdmin)
}
// Reconcile reads that state of the cluster for a System object,
// and makes changes based on the state read and what is in the Syste... | util.KubeCheck(r.CoreApp)
util.KubeCheck(r.ServiceMgmt)
util.KubeCheck(r.ServiceS3)
util.KubeCheck(r.SecretServer)
util.KubeCheck(r.SecretOp) | random_line_split | |
reconciler.go | : %s", err)
util.SetErrorCondition(&r.NooBaa.Status.Conditions, err)
r.UpdateStatus()
return reconcile.Result{}, nil
}
if err != nil {
log.Warnf("⏳ Temporary Error: %s", err)
util.SetErrorCondition(&r.NooBaa.Status.Conditions, err)
r.UpdateStatus()
return reconcile.Result{RequeueAfter: 2 * time.Second},... | r.NooBaa.Spec.CoreResources != nil {
c.Resources = *r.NooBaa.Spec.CoreResources
}
} else if c.Name == "mongodb" {
if r.NooBaa.Spec.MongoImage == nil {
c.Image = options.MongoImage
} else {
c.Image = *r.NooBaa.Spec.MongoImage
}
if r.NooBaa.Spec.MongoResources != nil {
c.Resources = *r.N... | if c.Env[j].Name == "AGENT_PROFILE" {
c.Env[j].Value = fmt.Sprintf(`{ "image": "%s" }`, r.NooBaa.Status.ActualImage)
}
}
if | conditional_block |
reconciler.go | %v", image)
imageTag = image.Tag()
case dockerref.Named:
log.Infof("Parsed image (Named) %v", image)
imageName = image.Name()
default:
log.Infof("Parsed image (unstructured) %v", image)
}
if imageName == options.ContainerImageName {
version, err := semver.NewVersion(imageTag)
if err == nil {
log.In... | g := r.Logger.WithField("func", "ReconcileSecretAdmin")
util.KubeCheck(r.SecretAdmin)
util.SecretResetStringDataFromData(r.SecretAdmin)
ns := r.Request.Namespace
name := r.Request.Name
secretAdminName := name + "-admin"
r.SecretAdmin = &corev1.Secret{}
err := r.GetObject(secretAdminName, r.SecretAdmin)
if er... | identifier_body | |
reconciler.go | ("Collected addresses: %+v", status)
}
// Connect initializes the noobaa client for making calls to the server.
func (r *Reconciler) Connect() error {
r.CheckServiceStatus(r.ServiceMgmt, &r.NooBaa.Status.Services.ServiceMgmt, "mgmt-https")
r.CheckServiceStatus(r.ServiceS3, &r.NooBaa.Status.Services.ServiceS3, "s3-h... | se(phase | identifier_name | |
lib.rs | /// Type for wrapping Vec<u8> data in cases you need to do a convenient
/// enum variant display derives with `#[display(inner)]`
#[cfg_attr(
feature = "serde",
derive(Serialize, Deserialize),
serde(crate = "serde_crate", transparent)
)]
#[derive(
Wrapper, Clone, Ord, PartialOrd, Eq, PartialEq, Hash, De... | }
| random_line_split | |
lib.rs |
fn to_bech32_data_string(&self) -> String {
::bech32::encode(
HRP_DATA,
self.to_bech32_payload().to_base32(),
Variant::Bech32m,
)
.expect("HRP is hardcoded and can't fail")
}
}
impl<T> ToBech32DataString for T where T: sealed::ToPayload {}
/// Trait... | Bech32Visitor | identifier_name | |
lib.rs | pcMessage::Subscribe(msg)
}
}
/// A channel to a `RpcClient`.
#[derive(Clone)]
pub struct RpcChannel(mpsc::Sender<RpcMessage>);
impl RpcChannel {
fn send(
&self,
msg: RpcMessage,
) -> impl Future<Item = mpsc::Sender<RpcMessage>, Error = mpsc::SendError<RpcMessage>> {
self.0.to_owned().send(msg)
}
}
impl Fr... | use crate::{RpcChannel, RpcError, TypedClient};
use jsonrpc_core::{self as core, IoHandler};
use jsonrpc_pubsub::{PubSubHandler, Subscriber, SubscriptionId};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; | random_line_split | |
lib.rs | Message {
fn from(msg: CallMessage) -> Self {
RpcMessage::Call(msg)
}
}
impl From<NotifyMessage> for RpcMessage {
fn from(msg: NotifyMessage) -> Self {
RpcMessage::Notify(msg)
}
}
impl From<SubscribeMessage> for RpcMessage {
fn from(msg: SubscribeMessage) -> Self {
RpcMessage::Subscribe(msg)
}
}
/// A ch... | {
let args = serde_json::to_value(subscribe_params)
.expect("Only types with infallible serialisation can be used for JSON-RPC");
let params = match args {
Value::Array(vec) => Params::Array(vec),
Value::Null => Params::None,
_ => {
return future::Either::A(future::err(RpcError::Other(format_err!(
... | identifier_body | |
lib.rs | Subscribe(SubscribeMessage),
}
impl From<CallMessage> for RpcMessage {
fn from(msg: CallMessage) -> Self {
RpcMessage::Call(msg)
}
}
impl From<NotifyMessage> for RpcMessage {
fn from(msg: NotifyMessage) -> Self {
RpcMessage::Notify(msg)
}
}
impl From<SubscribeMessage> for RpcMessage {
fn from(msg: Subscribe... | <T: Serialize, R: DeserializeOwned + 'static>(
&self,
subscribe: &str,
subscribe_params: T,
topic: &str,
unsubscribe: &str,
returns: &'static str,
) -> impl Future<Item = TypedSubscriptionStream<R>, Error = RpcError> {
let args = serde_json::to_value(subscribe_params)
.expect("Only types with infallib... | subscribe | identifier_name |
value.go | uncate = errors.New("Do truncate")
type logEntry func(e Entry) error
type safeRead struct {
k []byte
v []byte
um []byte
recordOffset uint32
}
func (r *safeRead) Entry(reader *bufio.Reader) (*Entry, error) {
var hbuf [headerBufSize]byte
var err error
hash := crc32.New(y.CastagnoliCrcTable)
tee := io.TeeRe... |
}
if _, err = io.ReadFull(tee, e.Key); err != nil {
if err == io.EOF {
err = errTruncate
}
return nil, err
}
if _, err = io.ReadFull(tee, e.Value); err != nil {
if err == io.EOF {
err = errTruncate
}
return nil, err
}
var crcBuf [4]byte
if _, err = io.ReadFull(reader, crcBuf[:]); err != nil {... | {
if err == io.EOF {
err = errTruncate
}
return nil, err
} | conditional_block |
value.go | uncate = errors.New("Do truncate")
type logEntry func(e Entry) error
type safeRead struct {
k []byte
v []byte
um []byte
recordOffset uint32
}
func (r *safeRead) Entry(reader *bufio.Reader) (*Entry, error) {
var hbuf [headerBufSize]byte
var err error
hash := crc32.New(y.CastagnoliCrcTable)
tee := io.TeeRe... |
func (vlog *valueLog) fpath(fid uint32) string {
return vlogFilePath(vlog.dirPath, fid)
}
func (vlog *valueLog) currentLogFile() *logFile {
if len(vlog.files) > 0 {
return vlog.files[len(vlog.files)-1]
}
return nil
}
func (vlog *valueLog) openOrCreateFiles(readOnly bool) error {
files, err := ioutil.ReadDir(... | {
return fmt.Sprintf("%s%s%06d.vlog", dirPath, string(os.PathSeparator), fid)
} | identifier_body |
value.go | Truncate = errors.New("Do truncate")
type logEntry func(e Entry) error
type safeRead struct {
k []byte
v []byte
um []byte
recordOffset uint32
}
func (r *safeRead) Entry(reader *bufio.Reader) (*Entry, error) {
var hbuf [headerBufSize]byte
var err error
hash := crc32.New(y.CastagnoliCrcTable)
tee := io.Tee... | if lf.fid == maxFid {
var flags uint32
if readOnly {
flags |= y.ReadOnly
}
if lf.fd, err = y.OpenExistingFile(lf.path, flags); err != nil {
return errors.Wrapf(err, "Unable to open value log file")
}
opt := &vlog.opt.ValueLogWriteOptions
vlog.curWriter = fileutil.NewBufferedWriter(lf.fd, ... | })
// Open all previous log files as read only. Open the last log file
// as read write (unless the DB is read only).
for _, lf := range vlog.files { | random_line_split |
value.go | Truncate = errors.New("Do truncate")
type logEntry func(e Entry) error
type safeRead struct {
k []byte
v []byte
um []byte
recordOffset uint32
}
func (r *safeRead) Entry(reader *bufio.Reader) (*Entry, error) {
var hbuf [headerBufSize]byte
var err error
hash := crc32.New(y.CastagnoliCrcTable)
tee := io.Tee... | (fid uint32) string {
return vlogFilePath(vlog.dirPath, fid)
}
func (vlog *valueLog) currentLogFile() *logFile {
if len(vlog.files) > 0 {
return vlog.files[len(vlog.files)-1]
}
return nil
}
func (vlog *valueLog) openOrCreateFiles(readOnly bool) error {
files, err := ioutil.ReadDir(vlog.dirPath)
if err != nil ... | fpath | identifier_name |
utils.go | return err
}
}
app := &AppImage{Filepath: targetAppImagePath, Executable: options.Executable}
if options.Executable == "" {
app.Executable = options.Executable
}
app.Source = Source{
Identifier: sourceIdentifier,
Meta: SourceMetadata{
Slug: sourceSlug,
CrawledOn: time.Now().String(),
},
}
... | logger.Debugf("Checking for updates")
hasUpdates, err := updater.Lookup()
if err != nil { | random_line_split | |
utils.go |
func Install(options types.InstallOptions, config config.Store) error {
var asset types.ZapDlAsset
var err error
sourceIdentifier := ""
sourceSlug := ""
indexFile := fmt.Sprintf("%s.json", path.Join(config.IndexStore, options.Executable))
logger.Debugf("Checking if %s exists", indexFile)
// check if the app ... | {
var apps []string
err := filepath.Walk(zapConfig.IndexStore, func(path string, info os.FileInfo, err error) error {
if info.IsDir() {
return err
}
appName := ""
if index {
appName = path
} else {
appName = filepath.Base(path)
appName = strings.TrimSuffix(appName, ".json")
}
apps = append(... | identifier_body | |
utils.go | config)
if err != nil {
return err
}
} else {
sourceIdentifier = SourceDirectURL
sourceSlug = options.From
// if the from argument is without the file:// protocol, match that
if helpers.CheckIfFileExists(sourceSlug) {
sourceSlug, err = filepath.Abs(sourceSlug)
if err != nil {
return err
}... | es.InstallOptions, config config.Store, app *AppImage) (*AppImage, error) {
// for github releases, we have to force the removal of the old
// appimage before continuing, because there is no verification
// of the method which can be used to check if the appimage is up to date
// or not.
err := Remove(types.Remove... | tall(options typ | identifier_name |
utils.go | , config)
if err != nil {
return err
}
} else {
sourceIdentifier = SourceDirectURL
sourceSlug = options.From
// if the from argument is without the file:// protocol, match that
if helpers.CheckIfFileExists(sourceSlug) {
sourceSlug, err = filepath.Abs(sourceSlug)
if err != nil {
return err
... | else {
// the file is probably a symlink, but just doesnt resolve properly
// we can safely remove it
// make sure we remove the file first to prevent conflicts
logger.Debugf("Failed to evaluate target of symlink")
logger.Debugf("Attempting to remove the symlink regardless")
err := os.Remove(binFile... | {
// this is some serious app which shares the same name
// as that of the target appimage
// we dont want users to be confused tbh
// so we need to ask them which of them, they would like to keep
logger.Debug("Detected another app which is not installed by zap. Refusing to remove")
// TODO: add a use... | conditional_block |
student-layout.component.ts | navBarTheme: string; /* theme1, themelight1(default)*/
activeItemTheme: string; /* theme1, theme2, theme3, theme4(default), ..., theme11, theme12 */
isCollapsedMobile: string;
isCollapsedSideBar: string;
chatToggle: string;
chatToggleInverse: string;
chatInnerToggle: string;
chatInnerToggleInverse: str... | tLayoutType(t | identifier_name | |
student-layout.component.ts | -out')),
transition('out => in', animate('400ms ease-in-out'))
]),
trigger('slideOnOff', [
state('on', style({
transform: 'translate3d(0, 0, 0)'
})),
state('off', style({
transform: 'translate3d(100%, 0, 0)'
})),
transition('on => off', animate('400ms ease-in-... | }
this.verticalNavType = this.verticalNavType === 'expanded' ? 'offcanvas' : 'expanded';
}
onClickedOutside(e: Event) {
if (this.windowWidth < 768 && this.toggleOn && this.verticalNavType !== 'offcanvas') {
this.toggleOn = true;
this.verticalNavType = 'offcanvas';
}
}
onMobileMenu(... | }
toggleOpened() {
if (this.windowWidth < 768) {
this.toggleOn = this.verticalNavType === 'offcanvas' ? true : this.toggleOn; | random_line_split |
student-layout.component.ts | verticalEffect: string; /* shrink(default), push, overlay */
vNavigationView: string; /* view1(default) */
pcodedHeaderPosition: string; /* fixed(default), relative*/
pcodedSidebarPosition: string; /* fixed(default), absolute*/
headerTheme: string; /* theme1(default), theme2, theme3, theme4, theme5, theme6 */
... | this.configOpenRightBar = this.configOpenRightBar === 'open' ? '' : 'open';
}
| identifier_body | |
student-layout.component.ts | Border: boolean;
subItemIcon: string; /* style1, style2, style3, style4, style5, style6(default) */
dropDownIcon: string; /* style1(default), style2, style3 */
configOpenRightBar: string;
isSidebarChecked: boolean;
isHeaderChecked: boolean;
@ViewChild('searchFriends', /* TODO: add static flag */ {static: f... | this.navBarTheme = 'themelight1';
} e | conditional_block | |
queue.go | ess(a), we treat this to mean a == b (i.e. we can only
// hold one of either a or b in the tree).
//
// default ordering is
// - [transmits=0, ..., transmits=inf]
// - [transmits=0:len=999, ..., transmits=0:len=2, ...]
// - [transmits=0:len=999,id=999, ..., transmits=0:len=999:id=1, ...]
func (b *limitedBroadcast) Less... | else if !unique {
// Slow path, hopefully nothing hot hits this.
var remove []*limitedBroadcast
q.tq.Ascend(func(item btree.Item) bool {
cur := item.(*limitedBroadcast)
// Special Broadcasts can only invalidate each other.
switch cur.b.(type) {
case NamedBroadcast:
// noop
case UniqueBroadcas... | {
if old, ok := q.tm[lb.name]; ok {
old.b.Finished()
q.deleteItem(old)
}
} | conditional_block |
queue.go | ess(a), we treat this to mean a == b (i.e. we can only
// hold one of either a or b in the tree).
//
// default ordering is
// - [transmits=0, ..., transmits=inf]
// - [transmits=0:len=999, ..., transmits=0:len=2, ...]
// - [transmits=0:len=999,id=999, ..., transmits=0:len=999:id=1, ...]
func (b *limitedBroadcast) Less... | () (minTransmit, maxTransmit int) {
if q.lenLocked() == 0 {
return 0, 0
}
minItem, maxItem := q.tq.Min(), q.tq.Max()
if minItem == nil || maxItem == nil {
return 0, 0
}
min := minItem.(*limitedBroadcast).transmits
max := maxItem.(*limitedBroadcast).transmits
return min, max
}
// GetBroadcasts is used to ... | getTransmitRange | identifier_name |
queue.go | ess(a), we treat this to mean a == b (i.e. we can only
// hold one of either a or b in the tree).
//
// default ordering is
// - [transmits=0, ..., transmits=inf]
// - [transmits=0:len=999, ..., transmits=0:len=2, ...]
// - [transmits=0:len=999,id=999, ..., transmits=0:len=999:id=1, ...]
func (b *limitedBroadcast) Less... |
// walkReadOnlyLocked calls f for each item in the queue traversing it in
// natural order (by Less) when reverse=false and the opposite when true. You
// must hold the mutex.
//
// This method panics if you attempt to mutate the item during traversal. The
// underlying btree should also not be mutated during traver... | {
q.mu.Lock()
defer q.mu.Unlock()
out := make([]*limitedBroadcast, 0, q.lenLocked())
q.walkReadOnlyLocked(reverse, func(cur *limitedBroadcast) bool {
out = append(out, cur)
return true
})
return out
} | identifier_body |
queue.go | ess(a), we treat this to mean a == b (i.e. we can only
// hold one of either a or b in the tree).
//
// default ordering is
// - [transmits=0, ..., transmits=inf]
// - [transmits=0:len=999, ..., transmits=0:len=2, ...]
// - [transmits=0:len=999,id=999, ..., transmits=0:len=999:id=1, ...]
func (b *limitedBroadcast) Less... | // getTransmitRange returns a pair of min/max values for transmit values
// represented by the current queue contents. Both values represent actual
// transmit values on the interval [0, len). You must already hold the mutex.
func (q *TransmitLimitedQueue) getTransmitRange() (minTransmit, maxTransmit int) {
if q.lenLo... | random_line_split | |
engine.go | 2) int32 {
ply := eng.ply()
pvNode := α+1 < β
pos := eng.Position
us := pos.Us()
// update statistics
eng.Stats.Nodes++
if !eng.stopped && eng.Stats.Nodes >= eng.checkpoint {
eng.checkpoint = eng.Stats.Nodes + checkpointStep
if eng.timeControl.Stopped() {
eng.stopped = true
}
}
if eng.stopped {
ret... | // dropped true if not all moves were searched
// mate cannot be declared unless all moves were tested
dropped := false
numMoves := int32(0)
eng.stack.GenerateMoves(Violent|Quiet, hash)
for move := eng.stack.PopMove(); move != NullMove; move = eng.stack.PopMove() {
if ply == 0 {
if eng.isIgnoredRootMove(mov... | // principal variation search: search with a null window if there is already a good move
bestMove, localα := NullMove, int32(-InfinityScore) | random_line_split |
engine.go | implements searchTree framework
//
// searchTree fails soft, i.e. the score returned can be outside the bounds
//
// α, β represent lower and upper bounds
// depth is the search depth (decreasing)
//
// returns the score of the current position up to depth (modulo reductions/extensions)
// the returned score is from cu... | != 0 {
return false
}
for _, m := range eng.ignoreRootMoves {
if m == move {
return true
}
}
for _, m := range eng.onlyRootMoves {
if m == move {
return false
}
}
return len(eng.onlyRootMoves) != 0
}
// searchTree | identifier_body | |
engine.go | uning
// statically evaluates the position. Use static evaluation from hash if available
static := int32(0)
allowLeafsPruning := false
if depth <= futilityDepthLimit && // enable when close to the frontier
!sideIsChecked && // disable in check
!pvNode && // disable in pv nodes
KnownLossScore < α && β < KnownW... | ee PlayMov | conditional_block | |
engine.go | Moves)/6
}
}
// skip illegal moves that leave the king in check
eng.DoMove(move)
if pos.IsChecked(us) {
eng.UndoMove()
continue
}
score := eng.tryMove(max(α, localα), β, newDepth, lmr, numMoves > 1)
if score >= β {
// fail high, cut node
eng.history.add(move, 5+5*depth)
eng.stack.Save... | e.static = | identifier_name | |
app.component.ts | ;
this.currentEvent = this.events[1];
this.helpRequested = false;
this.helpPressed = false;
this.helpInformation = false;
this.restartRequested = false;
this.showWaitSpinner = false;
this.newEvent = null;
if (this.currentEvent != null) {
this.occupied = true;
}
else {
... |
toggleDarkTheme(dark: boolean) {
this.darkTheme = dark;
this._keyboardRef.darkTheme = dark;
}
availabilityClass(e: Event): string {
if (e.Subject.toString() == 'Available') {
return "agenda-view-row-available";
}
else {
return "agenda-view-row-unavailable";
}
}
bookNewE... | {
if (this._keyboardRef) {
this._keyboardRef.dismiss();
}
} | identifier_body |
app.component.ts | 8;
this.currentEvent = this.events[1];
this.helpRequested = false;
this.helpPressed = false;
this.helpInformation = false;
this.restartRequested = false;
this.showWaitSpinner = false;
this.newEvent = null;
if (this.currentEvent != null) {
this.occupied = true;
}
else {
... | (): void {
// Populate valid time scheduling window
var d = new Date();
var tomorrow = new Date();
tomorrow.setDate(d.getDate() + 1);
tomorrow.setTime(0);
var minutes = d.getMinutes();
//var hours = d.getHours();
var m = 0;
if (this.timeIncrement... | populateTimeslots | identifier_name |
app.component.ts | ;
this.currentEvent = this.events[1];
this.helpRequested = false;
this.helpPressed = false;
this.helpInformation = false;
this.restartRequested = false;
this.showWaitSpinner = false;
this.newEvent = null;
if (this.currentEvent != null) {
this.occupied = true;
}
else {
... |
}
this.currentEvent = null;
//console.log(this.currentEvent);
}
/*getTimePeriod(d:Date): number {
var t = new Date(d.getDate());
var msIn15Min: number = 900000;
var secondsInADay: number = 24 * 60 * 60;
var hours: number = t.getHours() * 60 * 60;
var minutes: number = t.getMinutes()... | {
this.currentEvent = this.events[i];
//console.log(this.currentEvent);
return;
} | conditional_block |
app.component.ts | layout: string;
layouts: {
name: string;
layout: IKeyboardLayout;
}[];
get keyboardVisible(): boolean {
return this._keyboardService.isOpened;
}
constructor(private _keyboardService: MdKeyboardService,
@Inject(LOCALE_ID) public locale,
@Inject(MD_KEYBOARD_LAYOUTS) private _layouts,
... | isDebug: boolean;
defaultLocale: string;
| random_line_split | |
dhcpd.go | nil {
s.closeConn() // in case it was already started
return wrapErrPrint(err, "Couldn't find IPv4 address of interface %s %+v", s.InterfaceName, iface)
}
if s.LeaseDuration == 0 {
s.leaseTime = time.Hour * 2
s.LeaseDuration = uint(s.leaseTime.Seconds())
} else {
s.leaseTime = time.Second * time.Duration... |
s.leaseStop, err = parseIPv4(s.RangeEnd)
if err != nil {
s.closeConn() // in case it was already started
return wrapErrPrint(err, "Failed to parse range end address %s", s.RangeEnd)
}
subnet, err := parseIPv4(s.SubnetMask)
if err != nil {
s.closeConn() // in case it was already started
return wrapErrPri... | {
s.closeConn() // in case it was already started
return wrapErrPrint(err, "Failed to parse range start address %s", s.RangeStart)
} | conditional_block |
dhcpd.go | .Tracef("Lease not found for %s: creating new one", hwaddr)
ip, err := s.findFreeIP(hwaddr)
if err != nil {
i := s.findExpiredLease()
if i < 0 {
return nil, wrapErrPrint(err, "Couldn't find free IP for the lease %s", hwaddr.String())
}
log.Tracef("Assigning IP address %s to %s (lease for %s expired at %s)... | var lease *Lease
reqIP := net.IP(options[dhcp4.OptionRequestedIPAddress])
log.Tracef("Message from client: Request. IP: %s ReqIP: %s HW: %s",
p.CIAddr(), reqIP, p.CHAddr()) | random_line_split | |
dhcpd.go | := []byte(ip)
IP4 := [4]byte{rawIP[0], rawIP[1], rawIP[2], rawIP[3]}
s.IPpool[IP4] = hwaddr
}
func (s *Server) unreserveIP(ip net.IP) {
rawIP := []byte(ip)
IP4 := [4]byte{rawIP[0], rawIP[1], rawIP[2], rawIP[3]}
delete(s.IPpool, IP4)
}
// ServeDHCP handles an incoming DHCP request
func (s *Server) ServeDHCP(p dh... | {
s.Lock()
s.leases = nil
s.Unlock()
s.IPpool = make(map[[4]byte]net.HardwareAddr)
} | identifier_body | |
dhcpd.go | nil {
s.closeConn() // in case it was already started
return wrapErrPrint(err, "Couldn't find IPv4 address of interface %s %+v", s.InterfaceName, iface)
}
if s.LeaseDuration == 0 {
s.leaseTime = time.Hour * 2
s.LeaseDuration = uint(s.leaseTime.Seconds())
} else {
s.leaseTime = time.Second * time.Duration... | (p dhcp4.Packet, msgType dhcp4.MessageType, options dhcp4.Options) dhcp4.Packet {
s.printLeases()
switch msgType {
case dhcp4.Discover: // Broadcast Packet From Client - Can I have an IP?
return s.handleDiscover(p, options)
case dhcp4.Request: // Broadcast From Client - I'll take that IP (Also start for renewal... | ServeDHCP | identifier_name |
index.js | 24.256 911.33)" d="m505.58 148.29a70.219 68.464 0 0 1-54.814 66.796 70.219 68.464 0 0 1-78.865-37.488 70.219 68.464 0 0 1 20.211-83.244 70.219 68.464 0 0 1 87.733 0.96318" stroke="#000" stroke-linecap="round" stroke-width="22.66"/>
<path d="m377.05 468.98v75.785" stroke="#000002" stroke-linecap="square... | (id) {
let value = ''
if (this.restart) {
this.myCookie.eraseCookie(id)
value = ''
} else {
value = this.myCookie.getCookie(id)
if (value === null) {
value = ''
}
}
return value
},
/**
* test if the entered value is correct?
* @param {object} event ... | etValue | identifier_name |
index.js | 24.256 911.33)" d="m505.58 148.29a70.219 68.464 0 0 1-54.814 66.796 70.219 68.464 0 0 1-78.865-37.488 70.219 68.464 0 0 1 20.211-83.244 70.219 68.464 0 0 1 87.733 0.96318" stroke="#000" stroke-linecap="round" stroke-width="22.66"/>
<path d="m377.05 468.98v75.785" stroke="#000002" stroke-linecap="square... |
/**
* test if the entered value is correct?
* @param {object} event - what event caused the test?
* @param {object} el - element being tested
* @param {number} x - the value for x
* @param {number} y - the value for y
* @param {boolean} testGrid - ????
*/
test: function (event, el, x, y,... |
let value = ''
if (this.restart) {
this.myCookie.eraseCookie(id)
value = ''
} else {
value = this.myCookie.getCookie(id)
if (value === null) {
value = ''
}
}
return value
}, | identifier_body |
index.js | * @type {string}
*/
restartSVG: `
<svg version="1.1" viewBox="0 0 178.2 186.08" xmlns="http://www.w3.org/2000/svg">
<g transform="translate(-287.94 -456.48)" fill="none">
<path transform="matrix(.46642 -.98449 1.0097 .47838 24.256 911.33)" d="m505.58 148.29a70.219 68.464 0 0 ... | random_line_split | ||
parse_files_for_transcripts.py | , non_match_file)
## if -f flag is used, then just reformat data ###
# if 'format' in vars():
# # reformatted_data = _reformat_data(data_to_filter, mapfile)
#
# ### creating reformatted file
#
# final_file = open(outfile, 'w')
#
# ## print header row
# # final_file.write ("regulator feature name\... | (dict_to_print, outfile):
print "making GFF file"
#print headers #
newfile = open(outfile, 'w')
newfile.write("## GFF file for transcripts\n")
chr_order = ['chrI','chrII','chrIII','chrIV','chrV','chrVI','chrVII','chrVIII','chrIX','chrX','chrXI','chrXII','chrXIII','chrXIV','chrXV','chrXVI']
for chr in chr_orde... | _print_gff | identifier_name |
parse_files_for_transcripts.py | , non_match_file)
## if -f flag is used, then just reformat data ###
# if 'format' in vars():
# # reformatted_data = _reformat_data(data_to_filter, mapfile)
#
# ### creating reformatted file
#
# final_file = open(outfile, 'w')
#
# ## print header row
# # final_file.write ("regulator feature name\... |
for track in transcript_data[key]:
print 'adding ' + key + ' to file'
# print "|".join(track.values())
notes = track.get('notes', ".")
newfile.write("\t".join([chr,'rtracklayer_'+key,'sequence_feature',track['start'], track['stop'], track['score'],track['strand'],'.',notes]))
newfile.write("\... | continue | conditional_block |
parse_files_for_transcripts.py | data_to_filter = dict()
two_fold_data = dict()
genome_data = dict()
transcript_data = dict()
feat_type = 'gene' ## specific feature type; use 'all' if no specific feature type
filter_val = 3 ## number to filter by (count or score)
filter_type = 'count' # can filter by count('count') or score cutoff ('cutoff')
... |
def main(argv):
sorted_keys = list() | random_line_split | |
parse_files_for_transcripts.py | firstfile = arg
elif opt in ("-o", "--ofile"): # outfile name
outfile = arg
elif opt in ("-l","--lfile"): # s_cer gff3 file
locusfile = arg
elif opt in ("-f","--format"): #gff3 or tsv/wig file ## DOESN'T WORK
file_format = arg
elif opt in ("-v","--value"): ## filter value
filter_val = arg
e... | sorted_keys = list()
data_to_filter = dict()
two_fold_data = dict()
genome_data = dict()
transcript_data = dict()
feat_type = 'gene' ## specific feature type; use 'all' if no specific feature type
filter_val = 3 ## number to filter by (count or score)
filter_type = 'count' # can filter by count('count') or sco... | identifier_body | |
mod.rs |
fn swap_buffers(&mut self) {
if let Some(device_context) = self.device_context {
unsafe {
SwapBuffers(device_context);
}
}
}
fn resize(&mut self) {}
// wglSwapIntervalEXT sets VSync for the window bound to the current context.
// However he... | {
unsafe {
let window_device_context = self.device_context.unwrap_or(std::ptr::null_mut());
error_if_false(wglMakeCurrent(window_device_context, self.context_ptr))
}
} | identifier_body | |
mod.rs | .
self.swap_buffers();
if match vsync {
VSync::Off => wglSwapIntervalEXT(0),
VSync::On => wglSwapIntervalEXT(1),
VSync::Adaptive => wglSwapIntervalEXT(-1),
VSync::Other(i) => wglSwapIntervalEXT(i),
} == false
... |
}
}
}
}
impl GLContextBuilder {
pub fn build(&self) -> Result<GLContext, ()> {
Ok(new_opengl_context(
self.gl_attributes.color_bits,
self.gl_attributes.alpha_bits,
self.gl_attributes.depth_bits,
self.gl_attributes.stencil_bits,
... | {
panic!("Failed to release device context");
} | conditional_block |
mod.rs | happen.
self.swap_buffers();
if match vsync {
VSync::Off => wglSwapIntervalEXT(0),
VSync::On => wglSwapIntervalEXT(1),
VSync::Adaptive => wglSwapIntervalEXT(-1),
VSync::Other(i) => wglSwapIntervalEXT(i),
} == false
... | (&self, address: &str) -> *const core::ffi::c_void {
get_proc_address_inner(self.opengl_module, address)
}
}
fn get_proc_address_inner(opengl_module: HMODULE, address: &str) -> *const core::ffi::c_void {
unsafe {
let name = std::ffi::CString::new(address).unwrap();
let mut result = wglG... | get_proc_address | identifier_name |
mod.rs | _ => unreachable!(),
})
.unwrap();
let window_device_context = if let Some(_window) = window {
if let Some(current_device_context) = self.device_context {
ReleaseDC(window_handle, current_device_context);
... | RawWindowHandle::Windows(handle) => handle.hwnd as HWND, | random_line_split | |
appconfig.go | `json:"id"` // ACLs can reference this, so keep stable (i.e. service replicas/restarts should not affect this)
Frontends []Frontend `json:"frontends"`
Backend Backend `json:"backend"`
}
func (a *Application) Validate() error {
if err := ErrorIfUnset(a.Id == "", "Id"); err != nil {
return err
}
if err := ... | (hostnameRegexp string, options ...FrontendOpt) Frontend {
opts := getFrontendOptions(options)
return Frontend{
Kind: FrontendKindHostnameRegexp,
HostnameRegexp: hostnameRegexp,
PathPrefix: opts.pathPrefix,
StripPathPrefix: opts.stripPathPrefix,
AllowInsecureHTTP: opts.allowInsecur... | RegexpHostnameFrontend | identifier_name |
appconfig.go | `json:"id"` // ACLs can reference this, so keep stable (i.e. service replicas/restarts should not affect this)
Frontends []Frontend `json:"frontends"`
Backend Backend `json:"backend"`
}
func (a *Application) Validate() error {
if err := ErrorIfUnset(a.Id == "", "Id"); err != nil {
return err
}
if err := ... | ErrorIfUnset(b.BearerToken == "", "BearerToken"),
ErrorIfUnset(b.AuthorizedBackend == nil, "AuthorizedBackend"),
)
}
type BackendOptsAuthSso struct {
IdServerUrl string `json:"id_server_url,omitempty"`
AllowedUserIds []string `json:"allowed_user_ids"`
Audience string `json:"audience"`
Au... | return FirstError( | random_line_split |
appconfig.go | ) https://doc.traefik.io/traefik/routing/services/#pass-host-header
IndexDocument string `json:"index_document,omitempty"` // if request path ends in /foo/ ("directory"), rewrite it into /foo/index.html
RemoveQueryString bool `json:"remove_query_string,omitempty"` // reduces cache mis... | {
if err != nil {
return err
}
} | conditional_block | |
appconfig.go | `json:"id"` // ACLs can reference this, so keep stable (i.e. service replicas/restarts should not affect this)
Frontends []Frontend `json:"frontends"`
Backend Backend `json:"backend"`
}
func (a *Application) Validate() error {
if err := ErrorIfUnset(a.Id == "", "Id"); err != nil {
return err
}
if err := ... |
type BackendOptsAwsLambda struct {
FunctionName string `json:"function_name"`
RegionId string `json:"region_id"`
}
func (b *BackendOptsAwsLambda) Validate() error {
return FirstError(
ErrorIfUnset(b.FunctionName == "", "FunctionName"),
ErrorIfUnset(b.RegionId == "", "RegionId"),
)
}
type BackendOptsAuth... | {
return ErrorIfUnset(len(b.Origins) == 0, "Origins")
} | identifier_body |
flutter_service_worker.js | "assets/assets/sounds/Index13Length4.wav": "4eac2adb92f81fe26c37e268f703fa2c",
"assets/assets/sounds/Index14Length0.wav": "959c53595dba4a30fec8715149f2947a",
"assets/assets/sounds/Index14Length1.wav": "aa7777a5e53a9514c89a01beedf05a13",
"assets/assets/sounds/Index14Length2.wav": "85f14e073d1698e24709436f91eae42c",
"ass... | "assets/assets/sounds/Index13Length2.wav": "746f509a12e5f7f2ece7209e7722f3f9",
"assets/assets/sounds/Index13Length3.wav": "90665e5c989f7e7379e2a7e4d54f3aac", | random_line_split | |
flutter_service_worker.js | 1713a82800e28d25e4165",
"assets/assets/sounds/Index9Length0.wav": "959c53595dba4a30fec8715149f2947a",
"assets/assets/sounds/Index9Length1.wav": "ef3438e19d91637ec197ce7a0b5bfd0d",
"assets/assets/sounds/Index9Length2.wav": "0b870a0d1df07e11fc413c41e70b5d53",
"assets/assets/sounds/Index9Length3.wav": "f2cdebe3e1ce45cd426... | {
var resources = [];
var contentCache = await caches.open(CACHE_NAME);
var currentContent = {};
for (var request of await contentCache.keys()) {
var key = request.url.substring(origin.length + 1);
if (key == "") {
key = "/";
}
currentContent[key] = true;
}
for (var resourceKey of Obje... | identifier_body | |
flutter_service_worker.js | 5",
"assets/assets/sounds/Index9Length0.wav": "959c53595dba4a30fec8715149f2947a",
"assets/assets/sounds/Index9Length1.wav": "ef3438e19d91637ec197ce7a0b5bfd0d",
"assets/assets/sounds/Index9Length2.wav": "0b870a0d1df07e11fc413c41e70b5d53",
"assets/assets/sounds/Index9Length3.wav": "f2cdebe3e1ce45cd4263368a22fe94ec",
"ass... | onlineFirst | identifier_name | |
flutter_service_worker.js | ": "fe792670c83be5650b0a692e008c68e9",
"assets/assets/sounds/Index8Length4.wav": "c2c338ea17f946e033e63e740e84853e",
"assets/assets/sounds/Index8Length6.wav": "bf359945806a4c1a1af022d3ab7c8388",
"assets/assets/sounds/Index8Length8.wav": "7685dc4811b1713a82800e28d25e4165",
"assets/assets/sounds/Index9Length0.wav": "959c... | {
downloadOffline();
return;
} | conditional_block | |
facade.rs | // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_fuchsia_pkg::{RepositoryManagerMarker, RepositoryManagerProxy... |
Err(err) => {
return Err(format_err!("Listing Repositories failed with error {:?}", err))
}
};
}
/// Add a new source to an existing repository.
///
/// params format uses RepositoryConfig, example:
/// {
/// "repo_url": "fuchsia-pkg://exampl... | {
let return_value = to_value(&repos)?;
return Ok(return_value);
} | conditional_block |
facade.rs | // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_fuchsia_pkg::{RepositoryManagerMarker, RepositoryManagerProxy... | }
fn proxy(&self) -> Result<RepositoryManagerProxy, Error> {
get_proxy_or_connect::<RepositoryManagerMarker>(&self.proxy)
}
/// Lists repositories using the repository_manager fidl service.
///
/// Returns a list containing repository info in the format of
/// RepositoryConfig.
... |
#[cfg(test)]
fn new_with_proxy(proxy: RepositoryManagerProxy) -> Self {
Self { proxy: RwLock::new(Some(proxy)) } | random_line_split |
facade.rs | // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_fuchsia_pkg::{RepositoryManagerMarker, RepositoryManagerProxy... | () {
let repo_config = make_test_repo_config();
assert_value_round_trips_as(
repo_config,
json!(
{
"repo_url": "fuchsia-pkg://example.com",
"root_keys":[
{
"type":"ed25519",
... | serde_repo_configuration | identifier_name |
facade.rs | // Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use crate::common_utils::common::get_proxy_or_connect;
use crate::repository_manager::types::RepositoryOutput;
use anyhow::{format_err, Error};
use fidl_fuchsia_pkg::{RepositoryManagerMarker, RepositoryManagerProxy... |
/// Fetches repositories using repository_manager.list FIDL service.
async fn fetch_repos(&self) -> Result<Vec<RepositoryConfig>, anyhow::Error> {
let (iter, server_end) = fidl::endpoints::create_proxy()?;
self.proxy()?.list(server_end)?;
let mut repos = vec![];
loop {
... | {
let add_request: RepositoryConfig = from_value(args)?;
fx_log_info!("Add Repo request received {:?}", add_request);
let res = self.proxy()?.add(add_request.into()).await?;
match res.map_err(zx::Status::from_raw) {
Ok(()) => Ok(to_value(RepositoryOutput::Success)?),
... | identifier_body |
gulpfile.js | Depends on: watch
*/
gulp.task('live-reload', ['watch'], function() {
var livereload = require('gulp-livereload');
settings.liveReload = true;
// first, delete the index.html from the dist folder as we will copy it later
del([settings.dist + 'index.html']);
// add livereload script to the index.html
gul... | onError | identifier_name | |
gulpfile.js | });
/**
* Task for copying fonts only
*/
gulp.task('copy-fonts', function() {
var deferred = q.defer();
// copy all fonts
setTimeout(function() {
gulp.src( settings.src + 'fonts/**')
.pipe(gulp.dest(settings.dist + 'fonts'));
deferred.resolve();
}, 1);
return deferred.promise;
});
/*... | {
cb();
} | conditional_block |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.