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
utils.py
if(isinstance(objs, dict)): stringToReturn += "\n" for key in objs: stringToReturn += currentDepth*" "+key+": "+get_result_as_tree(objs[key], depth, currentDepth+1, key) return stringToReturn if (isinstance(objs, tuple)): return str(objs[0]) + "\n" if(objs i...
connection["verifyssl"] = False
conditional_block
utils.py
=False): #print(jsonpickle.encode(objs)) nestedDict = serializer.loads(jsonpickle.encode(objs)) filteredDict = type(nestedDict)() if(pickle==False): remove_pickling(nestedDict, filteredDict) else: filteredDict = nestedDict print(serializer.dumps(filteredDict,indent=4)) def remov...
def filter_objects_from_simple_keypaths(objs, simpleKeyPaths): # First, we assemble the key paths. # They start out like this: # [accouts.username, accounts.initiator_secret.secret, accounts.status] # and become like this: # {"accounts":{"username":True, "initiator_secret":{"secret":True}, "status"...
"""
random_line_split
assets.py
(self, sid_group): """Retrieve the most recent symbol for a set of sids. Parameters ---------- sid_group : iterable[int] The sids to lookup. The length of this sequence must be less than or equal to SQLITE_MAX_VARIABLE_NUMBER because the sids will be ...
if adjustment not in ADJUSTMENT_STYLES: raise ValueError( 'Invalid adjustment style {!r}. Allowed adjustment styles are ' '{}.'.format(adjustment, list(ADJUSTMENT_STYLES)) ) oc = self.get_ordered_contracts(root_symbol) exchange = self._get_root_sy...
identifier_body
assets.py
', 'sid start end') class AssetFinder(object): """ An AssetFinder is an interface to a database of Asset metadata written by an ``AssetDBWriter``. This class provides methods for looking up assets by unique integer id or by symbol. For historical reasons, we refer to these unique ids as 'sids'. ...
(self): es = sa.select(self.exchanges.c).execute().fetchall() return { name: ExchangeInfo(name, canonical_name, country_code) for name, canonical_name, country_code in es } @lazyval def symbol_ownership_map(self): return build_ownership_map( t...
exchange_info
identifier_name
assets.py
_by_type(self, sids): """ Group a list of sids by asset type. Parameters ---------- sids : list[int] Returns ------- types : dict[str or None -> list[int]] A dict mapping unique asset types to lists of sids drawn from sids. If we ...
raise EquitiesNotFound(sids=misses)
conditional_block
assets.py
etimes', 'sid start end') class AssetFinder(object): """ An AssetFinder is an interface to a database of Asset metadata written by an ``AssetDBWriter``. This class provides methods for looking up assets by unique integer id or by symbol. For historical reasons, we refer to these unique ids as 's...
missing.add(sid) # All requests were cache hits. Return requested sids in order. if not missing: return [hits[sid] for sid in sids] update_hits = hits.update # Look up cache misses by type. type_to_assets = self.group_by_type(missing) # Ha...
# about an asset. raise SidsNotFound(sids=[sid]) hits[sid] = asset except KeyError:
random_line_split
game.rs
f, "Callback<{}>", std::any::type_name::<T>()) } } impl Game { /// Create a new game alongside a handle to thet game. pub fn new() -> (Game, GameHandle) { let (sender, receiver) = mpsc::channel(1024); let world = logic::create_world(logic::WorldKind::WithObjects); let schedule = lo...
{ let (sender, receiver) = oneshot::channel(); (Callback { sender }, receiver) }
identifier_body
game.rs
32 = 60; /// The maximum number of events to buffer per player. const EVENT_BUFFER_SIZE: usize = 1024; pub struct Game { players: BTreeMap<PlayerId, PlayerData>, receiver: mpsc::Receiver<Command>, world: World, executor: logic::Executor, snapshots: SnapshotEncoder, time: u32, } #[derive(Deb...
(&mut self) -> crate::Result<Snapshot>
snapshot
identifier_name
game.rs
32 = 60; /// The maximum number of events to buffer per player. const EVENT_BUFFER_SIZE: usize = 1024; pub struct Game { players: BTreeMap<PlayerId, PlayerData>, receiver: mpsc::Receiver<Command>, world: World, executor: logic::Executor, snapshots: SnapshotEncoder, time: u32, } #[derive(Deb...
#[derive(Debug)] enum Command { Request { request: Request, callback: Callback<Response>, }, RegisterPlayer { callback: Callback<PlayerHandle>, }, DisconnectPlayer(PlayerId), Snapshot { callback: Callback<Snapshot>, }, PerformAction { action: Actio...
pub struct GameHandle { sender: mpsc::Sender<Command>, }
random_line_split
tmsExport_generated.go
), metric.value) if err != nil { log.Entry().WithError(err).Error("Error persisting influx environment.") errCount++ } } if errCount > 0 { log.Entry().Error("failed to persist Influx environment") } } // TmsExportCommand This step allows you to export an MTA file (multi-target application archive) and m...
} log.DeferExitHandler(handler) defer handler() telemetryClient.Initialize(GeneralConfig.NoTelemetry, STEP_NAME) tmsExport(stepConfig, &stepTelemetryData, &influx) stepTelemetryData.ErrorCode = "0" log.Entry().Info("SUCCESS") }, } addTmsExportFlags(createTmsExportCmd, &stepConfig) return cre...
{ splunkClient.Initialize(GeneralConfig.CorrelationID, GeneralConfig.HookConfig.SplunkConfig.ProdCriblEndpoint, GeneralConfig.HookConfig.SplunkConfig.ProdCriblToken, GeneralConfig.HookConfig.SplunkConfig.ProdCriblIndex, GeneralConfig.HookConfig.SplunkConfig.SendLogs) splunkClient.Send(...
conditional_block
tmsExport_generated.go
(path, resourceName string) { measurementContent := []struct { measurement string valType string name string value interface{} }{ {valType: config.InfluxField, measurement: "step_data", name: "tms", value: i.step_data.fields.tms}, } errCount := 0 for _, metric := range measurementConten...
persist
identifier_name
tmsExport_generated.go
var startTime time.Time var influx tmsExportInflux var logCollector *log.CollectorHook var splunkClient *splunk.Splunk telemetryClient := &telemetry.Telemetry{} var createTmsExportCmd = &cobra.Command{ Use: STEP_NAME, Short: "This step allows you to export an MTA file (multi-target application archive) and...
{ var theMetaData = config.StepData{ Metadata: config.StepMetadata{ Name: "tmsExport", Aliases: []config.Alias{}, Description: "This step allows you to export an MTA file (multi-target application archive) and multiple MTA extension descriptors into a TMS (SAP Cloud Transport Management service) ...
identifier_body
tmsExport_generated.go
.name), metric.value) if err != nil { log.Entry().WithError(err).Error("Error persisting influx environment.") errCount++ } } if errCount > 0 { log.Entry().Error("failed to persist Influx environment") } } // TmsExportCommand This step allows you to export an MTA file (multi-target application archive) ...
log.RegisterSecret(stepConfig.TmsServiceKey) if len(GeneralConfig.HookConfig.SentryConfig.Dsn) > 0 { sentryHook := log.NewSentryHook(GeneralConfig.HookConfig.SentryConfig.Dsn, GeneralConfig.CorrelationID) log.RegisterHook(&sentryHook) } if len(GeneralConfig.HookConfig.SplunkConfig.Dsn) > 0 { s...
}
random_line_split
par_granges.rs
- Optional argument to modify the default size ration of the channel that `R::P` is sent on. /// formula is: ((BYTES_INA_GIGABYTE * channel_size_modifier) * threads) / size_of(R::P) /// * `processor`- Something that implements [`RegionProcessor`](RegionProcessor) pub fn new( reads: P...
else { None }; let restricted_ivs = match (bed_intervals, bcf_intervals) { (Some(bed_ivs), Some(bcf_ivs)) => Some(Self::merge_intervals(bed_ivs, bcf_ivs)), (Some(bed_ivs), None) => Some(bed_ivs), (None, Some...
{ Some( Self::bcf_to_intervals(&header, regions_bcf) .expect("Parsed BCF/VCF to intervals"), ) }
conditional_block
par_granges.rs
=> Some(Self::merge_intervals(bed_ivs, bcf_ivs)), (Some(bed_ivs), None) => Some(bed_ivs), (None, Some(bcf_ivs)) => Some(bcf_ivs), (None, None) => None, }; let intervals = if let Some(restricted) = restricted_ivs { ...
{ prop::collection::vec(arb_ivs(max_iv, max_ivs), 0..max_chr) }
identifier_body
par_granges.rs
on::ThreadPoolBuilder::new() .num_threads(threads) .build() .unwrap(); info!("Using {} worker threads.", threads); Self { reads, ref_fasta, regions_bed, regions_bcf, threads, chunksize: chunksize...
lapper.merge_overlaps(); lapper })
random_line_split
par_granges.rs
val: (), }); } Ok(intervals .into_iter() .map(|ivs| { let mut lapper = Lapper::new(ivs); lapper.merge_overlaps(); lapper }) .collect()) } /// Merge two sets of restriction intervals tog...
process_region
identifier_name
medrs.rs
= File::open(filename).expect(format!("no such file: {}", filename).as_str()); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } fn read_file_to_string(filename: &str) -> String { let mut file = match File::open(filename) { Ok(file)...
("action", "query"), ("prop", "extlinks"), ("ellimit", "500"), ("titles", title.as_str()), ]); let result = api .get_query_api_json_all(&params) .expect("query.extlinks failed"); let mut urls: Vec<String> = vec![]; result["query"]["pages"] .as_obje...
random_line_split
medrs.rs
(filename: &str) -> Vec<String> { if filename.is_empty() { return vec![]; } let file = File::open(filename).expect(format!("no such file: {}", filename).as_str()); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } fn read_fil...
lines_from_file
identifier_name
medrs.rs
File::open(filename).expect(format!("no such file: {}", filename).as_str()); let buf = BufReader::new(file); buf.lines() .map(|l| l.expect("Could not parse line")) .collect() } fn read_file_to_string(filename: &str) -> String { let mut file = match File::open(filename) { Ok(file) =...
fn output_sparql_result_items(sparql: &String) { let api = Api::new("https://www.wikidata.org/w/api.php").expect("Can't connect to Wikidata"); let result = api.sparql_query(&sparql).expect("SPARQL query failed"); let varname = result["head"]["vars"][0] .as_str() .expect("Can't find first v...
{ let rep: String = if lines.is_empty() { "".to_string() } else { "wd:".to_string() + &lines.join(" wd:") }; sparql.replace(pattern, &rep) }
identifier_body
views.py
< time.time(): url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=%s" % (self.getAccessToken()) response = requests.get(url) jsapi_ticket = json.loads(response.text)['ticket'] data['jsapi_ticket'] = jsapi_ticket data['expire_tim...
draw.text((110, 230),unicode('昆明,你能为我们','utf-8'),(255,255,255),font=font1) draw.text((90, 290),unicode('带来第一场胜利吗?!','utf-8'),(255,255,255),font=font1) draw.text((130, 230),unicode('莫愁长征无知己,','utf-8'),(255,255,255),font=font1) draw.text((60, 290),unicode('天涯海角永相随!国足必胜!','utf-8'),(255,255,255),font=font2)...
draw.text((110, 290),unicode('心就一天是国足的!','utf-8'),(255,255,255),font=font1) draw.text((50, 230),unicode('赢了一起狂,输了一起扛!','utf-8'),(255,255,255),font=font1) draw.text((180, 290),unicode('国足雄起!','utf-8'),(255,255,255),font=font1)
random_line_split
views.py
.randrange(0, 10)}) def guozuSaveImage(request): # if request.is_ajax(): # img = request.POST.get("img") # openid = request.POST.get("openid") # file = cStringIO.StringIO(urllib.urlopen(img).read()) # im = Image.open(file) # im.thumbnail((100, 100), Image.ANTIALIAS) # im.save("/...
nail((100, 100), Image.ANTIALIAS
conditional_block
views.py
time.time(): url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=%s" % (self.getAccessToken()) response = requests.get(url) jsapi_ticket = json.loads(response.text)['ticket'] data['jsapi_ticket'] = jsapi_ticket data['expire_time'...
def guozuImage(request): ba = Image.open("/Users/dongli/Documents/Outsourcing/project/project/template/guozu/images/logo.png") im = Image.open('/Users/dongli/Documents/Outsourcing/project/project/template/guozu/images/test.png') bg = Image.open('/Users/dongli/Documents/Outsourcing/project/project/template...
return HttpResponse('1')
identifier_body
views.py
= "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s" % (self.appId, self.appSecret) response = requests.get(url) access_token = json.loads(response.text)['access_token'] data['access_token'] = access_token data['expire_time'] = int(...
.filter(open
identifier_name
host_window.py
NavigationToolbar import pylab def _configure_device(): """ Configure and get the USB device running. Returns device class if success and None if failed""" vendor_id = 0x04D8 # These ids are microchip's libusb based device product_id = 0x0204 # ids dev = usb.core.find(idVendor=ven...
info_sizer.Add(self.txt_info_box, 0, wx.ALL, 10) # Add the sizers to main sizer main_sizer.Add(button_sizer, flag=wx.ALIGN_CENTER_VERTICAL) main_sizer.AddSpacer(20) main_sizer.Add(info_sizer, flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND) # Bind events to the button s...
# Add the items to sizers button_sizer.Add(self.start_button, 0, wx.ALL, 10) info_sizer.Add(self.result_box, 0, wx.ALL, 10)
random_line_split
host_window.py
digit1, digit2 = self.dev.read(0x81, 64)[:2] # Save the data as voltage between 0.0 and 5.0 self.data1.append((digit1 + 256*digit2)*5.0/1024) def sample(self): """ Set the sample bit for getting intial DC offset""" self.dev.write(1, 'S') def hold(self): """ Clea...
average = 0.0
conditional_block
host_window.py
NavigationToolbar import pylab def _configure_device(): """ Configure and get the USB device running. Returns device class if success and None if failed""" vendor_id = 0x04D8 # These ids are microchip's libusb based device product_id = 0x0204 # ids dev = usb.core.find(idVendor=ven...
# Add the items to sizers button_sizer.Add(self.start_button, 0, wx.ALL, 10) info_sizer.Add(self.result_box, 0, wx.ALL, 10) info_sizer.Add(self.txt_info_box, 0, wx.ALL, 10) # Add the sizers to main sizer main_sizer.Add(button_sizer, flag=wx.ALIGN_CENTER_VERTICAL...
""" A static box for controlling the start and stop of the device and displaying the final result of the venous flow measurement.""" def __init__(self, parent, ID, label): wx.Panel.__init__(self, parent, ID) # Create two box sizers, one for the button and one for the status # me...
identifier_body
host_window.py
): """ Get the next data from ADC0. For ADC1, use get_dc_offset()""" self.dev.write(1, 'A0') digit1, digit2 = self.dev.read(0x81, 64)[:2] # Save the data as voltage between 0.0 and 5.0 self.data0.append((digit1 + 256*digit2)*5.0/1024) def get_dc_offset(self): ...
on_redraw_timer
identifier_name
plot_materials.py
f.seek(160); x_axis_type = np.fromfile(f, dtype=np.uint8, count=1)[0] print(x_axis_type) f.seek(166); x_start, x_end = np.fromfile(f, dtype=np.float32, count=2) print(x_start) print(x_end) ## Load the n, k data f.seek(174); raw_eps = np.fromfile(f, dtype=np.float32, count=datalengt...
f.seek(151); datalength = np.fromfile(f, dtype=np.uint16, count=1)[0] print(datalength)
random_line_split
plot_materials.py
scout/Au (J, & C,, L, & H,).b', 'scout/Au (JC).b', 'scout/Au (MQ).b', 'scout/Au [micron].b', 'scout/Au.b', 'scout/Au model.b', ] #}}} ## == Si == #{{{ Si_files = [ meep_materials.material_Si_NIR(), meep_materials.material_Si_MIR(), 'other/Si_Dai200...
plt.subplot(3,1,3) print(" Plotting k for '%s' with %d data points" % (plotlabel, len(k))) plt.plot(freq, k, color=color, marker='o', markersize=0, label=plotlabel) plt.xlim(freq_range); plt.grid(True)
conditional_block
plot_materials.py
(filename):#{{{ """ Reads the permittivity function from a given file with SCOUT binary format The SCOUT database of materials is supplied with the SCOUT program and may be freely downloaded from http://www.mtheiss.com/download/scout.zip Different files use different units for the x-axis (179 file...
load_SCOUT_permittivity
identifier_name
plot_materials.py
#}}} ## Functions loading data from different format files ## Note: you must obtain the SOPRA and SCOUT databases from the web, if you want to use them def load_SCOUT_permittivity(filename):#{{{ """ Reads the permittivity function from a given file with SCOUT binary format The SCOUT database of materials is...
complex_eps = mat.eps for polariz in mat.pol: complex_eps += polariz['sigma'] * polariz['omega']**2 / (polariz['omega']**2 - freq**2 - 1j*freq*polariz['gamma']) return complex_eps # + sum(0)
identifier_body
generate_concept_dicts.py
", "http://hl7.org/fhir/sid/ndc": "NDC", "urn:iso:std:iso:11073:10101": "MDC", "doi:10.1016/S0735-1097(99)00126-6": "BARI", "http://www.nlm.nih.gov/research/umls": "UMLS", "http://pubchem.ncbi.nlm.nih.gov": "PUBCHEM_CID", "http://braininfo.rprc.washington.edu/aboutBrainInfo.aspx#NeuroNames": "NE...
response = urllib_request.urlopen(url) return response.read() def _get_text(element): text = "".join(element.itertext()) return text.strip() def get_table_o1(): logger.info("process Table O1") url = "http://dicom.nema.org/medical/dicom/current/output/chtml/part16/chapter_O.html#table_O-1" ro...
rser=ET.XMLParser(encoding="utf-8")) def _download_html(url):
identifier_body
generate_concept_dicts.py
SI", "http://www.nlm.nih.gov/research/umls/rxnorm": "RXNORM", } DOC_LINES = [ f"# Auto-generated by {os.path.basename(__file__)}.\n", "# -*- coding: utf-8 -*-\n", "\n", ] def camel_case(s): leave_alone = ( "mm", "cm", "km", "um", "ms", # 'us'?-doesn't see...
random_line_split
generate_concept_dicts.py
UM", "http://hl7.org/fhir/sid/ndc": "NDC", "urn:iso:std:iso:11073:10101": "MDC", "doi:10.1016/S0735-1097(99)00126-6": "BARI", "http://www.nlm.nih.gov/research/umls": "UMLS", "http://pubchem.ncbi.nlm.nih.gov": "PUBCHEM_CID", "http://braininfo.rprc.washington.edu/aboutBrainInfo.aspx#NeuroNames": "...
_fhir_value_sets(local_dir): ftp_host = "medical.nema.org" if not os.path.exists(local_dir): os.makedirs(local_dir) logger.info("storing files in " + local_dir) logger.info(f'log into FTP server "{ftp_host}"') ftp = ftplib.FTP(ftp_host, timeout=60) ftp.login("anonymous") ftp_path =...
me def download
conditional_block
generate_concept_dicts.py
", "http://hl7.org/fhir/sid/ndc": "NDC", "urn:iso:std:iso:11073:10101": "MDC", "doi:10.1016/S0735-1097(99)00126-6": "BARI", "http://www.nlm.nih.gov/research/umls": "UMLS", "http://pubchem.ncbi.nlm.nih.gov": "PUBCHEM_CID", "http://braininfo.rprc.washington.edu/aboutBrainInfo.aspx#NeuroNames": "NE...
le D1") url = "http://dicom.nema.org/medical/dicom/current/output/chtml/part16/chapter_D.html#table_D-1" root = _parse_html(_download_html(url)) namespaces = {"w3": root.tag.split("}")[0].strip("{")} body = root.find("w3:body", namespaces=namespaces) table = body.findall(".//w3:tbody", namespaces=na...
"process Tab
identifier_name
lobby.go
{ log.Panic(err) } } /* Game table in DB will need Host and Port stored */ func newSession(g Game, sessId int, host *HostUser) (*Session, error) { session := Session{ sessionId: sessId, game: g, LobbyHost: host, userMap: make(map[string]*AnonUser), PlayerMap: make([]User, 0, g.MaxUsers() + 1), //Play...
(uId int, user string) (*HostUser, error) { hostUser := HostUser{ userId: uId, username: user, Send: make(chan interface{}), Receive: make(chan interface{}), } return &hostUser, nil } func newAnonUser(nick string) *AnonUser { anon := AnonUser{ Nickname: nick, Ready: false, Send: make(chan interface{...
newHostUser
identifier_name
lobby.go
{ log.Panic(err) } } /* Game table in DB will need Host and Port stored */ func newSession(g Game, sessId int, host *HostUser) (*Session, error) { session := Session{ sessionId: sessId, game: g, LobbyHost: host, userMap: make(map[string]*AnonUser), PlayerMap: make([]User, 0, g.MaxUsers() + 1), //Play...
else { user := s.PlayerMap[gMsg.Player].(AnonUser) user.Send <- gMsg } case "msgall": s.LobbyHost.Send <- gMsg } } } /* Main goroutine for processing lobby commands */ func (s Session) dataHandler() { for { select { case data := <-s.Data: switch jsonType := data.(type) { case SetRead...
{ user := s.PlayerMap[gMsg.Player].(HostUser) user.Send <- gMsg }
conditional_block
lobby.go
("removePlayer: player does not match retrieved") //} //delete(s.PlayerMap, index) s.removePlayer(index) delete(s.userMap, id) var msg Command if reason == "" { msg.Cmd = C_Leave } else { msg.Cmd = C_Kick msg.Data = reason } u.Send <- msg s.emitAnonUserData() return nil } /* Removes a player from the...
random_line_split
lobby.go
{ log.Panic(err) } } /* Game table in DB will need Host and Port stored */ func newSession(g Game, sessId int, host *HostUser) (*Session, error) { session := Session{ sessionId: sessId, game: g, LobbyHost: host, userMap: make(map[string]*AnonUser), PlayerMap: make([]User, 0, g.MaxUsers() + 1), //Play...
func (s Session) sendTimeout() { time.Sleep(10 * time.Second) s.timeout <- true } func (s Session) requestTimeout() { s.timeout = make(chan bool, 1) var gs GameStart select { case t := <- s.timeout: if t { //server timed out gs = GameStart{ Response: false, Feedback: "Server was unable to host."...
{ addr := s.game.host + ":" + s.game.port err := s.connectSession(addr) if err != nil { //return nil, err log.Print(err) } request := make(map[string]interface{}) request["event"] = "new" request["players"] = s.CurrentUserCount() request["maxplayers"] = s.game.MaxUsers() jsonMsg, err := json.Marshal(reques...
identifier_body
session.go
nil { s.handler.HandleSessionError(err) return // go home handler, you're drunk! } } if err := s.respondOK(strings.Join(helloParts, " ")); err != nil { s.handler.HandleSessionError(err) return // communication problem, most likely? } for { if keepGoing := s.serveOne(); !keepGoing { return } } }...
if err := s.handler.AuthenticatePASS(s.username, args[0]); err != nil { return err } return s.signIn() } // handleQUIT is a callback for the client terminating the session. It will do // slightly different things depending on the current state of the transaction. // RFC 1939, pages 5 (in authorization state) and...
{ return NewReportableError("please provide username first") }
conditional_block
session.go
const ( stateAuthorization = iota stateTransaction stateUpdate stateTerminateConnection ) type operationHandler func(s *session, args []string) error var ( operationHandlers = map[string]operationHandler{ "APOP": (*session).handleAPOP, "CAPA": (*session).handleCAPA, "DELE": (*session).handleDELE, "LIST":...
"time" )
random_line_split
session.go
nil { s.handler.HandleSessionError(err) return // go home handler, you're drunk! } } if err := s.respondOK(strings.Join(helloParts, " ")); err != nil { s.handler.HandleSessionError(err) return // communication problem, most likely? } for { if keepGoing := s.serveOne(); !keepGoing { return } } }...
(args []string) (err error) { return s.withMessageDo(args[0], func(msgId uint64) error { if err := s.respondOK("%d octets", s.msgSizes[msgId]); err != nil { return err } readCloser, err := s.handler.GetMessageReader(msgId) if err != nil { return err } defer s.closeOrReport(readCloser) dotWriter := ...
handleRETR
identifier_name
session.go
nil { s.handler.HandleSessionError(err) return // go home handler, you're drunk! } } if err := s.respondOK(strings.Join(helloParts, " ")); err != nil { s.handler.HandleSessionError(err) return // communication problem, most likely? } for { if keepGoing := s.serveOne(); !keepGoing { return } } }...
return err } } return nil }) } func printTopLine(line []byte, readErr error, writer io.Writer) error { if readErr == io.EOF || readErr == nil { if err := writeWithError(writer, line); err != nil { return err } } if readErr != nil { return readErr } return writeWithError(writer, []byte{'\n'})...
{ return s.withMessageDo(args[0], func(msgId uint64) error { noLines, err := strconv.ParseUint(args[1], 10, 64) if err != nil { return errInvalidSyntax } if err := s.writer.PrintfLine("+OK"); err != nil { return err } readCloser, err := s.handler.GetMessageReader(msgId) if err != nil { return er...
identifier_body
game.py
(BaseModel): """ Class representing a Game. A game only contains basic information about the game and the scores. """ id = PrimaryKeyField() game_acbid = IntegerField(unique=True, index=True) team_home_id = ForeignKeyField(Team, related_name='games_home', index=True, null=True) team_awa...
Game
identifier_name
game.py
IntegerField(null=True) score_home_fourth = IntegerField(null=True) score_away_fourth = IntegerField(null=True) score_home_extra = IntegerField(null=True) score_away_extra = IntegerField(null=True) venue = CharField(max_length=255, null=True) attendance = IntegerField(null=True) kickoff_tim...
score_home_attribute = 'score_home_first' score_away_attribute = 'score_away_first'
conditional_block
game.py
games_away', index=True, null=True) season = IntegerField(null=False) competition_phase = CharField(max_length=255, null=True) round_phase = CharField(max_length=255, null=True) journey = IntegerField(null=False) score_home = IntegerField(null=True) score_away = IntegerField(null=True) score...
@staticmethod def create_instance(raw_game, game_acbid, season, competition_phase,round_phase=None): """ Extract all the information regarding the game such as the date, attendance, venue, score per quarter or teams. Therefore, we need first to extract and insert the teams in the data...
sanity_check_game_copa(season.GAMES_COPA_PATH, logging_level)
identifier_body
game.py
=True) @staticmethod def save_games(season, logging_level=logging.INFO): """ Method for saving locally the games of a season. :param season: int :param logging_level: logging object :return: """ logger.info('Starting the download of games...') i...
elif i == 6: score_home_attribute = 'score_home_extra' score_away_attribute = 'score_away_extra' quarter_data = info_game_data('.estnaranja')('td').eq(i).text()
random_line_split
utils.py
if val: if attr.endswith('date'): display_value = repr(val.value) else: display_value = str(val.value) attr_confidence = val.confidence else: display_value = '...
val = getattr(obj, attr).get_value() except AttributeError: val = None
random_line_split
utils.py
_name) return class_ def get_osm_by_id(osm_id): osm_feature = None cursor = connection.cursor() query = ''' SELECT ST_X(ST_Centroid(geometry)), ST_Y(ST_Centroid(geometry)), * FROM osm_data WHERE id = {osm_id} '''.format(osm_id=osm_id) cur...
objects[index] = name
conditional_block
utils.py
()] if any(lst_values): lst_confidence = lst_values[0].confidence else: lst_confidence = '1' cleaned_lst = [] for inst in lst_values: cleaned_lst.append({ 'id': inst.id, ...
(change_type): for field in getattr(differ, change_type)(): if field not in skip_fields: if change_type == 'changed': yield { 'field_name': field, 'to': differ.current_dict[field], ...
makeIt
identifier_name
utils.py
osm_data WHERE id = {osm_id} '''.format(osm_id=osm_id) cursor.execute(query) columns = [c[0] for c in cursor.description] results_tuple = namedtuple('OSMFeature', columns) row = cursor.fetchone() if row: osm_feature = results_tuple(*row) return osm_feature def get_hier...
d = cl.rfind('.') classname = cl[d+1:len(cl)] m = __import__(cl[0:d], globals(), locals(), [classname]) return getattr(m, classname)
identifier_body
listing-ctrl.js
.Object.extend("listing"); var userquery = new Parse.Query(Parse.User); var query = new Parse.Query(Listing); var listing = $stateParams.listingId; console.log(listing); query.get(listing, { success: function(listing) { console.log(listing); $scope.listing = listing; $scope.listing.listingid = listin...
(dateString) { var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } r...
calculateAge
identifier_name
listing-ctrl.js
"); var userquery = new Parse.Query(Parse.User); var query = new Parse.Query(Listing); var listing = $stateParams.listingId; console.log(listing); query.get(listing, { success: function(listing) { console.log(listing); $scope.listing = listing; $scope.listing.listingid = listing.id; $scope.list...
{ user.albumid = user.profileData.albums.data[i].id; }
conditional_block
listing-ctrl.js
v: '3.17', libraries: 'places' }); }) .controller("ListingCtrl", function($scope, $rootScope, $state, $stateParams, $modal, fbookFactory, FacebookAngularPatch, uiGmapGoogleMapApi, markersFactory) { $scope.pictureFiles = []; $scope.picUrls = []; var Listing = Parse.Object.extend("listing"); va...
.config(function(uiGmapGoogleMapApiProvider) { console.log('config maps'); uiGmapGoogleMapApiProvider.configure({ key: 'AIzaSyCCMEJsPzyGW-oLOShTOJw_Pe9Qv2YMAZo',
random_line_split
listing-ctrl.js
.Object.extend("listing"); var userquery = new Parse.Query(Parse.User); var query = new Parse.Query(Listing); var listing = $stateParams.listingId; console.log(listing); query.get(listing, { success: function(listing) { console.log(listing); $scope.listing = listing; $scope.listing.listingid = listin...
// FACEBOOK PROFILE UPDATE updateProf = function () { FB.apiAngular('me?fields=id,name,first_name,last_name,email,birthday,education,gender,work,albums') .then(function (profileData) { user.profileData = profileData; user.age = calculateAge(profileData.birthday); }) ...
{ var today = new Date(); var birthDate = new Date(dateString); var age = today.getFullYear() - birthDate.getFullYear(); var m = today.getMonth() - birthDate.getMonth(); if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) { age--; } return age; ...
identifier_body
main.rs
will not be /// carried over to the output file because there is not a one-for-one feature correspondence between the /// two files due to the joins and splits of stream segments. Instead the output attribute table will /// only contain a feature ID (FID) entry. /// /// > Note: this tool should be used to pre-process...
working directory contained in the WhiteboxTools settings.json file. Example Usage: >> .*EXE_NAME run --routes=footpath.shp --dem=DEM.tif -o=assessedRoutes.shp --length=50.0 --dist=200 Note: Use of this tool requires a valid license. To obtain a license, contact Whitebox Geospatial Inc. (support@w...
Input/output file names can be fully qualified, or can rely on the
random_line_split
main.rs
not be /// carried over to the output file because there is not a one-for-one feature correspondence between the /// two files due to the joins and splits of stream segments. Instead the output attribute table will /// only contain a feature ID (FID) entry. /// /// > Note: this tool should be used to pre-process vect...
else if flag_val == "-outlet" { outlet_file = if keyval { vec[1].to_string() } else { args[i + 1].to_string() }; } else if flag_val == "-o" || flag_val == "-output" { output_file = if keyval { vec[1].to_string() ...
{ input_file = if keyval { vec[1].to_string() } else { args[i + 1].to_string() }; }
conditional_block
main.rs
not be /// carried over to the output file because there is not a one-for-one feature correspondence between the /// two files due to the joins and splits of stream segments. Instead the output attribute table will /// only contain a feature ID (FID) entry. /// /// > Note: this tool should be used to pre-process vect...
fn get_tool_name() -> String { String::from("CorrectStreamVectorDirection") // This should be camel case and is a reference to the tool name. } fn run(args: &Vec<String>) -> Result<(), std::io::Error> { let tool_name = get_tool_name(); let sep: String = path::MAIN_SEPARATOR.to_string(); // Read in ...
{ const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION"); println!( "correct_stream_vector_direction v{} by Dr. John B. Lindsay (c) 2023.", VERSION.unwrap_or("Unknown version") ); }
identifier_body
main.rs
mut old_progress: usize = 1; let start = Instant::now(); if !input_file.contains(path::MAIN_SEPARATOR) && !input_file.contains("/") { input_file = format!("{}{}", working_directory, input_file); } if !outlet_file.contains(path::MAIN_SEPARATOR) && !outlet_file.contains("/") { outlet_fi...
get_first_node
identifier_name
spmc.rs
Ptr::new(single_node.as_ptr()), incin, }), }; (sender, receiver) } /// The [`Sender`] handle of a SPMC channel. Created by [`create`] or /// [`with_incin`] function. pub struct
<T> { back: NonNull<Node<T>>, } impl<T> Sender<T> { /// Sends a message and if the receiver disconnected, an error is returned. pub fn send(&mut self, message: T) -> Result<(), NoRecv<T>> { // First we allocate the node for our message. let alloc = OwnedAlloc::new(Node { message...
Sender
identifier_name
spmc.rs
Ptr::new(single_node.as_ptr()), incin, }), }; (sender, receiver) } /// The [`Sender`] handle of a SPMC channel. Created by [`create`] or /// [`with_incin`] function. pub struct Sender<T> { back: NonNull<Node<T>>, } impl<T> Sender<T> { /// Sends a message and if the receiver discon...
} impl<T> Drop for Sender<T> { fn drop(&mut self) { // This dereferral is safe because the queue always have at least one // node. This single node is only dropped when the last side to // disconnect drops. let res = unsafe { // Let's try to mark next's bit so that rece...
{ // Safe because we always have at least one node, which is only dropped // in the last side to disconnect's drop. let back = unsafe { self.back.as_ref() }; back.next.load(Relaxed).is_null() }
identifier_body
spmc.rs
Ptr::new(single_node.as_ptr()), incin, }), }; (sender, receiver) } /// The [`Sender`] handle of a SPMC channel. Created by [`create`] or /// [`with_incin`] function. pub struct Sender<T> { back: NonNull<Node<T>>, } impl<T> Sender<T> { /// Sends a message and if the receiver discon...
// Safe to by-pass the check since we only store non-null // pointers on the front. Ok(bypass_null(next)) } } } impl<T> Clone for Receiver<T> { fn clone(&self) -> Self { Self { inner: self.inner.clone() } } } impl<T> fmt::Debug for Receiver<T> { fn ...
{ let ptr = expected.as_ptr(); // We are not oblied to succeed. This is just cleanup and some other // thread might do it. let next = match self .inner .front .compare_exchange(ptr, next, Relaxed, Relaxed) { ...
conditional_block
spmc.rs
AtomicPtr::new(single_node.as_ptr()), incin, }), }; (sender, receiver) } /// The [`Sender`] handle of a SPMC channel. Created by [`create`] or /// [`with_incin`] function. pub struct Sender<T> { back: NonNull<Node<T>>, } impl<T> Sender<T> { /// Sends a message and if the receiver...
// the front. let mut front_nnptr = unsafe { // First we load pointer stored in the front. bypass_null(self.inner.front.load(Relaxed)) }; loop { // Let's remove the node logically first. Safe to derefer this // pointer because we paused th...
// suffers from it, yeah. let pause = self.inner.incin.inner.pause(); // Bypassing null check is safe because we never store null in
random_line_split
threeHandle.js
this.width = 500 this.height = 500 this.scene = null this.light = null this.camera = null this.controls = null this.renderer = null this.fov = 60 this.mixer = null this.Stats = null this.manager = null this.crossOrigin = 'anonymous' this.requestHeader = {} this...
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls' class ThreeHandle { constructor() {
random_line_split
threeHandle.js
立方体 // v6----- v5 // /| /| // v1------v0| // | | | | // | |v7---| |v4 // | / | / // v2------v3 // v0 - v1 - v2 - v3 - v0 - v5 - v4 - v4 - v0 - v5 - v6 - v1 - v2 - v7 - v4 - v5 - v6 - v7 async drawCubeByLines( { width, height, depth } ) { const objects = [] const geometry...
' ) }
identifier_name
threeHandle.js
.camera = await this.setCamera() this.renderer = await this.setRenderer() this.renderer.setClearColor( 'rgb(92,92,92)', 1.0 ) this.controls = await this.setControls() container.appendChild( this.renderer.domElement ) await this.setStats( container ) await this.setClock() window.addEventL...
const loader = new THREE.TextureLoader() const texturePlante = loader.load( url ) const material = new THREE.MeshPhongMaterial( { map : texturePlante } ) return material } loadObj( baseUrl, objUrl, materials, fn ) { const loader = new OBJLoader( this.manager ) loader.setRequestHeade...
.manager ) loader.setCrossOrigin( this.crossOrigin ) loader.setRequestHeader( this.requestHeader ) const that = this loader.load( baseUrl, ( object ) => { fn && fn( object ) }, that.onProgress, that.onError ) } // fbx模型加载贴图 loadImage( url ) {
identifier_body
demo.py
translate is effectively canceled out, # leaving a rotation and then a translation. # Translate inverse(Translate) Rotate Translate # # Translate inverse(Translate) = Identity. i.e. 5 * 1/5 = 1, # so we really just need to do a rotation first, and then a translation, # but this can be counterintuitive at first becaus...
paddle2.rotation -= 0.1 TARGET_FRAMERATE = 60 # fps # to try to standardize on 60 fps, compare times between frames time_at_beginning_of_previous_frame = glfw.get_time() # Loop until the user closes the window while not glfw.window_should_close(window): # poll the time to try to get a constant framerate...
global paddle1, paddle2 if glfw.get_key(window, glfw.KEY_S) == glfw.PRESS: paddle1.input_offset_y -= 10.0 if glfw.get_key(window, glfw.KEY_W) == glfw.PRESS: paddle1.input_offset_y += 10.0 if glfw.get_key(window, glfw.KEY_K) == glfw.PRESS: paddle2.input_offset_y -= 10.0 if glfw.g...
identifier_body
demo.py
translate is effectively canceled out, # leaving a rotation and then a translation. # Translate inverse(Translate) Rotate Translate # # Translate inverse(Translate) = Identity. i.e. 5 * 1/5 = 1, # so we really just need to do a rotation first, and then a translation, # but this can be counterintuitive at first becaus...
Vertex(x= 10.0, y=30.0), Vertex(x=-10.0, y=30.0)], r=0.578123, g=0.0, b=1.0, initial_position=Vertex(-90.0,0.0)) paddle2 = Paddle(vertices=[Vertex(x=-10.0, y=-30.0), Vert...
random_line_split
demo.py
translate is effectively canceled out, # leaving a rotation and then a translation. # Translate inverse(Translate) Rotate Translate # # Translate inverse(Translate) = Identity. i.e. 5 * 1/5 = 1, # so we really just need to do a rotation first, and then a translation, # but this can be counterintuitive at first becaus...
(self): return f"Vertex(x={repr(self.x)},y={repr(self.y)})" def translate(self, tx, ty): return Vertex(x=self.x + tx, y=self.y + ty) def scale(self, scale_x, scale_y): return Vertex(x=self.x * scale_x, y=self.y * scale_y) def rotate(self,angle_in_radians): return Vertex(x=...
__repr__
identifier_name
demo.py
translate is effectively canceled out, # leaving a rotation and then a translation. # Translate inverse(Translate) Rotate Translate # # Translate inverse(Translate) = Identity. i.e. 5 * 1/5 = 1, # so we really just need to do a rotation first, and then a translation, # but this can be counterintuitive at first becaus...
global paddle_1_rotation, paddle_2_rotation if glfw.get_key(window, glfw.KEY_A) == glfw.PRESS: paddle1.rotation += 0.1 if glfw.get_key(window, glfw.KEY_D) == glfw.PRESS: paddle1.rotation -= 0.1 if glfw.get_key(window, glfw.KEY_J) == glfw.PRESS: paddle2.rotation += 0.1 if g...
paddle2.input_offset_y += 10.0
conditional_block
workplace_preparation.py
images') if path.exists(path_to_images) and path.isdir(path_to_images): shutil.rmtree(path_to_images) makedirs(path_to_images) # split the given video into images subprocess.run(['ffmpeg', '-i', temp_video, '-r', str(number_of_images / video_duration), '-f', 'image2', path.j...
qz = float(columns[3]) rotation_matrix = quaternion_to_rotation_matrix(qw, qx, qy, qz) tx = float(columns[5]) ty = float(columns[7]) tz = float(columns[6]) translation_vector = np.array([tx, ty, tz]) return [rotation_matrix, translation...
""" The function return the absolut R & T for the first image in temp model :param image_src: path to image file (colmap output) :return R&T: R = list[0], T list[1] or None if image1 not exists """ # read images file with open(image_src, 'r') as file: lines = file.readlines()[4::2] ...
identifier_body
workplace_preparation.py
.rmtree(path_to_temp_model) number_of_temp_images = 0 path_to_images = path.join(temp_dir_path, 'images') # take only part of the images for the temp model while number_of_temp_images < number_of_images_in_temp_model: try: number_of_temp_images = len([name for name in listdir(path_...
rotation = rel_rotation @ np.linalg.inv(prev_rotation.T) translation = rel_translation + prev_translation
conditional_block
workplace_preparation.py
2 * (q2 * q3 - q0 * q1) # Third row of the rotation matrix r20 = 2 * (q1 * q3 - q0 * q2) r21 = 2 * (q2 * q3 + q0 * q1) r22 = 2 * (q0 * q0 + q3 * q3) - 1 # 3x3 rotation matrix rot_matrix = np.array([[r00, r01, r02], [r10, r11, r12], [r20, r2...
clear_workspace
identifier_name
workplace_preparation.py
'images') if path.exists(path_to_images) and path.isdir(path_to_images): shutil.rmtree(path_to_images) makedirs(path_to_images) # split the given video into images subprocess.run(['ffmpeg', '-i', temp_video, '-r', str(number_of_images / video_duration), '-f', 'image2', path...
""" # create temp images folder path_to_temp_model = path.join(temp_dir_path, 'temp_model') path_to_temp_images = path.join(path_to_temp_model, 'temp_images') # remove old temporary folder if exists if path.exists(path_to_temp_model) and path.isdir(path_to_temp_model): shutil.rmtree(pa...
""" The function prepares the images for our model based on a given video :param temp_dir_path: video in h264 format :return number_of_images: path to temporary model folder
random_line_split
common.go
errors.New("cannot set invalid user agent") errHTTPClientInvalid = errors.New("custom http client cannot be nil") zeroValueUnix = time.Unix(0, 0) // ErrTypeAssertFailure defines an error when type assertion fails ErrTypeAssertFailure = errors.New("type assert failure") ) // MatchesEmailPattern ensures that...
case "eth": return regexp.MatchString("^0x[a-km-z0-9]{40}$", address) default: return false, fmt.Errorf("%w %s", errInvalidCryptoCurrency, crypto) } } // YesOrNo returns a boolean variable to check if input is "y" or "yes" func YesOrNo(input string) bool { if strings.EqualFold(input, "y") || strings.EqualFold(...
switch strings.ToLower(crypto) { case "btc": return regexp.MatchString("^(bc1|[13])[a-zA-HJ-NP-Z0-9]{25,90}$", address) case "ltc": return regexp.MatchString("^[L3M][a-km-zA-HJ-NP-Z1-9]{25,34}$", address)
random_line_split
common.go
.New("cannot set invalid user agent") errHTTPClientInvalid = errors.New("custom http client cannot be nil") zeroValueUnix = time.Unix(0, 0) // ErrTypeAssertFailure defines an error when type assertion fails ErrTypeAssertFailure = errors.New("type assert failure") ) // MatchesEmailPattern ensures that the st...
// SetHTTPClient sets a custom HTTP client. func SetHTTPClient(client *http.Client) error { if client == nil { return errHTTPClientInvalid } m.Lock() _HTTPClient = client m.Unlock() return nil } // NewHTTPClientWithTimeout initialises a new HTTP client and its underlying // transport IdleConnTimeout with the...
{ if agent == "" { return errUserAgentInvalid } m.Lock() _HTTPUserAgent = agent m.Unlock() return nil }
identifier_body
common.go
aystack []string, needle string) bool { for x := range haystack { if strings.EqualFold(haystack[x], needle) { return true } } return false } // StringDataContainsInsensitive checks the substring array with an input and returns // a bool irrespective of lower or upper case strings func StringDataContainsInsen...
AppendError
identifier_name
common.go
t} return h } // StringSliceDifference concatenates slices together based on its index and // returns an individual string array func StringSliceDifference(slice1, slice2 []string) []string { var diff []string for i := 0; i < 2; i++ { for _, s1 := range slice1 { found := false for _, s2 := range slice2 { ...
{ result = append(result, s[left:x]) left = x }
conditional_block
grafananet.go
GrafanaNetConfig: could not read schemasFile %q: %s", schemasFile, err.Error()) } if aggregationFile != "" { _, err = conf.ReadAggregations(aggregationFile) if err != nil { return GrafanaNetConfig{}, fmt.Errorf("NewGrafanaNetConfig: could not read aggregationFile %q: %s", aggregationFile, err.Error()) } } ...
else { r.dispatch = dispatchNonBlocking } r.wg.Add(cfg.Concurrency) for i := 0; i < cfg.Concurrency; i++ { r.in[i] = make(chan []byte, cfg.BufSize/cfg.Concurrency) go r.run(r.in[i]) } r.config.Store(baseConfig{matcher, make([]*dest.Destination, 0)}) // start off with a transport the same as Go's DefaultT...
{ r.dispatch = dispatchBlocking }
conditional_block
grafananet.go
er{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, DualStack: true, }).DialContext, MaxIdleConns: cfg.Concurrency, MaxIdleConnsPerHost: cfg.Concurrency, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, ExpectContinueTimeout: 1 * time.Second, }...
} else { // if it's neither of the above, let's log it, but make it look not too scary log.Infof("GrafanaNet %s resulted in code %s (should be harmless)", path, resp.Status)
random_line_split
grafananet.go
if err != nil { return GrafanaNetConfig{}, fmt.Errorf("NewGrafanaNetConfig: could not read aggregationFile %q: %s", aggregationFile, err.Error()) } } return GrafanaNetConfig{ Addr: addr, ApiKey: apiKey, SchemasFile: schemasFile, AggregationFile: aggregationFile, BufSize: ...
{ if len(metrics) == 0 { return metrics } mda := schema.MetricDataArray(metrics) data, err := msg.CreateMsg(mda, 0, msg.FormatMetricDataArrayMsgp) if err != nil { panic(err) } route.numOut.Inc(int64(len(metrics))) buffer.Reset() snappyBody := snappy.NewWriter(buffer) snappyBody.Write(data) snappyBody.C...
identifier_body
grafananet.go
GrafanaNetConfig: could not read schemasFile %q: %s", schemasFile, err.Error()) } if aggregationFile != "" { _, err = conf.ReadAggregations(aggregationFile) if err != nil { return GrafanaNetConfig{}, fmt.Errorf("NewGrafanaNetConfig: could not read aggregationFile %q: %s", aggregationFile, err.Error()) } } ...
(metrics []*schema.MetricData, buffer *bytes.Buffer) []*schema.MetricData { if len(metrics) == 0 { return metrics } mda := schema.MetricDataArray(metrics) data, err := msg.CreateMsg(mda, 0, msg.FormatMetricDataArrayMsgp) if err != nil { panic(err) } route.numOut.Inc(int64(len(metrics))) buffer.Reset() sn...
retryFlush
identifier_name
process.go
return allResults[0], nil } // GetProcesses lists all processes given some filter criteria. func (context Context) GetProcesses( filters F, limit int, cursor string, sortBy string, order string, ) (result []types.Process, cm types.CollectionMetadata, err error) { c := context.Session.DB(context.DBName).C("pr...
{ err = ErrNotFound return }
conditional_block
process.go
nextCursor := "" if limit > 0 && len(allResults) == limit { lastResult := allResults[len(allResults)-1] nextCursor = lastResult.ID.Hex() if sortBy != "" { var encoded string var b []byte switch sortBy { case "id": b = []byte(lastResult.ID) case "process-id": b = make([]byte, 4) binar...
{ if processType != types.ProcController && processType != types.ProcScheduler && processType != types.ProcWorker { panic("invalid processType") } var hostID string hostID, err = os.Hostname() if err != nil { err = errors.Wrap(err, "get hostname from os failed") return } var hostAddress string hostAddr...
identifier_body
process.go
", "type", "resource", "status": setDefault(&query, k, bson.M{}) query[k].(bson.M)["$eq"] = v.(string) default: err = errors.Wrap(ErrBadInput, "invalid value of argument filters") return } } // We count the result size given the filters. This is before pagination. var resultSize int resultSize, err...
// If a cursor was specified then we have to do a range query. if cursor != "" { comparer := "$gt" if order == "desc" { comparer = "$lt" } // If there is no sorting then the cursor only points to the _id field. if sortBy != "" && sortBy != "id" { splits := strings.Split(cursor, "-") cursor = split...
random_line_split
process.go
( filters F, limit int, cursor string, sortBy string, order string, ) (result []types.Process, cm types.CollectionMetadata, err error) { c := context.Session.DB(context.DBName).C("processes") // Validate the parameters. if sortBy != "" && sortBy != "id" && sortBy != "process-id" && sortBy != "host-id" &...
GetProcesses
identifier_name
intcode.rs
Pos = 0, Imm = 1, } impl TryFrom<isize> for AddrMode { type Error = &'static str; fn try_from(num: isize) -> Result<Self, Self::Error> { match num { 0 => Ok(Self::Pos), 1 => Ok(Self::Imm), _ => Err("invalid address mode value"), } } } #[derive(Debu...
/// `mem` is the initial machine memory state, it is modified during the run /// /// Will panic if it encounters an unknown opcode pub fn interpret(mut mem: &mut [isize], mut input: impl Input, mut output: impl Output) -> isize { let mut ip: usize = 0; loop { match step(&mut mem, ip, &mut input, &mut ou...
random_line_split
intcode.rs
} #[derive(Debug, PartialEq)] enum AddrMode { Pos = 0, Imm = 1, } impl TryFrom<isize> for AddrMode { type Error = &'static str; fn try_from(num: isize) -> Result<Self, Self::Error> { match num { 0 => Ok(Self::Pos), 1 => Ok(Self::Imm), _ => Err("invalid add...
{ match num { 1 => Ok(Self::Add), 2 => Ok(Self::Multiply), 3 => Ok(Self::ReadIn), 4 => Ok(Self::WriteOut), 5 => Ok(Self::JmpIfTrue), 6 => Ok(Self::JmpIfFalse), 7 => Ok(Self::LessThan), 8 => Ok(Self::Equals), ...
identifier_body
intcode.rs
(num: isize) -> Result<Self, Self::Error> { match num { 1 => Ok(Self::Add), 2 => Ok(Self::Multiply), 3 => Ok(Self::ReadIn), 4 => Ok(Self::WriteOut), 5 => Ok(Self::JmpIfTrue), 6 => Ok(Self::JmpIfFalse), 7 => Ok(Self::LessThan), ...
try_from
identifier_name
main.go
[:0] } continue } requestChan <- js tmpbyte = tmpbyte[:0] } } } func serverStart() { eventLoop() } func eventLoop() { for { js := <-requestChan if js.Method == "LoginQq" { LoginQQ, _ = js.Params.getInt64("loginqq") logger.Printf(">>> %d\n", LoginQQ) continue } subtype, _ := js...
oupMemberList { if v, ok := groups.Load(nm.GroupNum); ok { g := v.(Group) if flag { g.Members = GetGroupMembersFromDB(g.ID, g.GroupNum) flag = false } if g.Members == nil { g.Members = new(sync.Map) } if _, ok := g.Members.Load(nm.QQNum); !ok { g.Members.Store(nm.QQNum, nm) trans...
identifier_body
main.go
return } s := strings.SplitN(strings.TrimSpace(cmd), ":", 2) if len(s) == 2 { groupNum, err := strconv.ParseInt(strings.TrimSpace(s[0]), 10, 64) if err != nil { fmt.Println(err) return } if g, ok := groups.Load(groupNum); ok { sendGroupMessage(g.(Group).GroupNum, s[1]) } else { fmt.Println(...
{ leaveGroup(groupNum) getGroupList() }
conditional_block
main.go
0] continue } tmpbyte = append(tmpbyte, b...) } else { logger.Printf("%s, %s\n", err.Error(), string(b)) tmpbyte = tmpbyte[:0] } continue } requestChan <- js tmpbyte = tmpbyte[:0] } } } func serverStart() { eventLoop() } func eventLoop() { for { js := <-requestCha...
continue }
random_line_split
main.go
(cmd string) { if cmd == "exit" { close(closeSignChan) return } else if cmd == "init" { getLoginQQ() getGroupList() return } else if strings.HasPrefix(cmd, "random:") { var i int32 = 0 var target = rand.Int31n(300) groups.Range(func(key, value interface{}) bool { if i == target { sendGroupMess...
cmd
identifier_name
main.rs
pub mod shader; pub mod text; pub mod texture; // needed for font atlas but needed things can be ported out pub mod timer; pub mod util; pub use display::Display; pub use input::Handler; pub use loader::Loader; pub use render::{RenderMgr, }; pub use shader::Shader; pub use timer::Timer; fn main() { // Test code for...
fn cpu_name() -> String { // use cupid; let info = cupid::master(); match info { Some(x) => { match x.brand_string() { Some(x) => { ["CPU: ".to_owned(), x.to_owned()].join("") } _ => { "Could not get CPU Name".to_owned() } } } _ => { "Could not get CPU Name".to_owned() } ...
{ let ram_used = get_ram_used(system); [cpu.to_owned(), ram.to_owned(), ram_used].join("\n") }
identifier_body
main.rs
) .unwrap(); let windowed_context = unsafe { windowed_context.make_current().unwrap() }; // Set up OpenGL unsafe { load_with(|symbol| windowed_context.context().get_proc_address(symbol) as *const _); ClearColor(0.0, 1.0, 0.0, 1.0); } let mut render_mgr = RenderMgr::new(); let mut mgr = ren...
{ continue; }
conditional_block
main.rs
let gl_profile = glutin::GlProfile::Core; // Create a window let el = EventLoop::new(); let wb = glutin::window::WindowBuilder::new() .with_title("RaumEn SysInfo") .with_inner_size(glutin::dpi::LogicalSize::new(1024.0, 768.0)) .with_maximized(false); let windowed_context = glutin::ContextBuilder::...
get_hdd
identifier_name
main.rs
(|symbol| windowed_context.context().get_proc_address(symbol) as *const _); ClearColor(0.0, 1.0, 0.0, 1.0); } let mut render_mgr = RenderMgr::new(); let mut mgr = render_mgr.mgr.clone(); let mut system = sysinfo::System::new(); let cpu = cpu_name(); let ram = get_ram_total(&mut system); let c...
random_line_split
lib.rs
c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ).map(|c| if c >= '0' && c <= '9' { c as u64 - '0' as u64 } else if c >= 'a' && c <= 'f' { 10 + c as u64 - 'a' as u64 } else { 10 + c as u64 - 'A' as u64 } as u32 ) } fn unicode_char<'a>() -> imp...
__ <- satisfy(|c: char| c == 'e' || c == 'E'), sign_char <- optional(satisfy(|c: char| c == '+' || c == '-')), digits <- digit_sequence(); { let sign = match sign_char { Some('-') => -1.0, _ => 1.0 }; let mut acc = 0; ...
fn exponent_parser<'a>() -> impl Parser<&'a str, Output = f64> { c_hx_do!{
random_line_split
lib.rs
c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') ).map(|c| if c >= '0' && c <= '9' { c as u64 - '0' as u64 } else if c >= 'a' && c <= 'f' { 10 + c as u64 - 'a' as u64 } else { 10 + c as u64 - 'A' as u64 } as u32 ) } fn unicode_char<'a>() -> imp...
fn null_parser<'a>() -> impl Parser<&'a str, Output = Node> { c_hx_do!{ _word <- string("null"); Node::Null } } macro_rules! ref_parser { ($parser_fn:ident) => { parser(|input| { let _: &mut &str = input; $parser_fn().parse_stream(input).into_result() ...
{ c_hx_do!{ word <- string("true").or(string("false")); match word { "true" => Node::Boolean(true), _ => Node::Boolean(false) } } }
identifier_body