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
script.js
122.463701, 37.747683]) //-122.41, 37.79 .scale(width*200) .translate([width / 2, height / 2]); var path = d3.geo.path() .projection(projection); var ndx, yearDim, mhiDim, mgrDim, tractDim; var filterYear, filterMetric, sf_topojson; var parsed_data = []; var parsed_biz = []; var parsed_biz...
d.end_date = dateFormat.parse(d.end_date); d.start_date = dateFormat.parse(d.start_date); d.storetype = d.storetype; d.lat = +d.lat; d.lon = +d.lon; parsed_biz.push({"end_date": d.end_date, "storetype": d.storetype, "lat": d.lat, "lon": d.lon, "start_date": d.start_date}); }); ndx = crossf...
{ if (error) throw error; sf_topojson = topojson.feature(tracts, tracts.objects.sf).features; filterMetric = "mgr"; filterYear = 2014; svg.style("stroke", "black").style("fill", "lightgrey").style("stroke-width", "1px"); var dateFormat; data.forEach(function(d) { dateFormat = d3.time.format('%Y...
identifier_body
script.js
return d.value.mgr; } }) .colors(d3.scale.threshold().domain(specDomains).range(specColors)); if (yearChange) { var new_year_group = metricYearChange_map(); map.group(new_year_group); plot_biz(yearChange); } // var new_metric_group = metricChange_timeline(); // timeline.group(new_metric_gro...
} else { //default on mgr
random_line_split
step4_fit_prior_fast.py
(rates) mask = self.tObsMask[tidx] # if train: # # Randomly sample a subset of drugs and doses # mask = mask * autograd.Variable(torch.FloatTensor(np.random.random(size=self.tObsMask[tidx].shape) <= 0.5), requires_grad=False) # Get log probabilities of the data and filt...
print('3', loss) print('3 nans: {}'.format(np.isnan(loss.data.numpy()).sum())) return loss def fit_mu(self, verbose=False, **kwargs): self.models = [] self.train_folds = [] self.validation_folds = [] for fold_idx, fold in enumerate(self.folds): if...
print('2 nans: {}'.format(np.isnan(loss.data.numpy()).sum())) print() print('shape', loss.shape) loss = loss.sum(dim=1) / self.tObsMask[tidx].max(dim=-1).values.sum(dim=-1)
random_line_split
step4_fit_prior_fast.py
0.5), requires_grad=False) # Get log probabilities of the data and filter out the missing observations loss = -(logsumexp(likelihoods.log_prob(self.tY[tidx][:,:,:,None]) + self.tLogLamWeights[tidx][:,:,None], dim=-1) * mask) loss = loss.sum(dim=-1) / ...
forward
identifier_name
step4_fit_prior_fast.py
# noise = autograd.Variable(torch.FloatTensor(Z), requires_grad=False) noise = 0 # TEMP # Get the MVN draw as mu + epsilon beta = mu + noise else: beta = mu # Logistic transform on the log-odds prior sample tau = 1 / (1. + (-beta).exp...
for j in range(5): ebo._predict_mu_insample(0,i,j)
conditional_block
step4_fit_prior_fast.py
(dim=-1) print('3', loss) print('3 nans: {}'.format(np.isnan(loss.data.numpy()).sum())) return loss def fit_mu(self, verbose=False, **kwargs): self.models = [] self.train_folds = [] self.validation_folds = [] for fold_idx, fold in enumerate(self.folds): ...
print('Loading genomic features') X = load_dataset(genomic_features, index_col=0) # Remove any features not specified (this is useful for ablation studies) for ftype in ['MUT', 'CNV', 'EXP', 'TISSUE']: if ftype not in feature_types: select = [c for c in X.columns if not c.startswith(fty...
identifier_body
simulating_agent_model_2D.py
(Agent1=None, Agent2=None): """ ARGS: RETURN: DESCRIPTION: Gives displacement between two agents. DEBUG: FUTURE: """ if(type(Agent1) == AGENT): x1=Agent1.posL[0] y1=Agent1.posL[1] elif(type(Agent1) == list): x1=Agent1[0] y1=Agent1[1] else: ...
displacement
identifier_name
simulating_agent_model_2D.py
do an approximation of reality. Reasons : 1. Trying to avoid multiple infected individuals gets logically complicated to code. 2. Avoiding the bounds [0,0,0] -> [1,1,1] and trying to avoid an infected individual adds yet another level of logical complexit...
### With many root solvers, it requires that f(a)*f(b) < 0. However, ### fsolve doesn't care. It just needs bounds to look xroots = optimize.fsolve(f, [xc-r, xc+r]) # If there are two roots, which do i pick? Pick closest to Agent if(len(...
y = m*x+b return( (x-xc)**2 + (y-yc)**2 - r**2)
identifier_body
simulating_agent_model_2D.py
# # # import sys import numpy as np import time import pandas as pd from matplotlib import pyplot as plt from matplotlib.patches import Circle from error import exit_with_error from scipy import optimize import random random.seed(42) # Change later from classes import AGENT def print_help(ExitCode): """ ...
# 2. https://mbi.osu.edu/events/seminar-grzegorz-rempala-mathematical-models-epidemics-tracking-coronavirus-using-dynamic # # Future:
random_line_split
simulating_agent_model_2D.py
do an approximation of reality. Reasons : 1. Trying to avoid multiple infected individuals gets logically complicated to code. 2. Avoiding the bounds [0,0,0] -> [1,1,1] and trying to avoid an infected individual adds yet another level of logical complexit...
startTime = time.time() print("{} \n
quarantine = True
conditional_block
dashapp.py
_data,result.best_values['amp'],result.best_values['cen'],result.best_values['width']) new_dict = {'peak':1,'y':y_data[:,i].tolist(),'fit':result.best_fit.tolist(), 'y1':y1.tolist(),'mu1':result.best_values['cen']} elif len(peak_data[i]) == 2: # For t...
[Input('select_excel','value')] ) def fit_file(excel_file):
random_line_split
dashapp.py
ussian(x,a2,c2,w2) def
(x,a1,c1,w1,a2,c2,w2,a3,c3,w3): """ For fitting three gaussian peaks """ return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2)+gaussian(x,a3,c3,w3) # No need to re-run this again if data.json is already built def fit_and_write_json(excel_file): """ This function reads upon the excel file data and writes jso...
gauss3
identifier_name
dashapp.py
# Stack with the cummulative y built till now else: y = np.hstack((y, df_data.to_numpy())) # Ideally x_array should be (481, 1), and y should be (481, 169) return x_array, y def gaussian(x, amp, cen, width): """1-d gaussian: gaussian(x, amp, cen, width...
y = df_data.to_numpy()
conditional_block
dashapp.py
def gauss2(x,a1,c1,w1,a2,c2,w2): """ For fitting two gaussian peaks """ return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2) def gauss3(x,a1,c1,w1,a2,c2,w2,a3,c3,w3): """ For fitting three gaussian peaks """ return gaussian(x,a1,c1,w1)+gaussian(x,a2,c2,w2)+gaussian(x,a3,c3,w3) # No need to re-run this a...
"""1-d gaussian: gaussian(x, amp, cen, width) x: independent variable amp: amplitude/height of the curve cen: mean or peak position width: standard deviation/ spread of the curve """ return (amp / (np.sqrt(2*np.pi) * width)) * np.exp(-(x-cen)**2 / (2*width**2))
identifier_body
warm_start.py
2) * th2d ** 2 - 2 * m2 * l1 * lc2 * sin(th2) * th2d * th1d h2 = m2 * l1 * lc2 * sin(th2) * th1d ** 2 H = np.array([[h1], [h2]]) phi1 = (m1 * lc1 + m2 * l1) * g * cos(th1) + m2 * lc2 * g * cos(th1 + th2) phi2 = m2 * lc2 * g * cos(th1 + th2) PHI = np.array([[phi1], [phi2]]) Bl = np.linalg.inv(M) @ TAU Blin = np.array(...
for i in range(env.num_steps): actions = np.clip(np.asarray(control(obs)), -max_torque, max_torque) obs, reward, done, _ = env.step(actions) local_reward_hist[i, :] = np.copy(reward) if done: break return local_reward_hist, i # %%b start = time.time() config = {"i...
x, trial_num = args th1, th2, dth1, dth2 = x np.random.seed(trial_num) local_reward_hist = np.ones((env.num_steps, 1)) * -1 obs = env.reset(init_vec=[th1, th2, dth1, dth2])
random_line_split
warm_start.py
, 0, 0, 1], [Al[0, 0], Al[0, 1], 0, 0], [Al[1, 0], Al[1, 1], 0, 0]]) Ctr = ctrb(Alin, Blin) assert np.linalg.matrix_rank(Ctr) == 4 K, S, E = lqr(Alin, Blin, Q, R) k = np.array(K[1, :]) print(k) def control(q): gs = np.array([pi / 2, 0, 0, 0]) return -k.dot(q - gs) def reward_fn(s, a): reward = np.sin(...
reward = np.sin(s[0]) + 2 * np.sin(s[0] + s[1]) return reward, False
identifier_body
warm_start.py
2) * th2d ** 2 - 2 * m2 * l1 * lc2 * sin(th2) * th2d * th1d h2 = m2 * l1 * lc2 * sin(th2) * th1d ** 2 H = np.array([[h1], [h2]]) phi1 = (m1 * lc1 + m2 * l1) * g * cos(th1) + m2 * lc2 * g * cos(th1 + th2) phi2 = m2 * lc2 * g * cos(th1 + th2) PHI = np.array([[phi1], [phi2]]) Bl = np.linalg.inv(M) @ TAU Blin = np.array(...
preds = sig(net
coords[j, i, :] = np.array([pi/2, 0, th1dot_vals[i], th2dot_vals[j]])
conditional_block
warm_start.py
2) * th2d ** 2 - 2 * m2 * l1 * lc2 * sin(th2) * th2d * th1d h2 = m2 * l1 * lc2 * sin(th2) * th1d ** 2 H = np.array([[h1], [h2]]) phi1 = (m1 * lc1 + m2 * l1) * g * cos(th1) + m2 * lc2 * g * cos(th1 + th2) phi2 = m2 * lc2 * g * cos(th1 + th2) PHI = np.array([[phi1], [phi2]]) Bl = np.linalg.inv(M) @ TAU Blin = np.array(...
(q): gs = np.array([pi / 2, 0, 0, 0]) return -k.dot(q - gs) def reward_fn(s, a): reward = np.sin(s[0]) + 2 * np.sin(s[0] + s[1]) done = reward < 2 return reward, done def do_rollout(args): x, trial_num = args th1, th2, dth1, dth2 = x np.random.seed(trial_num) local_reward_hist = ...
control
identifier_name
fetch.rs
Map; use hyper::{Body, Client, Method, Request, StatusCode}; use hyper_tls::HttpsConnector; use std::io; use std::slice; use crate::metrics::*; use floating_duration::TimeAsFloat; use http::uri::Scheme; use std::time; lazy_static! { static ref HTTP_CLIENT: Client<HttpsConnector<HttpConnector>, Body> = { ...
let host = if let Some(port) = http_uri.port_part() { format!("{}:{}", host_str, port.as_str()) } else { let port = if let Some(scheme) = http_uri.scheme_part() { if scheme == &Scheme::HTTPS { "443" } else { "80" } } els...
{ let cmd_id = base.cmd_id(); let msg = base.msg_as_http_request().unwrap(); let url = msg.url().unwrap(); if url.starts_with("file://") { return file_request(rt, cmd_id, url); } let ptr = rt.ptr; let req_id = msg.id(); let http_uri: hyper::Uri = match url.parse() { O...
identifier_body
fetch.rs
HeaderMap; use hyper::{Body, Client, Method, Request, StatusCode}; use hyper_tls::HttpsConnector; use std::io; use std::slice; use crate::metrics::*; use floating_duration::TimeAsFloat; use http::uri::Scheme; use std::time; lazy_static! { static ref HTTP_CLIENT: Client<HttpsConnector<HttpConnector>, Body> = { ...
status: res.status.as_u16(), has_body: res.body.is_some(), ..Default::default() }, ); if let Some(stream) = res.body { send_body_stream(ptr, req_id, stream); } Ok(serialize_respons...
headers: Some(res_headers),
random_line_split
fetch.rs
Map; use hyper::{Body, Client, Method, Request, StatusCode}; use hyper_tls::HttpsConnector; use std::io; use std::slice; use crate::metrics::*; use floating_duration::TimeAsFloat; use http::uri::Scheme; use std::time; lazy_static! { static ref HTTP_CLIENT: Client<HttpsConnector<HttpConnector>, Body> = { ...
(rt: &mut Runtime, base: &msg::Base, raw: fly_buf) -> Box<Op> { debug!("handling http response"); let msg = base.msg_as_http_response().unwrap(); let req_id = msg.id(); let status = match StatusCode::from_u16(msg.status()) { Ok(s) => s, Err(e) => return odd_future(format!("{}", e).into(...
op_http_response
identifier_name
treeFactory.js
'15'},{ name: '欧洲游', id: '11', children: [{ name: '挪威游', id: '111' }, { name: '冰岛游', id: '112' }] }, { name: '北美游', id: '12', children: [{ name: '美国游', id: '121', children: [{ name: '加州游', id: '1211' }, { name: '纽...
ata; this.initRoot(data); this.initSVG(); if (this.root) { this.render(this.root) } } /************************************************************ * 初始化root ************************************************************/ initRoot() { const root = d3.hierarchy(this.data).count(); ...
/ init(data) { this.data = d
identifier_body
treeFactory.js
'15'},{ name: '欧洲游', id: '11', children: [{ name: '挪威游', id: '111' }, { name: '冰岛游', id: '112' }] }, { name: '北美游', id: '12', children: [{ name: '美国游', id: '121', children: [{ name: '加州游', id: '1211' }, { name: '纽...
**************************************************/ // 节点点击事件 handleNodeClick(d) { // toggle toolkit this.toggleToolkit(d); this.render(d); } // 编辑 handleEditClick(d) { const editFnArr = this.eventEmitter.edit; if (editFnArr) { editFnArr.forEach(fn => fn.call(null, d)) } } /...
******
identifier_name
treeFactory.js
: '15'},{ name: '欧洲游', id: '11', children: [{ name: '挪威游', id: '111' }, { name: '冰岛游', id: '112' }] }, { name: '北美游', id: '12', children: [{ name: '美国游', id: '121', children: [{ name: '加州游', id: '1211' }, { name: '...
************************************************************/ // 节点点击事件 handleNodeClick(d) { // toggle toolkit this.toggleToolkit(d); this.render(d); } // 编辑 handleEditClick(d) { const editFnArr = this.eventEmitter.edit; if (editFnArr) { editFnArr.forEach(fn => fn.call(null, d)) ...
} } /************************************************************ * 事件处理函数,可提取出去
random_line_split
treeFactory.js
'15'},{ name: '欧洲游', id: '11', children: [{ name: '挪威游', id: '111' }, { name: '冰岛游', id: '112' }] }, { name: '北美游', id: '12', children: [{ name: '美国游', id: '121', children: [{ name: '加州游', id: '1211' }, { name: '纽...
= d3.hierarchy(this.data).count(); root.x0 = dy / 2; root.y0 = 0; root.descendants().forEach((d, i) => { d.id = d.data.id ? d.data.id : i; d._children = d.children; }); this.root = root; } /************************************************************ * 初始化SVG **************...
***/ initRoot() { const root
conditional_block
SpinConfig.py
config = load(os.path.join(gameserver_dir(), 'config.json')) def reload(): # reload config file global config try: new_config = load(os.path.join(gameserver_dir(), 'config.json')) config = new_config except: pass # return identifier for this game (e.g. "mf" or "tr") def game(ov...
e = os.getenv('SPIN_GAMESERVER') if e: return e return '../gameserver' # global, used by code that imports SpinConfig
random_line_split
SpinConfig.py
# global, used by code that imports SpinConfig config = load(os.path.join(gameserver_dir(), 'config.json')) def reload(): # reload config file global config try: new_config = load(os.path.join(gameserver_dir(), 'config.json')) config = new_config except: pass # return identif...
e = os.getenv('SPIN_GAMESERVER') if e: return e return '../gameserver'
identifier_body
SpinConfig.py
'battlefront_heroes':'127918567418514', 'red_crucible_2':'126605594124234', 'stormfall_age_of_war':'450552231662626', 'boom_beach':'249340185214120', 'world_of_tanks':'494440040376', 'war_thunder':'362712050429431' } def game_launch_date(override_game_id = None): return { 'mf': 1326794...
parse_pgsql_config
identifier_name
SpinConfig.py
': 'C', 'ch': 'C', 'de': 'C', 'es': 'C', 'fr': 'C', 'gr': 'C', 'hk': 'C', 'hu': 'C', 'ie': 'C', 'il': 'C', 'it': 'C', 'pe': 'C', 'pr': 'C', 'pt': 'C', 'ro': 'C', 'sa': 'C', 'sg': 'C', 'sk': 'C', 've': 'C', 'al': 'D', 'ar': 'D', 'ba': 'D', 'bg': 'D', 'cl': 'D', 'co': 'D', 'cr': 'D', 'do': 'D', 'dz': 'D', 'eg': 'D', 'ge'...
ret += '%02dh' % h
conditional_block
chaintool.py
little') itms=int(lsoffset/34) for i in range(itms): index=i*34 if(index+34==itms*34): nextoffset=len(data) else: nextoffset=int.from_bytes(data[index:index+2],'little') self.items.append([data[index+2:index+34],data[lsoffse...
self.inUse=True else: info(" Node discovered: "+ip+':'+str(port)) self.inUse=False if running_node: self.inUse=True # stop polling processes self.avsend(b'IAMNODE') self.conn.recv(2) self.inUse=False...
if self.conn.recv(4).decode()!='OK': error(str(ip)+" is not a node.") self.conn.close()
random_line_split
chaintool.py
little') itms=int(lsoffset/34) for i in range(itms): index=i*34 if(index+34==itms*34): nextoffset=len(data) else: nextoffset=int.from_bytes(data[index:index+2],'little') self.items.append([data[index+2:index+34],data[lsoffse...
(cs, ip): global solved, ls_sub_blk index=0 while True: data=b'' length=0 try: tmp=cs.recv(8) if not tmp: break elif tmp==b'PING': data=b'PING' else: length= int.from_bytes(tmp,'little') ...
client_thread
identifier_name
chaintool.py
little') itms=int(lsoffset/34) for i in range(itms): index=i*34 if(index+34==itms*34): nextoffset=len(data) else: nextoffset=int.from_bytes(data[index:index+2],'little') self.items.append([data[index+2:index+34],data[lsoffse...
class Client(): def __init__(self, ip, port): self.ip=ip info("Connecting to "+str(ip)+':'+str(port)+"...") self.conn=socket.socket() self.conn.connect((ip, port)) self.conn.sendall(b"PING") if self.conn.recv(4).decode()!='OK': error(str(ip)+" is not a no...
global running_node, cs_list s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # bind the socket to a public host, and a well-known port try: s.bind(('', port)) info("Node on port "+str(port)+" started.") running_node=True except: error("Cannot run 2 nodes on same mac...
identifier_body
chaintool.py
little') itms=int(lsoffset/34) for i in range(itms): index=i*34 if(index+34==itms*34): nextoffset=len(data) else: nextoffset=int.from_bytes(data[index:index+2],'little') self.items.append([data[index+2:index+34],data[lsoffse...
elif data==b"GBLK": info("["+ip+"] Block requested.") if len(blocks)>index: chunk=blocks[index].pack() else: chunk=b"NONE" reply=chunk reply=len(reply).to_bytes(8, 'little')+reply elif data[:4]==b'FSB?': ...
data=data[2:] index=int.from_bytes(data[:8],"little") reply=b'DONE' info("["+ip+"] I set to "+str(index))
conditional_block
parsers.py
pathname2url(relate(obj.file_path, self.base_path)) self._store.append(obj) return obj except Exception as e: LOGGER.error(e) LOGGER.error('Exception occurred while creating an object for %s' % url) return None # return unmodified def default_h...
self.lxml.getroottree().write(self.url_obj.file_path, method="html") self._lxml = None # reset the tree
random_line_split
parsers.py
obj = self._base_handler(elem, attr, url, pos) if obj is None: return if attr is None: new = elem.text[:pos] + obj.rel_path + elem.text[len(url) + pos:] elem.text = new else: cur = elem.get(attr) if not pos and len(cur) == len(url): ...
__repr__
identifier_name
parsers.py
self.html""" if not isinstance(HTML, str): raise TypeError self._html = HTML.decode(self.encoding, errors='xmlcharrefreplace') def decode_html(self, html_string): converted = UnicodeDammit(html_string) if not converted.unicode_markup: raise UnicodeDecodeErro...
obj.rel_path = pathname2url(relate(obj.file_path, self.base_path)) self._store.append(obj) return obj except Exception as e: LOGGER.error(e) LOGGER.error('Exception occurred while creating an object for %s' % url) return None # return unm...
"""Can handle <img>, <link>, <script> :class: `lxml.html.Element` object.""" LOGGER.debug("Handling url %s" % url) if url.startswith(u"#") or url.startswith(u"data:") or url.startswith(u'javascript'): return None # not valid link try: if elem.tag == 'link': ...
identifier_body
parsers.py
self.html""" if not isinstance(HTML, str): raise TypeError self._html = HTML.decode(self.encoding, errors='xmlcharrefreplace') def decode_html(self, html_string): converted = UnicodeDammit(html_string) if not converted.unicode_markup: raise UnicodeDecodeErro...
# Scan meta tags for charset. if self._html: self._encoding = html_to_unicode(self.default_encoding, self._html)[0] # Fall back to requests' detected encoding if decode fails. try: self.raw_html.decode(self.encoding, errors='replace') exc...
return self._encoding
conditional_block
blockchain1.py
requests from uuid import uuid4 from urllib.parse import urlparse # Building a Blockchain class Blockchain: def __init__(self): self.chain = [] # our main block chain # now we will create the list of transation which will record the all transactions self.transactions = [] # cre...
# functions used to get add the transactions to the lists def add_transaction(self, senders, receiver, amount): self.transactions.append({ 'senders': senders, 'receiver': receiver, 'amount': amount }) previous_block = self.get_previous_block() ...
previous_block = chain[0] block_index = 1 # required for iteration while block_index < len(chain): block = chain[block_index] # cuurent block # checking weather the refernce stored in property previus_hash is currently matched or not with the hash of previous block using hash f...
identifier_body
blockchain1.py
requests from uuid import uuid4 from urllib.parse import urlparse # Building a Blockchain class Blockchain: def __init__(self): self.chain = [] # our main block chain # now we will create the list of transation which will record the all transactions self.transactions = [] # cre...
(self): # this variable help us to find the length of longest chain among different network max_length = len(self.chain) longest_chain = None network = self.nodes # this variable will hold the address of all the nodes in network for node in network: # we know the nod...
replace_chain
identifier_name
blockchain1.py
.datetime.now()), 'proof': proof, # works like a nounce of block stops when we reach at or below the target 'previous_hash': previous_hash, 'transactions': self.transactions} self.transactions = [] # this need to be done bcoz we cant have duplicates lists of transactions in...
ne.', 'actual_chain': blockchain.chain} return jsonify(response), 200 # Running the app # hos
conditional_block
blockchain1.py
requests from uuid import uuid4 from urllib.parse import urlparse # Building a Blockchain class Blockchain: def __init__(self): self.chain = [] # our main block chain # now we will create the list of transation which will record the all transactions self.transactions = [] # cre...
response = {'message': 'All the nodes are now connected. The Whalecoin 🐳🐳🐳🐳🐳
blockchain.add_node(node) # add our nodes to network
random_line_split
AgentConsole.controller.js
151.207193)); AgentConController.map.setZoom(18); marker = new google.maps.Marker({ // The below line is equivalent to writing: // position: new google.maps.LatLng(-34.397, 150.644) animation: google.maps.Animation.DROP, position: { lat: -33.862995, ...
var today = new Date(); AgentConController.getView().byId("dr_fromTo").setSecondDateValue(today); var oneWeekAgo = new Date(); oneWeekAgo.setDate(oneWeekAgo.getDate() - 7); AgentConController.getView().byId("dr_fromTo").setDateValue(oneWeekAgo); AgentConController.initialized = true; Agent...
conditional_block
AgentConsole.controller.js
AccountName === 'Deloitte') { AgentConController.map.panTo(new google.maps.LatLng(-33.862995, 151.207193)); AgentConController.map.setZoom(18); marker = new google.maps.Marker({ // The below line is equivalent to writing: // position: new google.maps.LatLng(-34.397, 150.6...
zoom: 16, mapTypeId: google.maps.MapTypeId.ROADMAP };
random_line_split
CS3243_P1_41_2.py
def __lt__(self, other): if (self.current_cost + self.heuristic_value) == (other.current_cost + other.heuristic_value): if (self.current_cost == other.current_cost): return (self.id > other.id) return (self.current_cost > other.current_cost) return (self...
self.state = orientation # a list of lists corresponding to the orientation of the tiles self.current_cost = float('inf') self.heuristic_value = float('inf') self.previous_action = "START" self.previous_node = None self.id = 0 # id of the node inserted (later nodes have a higher ...
identifier_body
CS3243_P1_41_2.py
# stats self.depth = float('inf') def __lt__(self, other): if (self.current_cost + self.heuristic_value) == (other.current_cost + other.heuristic_value): if (self.current_cost == other.current_cost): return (self.id > other.id) return (self.curren...
(self): return self.previous_node def set_id(self, next_id): self.id = next_id class Puzzle(object): def __init__(self, init_state, goal_state): # you may add more attributes if you think is useful self.name = "Manhattan Distance" self.size = len(init_state) sel...
get_previous_node
identifier_name
CS3243_P1_41_2.py
) # stats self.depth = float('inf') def __lt__(self, other): if (self.current_cost + self.heuristic_value) == (other.current_cost + other.heuristic_value): if (self.current_cost == other.current_cost): return (self.id > other.id) return (self.curr...
coord_in_goal = self.search_in_goal(curr); count += (abs(coord_in_goal[0]-i) + abs(coord_in_goal[1]-j)) return count def search_in_goal(self, query): return ((query - 1) // self.size, (query - 1) % self.size) def generate_possibilities(self, node): blank...
for i in range(self.size): for j in range(self.size): curr = node.state[i][j] if curr == 0: continue
random_line_split
CS3243_P1_41_2.py
return (self.current_cost + self.heuristic_value) == (other.current_cost + other.heuristic_value) # set current path cost def set_current_cost(self, cost): self.current_cost = cost # get current path cost def get_current_cost(self): return self.current_cost # set heuristic value ...
if len(sys.argv) != 3: raise ValueError("Wrong number of arguments!") try: f = open(sys.argv[1], 'r') except IOError: raise IOError("Input file not found!") lines = f.readlines() # n = num rows in input file n = len(lines) # max_num = n to the power of 2 - 1 ma...
conditional_block
handlers_events.go
return err } logger.Infof(strings.Repeat("-", 80)) logger.Infof("Registration Open from block %v to %v", event.DkgStarts, event.RegistrationEnds) logger.Infof(strings.Repeat("-", 80)) logger.Infof(" publicKey: %v", dkgtasks.FormatBigIntSlice(public[:])) logger.Infof(strings.Repeat("-", 80)) ...
{ eth := svcs.eth c := eth.Contracts() logger := svcs.logger event, err := c.Ethdkg.ParseRegistrationOpen(log) if err != nil { return err } if ETHDKGInProgress(state.ethdkg, log.BlockNumber) { logger.Warnf("Received RegistrationOpen event while ETHDKG in progress. Aborting old round.") AbortETHDKG(state...
identifier_body
handlers_events.go
:= dkgtasks.NewRegisterTask(taskLogger, eth, acct, state.ethdkg.TransportPublicKey, state.ethdkg.Schedule.RegistrationEnd) state.ethdkg.RegistrationTH = svcs.taskMan.NewTaskHandler(eth.Timeout(), eth.RetryDelay(), task) state.ethdkg.RegistrationTH.Start() } else { logger.Infof("Not participating in DKG...
{ logger.Debugf("Error in Services.ProcessDepositReceived at owner.New: %v", err) return err }
conditional_block
handlers_events.go
&EthDKGSchedule{} schedule.RegistrationStart = log.BlockNumber schedule.RegistrationEnd = event.RegistrationEnds.Uint64() schedule.ShareDistributionStart = schedule.RegistrationEnd + 1 schedule.ShareDistributionEnd = event.ShareDistributionEnds.Uint64() schedule.DisputeStart = schedule.ShareDistributionEnd...
(state *State, log types.Log) error { eth := svcs.eth c := eth.Contracts() event, err := c.Ethdkg.ParseValidatorMember(log) if err != nil { return err } epoch := uint32(event.Epoch.Int64()) index := uint8(event.Index.Uint64()) - 1 v := Validator{ Account: event.Account, Index: index, SharedKe...
ProcessValidatorMember
identifier_name
handlers_events.go
&EthDKGSchedule{} schedule.RegistrationStart = log.BlockNumber schedule.RegistrationEnd = event.RegistrationEnds.Uint64() schedule.ShareDistributionStart = schedule.RegistrationEnd + 1 schedule.ShareDistributionEnd = event.ShareDistributionEnds.Uint64() schedule.DisputeStart = schedule.ShareDistributionEnd...
updatedState := state event, err := c.Ethdkg.ParseValidatorSet(log) if err != nil { return err } epoch := uint32(event.Epoch.Int64()) vs := state.ValidatorSets[epoch] vs.NotBeforeMadNetHeight = event.MadHeight vs.ValidatorCount = event.ValidatorCount vs.GroupKey[0] = *event.GroupKey0 vs.GroupKey[1] = *e...
eth := svcs.eth c := eth.Contracts()
random_line_split
migrations.rs
DbWeight::get().reads(1) } } #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec<u8>) -> Result<(), TryRuntimeError> { frame_support::ensure!( Pallet::<T>::on_chain_storage_version() == 13, "v13 not applied" ); frame_support::ensure!( !StorageVersion::<T>::exists(), "Storage ...
traits::{GetStorageVersion, PalletInfoAccess}, }; #[cfg(feature = "try-runtime")] use sp_io::hashing::twox_128; pub struct MigrateToV11<T, P, N>(sp_std::marker::PhantomData<(T, P, N)>); impl<T: Config, P: GetStorageVersion + PalletInfoAccess, N: Get<&'static str>> OnRuntimeUpgrade for MigrateToV11<T, P, N> {...
use super::*; use frame_support::{ storage::migration::move_pallet,
random_line_split
migrations.rs
DbWeight::get().reads(1) } } #[cfg(feature = "try-runtime")] fn post_upgrade(_state: Vec<u8>) -> Result<(), TryRuntimeError> { frame_support::ensure!( Pallet::<T>::on_chain_storage_version() == 13, "v13 not applied" ); frame_support::ensure!( !StorageVersion::<T>::exists(), "Storage ...
<T>(sp_std::marker::PhantomData<T>); impl<T: Config> OnRuntimeUpgrade for MigrateToV12<T> { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> { frame_support::ensure!( StorageVersion::<T>::get() == ObsoleteReleases::V11_0_0, "Expected v11 before upgrading to v12" );...
MigrateToV12
identifier_name
migrations.rs
>(sp_std::marker::PhantomData<T>); impl<T: Config> OnRuntimeUpgrade for MigrateToV12<T> { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result<Vec<u8>, TryRuntimeError> { frame_support::ensure!( StorageVersion::<T>::get() == ObsoleteReleases::V11_0_0, "Expected v11 before upgrading to v12" ); ...
{ let prev_count = T::VoterList::count(); let weight_of_cached = Pallet::<T>::weight_of_fn(); for (v, _) in Validators::<T>::iter() { let weight = weight_of_cached(&v); let _ = T::VoterList::on_insert(v.clone(), weight).map_err(|err| { log!(warn, "failed to insert {:?} into VoterList: {:?}",...
conditional_block
migrations.rs
fn on_runtime_upgrade() -> Weight { let current = Pallet::<T>::current_storage_version(); let onchain = StorageVersion::<T>::get(); if current == 13 && onchain == ObsoleteReleases::V12_0_0 { StorageVersion::<T>::kill(); current.put::<Pallet<T>>(); log!(info, "v13 applied successfully"); T...
{ frame_support::ensure!( StorageVersion::<T>::get() == ObsoleteReleases::V12_0_0, "Required v12 before upgrading to v13" ); Ok(Default::default()) }
identifier_body
exec.go
command's output to the system logs, instead of the // task logs. This can be used to collect diagnostic data in the background of a running task. SystemLog bool `mapstructure:"system_log"` // WorkingDir is the working directory to start the shell in. WorkingDir string `mapstructure:"working_dir"` // IgnoreStan...
(params map[string]interface{}) error { err := mapstructure.Decode(params, c) if err != nil { return errors.Wrap(err, "decoding mapstructure params") } if c.Command != "" { if c.Binary != "" || len(c.Args) > 0 { return errors.New("must specify command as either binary and arguments, or a command string, but...
ParseParams
identifier_name
exec.go
will allow empty arguments in commands if set to true // note that non-blank whitespace arguments are never stripped KeepEmptyArgs bool `mapstructure:"keep_empty_args"` base } func subprocessExecFactory() Command { return &subprocessExec{} } func (c *subprocessExec) Name() string { return "subprocess.exec" } f...
return exec.LookPath(c.Binary) }
random_line_split
exec.go
command's output to the system logs, instead of the // task logs. This can be used to collect diagnostic data in the background of a running task. SystemLog bool `mapstructure:"system_log"` // WorkingDir is the working directory to start the shell in. WorkingDir string `mapstructure:"working_dir"` // IgnoreStan...
func (c *subprocessExec) Name() string { return "subprocess.exec" } func (c *subprocessExec) ParseParams(params map[string]interface{}) error { err := mapstructure.Decode(params, c) if err != nil { return errors.Wrap(err, "decoding mapstructure params") } if c.Command != "" { if c.Binary != "" || len(c.Args)...
{ return &subprocessExec{} }
identifier_body
exec.go
command's output to the system logs, instead of the // task logs. This can be used to collect diagnostic data in the background of a running task. SystemLog bool `mapstructure:"system_log"` // WorkingDir is the working directory to start the shell in. WorkingDir string `mapstructure:"working_dir"` // IgnoreStan...
cmdPath := c.Env["PATH"] // For non-Windows platforms, the filepath.Separator is always '/'. However, // for Windows, Go accepts both '\' and '/' as valid file path separators, // even though the native filepath.Separator for Windows is really '\'. This // detects both '\' and '/' as valid Windows file path sepa...
{ return c.Binary, err }
conditional_block
Randomizer.py
= "none" # clears recording constraints Selector_Screen.current_song = "none" Selector_Screen.current_diff = "none" Selector_Screen.report_mode = False Selector_Screen.match_winner = "none" Selector_Screen.player_array = ['none','none'] # clears entry boxes and radio buttons self.Game_...
(self,parent): # button function: saves winner to class variable and closes popup def return_value(event='<Button-1>'): # if button is selected if winner.get() != 0: # if not a draw if winner.get() != 3: Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() -...
Prompt_Winner
identifier_name
Randomizer.py
= "none" # clears recording constraints Selector_Screen.current_song = "none" Selector_Screen.current_diff = "none" Selector_Screen.report_mode = False Selector_Screen.match_winner = "none" Selector_Screen.player_array = ['none','none'] # clears entry boxes and radio buttons self.Ga...
# if a draw else: Selector_Screen.match_winner = "Draw" # close popup self.win.destroy() # creates popop window self.win = Toplevel(parent) self.win.wm_title("Select Winner") # button images self.Continue = Tkinter.PhotoImage(file="./Graphics/Continue.gif"...
Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() - 1]
conditional_block
Randomizer.py
= "none" # clears recording constraints Selector_Screen.current_song = "none" Selector_Screen.current_diff = "none" Selector_Screen.report_mode = False Selector_Screen.match_winner = "none" Selector_Screen.player_array = ['none','none'] # clears entry boxes and radio buttons self.Ga...
winner.set(0) # construct frame for widgets self.Inner_Frame = Frame(self.win) self.Inner_Frame.grid(row=0,column=0) # asks who the winner is Winner_Label = Label(self.Inner_Frame, text="The winner is:") Winner_Label.grid(row=0, column=0,columnspan=2) Winner_Label.configure(font=("TkDefa...
# initialize winner radio button variable winner = IntVar()
random_line_split
Randomizer.py
= "none" # clears recording constraints Selector_Screen.current_song = "none" Selector_Screen.current_diff = "none" Selector_Screen.report_mode = False Selector_Screen.match_winner = "none" Selector_Screen.player_array = ['none','none'] # clears entry boxes and radio buttons self.Ga...
# button images self.Continue = Tkinter.PhotoImage(file="./Graphics/Continue.gif") self.Cancel = Tkinter.PhotoImage(file="./Graphics/Cancel.gif") # initialize winner radio button variable winner = IntVar() winner.set(0) # construct frame for widgets self.Inner_Frame = Frame(self.win) ...
def return_value(event='<Button-1>'): # if button is selected if winner.get() != 0: # if not a draw if winner.get() != 3: Selector_Screen.match_winner = Selector_Screen.player_array[winner.get() - 1] # if a draw else: Selector_Screen.match_winner = "Draw" ...
identifier_body
list.go
VList creates and returns a pointer to a new vertical list panel // with the specified dimensions func NewVList(width, height float32) *List { return newList(true, width, height) } // NewHList creates and returns a pointer to a new horizontal list panel // with the specified dimensions func NewHList(width, height fl...
// SetItemPadLeftAt sets the additional left padding for this item // It is used mainly by the tree control func (li *List) SetItemPadLeftAt(pos int, pad float32) { if pos < 0 || pos >= len(li.items) { return } litem := li.items[pos].(*ListItem) litem.padLeft = pad litem.update() } // selNext selects or high...
{ if pos < 0 || pos >= len(li.items) { return } litem := li.items[pos].(*ListItem) if litem.selected == state { return } litem.SetSelected(state) li.update() li.Dispatch(OnChange, nil) }
identifier_body
list.go
(item IPanel) { for p, curr := range li.items { if curr.(*ListItem).item == item { li.RemoveAt(p) return } } } // ItemAt returns the list item at the specified position func (li *List) ItemAt(pos int) IPanel { item := li.ItemScroller.ItemAt(pos) if item == nil { return nil } litem := item.(*ListIte...
SetHighlighted
identifier_name
list.go
litem } // RemoveAt removes the list item from the specified position func (li *List) RemoveAt(pos int) IPanel { // Remove the list item from the internal scroller pan := li.ItemScroller.RemoveAt(pos) litem := pan.(*ListItem) // Remove item from the list item children and disposes of the list item panel item :...
} if litem.list.dropdown { litem.list.SetVisible(false) } }
random_line_split
list.go
*List) SetSingle(state bool) { li.single = state } // Single returns the current state of the single/multiple selection flag func (li *List) Single() bool { return li.single } // SetStyles set the listr styles overriding the default style func (li *List) SetStyles(s *ListStyles) { li.styles = s li.ItemScrolle...
{ item.(*ListItem).update() }
conditional_block
test_network_moreMeasures.py
onlyfiles_mask.sort(key = natsort_key1) counter = list(range(len(onlyfiles_mask))) # create a counter, so can randomize it """ Load avg_img and std_img from TRAINING SET """ mean_arr = 0; std_arr = 0; with open('./Data_functions/mean_arr.pkl', 'rb') as f: # Py...
try: tf.reset_default_graph() # necessary? # Variable Declaration x = tf.placeholder('float32', shape=[None, len_x, width_x, channels], name='InputImage') y_ = tf.placeholder('float32', shape=[None, len_x, width_x, 2], name='CorrectLabel') training = tf.placeholder(t...
identifier_body
test_network_moreMeasures.py
]) DAPI_im = np.zeros([1024, 640]) while N < len(cc): DAPI_idx = cc[N]['centroid'] if rotate: width_x = 640 # extract CROP outo of everything ...
for T in range(len(overlap_coords)): no_overlap[overlap_coords[T,0], overlap_coords[T,1]] = seg_im[overlap_coords[T,0], overlap_coords[T,1]]
conditional_block
test_network_moreMeasures.py
onlyfiles_mask.sort(key = natsort_key1) counter = list(range(len(onlyfiles_mask))) # create a counter, so can randomize it """ Load avg_img and std_img from TRAINING SET """ mean_arr = 0; std_arr = 0; with open('./Data_functions/mean_arr.pkl', 'rb') as f: # Py...
onlyfiles_mask = [ f for f in listdir(input_path) if isfile(join(input_path,f))] natsort_key1 = natsort_keygen(key = lambda y: y.lower()) # natural sorting order
random_line_split
test_network_moreMeasures.py
(s_path, sav_dir, input_path, checkpoint, im_scale, minLength, minSingle, minLengthDuring, radius, len_x, width_x, channels, CLAHE, rotate, jacc_test, rand_rot, rolling_ball, resize, debug): try: tf.reset_default_graph() # necessary? # ...
run_analysis
identifier_name
filter_jpeg.js
= options.maxEntrySize; this._onIFDEntry = options.onIFDEntry; // internal data this._markerCode = 0; this._bytesLeft = 0; this._segmentLength = 0; this._app1buffer = null; this._app1pos = 0; this._bytesRead = 0; // this._BufferConstructor = null; th...
// Perform a shallow copy of a buffer or typed array // function slice(buf, start, end) { if (buf.slice && buf.copy && buf.writeDoubleBE) { // // Looks like node.js buffer // // - we use buf.slice() in node.js buffers because // buf.subarray() is not a buffer // // - we use buf.subarr...
{ let n = number.toString(16).toUpperCase(); for (let i = 2 - n.length; i > 0; i--) n = '0' + n; return '0x' + n; }
identifier_body
filter_jpeg.js
= options.maxEntrySize; this._onIFDEntry = options.onIFDEntry; // internal data this._markerCode = 0; this._bytesLeft = 0; this._segmentLength = 0; this._app1buffer = null; this._app1pos = 0; this._bytesRead = 0; // this._BufferConstructor = null; th...
(number) { let n = number.toString(16).toUpperCase(); for (let i = 2 - n.length; i > 0; i--) n = '0' + n; return '0x' + n; } // Perform a shallow copy of a buffer or typed array // function slice(buf, start, end) { if (buf.slice && buf.copy && buf.writeDoubleBE) { // // Looks like node.js buffer ...
toHex
identifier_name
filter_jpeg.js
JpegFilter.prototype._error = function (message, code) { // double error? if (this._state === FINAL) return; let err = new Error(message); err.code = code; this._state = FINAL; this.onError(err); }; // Detect required output type by first input chunk JpegFilter.prototype._detectBuffer = function (data)...
random_line_split
filter_jpeg.js
= options.maxEntrySize; this._onIFDEntry = options.onIFDEntry; // internal data this._markerCode = 0; this._bytesLeft = 0; this._segmentLength = 0; this._app1buffer = null; this._app1pos = 0; this._bytesRead = 0; // this._BufferConstructor = null; th...
// unknown markers this._error('unknown marker: ' + toHex(b) + ' (offset ' + toHex(this._bytesRead + i) + ')', 'EBADDATA'); return; // return after error, not break // read segment length (2 bytes total) case SEGMENT_LENGTH: while (t...
{ // padding byte, skip it i++; break; }
conditional_block
ptsrc_gibbs.py
5) self.ps = ps self.b, self.x = None, None # Prepare the preconditioner. It approximates the noise as the # same in every pixel, and ignores the cmb-template coupling. # See M(self,u) for details. iN_white = np.array(np.sum(np.mean(np.mean(self.iN,-1),-1),0)) # iN_white is now in pixel space, but the pr...
sample
identifier_name
ptsrc_gibbs.py
(self, u): s, a = self.dof.unzip(u) return s[None,:,:,:] + np.sum(self.T*a[:,None,None,None,None],0) def PT(self, d): return self.dof.zip(np.sum(d,0), np.einsum("qijyx,ijyx->q",self.T, d)) def A(self, u): s, a = self.dof.unzip(u) # U"u = [S"s, 0a] Uu = self.dof.zip(en.harm2map(en.map_mul(self.iS, en.map...
def __init__(self, maps, inoise, model, amps, pos, pos0, irads, nsamp=1500, stepsize=0.02, maxdist=1.5*np.pi/180/60): self.samplers = [ShapeSampler(maps, inoise, model, amp1, pos1, pos01, irads1, nsamp=1, stepsize=stepsize, maxdist=maxdist) for amp1, pos1, pos01, irads1 in zip(amps, pos, pos0, irads)] self.nsamp ...
identifier_body
ptsrc_gibbs.py
return nmat def parse_floats(strs): return np.array([float(w) for w in strs.split(",")]) def apodize(m, rad, apod_fun): scale = m.extent()/m.shape[-2:] y = np.arange(m.shape[-2])*scale[0] x = np.arange(m.shape[-1])*scale[1] yfun = apod_fun(y, rad)*apod_fun(y[-1]-y, rad) xfun = apod_fun(x, rad)*apod_fun(x[-1]-x...
raise ValueError("Noise and maps have inconsistent shape!")
conditional_block
ptsrc_gibbs.py
,cmb,A) # MCMC # To take into account the nonperiodicity of each submap, we must introduce # a region of extra noise around the edge. class CMBSampler: """Draws samples from P(s,a|d,Cl,N,T), where T[ntemp,nfreq,ncomp,ny,nx] is a set of templates. a[ntemp] is the set of template amplitudes.""" def __init__(self, m...
if np.random.uniform() < np.exp(self.lik-lik): self.pos, self.lik = pos, lik irads = self.newshape(self.irads)
random_line_split
day20.rs
); assert_eq!(invert(512), 1); assert_eq!(invert(2), 256); } } impl std::fmt::Display for Tile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut first = true; for line in self.rows.iter() { if first { first = false; ...
fn west_edge(self: &Self) -> Line { self.rotate_cw().rows[0] } fn east_edge(self: &Self) -> Line { self.rotate_cw().rotate_cw().rotate_cw().rows[0] } fn south_edge(self: &Self) -> Line { self.rotate_cw().rotate_cw().rows[0] } fn get_edges(self: &Self) -> [Line; 4]...
self.rows[0] }
random_line_split
day20.rs
0, flip1, flip2, flip3] } } // All tiles and various helper structs. #[derive(Debug)] struct TileBag { // Mapping from tile id to tile. These tiles will get rotated once we start linking them // together. tiles: HashMap<usize, Tile>, // Mapping from edges to a list of Tiles, rotated such that the ...
mirror_vertical
identifier_name
day20.rs
#[test] fn test_invert() { assert_eq!(invert(1), 512); assert_eq!(invert(512), 1); assert_eq!(invert(2), 256); } } impl std::fmt::Display for Tile { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let mut first = true; for line in self.rows...
{ assert_eq!(line_to_string(1), ".........#"); assert_eq!(line_to_string(391), ".##....###"); }
identifier_body
noise.go
to return } func (r returnErrReader) Read([]byte) (int, error) { return 0, r.err } // Read is basically the same as controlbase.Conn.Read, but it first reads the // "early payload" header from the server which may or may not be present, // depending on the server. func (c *noiseConn) Read(p []byte) (n int, err error...
return nil, nil, errors.New("[unexpected] failed to reserve a request on a connection") } // contextErr is an error that wraps another error and is used to indicate that // the error was because a context expired. type contextErr struct { err error } func (e contextErr) Error() string { return e.err.Error() } fu...
{ conn, err := nc.getConn(ctx) if err != nil { return nil, nil, err } earlyPayloadMaybeNil, err := conn.getEarlyPayload(ctx) if err != nil { return nil, nil, err } if conn.h2cc.ReserveNewRequest() { return conn, earlyPayloadMaybeNil, nil } }
conditional_block
noise.go
if set, is a function that should return an explicit plan // on how to connect to the server. DialPlan func() *tailcfg.ControlDialPlan } // NewNoiseClient returns a new noiseClient for the provided server and machine key. // serverURL is of the form https://<host>:<port> (no trailing slash). // // netMon may be nil...
}).Dial(ctx) if err != nil { return nil, err
random_line_split
noise.go
// The first 9 bytes from the server to client over Noise are either an HTTP/2 // settings frame (a normal HTTP/2 setup) or, as we added later, an "early payload" // header that's also 9 bytes long: 5 bytes (earlyPayloadMagic) followed by 4 bytes // of length. Then that many bytes of JSON-encoded tailcfg.EarlyNoise. ...
{ select { case <-c.earlyPayloadReady: return c.earlyPayload, c.earlyPayloadErr case <-ctx.Done(): return nil, ctx.Err() } }
identifier_body
noise.go
to return } func (r returnErrReader) Read([]byte) (int, error) { return 0, r.err } // Read is basically the same as controlbase.Conn.Read, but it first reads the // "early payload" header from the server which may or may not be present, // depending on the server. func (c *noiseConn) Read(p []byte) (n int, err error...
() error { if err := c.Conn.Close(); err != nil { return err } c.pool.connClosed(c.id) return nil } // NoiseClient provides a http.Client to connect to tailcontrol over // the ts2021 protocol. type NoiseClient struct { // Client is an HTTP client to talk to the coordination server. // It automatically makes a ...
Close
identifier_name
write.rs
// does, and are by populated by LLVM's default PassManagerBuilder. // Each manager has a different set of passes, but they also share // some common passes. let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod); let mpm = llvm::LLVMCreatePassManager(); { le...
let msg = format!("failed to write bytecode to {}: {}", dst.display(), e);
random_line_split
write.rs
}) } pub(crate) fn save_temp_bitcode( cgcx: &CodegenContext<LlvmCodegenBackend>, module: &ModuleCodegen<ModuleLlvm>, name: &str ) { if !cgcx.save_temps { return } unsafe { let ext = format!("{}.bc", name); let cgu = Some(&module.name[..]); let path = cgcx.output...
(cgcx: &CodegenContext<LlvmCodegenBackend>, msg: &str, cookie: c_uint) { cgcx.diag_emitter.inline_asm_error(cookie as u32, msg.to_owned()); } unsafe extern "C" fn inline_asm_handler(diag: &SMDiagnostic, ...
report_inline_asm
identifier_name
write.rs
might have to clone the // module to produce the asm output let llmod = if config.emit_obj { llvm::LLVMCloneModule(llmod) } else { llmod }; with_codegen(tm, llmod, config.no_builtins, |cpm| { ...
{ "\x01__imp__" }
conditional_block
write.rs
pub fn to_llvm_opt_settings(cfg: config::OptLevel) -> (llvm::CodeGenOptLevel, llvm::CodeGenOptSize) { use self::config::OptLevel::*; match cfg { No => (llvm::CodeGenOptLevel::None, llvm::CodeGenOptSizeNone), Less => (llvm::CodeGenOptLevel::Less, llvm::CodeGenOptSizeNone), Default => (l...
{ target_machine_factory(&tcx.sess, tcx.backend_optimization_level(LOCAL_CRATE), find_features)() .unwrap_or_else(|err| { llvm_err(tcx.sess.diagnostic(), &err).raise() }) }
identifier_body
lib.rs
and thus //! backup currently running tasks, //! in case you want to shutdown/restart your application, //! constructing a new scheduler is doable. //! However, please make sure your internal clock is synced. #![deny(rust_2018_idioms)] use chrono::Duration as ChronoDuration; use parking_lot::{Condvar, Mutex, RwLock}; ...
lse { let mut scheduler_state = state_lock.lock(); if let SchedulerState::PauseTime(_) = *scheduler_state { let peeked = locked_heap.peek().expect("Expected heap to be filled."); if task.context.time < peeked.context.time { let left = task.co...
*scheduler_state = SchedulerState::new_pause_time(left); notifier.notify_one(); } } e
conditional_block
lib.rs
and thus //! backup currently running tasks, //! in case you want to shutdown/restart your application, //! constructing a new scheduler is doable. //! However, please make sure your internal clock is synced. #![deny(rust_2018_idioms)] use chrono::Duration as ChronoDuration; use parking_lot::{Condvar, Mutex, RwLock}; ...
scheduler exists on two levels: The handle, granting you the /// ability of adding new tasks, and the executor, dating and executing these /// tasks when specified time is met. /// /// **Info**: This scheduler may not be precise due to anomalies such as /// preemption or platform differences. pub struct Scheduler { ...
hedulerState::PauseTime( duration .to_std() .unwrap_or_else(|_| StdDuration::from_millis(0)), ) } } /// This
identifier_body
lib.rs
ise and thus //! backup currently running tasks, //! in case you want to shutdown/restart your application, //! constructing a new scheduler is doable. //! However, please make sure your internal clock is synced. #![deny(rust_2018_idioms)] use chrono::Duration as ChronoDuration; use parking_lot::{Condvar, Mutex, RwLock...
DateTime<Utc>, } /// Every task will return this `enum`. pub enum DateResult { /// The task is considered finished and can be fully removed. Done, /// The task will be scheduled for a new date on passed `DateTime<Utc>`. Repeat(DateTime<Utc>), } /// Every job gets a planned `Date` with the scheduler. ...
time:
identifier_name
lib.rs
ise and thus //! backup currently running tasks, //! in case you want to shutdown/restart your application, //! constructing a new scheduler is doable. //! However, please make sure your internal clock is synced. #![deny(rust_2018_idioms)] use chrono::Duration as ChronoDuration; use parking_lot::{Condvar, Mutex, RwLock...
} #[must_use] enum Break { Yes, No, } #[inline] fn process_states(state_lock: &Mutex<SchedulerState>, notifier: &Condvar) -> Break { let mut scheduler_state = state_lock.lock(); while let SchedulerState::PauseEmpty = *scheduler_state { notifier.wait(&mut scheduler_state); } while le...
*state = SchedulerState::new_pause_time(left); _push_and_notfiy(date, &mut heap_lock, &notifier); }
random_line_split
project.py
_window].ravel() hog_features = np.hstack((hog_feat1, hog_feat2, hog_feat3)) else: hog_features = hog_feat1 xleft = xpos*pix_per_cell ytop = ypos*pix_per_cell test_prediction = svc.predict(hog_features) ...
self.prev_rects.append(rects) if len(self.prev_rects) > 15: # throw out oldest rectangle set(s) self.prev_rects = self.prev_rects[len(self.prev_rects)-15:]
identifier_body
project.py
image if other than 1.0 scale if scale != 1: imshape = ctrans_tosearch.shape ctrans_tosearch = cv2.resize(ctrans_tosearch, (np.int(imshape[1]/scale), np.int(imshape[0]/scale))) # select colorspace channel for HOG if hog_channel == 'ALL': ch1 = ctrans_tosearch[:,:,0] ch...
ThresholdImage
identifier_name
project.py
_per_block=2, hog_channel=0): # Create a list to append feature vectors to
# apply color conversion if other than 'RGB' if cspace != 'RGB': if cspace == 'HSV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2HSV) elif cspace == 'LUV': feature_image = cv2.cvtColor(image, cv2.COLOR_RGB2LUV) elif cspace == 'HLS...
features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file)
random_line_split
project.py
_per_block=2, hog_channel=0): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file) # apply color conversion if other than 'RGB' if cspace != 'RGB': ...
for xb in range(nxsteps): for yb in range(nysteps): ypos = yb*cells_per_step xpos = xb*cells_per_step # Extract HOG for this patch hog_feat1 = hog1[ypos:ypos+nblocks_per_window, xpos:xpos+nblocks_per_window].ravel() if hog_channel == 'ALL': ...
hog2 = getHOG(ch2, orient, pix_per_cell, cell_per_block, feature_vec=False) hog3 = getHOG(ch3, orient, pix_per_cell, cell_per_block, feature_vec=False)
conditional_block
storage_service.go
, ",") if sc.ScType == models.ScTypeUnique { // 处理独占存储 var clusterCount int64 clusterCount, err = ss.Engine.Where("sc_name = ?", sc.Name).Count(new(models.ClusterInstance)) if err != nil { return err } if clusterCount > 0 { return response.NewMsg("This storage is already in use and cannot be...
random_line_split
storage_service.go
_, err = ss.Engine.Get(&u) utils.LoggerError(err) scUser[i].UserName = u.UserName } scUserRaw, _ = json.Marshal(scUser) } scReturn[i] = models.ReturnSc{Sc: sc, Children: pv, Cluster: cluster, ScUser: scUserRaw} } if isFilter { for i, sc := range scReturn { if sc.ScType == models.ScTypeUnique...
rror { session :
identifier_name