file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
bibtexParser.ts
export class RootNode { type = 'root' as const; constructor(public children: (TextNode | BlockNode)[] = []) {} } export class TextNode { type = 'text' as const; constructor(public parent: RootNode, public text: string) { parent.children.push(this); } } export class BlockNode { type = 'block' as const; public ...
function isValidFieldName(char: string): boolean { return !/[=,{}()[\]]/.test(char); } export class BibTeXSyntaxError extends Error { public char: string; constructor( input: string, public node: Node, pos: number, public line: number, public column: number, public hint?: string ) { super( `Line...
{ return !/[#%{}~$,]/.test(char); }
identifier_body
document.py
import cgi import logging from normality import slugify from followthemoney import model from followthemoney.types import registry from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm.attributes import flag_modified from aleph.core import db, cache from aleph.model.metadata import Metadata from aleph.m...
(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
import cgi import logging from normality import slugify from followthemoney import model from followthemoney.types import registry from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm.attributes import flag_modified from aleph.core import db, cache from aleph.model.metadata import Metadata from aleph.m...
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
import cgi import logging from normality import slugify from followthemoney import model from followthemoney.types import registry from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm.attributes import flag_modified from aleph.core import db, cache from aleph.model.metadata import Metadata from aleph.m...
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
import cgi import logging from normality import slugify from followthemoney import model from followthemoney.types import registry from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.orm.attributes import flag_modified from aleph.core import db, cache from aleph.model.metadata import Metadata from aleph.m...
@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
// Package ppsutil contains utilities for various PPS-related tasks, which are // shared by both the PPS API and the worker binary. These utilities include: // - Getting the RC name and querying k8s reguarding pipelines // - Reading and writing pipeline resource requests and limits // - Reading and writing EtcdPipeline...
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
// Package ppsutil contains utilities for various PPS-related tasks, which are // shared by both the PPS API and the worker binary. These utilities include: // - Getting the RC name and querying k8s reguarding pipelines // - Reading and writing pipeline resource requests and limits // - Reading and writing EtcdPipeline...
// 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
// Package ppsutil contains utilities for various PPS-related tasks, which are // shared by both the PPS API and the worker binary. These utilities include: // - Getting the RC name and querying k8s reguarding pipelines // - Reading and writing pipeline resource requests and limits // - Reading and writing EtcdPipeline...
} 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
// Package ppsutil contains utilities for various PPS-related tasks, which are // shared by both the PPS API and the worker binary. These utilities include: // - Getting the RC name and querying k8s reguarding pipelines // - Reading and writing pipeline resource requests and limits // - Reading and writing EtcdPipeline...
(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
use crate::ai_utils::playout_result; use crate::competing_optimizers::StrategyOptimizer; use crate::condition_strategy::{ Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule, }; use crate::representative_sampling::NewFractalRepresentativeSeedSearch; use crate::seed_system::{Seed, Si...
let mut verification_seeds: Vec<_> = verification_seeds .into_iter() .map(|s| HillClimbSeedInfo { seed: s, current_score: playout_result(&seed_search.starting_state, s.view(), &current).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
use crate::ai_utils::playout_result; use crate::competing_optimizers::StrategyOptimizer; use crate::condition_strategy::{ Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule, }; use crate::representative_sampling::NewFractalRepresentativeSeedSearch; use crate::seed_system::{Seed, Si...
tweak_rules(&mut result.rules, state, rng, &promising_conditions); result } }
.collect(); let mut result = self.clone();
random_line_split
condition_strategy_generators.rs
use crate::ai_utils::playout_result; use crate::competing_optimizers::StrategyOptimizer; use crate::condition_strategy::{ Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule, }; use crate::representative_sampling::NewFractalRepresentativeSeedSearch; use crate::seed_system::{Seed, Si...
pub fn step(&mut self, rng: &mut impl Rng) { let generator = self .generators .iter_mut() .min_by_key(|g| g.time_used) .unwrap(); let start = Instant::now(); let strategy = generator.generator.gen_strategy(&self.seed_search, rng); let duration = start.elapsed(); generator...
{ 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
use crate::ai_utils::playout_result; use crate::competing_optimizers::StrategyOptimizer; use crate::condition_strategy::{ Condition, ConditionKind, ConditionStrategy, EvaluatedPriorities, EvaluationData, Rule, }; use crate::representative_sampling::NewFractalRepresentativeSeedSearch; use crate::seed_system::{Seed, Si...
<'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
/* * Philip Crotwell * University of South Carolina, 2019 * http://www.seis.sc.edu */ import {DateTime, Duration, Interval} from "luxon"; import {removeTrend } from "./filter"; import {Seismogram, SeismogramDisplayData, findMinMaxOverTimeRange} from "./seismogram"; import {SeismogramSegment} from "./seismogramsegme...
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
/* * Philip Crotwell * University of South Carolina, 2019 * http://www.seis.sc.edu */ import {DateTime, Duration, Interval} from "luxon"; import {removeTrend } from "./filter"; import {Seismogram, SeismogramDisplayData, findMinMaxOverTimeRange} from "./seismogram"; import {SeismogramSegment} from "./seismogramsegme...
} 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
/* * Philip Crotwell * University of South Carolina, 2019 * http://www.seis.sc.edu */ import {DateTime, Duration, Interval} from "luxon"; import {removeTrend } from "./filter"; import {Seismogram, SeismogramDisplayData, findMinMaxOverTimeRange} from "./seismogram"; import {SeismogramSegment} from "./seismogramsegme...
(): 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
/* * Philip Crotwell * University of South Carolina, 2019 * http://www.seis.sc.edu */ import {DateTime, Duration, Interval} from "luxon"; import {removeTrend } from "./filter"; import {Seismogram, SeismogramDisplayData, findMinMaxOverTimeRange} from "./seismogram"; import {SeismogramSegment} from "./seismogramsegme...
} /** default styling for helicorder plots. */ export const helicorder_css = ` :host { display: block; min-height: 200px; height: 100%; cursor: crosshair; } `; export const HELICORDER_SELECTOR = "helicorder"; export const HELI_COLOR_CSS_ID = "helicordercolors"; export type HeliMouseEventType = { mouseevent...
{ this.interval = Interval.after(startTime, duration); this.lineNumber = lineNumber; }
identifier_body
testkeras.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split import glob from root_numpy import root2array from numpy.lib.recfunctions import stack_arrays def root2pandas(files_path, tree_name, **kwargs): ''' Args: ----- ...
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
import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split import glob from root_numpy import root2array from numpy.lib.recfunctions import stack_arrays def root2pandas(files_path, tree_name, **kwargs): ''' Args: ----- ...
plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') ''' #compute confusion matrix cnf_matrix = confusion_matrix(y_test, yhat_cls, sample_weight=w_test) np.set_printoptions(precision=4) plot_confusion_matrix(cnf_matrix, classes=['Sig', 'Bkg'], normalize=True, ...
plt.text(j, i, format(cm[i, j], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black")
conditional_block
testkeras.py
import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split import glob from root_numpy import root2array from numpy.lib.recfunctions import stack_arrays def root2pandas(files_path, tree_name, **kwargs): ''' Args: ----- ...
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
import numpy as np import matplotlib import matplotlib.pyplot as plt import pandas as pd from sklearn.model_selection import train_test_split import glob from root_numpy import root2array from numpy.lib.recfunctions import stack_arrays def root2pandas(files_path, tree_name, **kwargs): ''' Args: ----- ...
(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ This function prints and plots the confusion matrix. Normalization can be applied by setting `normalize=True`. """ if normalize: cm =...
plot_confusion_matrix
identifier_name
runner.rs
use core::fmt::{Display, Formatter, Result as FmtResult}; use std::error::Error as StdError; use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use std::{cell::RefCell, sync::mpsc::Receiver}; use skulpin_renderer::{ash, Logi...
#[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
use core::fmt::{Display, Formatter, Result as FmtResult}; use std::error::Error as StdError; use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use std::{cell::RefCell, sync::mpsc::Receiver}; use skulpin_renderer::{ash, Logi...
} 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
use core::fmt::{Display, Formatter, Result as FmtResult}; use std::error::Error as StdError; use std::sync::mpsc::{sync_channel, SyncSender, TryRecvError, TrySendError}; use std::thread::{sleep, spawn}; use std::time::{Duration, Instant}; use std::{cell::RefCell, sync::mpsc::Receiver}; use skulpin_renderer::{ash, Logi...
() -> 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
// Copyright 2019-2023 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT //! This module defines a [parser](parse()) and //! [pretty-printer](TokenAmountPretty::pretty) for //! `TokenAmount` //! //! See the `si` module source for supported prefixes. pub use parse::parse; pub use print::TokenAmountPretty; ...
attos: BigInt, } impl From<&TokenAmount> for Pretty { fn from(value: &TokenAmount) -> Self { Self { attos: value.atto().clone(), } } } pub trait TokenAmountPretty { fn pretty(&self) -> Pretty; } impl TokenAmountPretty fo...
etty {
identifier_name
humantoken.rs
// Copyright 2019-2023 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT //! This module defines a [parser](parse()) and //! [pretty-printer](TokenAmountPretty::pretty) for //! `TokenAmount` //! //! See the `si` module source for supported prefixes. pub use parse::parse; pub use print::TokenAmountPretty; ...
}
quickcheck! { fn parser_no_panic(s: String) -> () { let _ = parse(&s); } }
random_line_split
humantoken.rs
// Copyright 2019-2023 ChainSafe Systems // SPDX-License-Identifier: Apache-2.0, MIT //! This module defines a [parser](parse()) and //! [pretty-printer](TokenAmountPretty::pretty) for //! `TokenAmount` //! //! See the `si` module source for supported prefixes. pub use parse::parse; pub use print::TokenAmountPretty; ...
/// 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(recognize_float, str::parse)(input) } #[cfg(test)] mod tests { us...
// 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
import os import hashlib import struct def int_to_bytes(raw, length): data = [] for _ in range(length): data.append(raw % 256) raw //= 256 return bytes(data[::-1]) def bytes_to_int(data): raw = 0 for byte in data: raw = raw * 256 + byte return raw def legendre(a, p)...
(self, backend_factory, params, aes, nid): self._backend = backend_factory(**params) self.params = params self._aes = aes self.nid = nid def _encode_public_key(self, x, y, is_compressed=True, raw=True): if raw: if is_compressed: return bytes([0x02...
__init__
identifier_name
eccrypto.py
import os import hashlib import struct def int_to_bytes(raw, length): data = [] for _ in range(length): data.append(raw % 256) raw //= 256 return bytes(data[::-1]) def bytes_to_int(data): raw = 0 for byte in data: raw = raw * 256 + byte return raw def legendre(a, p)...
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
import os import hashlib import struct def int_to_bytes(raw, length): data = [] for _ in range(length): data.append(raw % 256) raw //= 256 return bytes(data[::-1]) def bytes_to_int(data): raw = 0 for byte in data: raw = raw * 256 + byte return raw def legendre(a, p)...
def private_to_public(self, private_key): if len(private_key) == self._backend.public_key_length: is_compressed = False elif len( private_key ) == self._backend.public_key_length + 1 and private_key[-1] == 1: is_compressed = True private_k...
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
import os import hashlib import struct def int_to_bytes(raw, length): data = [] for _ in range(length): data.append(raw % 256) raw //= 256 return bytes(data[::-1]) def bytes_to_int(data): raw = 0 for byte in data: raw = raw * 256 + byte return raw def legendre(a, p)...
# 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
package github import ( "context" "errors" "fmt" "net/http" "os" "strconv" "strings" "sync" "time" "golang.org/x/oauth2" githubO2 "golang.org/x/oauth2/github" "github.com/google/go-github/github" "github.com/watchly/ngbuild/core" ) var oauth2State = fmt.Sprintf("%d%d%d", os.Getuid(), os.Getpid(), time....
ret = fmt.Sprintf("github-info: "+str+"\n", args...) fmt.Printf(ret) return ret } func logwarnf(str string, args ...interface{}) (ret string) { ret = fmt.Sprintf("github-warn: "+str+"\n", args...) fmt.Printf(ret) return ret } func logcritf(str string, args ...interface{}) (ret string) { ret = fmt.Sprintf("gith...
random_line_split
github.go
package github import ( "context" "errors" "fmt" "net/http" "os" "strconv" "strings" "sync" "time" "golang.org/x/oauth2" githubO2 "golang.org/x/oauth2/github" "github.com/google/go-github/github" "github.com/watchly/ngbuild/core" ) var oauth2State = fmt.Sprintf("%d%d%d", os.Getuid(), os.Getpid(), time....
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
package github import ( "context" "errors" "fmt" "net/http" "os" "strconv" "strings" "sync" "time" "golang.org/x/oauth2" githubO2 "golang.org/x/oauth2/github" "github.com/google/go-github/github" "github.com/watchly/ngbuild/core" ) var oauth2State = fmt.Sprintf("%d%d%d", os.Getuid(), os.Getpid(), time....
() { 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
package github import ( "context" "errors" "fmt" "net/http" "os" "strconv" "strings" "sync" "time" "golang.org/x/oauth2" githubO2 "golang.org/x/oauth2/github" "github.com/google/go-github/github" "github.com/watchly/ngbuild/core" ) var oauth2State = fmt.Sprintf("%d%d%d", os.Getuid(), os.Getpid(), time....
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
#%% Image class import logging import imutils import numpy as np import sklearn as sk # import sklearn.cluster import cv2 import pandas as pd import base64 class SimpleImage: def __init__(self, image_id): pass class Image(): def __init__(self, image_id): """An object representing a full satel...
# 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
#%% Image class import logging import imutils import numpy as np import sklearn as sk # import sklearn.cluster import cv2 import pandas as pd import base64 class SimpleImage: def __init__(self, image_id): pass class Image(): def __init__(self, image_id): """An object representing a full satel...
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
#%% Image class import logging import imutils import numpy as np import sklearn as sk # import sklearn.cluster import cv2 import pandas as pd import base64 class SimpleImage: def __init__(self, image_id): pass class Image(): def __init__(self, image_id): """An object representing a full satel...
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
#%% Image class import logging import imutils import numpy as np import sklearn as sk # import sklearn.cluster import cv2 import pandas as pd import base64 class SimpleImage: def __init__(self, image_id): pass class Image(): def __init__(self, image_id): """An object representing a full satel...
(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
package system import ( "bytes" "context" "fmt" "strings" "text/template" "time" "github.com/noobaa/noobaa-operator/build/_output/bundle" nbv1 "github.com/noobaa/noobaa-operator/pkg/apis/noobaa/v1alpha1" "github.com/noobaa/noobaa-operator/pkg/nb" "github.com/noobaa/noobaa-operator/pkg/options" "github.com/...
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
package system import ( "bytes" "context" "fmt" "strings" "text/template" "time" "github.com/noobaa/noobaa-operator/build/_output/bundle" nbv1 "github.com/noobaa/noobaa-operator/pkg/apis/noobaa/v1alpha1" "github.com/noobaa/noobaa-operator/pkg/nb" "github.com/noobaa/noobaa-operator/pkg/options" "github.com/...
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
package system import ( "bytes" "context" "fmt" "strings" "text/template" "time" "github.com/noobaa/noobaa-operator/build/_output/bundle" nbv1 "github.com/noobaa/noobaa-operator/pkg/apis/noobaa/v1alpha1" "github.com/noobaa/noobaa-operator/pkg/nb" "github.com/noobaa/noobaa-operator/pkg/options" "github.com/...
readmeTemplate = template.Must(template.New("NooBaaSystem.Status.Readme").Parse(` Welcome to NooBaa! ----------------- Lets get started: 1. Connect to Management console: Read your mgmt console login information (email & password) from secret: "{{.SecretAdmin.Name}}". kubectl get secret {{.SecretAdmin.Nam...
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
package system import ( "bytes" "context" "fmt" "strings" "text/template" "time" "github.com/noobaa/noobaa-operator/build/_output/bundle" nbv1 "github.com/noobaa/noobaa-operator/pkg/apis/noobaa/v1alpha1" "github.com/noobaa/noobaa-operator/pkg/nb" "github.com/noobaa/noobaa-operator/pkg/options" "github.com/...
nbv1.SystemPhase) { r.Logger.Infof("SetPhase: %s", phase) r.NooBaa.Status.Phase = phase conditions := &r.NooBaa.Status.Conditions reason := fmt.Sprintf("NooBaaSystemPhase%s", phase) message := fmt.Sprintf("NooBaa operator system reconcile phase %s", phase) switch phase { case nbv1.SystemPhaseReady: util.SetAv...
se(phase
identifier_name
lib.rs
// LNP/BP lLibraries implementing LNPBP specifications & standards // Written in 2021-2022 by // Dr. Maxim Orlovsky <orlovsky@pandoraprime.ch> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. ...
/// 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
// LNP/BP lLibraries implementing LNPBP specifications & standards // Written in 2021-2022 by // Dr. Maxim Orlovsky <orlovsky@pandoraprime.ch> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. ...
<Value>(std::marker::PhantomData<Value>); #[cfg(feature = "serde")] impl<'de, ValueT> Visitor<'de> for Bech32Visitor<ValueT> where ValueT: FromBech32Str, { type Value = ValueT; fn expecting( &self, formatter: &mut std::fmt::Formatter, ) -> std::fmt::Result { formatter.write_str...
Bech32Visitor
identifier_name
lib.rs
//! JSON-RPC client implementation. #![deny(missing_docs)] use failure::{format_err, Fail}; use futures::sync::{mpsc, oneshot}; use futures::{future, prelude::*}; use jsonrpc_core::{Error, Params}; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::Value; use std::marker::PhantomData; pub mod tra...
#[derive(Clone)] struct AddClient(TypedClient); impl From<RpcChannel> for AddClient { fn from(channel: RpcChannel) -> Self { AddClient(channel.into()) } } impl AddClient { fn add(&self, a: u64, b: u64) -> impl Future<Item = u64, Error = RpcError> { self.0.call_method("add", "u64", (a, b)) } fn ...
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
//! JSON-RPC client implementation. #![deny(missing_docs)] use failure::{format_err, Fail}; use futures::sync::{mpsc, oneshot}; use futures::{future, prelude::*}; use jsonrpc_core::{Error, Params}; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::Value; use std::marker::PhantomData; pub mod tra...
} #[cfg(test)] mod tests { use super::*; use crate::transports::local; 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; #[derive(Clon...
{ 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
//! JSON-RPC client implementation. #![deny(missing_docs)] use failure::{format_err, Fail}; use futures::sync::{mpsc, oneshot}; use futures::{future, prelude::*}; use jsonrpc_core::{Error, Params}; use serde::de::DeserializeOwned; use serde::Serialize; use serde_json::Value; use std::marker::PhantomData; pub mod tra...
<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
/* * Copyright 2017 Dgraph Labs, Inc. and Contributors * * 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 appli...
} 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
/* * Copyright 2017 Dgraph Labs, Inc. and Contributors * * 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 appli...
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
/* * Copyright 2017 Dgraph Labs, Inc. and Contributors * * 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 appli...
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
/* * Copyright 2017 Dgraph Labs, Inc. and Contributors * * 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 appli...
(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
package appimage import ( "bytes" "debug/elf" "encoding/json" "errors" "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/adrg/xdg" au "github.com/srevinsaju/appimage-update" "github.com/srevinsaju/zap/config" "github.com/srevinsaju/zap/index"...
return app, err } if !hasUpdates { return app, errors.New("up-to-date") } logger.Debugf("Downloading updates for %s", app.Executable) newFileName, err := updater.Download() fmt.Print("\n") app.Filepath = newFileName _ = os.Remove(app.IconPath) _ = os.Remove(app.DesktopFile) app.ExtractThumbnail(config....
logger.Debugf("Checking for updates") hasUpdates, err := updater.Lookup() if err != nil {
random_line_split
utils.go
package appimage import ( "bytes" "debug/elf" "encoding/json" "errors" "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/adrg/xdg" au "github.com/srevinsaju/appimage-update" "github.com/srevinsaju/zap/config" "github.com/srevinsaju/zap/index"...
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
package appimage import ( "bytes" "debug/elf" "encoding/json" "errors" "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/adrg/xdg" au "github.com/srevinsaju/appimage-update" "github.com/srevinsaju/zap/config" "github.com/srevinsaju/zap/index"...
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
package appimage import ( "bytes" "debug/elf" "encoding/json" "errors" "fmt" "io/ioutil" "os" "path" "path/filepath" "strings" "time" "github.com/AlecAivazis/survey/v2" "github.com/adrg/xdg" au "github.com/srevinsaju/appimage-update" "github.com/srevinsaju/zap/config" "github.com/srevinsaju/zap/index"...
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
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations'; import {studentMenuItems} from '../../shared/menu-items/student-menu'; import { DataserviceService } from 'src/app/dataservice/dataservice.service'; import ...
ype: string) { this.layoutType = type; if (type === 'dark') { this.headerTheme = 'theme6'; this.navBarTheme = 'theme1'; this.logoTheme = 'theme6'; document.querySelector('body').classList.add('dark'); } else { this.headerTheme = 'theme1'; this.navBarTheme = 'themelight1';...
tLayoutType(t
identifier_name
student-layout.component.ts
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations'; import {studentMenuItems} from '../../shared/menu-items/student-menu'; import { DataserviceService } from 'src/app/dataservice/dataservice.service'; import ...
} 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
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations'; import {studentMenuItems} from '../../shared/menu-items/student-menu'; import { DataserviceService } from 'src/app/dataservice/dataservice.service'; import ...
setSidebarPosition() { this.isSidebarChecked = !this.isSidebarChecked; this.pcodedSidebarPosition = this.isSidebarChecked === true ? 'fixed' : 'absolute'; } setHeaderPosition() { this.isHeaderChecked = !this.isHeaderChecked; this.pcodedHeaderPosition = this.isHeaderChecked === true ? 'fixed' : 'r...
this.configOpenRightBar = this.configOpenRightBar === 'open' ? '' : 'open'; }
identifier_body
student-layout.component.ts
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core'; import {animate, AUTO_STYLE, state, style, transition, trigger} from '@angular/animations'; import {studentMenuItems} from '../../shared/menu-items/student-menu'; import { DataserviceService } from 'src/app/dataservice/dataservice.service'; import ...
lse { this.navBarTheme = 'theme1'; } } urlToObject = async (imageName) => { const response = await fetch((this.profile_image_api + imageName)); if(response.ok) { const blob = await response.blob(); // console.log(blob) // const file = new File([blob], imageName, {type: blob.type...
this.navBarTheme = 'themelight1'; } e
conditional_block
queue.go
package memberlist import ( "math" "sync" "github.com/google/btree" ) // TransmitLimitedQueue is used to queue messages to broadcast to // the cluster (via gossip) but limits the number of transmits per // message. It also prioritizes messages with lower transmit counts // (hence newer messages). type TransmitLim...
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
package memberlist import ( "math" "sync" "github.com/google/btree" ) // TransmitLimitedQueue is used to queue messages to broadcast to // the cluster (via gossip) but limits the number of transmits per // message. It also prioritizes messages with lower transmit counts // (hence newer messages). type TransmitLim...
() (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
package memberlist import ( "math" "sync" "github.com/google/btree" ) // TransmitLimitedQueue is used to queue messages to broadcast to // the cluster (via gossip) but limits the number of transmits per // message. It also prioritizes messages with lower transmit counts // (hence newer messages). type TransmitLim...
// 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
package memberlist import ( "math" "sync" "github.com/google/btree" ) // TransmitLimitedQueue is used to queue messages to broadcast to // the cluster (via gossip) but limits the number of transmits per // message. It also prioritizes messages with lower transmit counts // (hence newer messages). type TransmitLim...
// 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
package bengine ///////////////////////////////////////////////////////////////////// // imports import ( "math/rand" . "github.com/easychessanimations/gochess/butils" ) ///////////////////////////////////////////////////////////////////// // package bengine implements board, move generation and position searchi...
// 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
package bengine ///////////////////////////////////////////////////////////////////// // imports import ( "math/rand" . "github.com/easychessanimations/gochess/butils" ) ///////////////////////////////////////////////////////////////////// // package bengine implements board, move generation and position searchi...
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
package bengine ///////////////////////////////////////////////////////////////////// // imports import ( "math/rand" . "github.com/easychessanimations/gochess/butils" ) ///////////////////////////////////////////////////////////////////// // package bengine implements board, move generation and position searchi...
es for the returned values func (eng *Engine) Play(tc *TimeControl) (score int32, moves []Move) { return eng.PlayMoves(tc, nil) } // PlayMoves evaluates current position searching only moves specifid by rootMoves // // returns the principal variation, that is // moves[0] is the best move found and // moves[...
ee PlayMov
conditional_block
engine.go
package bengine ///////////////////////////////////////////////////////////////////// // imports import ( "math/rand" . "github.com/easychessanimations/gochess/butils" ) ///////////////////////////////////////////////////////////////////// // package bengine implements board, move generation and position searchi...
int16(eng.Score()) } return int32(e.static) } // endPosition determines whether the current position is an end game // returns score and a bool if the game has ended func (eng *Engine) endPosition() (int32, bool) { pos := eng.Position // shortcut // trivial cases when kings are missing if Kings(pos, White) == 0 {...
e.static =
identifier_name
app.component.ts
import { Component, ElementRef, HostListener, Inject, LOCALE_ID, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { HttpClient, HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http'; import { SimpleTimer } from 'ng2-simple-timer'; imp...
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
import { Component, ElementRef, HostListener, Inject, LOCALE_ID, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { HttpClient, HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http'; import { SimpleTimer } from 'ng2-simple-timer'; imp...
(): 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
import { Component, ElementRef, HostListener, Inject, LOCALE_ID, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { HttpClient, HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http'; import { SimpleTimer } from 'ng2-simple-timer'; imp...
} 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
import { Component, ElementRef, HostListener, Inject, LOCALE_ID, OnInit } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { HttpClient, HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders } from '@angular/common/http'; import { SimpleTimer } from 'ng2-simple-timer'; imp...
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
package dhcpd import ( "bytes" "fmt" "net" "strings" "sync" "time" "github.com/happyhater/golibs/log" "github.com/krolaw/dhcp4" ping "github.com/sparrc/go-ping" ) const defaultDiscoverTime = time.Second * 3 // Lease contains the necessary information about a DHCP lease // field ordering is important -- yam...
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
package dhcpd import ( "bytes" "fmt" "net" "strings" "sync" "time" "github.com/happyhater/golibs/log" "github.com/krolaw/dhcp4" ping "github.com/sparrc/go-ping" ) const defaultDiscoverTime = time.Second * 3 // Lease contains the necessary information about a DHCP lease // field ordering is important -- yam...
if !isValidPacket(p) { return nil } server := options[dhcp4.OptionServerIdentifier] if server != nil && !net.IP(server).Equal(s.ipnet.IP) { log.Tracef("Request message not for this DHCP server (%v vs %v)", server, s.ipnet.IP) return nil // Message not for this dhcp server } if reqIP == nil { reqIP = p....
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
package dhcpd import ( "bytes" "fmt" "net" "strings" "sync" "time" "github.com/happyhater/golibs/log" "github.com/krolaw/dhcp4" ping "github.com/sparrc/go-ping" ) const defaultDiscoverTime = time.Second * 3 // Lease contains the necessary information about a DHCP lease // field ordering is important -- yam...
{ s.Lock() s.leases = nil s.Unlock() s.IPpool = make(map[[4]byte]net.HardwareAddr) }
identifier_body
dhcpd.go
package dhcpd import ( "bytes" "fmt" "net" "strings" "sync" "time" "github.com/happyhater/golibs/log" "github.com/krolaw/dhcp4" ping "github.com/sparrc/go-ping" ) const defaultDiscoverTime = time.Second * 3 // Lease contains the necessary information about a DHCP lease // field ordering is important -- yam...
(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
if ('serviceWorker' in navigator) { // register service worker navigator.serviceWorker.register('service-worker.js') } const tableBuilder = { /** * minimum width in pixels for each column. * @type {number} */ minWidthForColumn: 150, /** * default max number of columns * @type {number} */ ...
(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
if ('serviceWorker' in navigator) { // register service worker navigator.serviceWorker.register('service-worker.js') } const tableBuilder = { /** * minimum width in pixels for each column. * @type {number} */ minWidthForColumn: 150, /** * default max number of columns * @type {number} */ ...
/** * 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
if ('serviceWorker' in navigator) { // register service worker navigator.serviceWorker.register('service-worker.js') } const tableBuilder = { /** * minimum width in pixels for each column. * @type {number} */ minWidthForColumn: 150, /** * default max number of columns * @type {number} */ ...
* @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
#!/usr/bin/python import sys, getopt, os import re from operator import itemgetter ## Parse Pelechano datafiles ### def main(argv): 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 spec...
(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
#!/usr/bin/python import sys, getopt, os import re from operator import itemgetter ## Parse Pelechano datafiles ### def main(argv): 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 spec...
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
#!/usr/bin/python import sys, getopt, os import re from operator import itemgetter ## Parse Pelechano datafiles ###
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
#!/usr/bin/python import sys, getopt, os import re from operator import itemgetter ## Parse Pelechano datafiles ### def main(argv):
# 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\tregulator gene name\ttarget feature name\ttarget gene name\tvalue\tstra...
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
use std::io::Error; use std::mem::size_of; use std::os::raw::{c_float, c_int, c_uint, c_void}; use std::ptr::null_mut; use lawrencium::*; mod utils_windows; use utils_windows::*; use crate::common::*; pub struct GLContext { context_ptr: HGLRC, pixel_format_id: i32, _pixel_format_descriptor: PIXELFORMATDE...
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
use std::io::Error; use std::mem::size_of; use std::os::raw::{c_float, c_int, c_uint, c_void}; use std::ptr::null_mut; use lawrencium::*; mod utils_windows; use utils_windows::*; use crate::common::*; pub struct GLContext { context_ptr: HGLRC, pixel_format_id: i32, _pixel_format_descriptor: PIXELFORMATDE...
} } } } 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
use std::io::Error; use std::mem::size_of; use std::os::raw::{c_float, c_int, c_uint, c_void}; use std::ptr::null_mut; use lawrencium::*; mod utils_windows; use utils_windows::*; use crate::common::*; pub struct GLContext { context_ptr: HGLRC, pixel_format_id: i32, _pixel_format_descriptor: PIXELFORMATDE...
(&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
use std::io::Error; use std::mem::size_of; use std::os::raw::{c_float, c_int, c_uint, c_void}; use std::ptr::null_mut; use lawrencium::*; mod utils_windows; use utils_windows::*; use crate::common::*; pub struct GLContext { context_ptr: HGLRC, pixel_format_id: i32, _pixel_format_descriptor: PIXELFORMATDE...
_ => 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
// Application configuration data structures package erconfig import ( "fmt" "regexp" "strings" "time" "github.com/function61/edgerouter/pkg/turbocharger" ) // can be used to fetch the current state of configuration - the apps Edgerouter knows *right now*, // based on all the discovery mechanisms used type Curr...
(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
// Application configuration data structures package erconfig import ( "fmt" "regexp" "strings" "time" "github.com/function61/edgerouter/pkg/turbocharger" ) // can be used to fetch the current state of configuration - the apps Edgerouter knows *right now*, // based on all the discovery mechanisms used type Curr...
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
// Application configuration data structures package erconfig import ( "fmt" "regexp" "strings" "time" "github.com/function61/edgerouter/pkg/turbocharger" ) // can be used to fetch the current state of configuration - the apps Edgerouter knows *right now*, // based on all the discovery mechanisms used type Curr...
return nil } // frontend options builder type frontendOptions struct { pathPrefix string stripPathPrefix bool allowInsecureHTTP bool } func getFrontendOptions(fns []FrontendOpt) frontendOptions { opts := &frontendOptions{ pathPrefix: "/", } for _, fn := range fns { fn(opts) } return *opts } ...
{ if err != nil { return err } }
conditional_block
appconfig.go
// Application configuration data structures package erconfig import ( "fmt" "regexp" "strings" "time" "github.com/function61/edgerouter/pkg/turbocharger" ) // can be used to fetch the current state of configuration - the apps Edgerouter knows *right now*, // based on all the discovery mechanisms used type Curr...
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
'use strict'; const MANIFEST = 'flutter-app-manifest'; const TEMP = 'flutter-temp-cache'; const CACHE_NAME = 'flutter-app-cache'; const RESOURCES = { "assets/AssetManifest.json": "9b877279b82fcd9d9c6f92ca3c999525", "assets/assets/sounds/Index10Length0.wav": "959c53595dba4a30fec8715149f2947a", "assets/assets/sounds/In...
"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
'use strict'; const MANIFEST = 'flutter-app-manifest'; const TEMP = 'flutter-temp-cache'; const CACHE_NAME = 'flutter-app-cache'; const RESOURCES = { "assets/AssetManifest.json": "9b877279b82fcd9d9c6f92ca3c999525", "assets/assets/sounds/Index10Length0.wav": "959c53595dba4a30fec8715149f2947a", "assets/assets/sounds/In...
// Attempt to download the resource online before falling back to // the offline cache. function onlineFirst(event) { return event.respondWith( fetch(event.request).then((response) => { return caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, response.clone()); return resp...
{ 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
'use strict'; const MANIFEST = 'flutter-app-manifest'; const TEMP = 'flutter-temp-cache'; const CACHE_NAME = 'flutter-app-cache'; const RESOURCES = { "assets/AssetManifest.json": "9b877279b82fcd9d9c6f92ca3c999525", "assets/assets/sounds/Index10Length0.wav": "959c53595dba4a30fec8715149f2947a", "assets/assets/sounds/In...
(event) { return event.respondWith( fetch(event.request).then((response) => { return caches.open(CACHE_NAME).then((cache) => { cache.put(event.request, response.clone()); return response; }); }).catch((error) => { return caches.open(CACHE_NAME).then((cache) => { retur...
onlineFirst
identifier_name
flutter_service_worker.js
'use strict'; const MANIFEST = 'flutter-app-manifest'; const TEMP = 'flutter-temp-cache'; const CACHE_NAME = 'flutter-app-cache'; const RESOURCES = { "assets/AssetManifest.json": "9b877279b82fcd9d9c6f92ca3c999525", "assets/assets/sounds/Index10Length0.wav": "959c53595dba4a30fec8715149f2947a", "assets/assets/sounds/In...
}); // Download offline will check the RESOURCES for all files not in the cache // and populate them. async function downloadOffline() { var resources = []; var contentCache = await caches.open(CACHE_NAME); var currentContent = {}; for (var request of await contentCache.keys()) { var key = request.url.sub...
{ downloadOffline(); return; }
conditional_block
facade.rs
// Copyright 2020 The Fuchsia Authors. All rights reserved. // 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_f...
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
// Copyright 2020 The Fuchsia Authors. All rights reserved. // 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_f...
} 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
// Copyright 2020 The Fuchsia Authors. All rights reserved. // 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_f...
() { 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
// Copyright 2020 The Fuchsia Authors. All rights reserved. // 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_f...
/// 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
var gulp = require('gulp'), argv = require('yargs').argv, cache = require('gulp-cache'), concat = require('gulp-concat'), del = require('del'), gulpif = require('gulp-if'), gutil = require('gulp-util') notify = require('gulp-notify'), plumber = require('gulp-plumber'), q = require('q...
(error){ // TODO log error with gutil notify.onError(function (error) { return error.message; }); this.emit('end'); }
onError
identifier_name