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
main.rs
r: init::Resources) -> init::LateResources { let mut rcc = p.device.RCC.constrain(); let mut flash = p.device.FLASH.constrain(); let mut gpioa = p.device.GPIOA.split(&mut rcc.ahb); let mut gpiob = p.device.GPIOB.split(&mut rcc.ahb); let mut gpioc = p.device.GPIOC.split(&mut rcc.ahb); // Enable ...
} Err(nb::Error::Other(_)) => { r.BLE.handle_error(|uart| { uart.clear_overflow_error(); } ); } Err(nb::Error::WouldBlock) => {} } } fn exti9_5(_t: &mut Threshold, mut r: EXTI9_5::Resources) { if r.EXTI.pr1.read().pr8().bit_is_set() { r.EXTI.pr1.modify(|_, w...
{ *r.BUFFER_POS = 0; }
conditional_block
main.rs
r: init::Resources) -> init::LateResources { let mut rcc = p.device.RCC.constrain(); let mut flash = p.device.FLASH.constrain(); let mut gpioa = p.device.GPIOA.split(&mut rcc.ahb); let mut gpiob = p.device.GPIOB.split(&mut rcc.ahb); let mut gpioc = p.device.GPIOC.split(&mut rcc.ahb); // Enable ...
(_t: &mut Threshold, mut r: TIM7::Resources) { } fn sys_tick(_t: &mut Threshold, mut r: SYS_TICK::Resources) { let toggle = *r.TOGGLE; let extcomin = &mut *r.EXTCOMIN; if *r.RESET_BLE { r.BLE.hard_reset_on(); *r.RESET_BLE = false; } else { r.BLE.hard_reset_off(); } mat...
tick
identifier_name
model.py
1) # Scalar Encoder self.scalar_encoder = nn.Linear(num_players, 128) # transformer # self.max_entities = 10 self.action_map = [None, "NORTH", "EAST", "SOUTH", "WEST", "CONVERT", "SPAWN"] self.SHIP_TYPE = 2 self.SHIPYARD_TYPE = 1 num_actions = len(sel...
(self, state, mask = False): # Scalar encoding state = self.parse_state(state) scalar = state['scalar'].to(self.device()) scalar_encoding = F.relu(self.scalar_encoder(scalar)).unsqueeze(1) # Spatial Encoding game_map = state['map'].to(self.device()) ...
forward
identifier_name
model.py
1) # Scalar Encoder self.scalar_encoder = nn.Linear(num_players, 128) # transformer # self.max_entities = 10 self.action_map = [None, "NORTH", "EAST", "SOUTH", "WEST", "CONVERT", "SPAWN"] self.SHIP_TYPE = 2 self.SHIPYARD_TYPE = 1 num_actions = len(sel...
# Retrieved from pytorch website class PositionalEncoding2D(nn.Module): def __init__(self, d_model, height, width): super(PositionalEncoding2D, self).__init__() if d_model % 4 != 0: raise Error() pe = torch.zeros(d_model, height, width) d_model = int(d_model / 2) ...
return self.EntityType(typ) + self.EntityPosition(pos) + self.fc(scalar)
identifier_body
model.py
1) # Scalar Encoder self.scalar_encoder = nn.Linear(num_players, 128) # transformer # self.max_entities = 10 self.action_map = [None, "NORTH", "EAST", "SOUTH", "WEST", "CONVERT", "SPAWN"] self.SHIP_TYPE = 2 self.SHIPYARD_TYPE = 1 num_actions = len(sel...
entity_typ_iter.append(entity_typ) entity_pos_iter.append(entity_pos) entity_id_iter.append(entity_id) entity_scalar_iter.append(entity_scalar) scalar_iter.append(scalar) return { 'map': torch.cat(spat_map_iter), 'entity_typ': ...
entity_scalar = F.pad(torch.tensor(entity_scalar).float().unsqueeze(0), (0, 0, 0, diff), "constant", 0) scalar = scalar.unsqueeze(0) / self.starting_halite spat_map_iter.append(spat_map)
random_line_split
model.py
1) # Scalar Encoder self.scalar_encoder = nn.Linear(num_players, 128) # transformer # self.max_entities = 10 self.action_map = [None, "NORTH", "EAST", "SOUTH", "WEST", "CONVERT", "SPAWN"] self.SHIP_TYPE = 2 self.SHIPYARD_TYPE = 1 num_actions = len(sel...
else: act = None if act is not None: actions[eid] = act actions_iter.append(actions) raw_actions_iter.append(raw_actions) return actions_iter, raw_actions_iter class ParseState(objec...
n_entities += 1
conditional_block
match.go
the default tag to return in case there is no match // - desired: list of desired tags, ordered by preference, starting with // the most-preferred. // // Algorithm: // 1) Set the best match to the lowest confidence level // 2) For each tag in "desired": // a) For each tag in "supported": // ...
(l language.Language, s language.Script) language.Script { for _, alt := range matchScript { // TODO: also match cases where language is not the same. if (language.Language(alt.wantLang) == l || language.Language(alt.haveLang) == l) && language.Script(alt.haveScript) == s { return language.Script(alt.wantScr...
altScript
identifier_name
match.go
n.tag.VariantOrPrivateUseTags() { for h.haveTags[i].nextMax != 0 { i = int(h.haveTags[i].nextMax) } h.haveTags[i].nextMax = uint16(len(h.haveTags)) break } } h.haveTags = append(h.haveTags, &n) } // header returns the matchHeader for the given language. It creates one if // it doesn't already exis...
{ // Bail if the maximum attainable confidence is below that of the current best match. c := have.conf if c < m.conf { return } // Don't change the language once we already have found an exact match. if m.pinLanguage && tag.LangID != m.want.LangID { return } // Pin the region group if we are comparing tags ...
identifier_body
match.go
// A MatchOption configures a Matcher. type MatchOption func(*matcher) // PreferSameScript will, in the absence of a match, result in the first // preferred tag with the same script as a supported tag to match this supported // tag. The default is currently true, but this may change in the future. func PreferSameScri...
"golang.org/x/text/internal/language" )
random_line_split
match.go
m *matcher) header(l language.Language) *matchHeader { if h := m.index[l]; h != nil { return h } h := &matchHeader{} m.index[l] = h return h } func toConf(d uint8) Confidence { if d <= 10 { return High } if d < 30 { return Low } return No } // newMatcher builds an index for the given supported tags an...
{ // There is usually very little comprehension between different scripts. // In a few cases there may still be Low comprehension. This possibility // is pre-computed and stored in have.altScript. if Low < m.conf || have.altScript != maxScript { return } c = Low }
conditional_block
lane_detector.py
(self, img): ''' Apply polynomial fit to the given image, returning fit for left/right lanes Called when one frame of image has previously found left_fit/right_fit. This method attempts to find lane fits in the vicinity of previous fits :param img -- input image with lane l...
window_fit
identifier_name
lane_detector.py
# from the next frame of video (also called "binary_warped") # It's now much easier to find line pixels! nonzero = img.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_lane_inds = ((nonzerox > (self.left_fit[0...
return self.sliding_window_fit(img)
conditional_block
lane_detector.py
# Again, extract left and right line pixel positions self.leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] self.rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit a second order polynomial to each self.left_f...
''' Apply polynomial fit to the given image, returning fit for left/right lanes Called when one frame of image has previously found left_fit/right_fit. This method attempts to find lane fits in the vicinity of previous fits :param img -- input image with lane lines :ret...
identifier_body
lane_detector.py
, 2) self.right_fit = np.polyfit(righty, self.rightx, 2) return self.left_fit, self.right_fit def sliding_window_fit(self, img): ''' Apply sliding windows search to the given image to find polynomial to find lane lines Code based largely on Udacity lessons :param img - ...
def draw_polygon(self, img, left_fit, right_fit, M_inverse): ''' Draw shaded polygon on the lane between left_fit and right_fit
random_line_split
quiz.js
: 0, quizNameArray: [], aniArray: [], aniId: null, init: function () { var quiz = QSAll('.quiz'), popupQuiz = QSAll('.popupPageContainer .quiz'); this.objCount = new Array(quiz.length); for (var i = 0; i < quiz.length; i++) { var quizNameArray = quiz[i].getAttribute('quiz'), quizNum = i ...
random_line_split
quiz.js
on DragDrop (param) { this.element = param.element; this.parentElment = window; this.createDragDrop(param); } // 드래그&드랍 : 위치 이동 DragDrop.prototype.createDragDrop = function (param) { var dragObj = this, left = param.left + param.width, top = param.top + param.height, answerLine...
Audio; var efPlay = function () { efAudio.removeEventListener('loadeddata', efPlay); efAudio.play(); }; efAudio.src = src; efAudio.addEventListener('loadeddata', efPlay); efAudio.load(); } // 드래그&드랍 : 설정 functi
identifier_body
quiz.js
type) { var svgContainer = document.createElementNS('http://www.w3.org/2000/svg', type); target.appendChild(svgContainer); return svgContainer; } // 효과음 기본 설정 function efSound (src) { var efAudio = new Audio; var efPlay = function () { efAudio.removeEventListener('loadeddata', efPlay); ...
get,
identifier_name
quiz.js
/ GameManager.event.zoomRate; var newTop = (dragObj.newY + param.height * GameManager.event.zoomRate) / GameManager.event.zoomRate; if (answerLine !== null) { answerLine.setAttribute('d', 'M '+ left +' '+ top + ' L '+ newLeft +' '+ newTop); } ...
function (quizNum, quizName) { this.quizNameArray.push(quizName); for (var i = 0; i < quizName.length; i++) this[quizName[i]]['init'](quizNum); } } return quizObj; })(); // 퀴즈 : dragLine 이벤트 QUIZ.dragLine = { name: 'dragLine', dragLineObj: null, dropArea: null, path: null, objSize: {width: null, he...
? quizNameArray.split(',') : [quizNameArray]; this.start(quizNum, quizNameArray); } else { console.log('noQuiz'); } } }, start:
conditional_block
intraday.py
self._state = {} self._syms = [ "BINANCE:UNIUSD", "BINANCE:ETHUSD", "BINANCE:DOTUSD", "SGX:ES3", "SGX:CLR" ] self._t = None self._timeframe = 240 # Default to 4 hours chart self._ws_url = "wss://data.tradingview.com/socket.io/websocket" def ...
self._alerts["indicators"][sym][ indicator] = val elif v.get("s"): # series vals = v.get("s")[0].get("v") val_dict = dict( ...
self._alerts["indicators"][sym] = {}
conditional_block
intraday.py
mins self._state = {} self._syms = [ "BINANCE:UNIUSD", "BINANCE:ETHUSD", "BINANCE:DOTUSD", "SGX:ES3", "SGX:CLR" ] self._t = None self._timeframe = 240 # Default to 4 hours chart self._ws_url = "wss://data.tradingview.com/socket.io/websocket" ...
send(ws, "switch_timezone", [c_session, "Asia/Singapore"]) send(ws, "resolve_symbol", [ c_session, f"symbol_{i}", self._add_chart_symbol(sym) ]) # s (in resp) -> series sel...
send(ws, "chart_create_session", [c_session, ""])
random_line_split
intraday.py
self._state = {} self._syms = [ "BINANCE:UNIUSD", "BINANCE:ETHUSD", "BINANCE:DOTUSD", "SGX:ES3", "SGX:CLR" ] self._t = None self._timeframe = 240 # Default to 4 hours chart self._ws_url = "wss://data.tradingview.com/socket.io/websocket" def ...
(*args, **kwargs): # ~m~52~m~{"m":"quote_create_session","p":["qs_3bDnffZvz5ur"]} # ~m~395~m~{"m":"quote_set_fields","p":["qs_3bDnffZvz5ur","ch","chp","lp"]} # ~m~89~m~{"m":"quote_add_symbols","p":["qs_3bDnffZvz5ur","SP:SPX",{"flags":["force_permission"]}]} # ~m~315~m~{"m...
run
identifier_name
intraday.py
"BINANCE:ETHUSD", "BINANCE:DOTUSD", "SGX:ES3", "SGX:CLR" ] self._t = None self._timeframe = 240 # Default to 4 hours chart self._ws_url = "wss://data.tradingview.com/socket.io/websocket" def get(self, type: str, **kwargs): """ Type is either quote (liv...
""" Indicator params that are accepted by the tv server """ return { "rsi": { "text": "1f0fkZ72S0de2geyaUhXXw==_xwY73vljRXeew69Rl27RumLDs6aJ9NLsTYN9Xrht254BTb8uSOgccpLDt/cdRWopwJPNZx40m19yEFwJFswkSi62X4guNJYpXe4A6S9iq2n+OXM6mqWeWzDbjTl0lYmEf1ujbg7i3FvUdV/zCSrqd+iwnvvZ...
identifier_body
conv2d_compact.rs
= Vec::new(); ext.resize((packed_size + k_col - 1) as usize, T::zero()); for k in 0..(packed_size + k_col - 1) * bit_length { ext[(k / bit_length) as usize] += T::from_i32(((val[(k/8) as usize] >> (k % 8)) & 1) as i32) * power_of_two(k % bit_length); ...
} mul_input.push(mul_input_row); } //packing bias let mut packed_bias: Vec<Vec<TensorAddress>> = Vec::with_capacity(fout as usize); let mut bias_dim = 0; let mut bias_scale = 0; if let Some((b, scale)) = bias { bias_dim = (col - k_col)...
let mut mul_input_row = Vec::new(); for c in 0..col_packed { mul_input_row.push(self.mem.save(self.mem[packed_layer].at(&[RangeFull(), Range(r..r + k_row), Id(c)])));
random_line_split
conv2d_compact.rs
= Vec::new(); ext.resize((packed_size + k_col - 1) as usize, T::zero()); for k in 0..(packed_size + k_col - 1) * bit_length { ext[(k / bit_length) as usize] += T::from_i32(((val[(k/8) as usize] >> (k % 8)) & 1) as i32) * power_of_two(k % bit_length); ...
for r in 0..row - k_row + 1 { let mut mul_input_row = Vec::new(); for c in 0..col_packed { mul_input_row.push(self.mem.save(self.mem[packed_layer].at(&[RangeFull(), Range(r..r + k_row), Id(c)]))); } mul_input.push(mul_input_row); } ...
{ // packing weight let dim = &self.mem[weight_rev].dim; let (fout, fin, k_row, k_col) = (dim[0], dim[1], dim[2], dim[3]); let packed_weight = self.mem.alloc(&[fout, fin, k_row]); assert!(k_col * (bit_length as u32) <= SCALAR_SIZE); self.packing_tensor(weight_rev, packed...
identifier_body
conv2d_compact.rs
+ k_row), Id(c)]))); } mul_input.push(mul_input_row); } //packing bias let mut packed_bias: Vec<Vec<TensorAddress>> = Vec::with_capacity(fout as usize); let mut bias_dim = 0; let mut bias_scale = 0; if let Some((b, scale)) = bias { bi...
conv2d_compact_test_small
identifier_name
conv2d_compact.rs
= Vec::new(); ext.resize((packed_size + k_col - 1) as usize, T::zero()); for k in 0..(packed_size + k_col - 1) * bit_length { ext[(k / bit_length) as usize] += T::from_i32(((val[(k/8) as usize] >> (k % 8)) & 1) as i32) * power_of_two(k % bit_length); ...
else { None }; res[i] = (full, rem); } res } fn extract_sign_part(c: &mut ConstraintSystem, extracted: TensorAddress, bit_length: u8) { let output = c.mem.alloc(&c.mem[extracted].dim.to_owned()); c.sign...
{ Some(mem.save(tmp.at(&[RangeFull(), RangeFull(), Id(n), Range(pos[i]..remainder)]))) }
conditional_block
director_test.go
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the Licen...
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0
random_line_split
director_test.go
}() go directorIncomingDPMessages(rcv, dpCh) // Sending a bogus message should not cause anything be written to dpCh rcv <- &cluster.Msg{} rcv <- &cluster.Msg{} // second send ensures the loop has gone full circle if count > 0 { t.Errorf("Malformed messages should not cause data points, count: %d", count) } ...
{ defer func() { // restore default output log.SetOutput(os.Stderr) }() fl := &fakeLogger{} log.SetOutput(fl) rcv := make(chan *cluster.Msg) dpCh := make(chan *IncomingDP) count := 0 go func() { for { if _, ok := <-dpCh; !ok { break } count++ }
identifier_body
director_test.go
} if rds.PointCount() != 0 { t.Errorf("directorProcessOrForward: ClearRRAs(true) not called") } // restore directorForwardDPToNode directorForwardDPToNode = saveFn } func Test_directorProcessIncomingDP(t *testing.T) { saveFn := directorProcessOrForward dpofCalled := 0 directorProcessOrForward = func(dsc *ds...
Test_director_checkSetAside
identifier_name
director_test.go
t.Errorf("Hops exceeded messages should log 'max hops'") } // Closing the dpCh should cause the recover() to happen // The test here is that it doesn't panic close(dpCh) dp.Hops = 0 m, _ = cluster.NewMsg(&cluster.Node{}, dp) rcv <- m // Closing the channel exists (not sure how to really test for that) go di...
if dpofCalled != 1 { t.Errorf("directorProcessIncomingDP: With a value, directorProcessOrForward should be called once: %v", dpofCalled) } // A blank name should cause a nil rds dp.Name = "" scr.called, dpofCalled = 0, 0 directorProcessIncomingDP(dp, scr, dsc, nil, nil, nil) if scr.called != 1 { t.Errorf("...
{ t.Errorf("directorProcessIncomingDP: With a value, reportStatCount() should be called twice: %v", scr.called) }
conditional_block
search.rs
> { pub fn new(cl: C) -> Self
} impl<C: IntoIterator> Iterator for TaskIter<C> { type Item = <C::IntoIter as Iterator>::Item; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } pub type Task<'t, P, C> = TaskIter<super::clause::OClause<'t, Lit<P, C, usize>>>; pub type Context<'t, P, C> = context::Context<Vec<OLit<'t...
{ Self(cl.into_iter().skip(0)) }
identifier_body
search.rs
pub type Task<'t, P, C> = TaskIter<super::clause::OClause<'t, Lit<P, C, usize>>>; pub type Context<'t, P, C> = context::Context<Vec<OLit<'t, P, C>>>; #[derive(Clone, Debug)] pub enum Action<'t, P, C> { Prove, Reduce(OLit<'t, P, C>, Index), Extend(OLit<'t, P, C>, Contras<'t, P, C>, Index), } impl<'t, P, C...
try_alternative
identifier_name
search.rs
{ task: T, ctx_ptr: context::Ptr, alt_len: usize, } pub struct Opt { pub lim: usize, pub cuts: Cuts, } impl<'t, P, C> Search<'t, P, C> { pub fn new(task: Task<'t, P, C>, db: &'t Db<P, C, usize>, opt: Opt) -> Self { Self { task, ctx: Context::default(), ...
{ self.ctx = ctx; }
conditional_block
search.rs
> { pub fn new(cl: C) -> Self { Self(cl.into_iter().skip(0)) } } impl<C: IntoIterator> Iterator for TaskIter<C> { type Item = <C::IntoIter as Iterator>::Item; fn next(&mut self) -> Option<Self::Item> { self.0.next() } } pub type Task<'t, P, C> = TaskIter<super::clause::OClause<'t, ...
} } fn ext(&mut self, lit: OLit<'t, P, C>, cs: Contras<'t, P, C>, skip: usize) -> State<'t, P, C> { let alt = Alternative::from(&*self); let prm = Promise::from(&*self); let sub = SubPtr::from(&self.sub); for (eidx, entry) in cs.iter().enumerate().skip(skip) { ...
let neg = -lit.head().clone(); match self.db.get(&neg) { Some(entries) => self.ext(lit, entries, 0), None => self.try_alternative(),
random_line_split
ESealedRadioactiveSourceDetail.js
$("#sourceType").val("0"); $("#sourceType1").html(""); var sourceType = sourceCode.substr(sourceCode.length-1,1); return; } //根据最后一个字符生成类别 var sourceType = sourceCode.substr(sourceCode.length-1,1); if(sourceType == "N"){ $("#sourceType").val("0"); $("#sourceType1").html...
if( /^[A-Z0-9\d]{2}$/.test(str) ){ return true; } return false; }); //验证编号是否正确 jQuery.validator.addMethod("verifySourceCode", function(value, element) { var SourceCode = $.trim($("#ESealedRadioactiveSourceForm").find("#sourceCode").val()); if(SourceCode == ''){ ...
} break; } }
conditional_block
ESealedRadioactiveSourceDetail.js
2}$/.test(time) ){//不是数字或NN return true; } return false; }); //验证编号五六位 核素代码 jQuery.validator.addMethod("verifySourceCodeNuclide", function(value, element) { var SourceCode = $.trim($("#ESealedRadioactiveSourceForm").find("#sourceCode").val()); if(SourceCode == ''){ re...
identifier_body
ESealedRadioactiveSourceDetail.js
$("#sourceType").val("3"); $("#sourceType1").html("III"); } if(sourceType == 4){ $("#sourceType").val("4"); $("#sourceType1").html("IV"); } if(sourceType == 5){ $("#sourceType").val("5"); $("#sourceType1").html("V"); } }); ESealedRadioactiveSourc...
}
random_line_split
ESealedRadioactiveSourceDetail.js
jQuery.validator.addMethod("verifySourceCodeYear", function(value, element) { var SourceCode = $.trim($("#ESealedRadioactiveSourceForm").find("#sourceCode").val()); if(SourceCode == ''){ return true; } var time = SourceCode.substring(2,4);//获取年份 if(/^[0-9N]{2}$/.test(time) ){//不是数字或NN ...
cus().blur(
identifier_name
array.ts
< inputs.length; index++) inputs[index] = getNewValue(inputs[index], index) } /** Delete elements of an array not satisfying `predicate`. If `predicate` throws, the array will be left in a bad state. */ export function filterMutate<T>(inputs: T[], predicate: Predicate<T>): void { let writeIndex = 0 for (const inp...
let writeIndex = 0 let readIndex = 0 while (readIndex < maxNumberOfThreads && readIndex < inputs.length) startOne() while (readIndex < inputs.length) { await awaitOne() startOne() } while (writeIndex < inputs.length) await awaitOne() async function awaitOne(): Promise<void> { inputs[writ...
async map(mapper: (element: T, index: number) => Promise<T>): Promise<void> { const { inputs, maxNumberOfThreads } = this
random_line_split
array.ts
< inputs.length; index++) inputs[index] = getNewValue(inputs[index], index) } /** Delete elements of an array not satisfying `predicate`. If `predicate` throws, the array will be left in a bad state. */ export function filterMutate<T>(inputs: T[], predicate: Predicate<T>): void { let writeIndex = 0 for (const inp...
(readonly inputs: T[], readonly maxNumberOfThreads: number = Number.POSITIVE_INFINITY) { if (maxNumberOfThreads !== Number.POSITIVE_INFINITY) checkNat(maxNumberOfThreads) } /** Parallel [[mapMutate]]. */ async map(mapper: (element: T, index: number) => Promise<T>): Promise<void> { const { inputs, maxNumberOf...
constructor
identifier_name
array.ts
inputs.length; index++) inputs[index] = getNewValue(inputs[index], index) } /** Delete elements of an array not satisfying `predicate`. If `predicate` throws, the array will be left in a bad state. */ export function filterMutate<T>(inputs: T[], predicate: Predicate<T>): void { let writeIndex = 0 for (const input...
/** Parallel [[mapMutate]]. */ async map(mapper: (element: T, index: number) => Promise<T>): Promise<void> { const { inputs, maxNumberOfThreads } = this let writeIndex = 0 let readIndex = 0 while (readIndex < maxNumberOfThreads && readIndex < inputs.length) startOne() while (readIndex < inputs.length...
{ if (maxNumberOfThreads !== Number.POSITIVE_INFINITY) checkNat(maxNumberOfThreads) }
identifier_body
main.rs
Error> { fern::Dispatch::new() .format(|out, message, record| unsafe { out.finish(format_args!( "{}[{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), libc::pthread_self(), message )) }) .level(log::LevelFilter::Info) .chain(fe...
fn get_virtual_link(&self) -> VirtualLink { VirtualLink::to_iface(self) } } /*============================================================================== * Host * */ struct Host { nic: NetworkInterface, } impl Host { fn new() -> Host { Host { nic: NetworkInterface::new(), ...
{ self.r.recv().unwrap() }
identifier_body
main.rs
Error> { fern::Dispatch::new() .format(|out, message, record| unsafe { out.finish(format_args!( "{}[{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), libc::pthread_self(), message )) }) .level(log::LevelFilter::Info) .chain(fe...
(self.total as f64) / (self.samples as f64) } } /*============================================================================== * Server * */ struct Server { id: u32, host: Host, processing_power: u64 } impl Server { fn new(id: u32, server_data: ServerData) -> Server { Server { id: id, ...
{ return 0.0; }
conditional_block
main.rs
from: (*iface).get_virtual_link(), workload: workload, origin: origin, timestamp: SystemTime::now(), } } fn answer_me_at(tx: &mpsc::Sender<Packet>, workload: u64, origin: u32, timestamp: SystemTime) -> Packet { Packet { from: VirtualLink::linked_to(tx), workload: workloa...
random_line_split
main.rs
Error> { fern::Dispatch::new() .format(|out, message, record| unsafe { out.finish(format_args!( "{}[{}] {}", chrono::Local::now().format("[%Y-%m-%d][%H:%M:%S]"), libc::pthread_self(), message )) }) .level(log::LevelFilter::Info) .chain(fe...
() -> NetworkInterface { let (tx, rx) = mpsc::channel(); NetworkInterface { s: tx, r: rx } } fn read(&self) -> Packet { self.r.recv().unwrap() } fn get_virtual_link(&self) -> VirtualLink { VirtualLink::to_iface(self) } } /*==================================================...
new
identifier_name
get_company_test.py
;q=0.9", # "Connection": "keep-alive", # "Content-Length": "18", "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8", "Cookie": "__root_domain_v=.52wmb.com; _qddaz=QD.oxnn0z.8hqf3r.kjru3sro; _QUY=wqXCh8KywpbCmMKVwplrwpzCk8KeZ8KbwpJnZnDCk2htaQ==; _DP=2; company_search_tips=...
owser里添加cookies for cookie in listCookies: cookie_dict = { 'name': cookie.get('name'), 'value': cookie.get('value'), "expires": '', 'path': '/', 'httpOnly': False, 'HostOnly': False, 'Secure': False } # 添加co...
identifier_body
get_company_test.py
# item = item.rstrip("\n") # with open('adjunct.json') as f: # con_dict = json.loads(f.read()) # # cookie_path = con_dict['cookie_filepath'] # cookie_path = 'w_cookies.txt' # mysql_db = con_dict[item]['datebase'] # data_hs = con_dict[item]['hs'] # try: # data_hs = data_hs.spl...
random_line_split
get_company_test.py
_st=3&main=0&extend_search=false&fw%5B%5D=email&filterweight=email&_' \ '=1604476115171&page={}'.format(data['key'], data['key'], pageNum) url1 = 'https://www.52wmb.com/async/company?key={}&old_key={' \ '}&country=&country_id=0&type=0&sort=default&click_search=0&st=2&old_st=2&main=...
3D&key=crane&st=2' data1 = collections.OrderedDict() data1['company_id'] = company_info['number'] # headers = { # 'Referer': 'https://www.52wmb.com/buyer/{}'.format(data1['company_id']), # 'cookie': cookiestr, # 'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (K...
wphnwpZsag%3D%
identifier_name
get_company_test.py
_st=3&main=0&extend_search=false&fw%5B%5D=email&filterweight=email&_' \ '=1604476115171&page={}'.format(data['key'], data['key'], pageNum) url1 = 'https://www.52wmb.com/async/company?key={}&old_key={' \ '}&country=&country_id=0&type=0&sort=default&click_search=0&st=2&old_st=2&main=...
) >= 1: print('有数据') strt = int(time.time()) company_info['time'] = strt company_info['tableid'] = 0 company_info['spider'] = 1 try: # 数据来源 region = html.xpath('tr[4]/td[1]/text()')[1].strip() except: region = '-' co...
html
conditional_block
main.rs
fn vectors() { let v: Vec<i32> = Vec::new(); let mut v = vec![1, 2, 3]; match v.binary_search(&16) { Ok(pos) => v.insert(pos, 16), Err(_) => v.push(16) } match v.binary_search(&12) { Ok(pos) => v.insert(pos, 12), Err(pos) => v.insert(pos, 12) } println!("...
{ vectors(); strings(); hashmaps(); }
identifier_body
main.rs
can’t have mutable // and immutable references in the same scope. That rule applies in Listing 8-7, where we hold // an immutable reference to the first element in a vector and try to add an element to the end, // which won’t work. let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.push(6)...
let hello = String::from("שָׁלוֹם"); let hello = String::from("नमस्ते"); let hello = String::from("こんにちは"); let hello = String::from("안녕하세요"); let hello = String::from("你好"); let hello = String::from("Olá"); let hello = String::from("Здравствуйте"); let hello = String::from("Hola"); ...
let hello = String::from("Dobrý den"); let hello = String::from("Hello");
random_line_split
main.rs
can’t have mutable // and immutable references in the same scope. That rule applies in Listing 8-7, where we hold // an immutable reference to the first element in a vector and try to add an element to the end, // which won’t work. let mut v = vec![1, 2, 3, 4, 5]; let first = &v[0]; v.push(6)...
let mut s = String::new(); let m = String::from("sdfsdf"); let data = "initial contents"; let s = data.to_string(); // the method also works on a literal directly: let s = "initial contents".to_string(); let hello = String::from("السلام عليكم"); let hello = String::from("Dobrý den"); ...
s() {
identifier_name
protocol.py
0000000000000ccff41007200690061006c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" self.msg_blob = self.msg_blob.decode('hex') print "UDP start" self.poll_messages() self.hello_everybody_lc = task.LoopingCall(sel...
(self, data): seq = struct.unpack("<I", data[1:5])[0] # print "remote => i got #%s" % seq lc = self.resenders.get(seq) if lc: lc.stop() del self.resenders[seq] del self.tries[seq] def resend_message(self, seq, packet, addr): ...
invalidate_resender
identifier_name
protocol.py
action = msg.get("action") print data if action == "start": for bot in self.bots: for login in [bot.logins.get(id) for id, online in bot.online.items() if online]: self.player_came(bot.name, login) ...
def send_json(self, obj): self.transport.write(json.dumps(obj), self.node_io_addr) def datagramReceived(self, data, addr): msg = json.loads(data)
random_line_split
protocol.py
0000000000000ccff41007200690061006c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" self.msg_blob = self.msg_blob.decode('hex') print "UDP start" self.poll_messages() self.hello_everybody_lc = task.LoopingCall(sel...
def timeout(self): self.log.error(u"Garena did not send WELCOME packet in 45 seconds, dropping connection now") self.transport.loseConnection() def dataReceived(self, data): self.buffer += data self.decodeHeader() def decodeHeader(self): if len(...
self.log = logging.getLogger("GRSP[%s]" % self.factory.account.login) self.log.info(u"connection made, sending auth packet") self.write_hex(self.factory.packet) self.log.info(u"issuing disconnect in 45 seconds if Garena did not respond with WELCOME") self.timeout_deferred...
identifier_body
protocol.py
0000000000000ccff41007200690061006c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" self.msg_blob = self.msg_blob.decode('hex') print "UDP start" self.poll_messages() self.hello_everybody_lc = task.LoopingCall(sel...
def handle_hello(self, data): id = struct.unpack("<I", data[4:8])[0] addr = self.factory.bot.addr(id) if addr: reply = struct.pack("< I I 4x I", 15, self.factory.account.id, id) self.transport.write(reply, addr) class GarenaRSProtocol(Proto...
self.tries[seq] += 1 self.transport.write(packet, addr) # print "sending #%s, tries: %s" % (seq, self.tries[seq]) if self.tries[seq] > 6: lc.stop() del self.resenders[seq] del self.tries[seq]
conditional_block
WeightedSum.go
// The basic idea of WeightedSum is to substitute the WeightedSum equation to // many Ci*Xi=Hi, so that a Sum constraint results with H1+H2+...+Hn=Z. This // Sum constraint is substituted as well with X+Y=Z equations (see Sum // constraint for more information). type WeightedSum struct { vars []core.VarId ...
random_line_split
WeightedSum.go
, this.outCh = store.RegisterPropagatorMap(allvars, this.id) this.varidToDomainMap = core.GetVaridToIntervalDomains(domains) this.store = store } // SetID is used by the store to set the propagator's ID, don't use it // yourself or bad things will happen func (this *WeightedSum) SetID(propID core.PropId) { this.i...
{ return this.inCh }
identifier_body
WeightedSum.go
.varidToDomainMap, this.pseudoPropsXYZ, evt) } // initialCheck check for changes. First look for X*C=Y propagators, then // X+Y=Z and finally for the final propagator X=Y. Collect changes func (this *WeightedSum) ivweightSumInitialCheck(evt *core.ChangeEvent) { this.checkXmultCeqY(-1, evt) hvarXCY := make([]core.V...
{ removeParts = append(removeParts, xPart.DIFFERENCE_MIN_MAX(minY, maxY)...) if xPart.GT(maxY) { removeParts = append(removeParts, firstOutDomain.GetParts()[i:]...) break } }
conditional_block
WeightedSum.go
i++ } for _, v := range this.hvars { allvars[i] = v i++ } allvars[i] = this.resultVar var domains map[core.VarId]core.Domain this.inCh, domains, this.outCh = store.RegisterPropagatorMap(allvars, this.id) this.varidToDomainMap = core.GetVaridToIntervalDomains(domains) this.store = store } // SetID is u...
GetDomains
identifier_name
1505.js
-------------- var CITY = $.cookie('city'); var urlTemp = dxlHttp.m + "index/jsonpnew/index?act=hunShaList&callback=?&"; //瀑布流接口 var groupSubmit = $(".group.submit"); //筛选 确认按钮 var loadWrap = $(".loadWrap"); //加载提示 var allSellerSpan = $(".allSeller .selectShow span"); //全部商区 span var allStyleSpan = $("....
$("footer").remove(); }; // ---------------------
conditional_block
1505.js
框,匹配价格tag $(".priceRange input").on("input", function () { var minPriceInputVal = parseInt(minPriceInput.val()) || ""; var maxPriceInputVal = parseInt(maxPriceInput.val()) || ""; var priceStr = minPriceInputVal + "-" + maxPriceInputVal; $(this).parent().parent().siblings().find("span").removeClass("s...
identifier_body
1505.js
("display", 'block'); //关闭广告条 $(".banner .close").touchClick(function (e) { e.stopPropagation(); e.preventDefault(); $(".banner").slideUp(500); }) //底部app下载调用 $.wFootAppDown(); //返回顶部 $.mTopCall(); //搜索 $.mSearch(function () { $.dxlGaPageTracker("/VPTracker/WapHunShaSheYing/Search");...
//动态取值 排序区域宽高 sortUlWidth() $(window).on("resize", sortUlWidth); //全部商户 婚宴/婚纱/婚庆业务切换 $(".selectTag").touchClick(function () { $(".allStyle").find(".active").removeClass("active"); $(this).parent().addClass("active"); }); //点击显示筛选条目 $(".selectShow").touchClick(function (e) { //添加虚拟url ...
random_line_split
1505.js
pl: tpl, dom: "ul", //竖列容器元素标签(可省略) selector: "#sellerList", //瀑布流容器 preLoad: false, //无图片或无需预加载时设为false, 默认为true(可省略) imgUrl: "path", initNum: 15, //初始化获取数量 newNum: 15, //每次新获取数量 watchHeight: 100 //页面离底部多远拉取数据,单位px(可省略) }, "haddle": { "onLoading": onLoading, "onLoad...
*/ (d
identifier_name
udpopnet_random.py
range(0, npop): if (i != l): if(link[l]==0): if(net[j][l]==1): linkcopy[l]=k link = copy.deepcopy(linkcopy) #print link for j in range(0, npop): if(link[j]>maxdiameter): maxdiameter=link[j] #print "diameter: ", maxdiameter # alternative could return diamete...
(net,npop): # what fraction of the nodes are terminal nodes # these only have one connection in the rows term = 0 for i in range(0, npop): rowsum = 0 for j in range(0, npop): rowsum = rowsum + net[i][j] if(rowsum == 1): term = term + 1 #print rowsum #print term return float(term)/float(npop) for ...
terminalness
identifier_name
udpopnet_random.py
link = copy.deepcopy(linkcopy) #print link for j in range(0, npop): if(link[j]>maxdiameter): maxdiameter=link[j] #print "diameter: ", maxdiameter # alternative could return diameter by uncommenting below #return maxdiameter #print "linearness: ", (float(maxdiameter)-1)/(float(npop)-2) retu...
if(npop == 2): return 1 else: # determine the distance between all popualtion pairs maxdiameter=0 for i in range(1, npop): link = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] linkcopy = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] for k in range(1, npop): for j in range(0, npop): if (i != j): ...
identifier_body
udpopnet_random.py
in range(0, npop): if (i != l): if(link[l]==0): if(net[j][l]==1): linkcopy[l]=k link = copy.deepcopy(linkcopy) #print link for j in range(0, npop): if(link[j]>maxdiameter): maxdiameter=link[j] #print "diameter: ", maxdiameter # alternative could return diam...
# calculate distance in allele frequency between popualtions def dist(freq): distance=0 for i in range(0, nodes): for j in range(0, nodes): distance=distance+abs(freq[i]-freq[j]) return distance def terminalness(net,npop): # what fraction of the nodes are terminal nodes # these only have one connection in th...
return diff
random_line_split
udpopnet_random.py
range(0, npop): if (i != l): if(link[l]==0): if(net[j][l]==1): linkcopy[l]=k link = copy.deepcopy(linkcopy) #print link for j in range(0, npop): if(link[j]>maxdiameter): maxdiameter=link[j] #print "diameter: ", maxdiameter # alternative could return diamete...
totedge=(sum(edgesum)/2) #print "Then total number of edges in the matrix: %i" % totedge totbridge=sum(bridges)/2 #print "The total number of bridges in the network: %i" % totbridge #Sums the total number of non-terminal edges. #nontbedge=float(len(unique(bridgeconnect))) #Checks if the bridges involving non-te...
if net[i][j]==net[j][i]==1: bridgeconnect.append(str(i)+str(j)) if sum(net[i])==3: threebridgeconnect.append(i)
conditional_block
transcribe.py
if not line.endswith(BR): print "SKIP", line, continue line = line[0:-len(BR)] if line[0].isdigit(): try: lastLineNo = int(line) except ValueError: if PRINT_PRE: print >>o, line, BR, els...
(o, dialogue, pageNo, lastLineNo, speaker): if dialogue: printDialogue(o, dialogue) dialogue = Dialogue(pageNo, lastLineNo, speaker) return dialogue def parsePageAnchor(anchor): # e.g., # <A name=38></a>35<br> # The first number is produced by the pdftohtml conversion; # the seco...
switchDialogue
identifier_name
transcribe.py
if not line.endswith(BR): print "SKIP", line, continue line = line[0:-len(BR)] if line[0].isdigit(): try: lastLineNo = int(line) except ValueError: if PRINT_PRE: print >>o, line, BR, ...
pageAnchor = line if PRINT_PRE: print >>o, line continue
conditional_block
transcribe.py
if not line.endswith(BR): print "SKIP", line, continue line = line[0:-len(BR)] if line[0].isdigit(): try: lastLineNo = int(line) except ValueError: if PRINT_PRE: print >>o, line, BR, els...
def parsePage(o, i, p, pageAnchor, dialogue, lastLineNo = None): global examiner print "page", p prevLineNo = None pageNo = parsePageAnchor(pageAnchor) print >>o, '<a name=p%02d></a>' % (pageNo, ) for line in i: # these are eaten by the outer loop assert not line.sta...
return int(anchor.split('>')[2].split('<')[0])
identifier_body
transcribe.py
if not line.endswith(BR): print "SKIP", line, continue line = line[0:-len(BR)] if line[0].isdigit(): try: lastLineNo = int(line) except ValueError: if PRINT_PRE: print >>o, line, BR, els...
if line.count(' ') < 2: if dialogue is None or dialogue.speaker != 'Narrator': dialogue = switchDialogue(o, dialogue, pageNo, lastLineNo, speaker=line[0:-1]) else: if line != 'THE COURT:': dialogue.addLine(line) ...
elif line.endswith(':'):
random_line_split
order.go
NoStorageException, _ := logic.VerifyGoodsNum(goodsIdMap, goodsList) // 获取 goodsId 信息 shipTimeList := []string{"XX", "XX"} // shipTimeList := logic.GetShipTime() // 获取用户所有地址 myAddressList, err := daoSql.GetAddressListByUid(uid, false) if nil != err && RecordEmpty != err { // log return util.Fail(ctx, 10, er...
} // 确认信息页 form-> goods_list:[{"goods_id":"3","selected":"1","goods_num":"2"}] func (OrderController) DoOrder(ctx echo.Context) error { // 设置 redis key uid := ctx.Get("uid").(uint64) // 避免同一个订单重复提交 // data, _ := json.Marshal(ctx.Request()) // curOrderMd5 = fmt.Printf("%x", md5.Sum(data)) // preOrderMd5 := daoR...
random_line_split
order.go
StorageException, _ := logic.VerifyGoodsNum(goodsIdMap, goodsList) // 获取 goodsId 信息 shipTimeList := []string{"XX", "XX"} // shipTimeList := logic.GetShipTime() // 获取用户所有地址 myAddressList, err := daoSql.GetAddressListByUid(uid, false) if nil != err && RecordEmpty != err { // log return util.Fail(ctx, 10, err....
uid := uint64(10) orderSn := ctx.FormValue("order_sn") cancelFlag := util.Atoi(ctx.FormValue("cancel_flag"), 16, false).(uint16) err := logic.CancelOrder(uid, orderSn, cancelFlag) if nil != err { return util.Fail(ctx, 10, err.Error()) } return util.Success(ctx, nil) } // 订单列表页 func (OrderController) EvalOrd ...
"goodsList"].([]*daoSql.OrderGoods) { arrApiOrderGoods[idx] = &apiIndex.OrderGoods{OrderGoods: item} } orderData.List = append(orderData.List, &apiIndex.Order{ Address: (*apiIndex.AddressType)(v["addressInfo"].(*daoSql.Address)), OrderInfo: apiIndex.OrderInfo{ Order: &apiIndex.OrderBase{Order: v["...
identifier_body
order.go
= append(goodsIdList, goodsInfo.GoodsId) } } } // 获取 商品详情 goodsException, goodsIdMap, _ := logic.GetCartInfo(goodsIdList) // 验证并修正库存信息 如果只有3个,购买5个,会强制改为3个 goodsNoStorageException, _ := logic.VerifyGoodsNum(goodsIdMap, goodsList) // 获取地址信息 address, err := fetchAddress(ctx) if nil != err { return util....
cancelRea
identifier_name
order.go
StorageException, _ := logic.VerifyGoodsNum(goodsIdMap, goodsList) // 获取 goodsId 信息 shipTimeList := []string{"XX", "XX"} // shipTimeList := logic.GetShipTime() // 获取用户所有地址 myAddressList, err := daoSql.GetAddressListByUid(uid, false) if nil != err && RecordEmpty != err { // log return util.Fail(ctx, 10, err....
goodsIdMap, _ := logic.GetCartInfo(goodsIdList) // 验证并修正库存信息 如果只有3个,购买5个,会强制改为3个 goodsNoStorageException, _ := logic.VerifyGoodsNum(goodsIdMap, goodsList) // 获取地址信息 address, err := fetchAddress(ctx) if nil != err { return util.Fail(ctx, 10, "地址信息无效") } // 读入配置信息 orderConf, err := daoConf.OrderConf() if ni...
fo.GoodsId) } } } // 获取 商品详情 goodsException,
conditional_block
symbol.ts
'; import { SymbolOptionMixin, ZRColor } from './types'; import { parsePercent } from './number'; export type ECSymbol = graphic.Path & { __isEmptyBrush?: boolean setColor: (color: ZRColor, innerColor?: ZRColor) => void getColor: () => ZRColor }; type SymbolCtor = { new(): ECSymbol }; type SymbolShapeMaker...
rect: graphic.Rect as unknown as SymbolCtor, roundRect: graphic.Rect as unknown as SymbolCtor, square: graphic.Rect as unknown as SymbolCtor, circle: graphic.Circle as unknown as SymbolCtor, diamond: Diamond as unknown as SymbolCtor, pin: Pin as unknown as SymbolCtor, arrow: Arrow as u...
*/ // TODO Use function to build symbol path. const symbolCtors: Dictionary<SymbolCtor> = { line: graphic.Line as unknown as SymbolCtor,
random_line_split
symbol.ts
boolean setColor: (color: ZRColor, innerColor?: ZRColor) => void getColor: () => ZRColor }; type SymbolCtor = { new(): ECSymbol }; type SymbolShapeMaker = (x: number, y: number, w: number, h: number, shape: Dictionary<any>) => void; /** * Triangle shape * @inner */ const Triangle = graphic.Path.extend({ ...
createSymbol
identifier_name
symbol.ts
import { SymbolOptionMixin, ZRColor } from './types'; import { parsePercent } from './number'; export type ECSymbol = graphic.Path & { __isEmptyBrush?: boolean setColor: (color: ZRColor, innerColor?: ZRColor) => void getColor: () => ZRColor }; type SymbolCtor = { new(): ECSymbol }; type SymbolShapeMaker = ...
}); // Provide setColor helper method to avoid determine if set the fill or stroke outside function symbolPathSetColor(this: ECSymbol, color: ZRColor, innerColor?: ZRColor) { if (this.type !== 'image') { const symbolStyle = this.style; if (this.__isEmptyBrush) { symbolStyle.stroke = co...
{ let symbolType = shape.symbolType; if (symbolType !== 'none') { let proxySymbol = symbolBuildProxies[symbolType]; if (!proxySymbol) { // Default rect symbolType = 'rect'; proxySymbol = symbolBuildProxies[symbolType]; }...
identifier_body
main.rs
root.step_in_direction(&d))) .filter_map(|(d, p)| match gd.get(&p) { Some(Tile::Unexplored) | None => Some((d, p)), Some(_) => None, }) .collect::<Vec<_>>(); for (d, target) in unexplored { let (ended_u...
(gd: &GameDisplay<Tile>, pos: &(Word, Word), target: &(Word, Word)) -> Option<Vec<Direction>> { //println!("path_to: {:?} to {:?}", pos, target); use std::collections::{HashMap, BinaryHeap}; use std::collections::hash_map::Entry; use std::cmp; let mut ret = Vec::new(); let mut work = BinaryHea...
path_to
identifier_name
main.rs
root.step_in_direction(&d))) .filter_map(|(d, p)| match gd.get(&p) { Some(Tile::Unexplored) | None => Some((d, p)), Some(_) => None, }) .collect::<Vec<_>>(); for (d, target) in unexplored { let (ended_u...
if alt < *dist.get(&p2).unwrap_or(&usize::max_value()) { //println!(" {:?} --{:?}--> {:?}", p, dir, p2); dist.insert(p2, alt); prev.insert(p2, p); work.push(cmp::Reverse((alt, p2))); } } } None } #[test] fn test...
} } for (p2, dir) in adjacent(gd, &p) { let alt = steps_here + 1;
random_line_split
booting.py
(msg) # should we run configure for all the wan devices? or just wan? for x in devices: # if isinstance(x, DebianWAN): # does not work for mitm if hasattr(x, "name") and "wan" in x.name: logger.info(f"Configuring {x.name}") x.configure(config=config) # if more than 1...
# Start to connect all clients after registartions done: for client in wifi_clients: check_and_connect_to_wifi(devices, client) logger.info(colored("\nWlan clients:", color="green")) devices.wlan_clients.registered_clients_summary()
devices.wlan_clients.register(client)
conditional_block
booting.py
devices.sipcenter, devices.softphone, ] if env_helper.get_external_voip(): dev_list.append(devices.softphone2) dev_list.append(getattr(devices, "FXS", [devices.lan, devices.lan2])) boardfarm.lib.voice.voice_configure( dev_list, ...
run_actions
identifier_name
booting.py
import boardfarm.lib.booting import boardfarm.lib.voice from boardfarm.devices.debian_lan import DebianLAN from boardfarm.exceptions import ( BootFail, CodeError, DeviceDoesNotExistError, NoTFTPServer, ) from boardfarm.lib.booting_utils import check_and_connect_to_wifi from boardfarm.library import chec...
import time import traceback import warnings
random_line_split
booting.py
x.configure(config=config) # if more than 1 tftp server should we start them all? # currently starting the 1 being used logger.info(f"Starting TFTP server on {tftp_device.name}") tftp_device.start_tftp_server() devices.board.tftp_device = tftp_device def pre_boot_lan_clients(config, e...
if env_helper.get_dns_dict(): # to get reachable and unreachable ips for ACS DNS devices.wan.auth_dns = True dns_acs_config(devices, env_helper.get_dns_dict()) tftp_device, tftp_servers = boardfarm.lib.booting.get_tftp(config) if not tftp_servers: logger.error(colored("No tftp s...
identifier_body
transaction.go
() bool { return f.FCTInputs != nil && // This array should not be nil f.Signatures != nil && !f.TimestampSalt.IsZero() } // IsPopulated returns true if s has already been successfully populated by a // call to Get. IsPopulated returns false if s.SignatureBlock or // s.ReedeemCondition are nil func (s FactoidTran...
IsPopulated
identifier_name
transaction.go
Valid returns if the inputs of the factoid transaction are properly signed // by the redeem conditions. It will also validate the total inputs is greater // than the total outputs. func (f *FactoidTransaction) Valid() bool { if !f.IsPopulated() { return false } // Validate amounts if f.TotalFCTInputs() < f.Tota...
return data, nil } // MarshalHeaderBinary marshals the transaction's header to its binary // representation. See UnmarshalHeaderBinary for encoding details. func (f *FactoidTransaction) MarshalHeaderBinary() ([]byte, error) { version := varintf.Encode(f.Version) data := make([]byte, TransactionHeadMinLen+len(vers...
{ sig, err := s.MarshalBinary() if err != nil { return nil, err } data = append(data, sig...) }
conditional_block
transaction.go
// Valid returns if the inputs of the factoid transaction are properly signed // by the redeem conditions. It will also validate the total inputs is greater // than the total outputs. func (f *FactoidTransaction) Valid() bool { if !f.IsPopulated() { return false } // Validate amounts if f.TotalFCTInputs() < f....
{ return s.SignatureBlock != nil }
identifier_body
transaction.go
// Valid returns if the inputs of the factoid transaction are properly signed // by the redeem conditions. It will also validate the total inputs is greater // than the total outputs. func (f *FactoidTransaction) Valid() bool { if !f.IsPopulated() { return false } // Validate amounts if f.TotalFCTInputs() < f.To...
// See UnmarshalBinary for encoding details. func (io *FactoidTransactionIO) MarshalBinary() ([]byte, error) { amount := varintf.Encode(io.Amount) data := make([]byte, 32+len(amount)) var i int i += copy(data[i:], amount) i += copy(data[i:], io.Address[:]) return data, nil } // MarshalBinary marshals a transacti...
} // MarshalBinary marshals a transaction io to its binary representation.
random_line_split
core_bert.py
= q.replace(self.sub,'') # 去掉subject剩下的部分 qtKey = (self.qRaw.replace(self.sub,'(SUB)',1) + ' ||| ' + pre) # 把subject换成(sub)然后加上predicate if qtKey in qtList: scoreAP = qtList[qtKey] # 查看当前的问题有没有在知识库中出现过 self.scoreAP = scoreAP qWithoutSubSet1 = set(qWithoutSub1) qWitho...
=True) if scoreReCal > maxScore:
conditional_block
core_bert.py
self.qRaw subIndex = q.index(self.sub) qWithoutSub1 = q[:subIndex] # subject左边的部分 qWithoutSub2 = q[subIndex+lenSub:] # subject右边的部分 qWithoutSub = q.replace(self.sub,'') # 去掉subject剩下的部分 qtKey = (self.qRaw.replace(self.sub,'(SUB)',1) + ' ||| ' + pre) # 把subject换成(sub)然后加上predica...
= '' maxScore = 0 bestAnswer = set() for key in lKey: if -1 != q.find(key): # 如果问题中出现了该subject,那么我们就要考虑这个subject的triples for kb in kbDict[key]: for pre in list(kb): newAnswerCandidate = answerCandidate(key, pre, q, wP=wP) # 构建一个新的answer candidate ...
result
identifier_name
core_bert.py
self.qRaw subIndex = q.index(self.sub) qWithoutSub1 = q[:subIndex] # subject左边的部分 qWithoutSub2 = q[subIndex+lenSub:] # subject右边的部分 qWithoutSub = q.replace(self.sub,'') # 去掉subject剩下的部分 qtKey = (self.qRaw.replace(self.sub,'(SUB)',1) + ' ||| ' + pre) # 把subject换成(sub)然后加上predica...
try: lengths.append(len(x)) except TypeError: raise ValueError('`sequences` must be a list of iterables. ' 'Found non-iterable: ' + str(x)) if maxlen is None: maxlen = np.max(lengths) sample_shape = tuple() for s in sequences: ...
lengths = [] for x in sequences:
random_line_split
core_bert.py
scoreAP = 0 pre = self.pre q = self.qRaw subIndex = q.index(self.sub) qWithoutSub1 = q[:subIndex] # subject左边的部分 qWithoutSub2 = q[subIndex+lenSub:] # subject右边的部分 qWithoutSub = q.replace(self.sub,'') # 去掉subject剩下的部分 qtKey = (self.qRaw.replace(self.sub,'(...
f, sub = '', pre = '', qRaw = '', qType = 0, score = 0, kbDict = [], wS = 1, wP = 10, wAP = 100): self.sub = sub # subject self.pre = pre # predicate self.qRaw = qRaw # raw question self.qType = qType # question type self.score = score # 分数 self.kbDict = kbDict # kd dict...
identifier_body
connection.rs
2, usize>>, pub(crate) active_surface_id: RefCell<u32>, /// Repeats per second pub(crate) key_repeat_rate: RefCell<i32>, pub(crate) mem_pool: RefCell<AutoMemPool>, /// Delay before repeating, in milliseconds pub(crate) key_repeat_delay: RefCell<i32>, pub(crate) last_serial: RefCell<u32>, ...
} _ => {} } } _ => {} } if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() { if let Some(win) = self.window_by_id(window_id) { let mut inner = win.borrow_mut(); i...
{ let file = unsafe { std::fs::File::from_raw_fd(*fd) }; match format { KeymapFormat::XkbV1 => { let mut data = vec![0u8; *size as usize]; file.read_exact_at(&mut data, 0)?; // Dance around CStrin...
conditional_block
connection.rs
2, usize>>, pub(crate) active_surface_id: RefCell<u32>, /// Repeats per second pub(crate) key_repeat_rate: RefCell<i32>, pub(crate) mem_pool: RefCell<AutoMemPool>, /// Delay before repeating, in milliseconds pub(crate) key_repeat_delay: RefCell<i32>, pub(crate) last_serial: RefCell<u32>, ...
( &self, keyboard: Main<WlKeyboard>, event: WlKeyboardEvent, ) -> anyhow::Result<()> { match &event { WlKeyboardEvent::Enter { serial, surface, .. } => { // update global active surface id *self.active_surface_id...
keyboard_event
identifier_name
connection.rs
2, usize>>, pub(crate) active_surface_id: RefCell<u32>, /// Repeats per second pub(crate) key_repeat_rate: RefCell<i32>, pub(crate) mem_pool: RefCell<AutoMemPool>, /// Delay before repeating, in milliseconds pub(crate) key_repeat_delay: RefCell<i32>, pub(crate) last_serial: RefCell<u32>, ...
windows: RefCell::new(HashMap::new()), event_q: RefCell::new(event_q), pointer: RefCell::new(pointer), seat_listener, mem_pool: RefCell::new(mem_pool), gl_connection: RefCell::new(None), keyboard_mapper: RefCell::new(None), ...
random_line_split
connection.rs
, usize>>, pub(crate) active_surface_id: RefCell<u32>, /// Repeats per second pub(crate) key_repeat_rate: RefCell<i32>, pub(crate) mem_pool: RefCell<AutoMemPool>, /// Delay before repeating, in milliseconds pub(crate) key_repeat_delay: RefCell<i32>, pub(crate) last_serial: RefCell<u32>, ...
pub(crate) fn next_window_id(&self) -> usize { self.next_window_id .fetch_add(1, ::std::sync::atomic::Ordering::Relaxed) } fn flush(&self) -> anyhow::Result<()> { if let Err(e) = self.display.borrow_mut().flush() { if e.kind() != ::std::io::ErrorKind::WouldBlock { ...
{ if let Some(&window_id) = self.keyboard_window_id.borrow().as_ref() { if let Some(win) = self.window_by_id(window_id) { let mut inner = win.borrow_mut(); inner.events.dispatch(event); } } }
identifier_body
substitution.rs
forward_type_interner_methods!(Symbol, T, self_, &self_.interner); } impl<'a> types::Substitution<Symbol, RcType> for &'a Substitution<RcType> { fn new_var(&mut self) -> RcType { Substitution::new_var(*self) } fn new_skolem(&mut self, name: Symbol, kind: ArcKind) -> RcType { Substitution::n...
get_var
identifier_name
substitution.rs
pub trait Variable { fn get_id(&self) -> u32; } impl Variable for u32 { fn get_id(&self) -> u32 { *self } } pub trait VariableFactory { type Variable: Variable; fn new(&self, x: u32) -> Self::Variable; } impl VariableFactory for () { type Variable = u32; fn new(&self, x: u32) ->...
/// Updates the level of `other` to be the minimum level value of `var` and `other` pub fn update_level(&self, var: u32, other: u32) { let level = ::std::cmp::min(self.get_level(var), self.get_level(other));
random_line_split
index.ts
embed(url: string, container: Element, options?: IEmbeddOptions): Promise<Glue> { const state: { glue?: Glue; beforeInitResolve?: (value?: unknown) => void; beforeInitReject?: (reason?: unknown) => void; retryTimer?: ReturnType<typeof setTimeout>; } = {}; return new Promise((resolve, reject) => { // Add...
if (options && options.timeout) { state.retryTimer = setTimeout(() => { if (!state.glue) { retry(); } }, options.timeout); } else { reject(new Error('glue timeout')); } }); append(); }); } /** * Enables glue for the provided sourceWindow with options. * * @param sourceWind...
{ delete state.glue; }
conditional_block