file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
main.rs
#![feature(proc_macro)] #![no_std] extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate stm32f30x_hal as hal; extern crate ls010b7dh01; extern crate rn4870; extern crate embedded_graphics as graphics; extern crate panic_abort; extern crate nb; mod display; mod ble; use cortex_m::asm; use cortex_m:...
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| w.pr8().set_bit()); *r.STATE = State::Ble; } if r.EXTI.pr1.read().pr9().bit_is_set() { r.EXTI.pr1.modify(|_, w| w.pr9().set_bit()); *r.STATE = Sta...
{ let res = r.BLE.read_raw(); match res { Ok(n) => { if n < 32 { return } (*r.DRAW_BUFFER)[*r.BUFFER_POS as usize] = n; *r.BUFFER_POS += 1; if *r.BUFFER_POS == 16 { *r.BUFFER_POS = 0; } } ...
identifier_body
main.rs
#![feature(proc_macro)] #![no_std] extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate stm32f30x_hal as hal; extern crate ls010b7dh01; extern crate rn4870; extern crate embedded_graphics as graphics; extern crate panic_abort; extern crate nb; mod display; mod ble; use cortex_m::asm; use cortex_m:...
} 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
#![feature(proc_macro)] #![no_std] extern crate cortex_m; extern crate cortex_m_rtfm as rtfm; extern crate stm32f30x_hal as hal; extern crate ls010b7dh01; extern crate rn4870; extern crate embedded_graphics as graphics; extern crate panic_abort; extern crate nb; mod display; mod ble; use cortex_m::asm; use cortex_m:...
(_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
import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F import math import torch from resnet import ResNetEncoder class Policy(nn.Module): def __init__(self, env_config, num_players=2, max_entities=10): super(Policy, self).__init__() ...
(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
import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F import math import torch from resnet import ResNetEncoder class Policy(nn.Module): def __init__(self, env_config, num_players=2, max_entities=10): super(Policy, self).__init__() ...
# 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
import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F import math import torch from resnet import ResNetEncoder class Policy(nn.Module): def __init__(self, env_config, num_players=2, max_entities=10): super(Policy, self).__init__() ...
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
import torch from torch import nn from torch.distributions.categorical import Categorical from torch.nn import functional as F import math import torch from resnet import ResNetEncoder class Policy(nn.Module): def __init__(self, env_config, num_players=2, max_entities=10): super(Policy, self).__init__() ...
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
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package language import ( "errors" "strings" "golang.org/x/text/internal/language" ) // A MatchOption configures a Matcher. type MatchOption func(*matcher...
(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
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package language import ( "errors" "strings" "golang.org/x/text/internal/language" ) // A MatchOption configures a Matcher. type MatchOption func(*matcher...
func isParadigmLocale(lang language.Language, r language.Region) bool { for _, e := range paradigmLocales { if language.Language(e[0]) == lang && (r == language.Region(e[1]) || r == language.Region(e[2])) { return true } } return false } // regionGroupDist computes the distance between two regions based on...
{ // 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
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package language import ( "errors" "strings"
// 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
// Copyright 2013 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package language import ( "errors" "strings" "golang.org/x/text/internal/language" ) // A MatchOption configures a Matcher. type MatchOption func(*matcher...
else if have.maxRegion != maxRegion { if High < c { // There is usually a small difference between languages across regions. c = High } } // We store the results of the computations of the tie-breaker rules along // with the best match. There is no need to do the checks once we determine // we have a wi...
{ // 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
import cv2 import numpy as np class LaneDetector(): ''' Lane Detector - performs three key functions: 1a) detects lanes in given image using sliding window algorithm 1b) detects lanes around previously found lanes 2) calculates lane curvature 3) displays lane information Us...
(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
import cv2 import numpy as np class LaneDetector(): ''' Lane Detector - performs three key functions: 1a) detects lanes in given image using sliding window algorithm 1b) detects lanes around previously found lanes 2) calculates lane curvature 3) displays lane information Us...
# 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
import cv2 import numpy as np class LaneDetector(): ''' Lane Detector - performs three key functions: 1a) detects lanes in given image using sliding window algorithm 1b) detects lanes around previously found lanes 2) calculates lane curvature 3) displays lane information Us...
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 - given image :return left_fit, right_fit - polynomials fitting the left/right lane lines ''' ...
''' 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
import cv2 import numpy as np class LaneDetector(): ''' Lane Detector - performs three key functions: 1a) detects lanes in given image using sliding window algorithm 1b) detects lanes around previously found lanes 2) calculates lane curvature 3) displays lane information Us...
:param img - undistorted image, on which to draw the lane polygon :param left_fit - left lane values (x) :param right_fit - right lane values (x) :param M_inverse - matrix for inverse transform warping :return - img - the modified image with polygon ''...
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
// 선긋기************************************************************************* // svg : 생성 function CESVG (target, type) { var svgContainer = document.createElementNS('http://www.w3.org/2000/svg', type); target.appendChild(svgContainer); return svgContainer; } // 효과음 기본 설정 function efSound (src) { var...
}); }, // 드래그&드랍 성공 COMPLETE: function (correct, quizNum) { QUIZ.dragLine.append(quizNum); this.path = QSAll('.quiz_' + quizNum +' .svgContainer > path'); if (correct) { for (var i = 0, path, value, left1, top1, left2, top2; i < this.path.length; i++) { path = this.path[i]; value = this....
random_line_split
quiz.js
// 선긋기************************************************************************* // svg : 생성 function CESVG (target, type) { var svgContainer = document.createElementNS('http://www.w3.org/2000/svg', type); target.appendChild(svgContainer); return svgContainer; } // 효과음 기본 설정 function efSound (src) { v...
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
// 선긋기************************************************************************* // svg : 생성 function CESVG (tar
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
// 선긋기************************************************************************* // svg : 생성 function CESVG (target, type) { var svgContainer = document.createElementNS('http://www.w3.org/2000/svg', type); target.appendChild(svgContainer); return svgContainer; } // 효과음 기본 설정 function efSound (src) { v...
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
""" IntradayPriceManager connects to TradingView and stores indicators and price series in an in memory dictionary self._alerts. These indicators are then published to slack periodically. """ import datetime import json import pandas as pd import random import re import string import time import threading import webs...
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
""" IntradayPriceManager connects to TradingView and stores indicators and price series in an in memory dictionary self._alerts. These indicators are then published to slack periodically. """ import datetime import json import pandas as pd import random import re import string import time import threading import webs...
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
""" IntradayPriceManager connects to TradingView and stores indicators and price series in an in memory dictionary self._alerts. These indicators are then published to slack periodically. """ import datetime import json import pandas as pd import random import re import string import time import threading import webs...
(*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
""" IntradayPriceManager connects to TradingView and stores indicators and price series in an in memory dictionary self._alerts. These indicators are then published to slack periodically. """ import datetime import json import pandas as pd import random import re import string import time import threading import webs...
def _create_msg(self, func, params): """ _create_msg("set_auth_token", "unauthorized_user_token") """ msg = self._prepend_header(json.dumps({"m": func, "p": params})) if self._debug: print("DEBUG:", msg) return msg def _gen_session(self, type="chart"): # ...
""" Indicator params that are accepted by the tv server """ return { "rsi": { "text": "1f0fkZ72S0de2geyaUhXXw==_xwY73vljRXeew69Rl27RumLDs6aJ9NLsTYN9Xrht254BTb8uSOgccpLDt/cdRWopwJPNZx40m19yEFwJFswkSi62X4guNJYpXe4A6S9iq2n+OXM6mqWeWzDbjTl0lYmEf1ujbg7i3FvUdV/zCSrqd+iwnvvZ...
identifier_body
conv2d_compact.rs
use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction}; use crate::scalar::power_of_two; impl ConstraintSystem { pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di...
} 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
use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction}; use crate::scalar::power_of_two; impl ConstraintSystem { pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di...
} #[cfg(test)] mod tests { use super::*; use crate::scalar::slice_to_scalar; #[test] fn conv2d_compact_test() { let mut x = ConstraintSystem::new(); let input = x.mem.alloc(&[2,5,5]); let weight = x.mem.alloc(&[2,2,3,3]); let output = x.mem.alloc(&[2,3,3]); let...
{ // 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
use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction}; use crate::scalar::power_of_two; impl ConstraintSystem { pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di...
() { let mut x = ConstraintSystem::new(); let input = x.mem.alloc(&[1,4,3]); let weight = x.mem.alloc(&[1,1,3,3]); let output = x.mem.alloc(&[1,2,1]); let weight_rev = x.mem.save(x.mem[weight].reverse(3)); x.conv2d_compact(input, output, weight_rev, None, 5,ActivationF...
conv2d_compact_test_small
identifier_name
conv2d_compact.rs
use super::{ConstraintSystem, Scalar, MemoryManager, Memory, TensorAddress, SCALAR_SIZE, BigScalar, RangeFull, Range, RangeFrom, RangeTo, Id, min, Functions, ActivationFunction}; use crate::scalar::power_of_two; impl ConstraintSystem { pub fn run_conv2d_compact<T: Scalar>(mem: &MemoryManager, param: &[u32], var_di...
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
// // Copyright 2016 Gregory Trubetskoy. All Rights Reserved. //
// // 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
// // Copyright 2016 Gregory Trubetskoy. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by...
func Test_directorForwardDPToNode(t *testing.T) { dp := &IncomingDP{Name: "foo", TimeStamp: time.Unix(1000, 0), Value: 123} md := make([]byte, 20) md[0] = 1 // Ready node := &cluster.Node{Node: &memberlist.Node{Meta: md}} snd := make(chan *cluster.Msg) count := 0 go func() { for { if _, ok := <-snd; !ok...
{ 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++ } }() go directorIncomingDPMessages(rcv, d...
identifier_body
director_test.go
// // Copyright 2016 Gregory Trubetskoy. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by...
(t *testing.T) { queue := &dpQueue{} dp := &IncomingDP{} dp2 := &IncomingDP{} r := checkSetAside(dp, queue, true) if r != nil { t.Errorf("with skip, checkSetAside should return nil") } if queue.size() != 1 { t.Errorf("checkSetAside: queue size != 1") } r = checkSetAside(dp2, queue, false) if r != dp { ...
Test_director_checkSetAside
identifier_name
director_test.go
// // Copyright 2016 Gregory Trubetskoy. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by...
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
use super::context; use super::Contrapositive; use super::{Cuts, Db, Steps}; use crate::offset::{OLit, Offset, Sub}; use crate::subst::Ptr as SubPtr; use crate::{Lit, Rewind}; use alloc::vec::Vec; use core::{fmt::Display, hash::Hash, ops::Neg}; use log::debug; pub struct Search<'t, P, C> { task: Task<'t, P, C>, ...
} 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
use super::context; use super::Contrapositive; use super::{Cuts, Db, Steps}; use crate::offset::{OLit, Offset, Sub}; use crate::subst::Ptr as SubPtr; use crate::{Lit, Rewind}; use alloc::vec::Vec; use core::{fmt::Display, hash::Hash, ops::Neg}; use log::debug; pub struct Search<'t, P, C> { task: Task<'t, P, C>, ...
(&mut self) -> State<'t, P, C> { debug!("try alternative ({} left)", self.alternatives.len()); self.alternatives.pop().ok_or(false).map(|(alt, action)| { self.rewind(alt); action }) } } impl<'t, P, C> From<&Search<'t, P, C>> for Alternative<'t, P, C> { fn from(st...
try_alternative
identifier_name
search.rs
use super::context; use super::Contrapositive; use super::{Cuts, Db, Steps}; use crate::offset::{OLit, Offset, Sub}; use crate::subst::Ptr as SubPtr; use crate::{Lit, Rewind}; use alloc::vec::Vec; use core::{fmt::Display, hash::Hash, ops::Neg}; use log::debug; pub struct Search<'t, P, C> { task: Task<'t, P, C>, ...
else { self.ctx.rewind(alt.ctx_ptr); } if let Some(promises) = alt.promises { self.promises = promises; } else { assert!(self.promises.len() >= alt.promises_len); self.promises.truncate(alt.promises_len); } self.sub.rewind(&alt.s...
{ self.ctx = ctx; }
conditional_block
search.rs
use super::context; use super::Contrapositive; use super::{Cuts, Db, Steps}; use crate::offset::{OLit, Offset, Sub}; use crate::subst::Ptr as SubPtr; use crate::{Lit, Rewind}; use alloc::vec::Vec; use core::{fmt::Display, hash::Hash, ops::Neg}; use log::debug; pub struct Search<'t, P, C> { task: Task<'t, P, C>, ...
} } 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
//密封放射 var ESealedRadioactiveSourceDetail = (function() { return { init : function(){//初始化 // 区域 绑定删除事件 删除li的时候更新数据 $("#areaList1").click(function(e){ if(e.target.nodeName != "I"){//点击i的时候触发 return; } //获取i-> a-> li $(e.target).parent().parent().remove(); //所在院区 ...
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
//密封放射 var ESealedRadioactiveSourceDetail = (function() { return { init : function(){//初始化 // 区域 绑定删除事件 删除li的时候更新数据 $("#areaList1").click(function(e){ if(e.target.nodeName != "I"){//点击i的时候触发 return; } //获取i-> a-> li $(e.target).parent().parent().remove(); //所在院区 ...
identifier_body
ESealedRadioactiveSourceDetail.js
//密封放射 var ESealedRadioactiveSourceDetail = (function() { return { init : function(){//初始化 // 区域 绑定删除事件 删除li的时候更新数据 $("#areaList1").click(function(e){ if(e.target.nodeName != "I"){//点击i的时候触发 return; } //获取i-> a-> li $(e.target).parent().parent().remove(); //所在院区 ...
}, messages: { sourceCode : {//放射源编号 rangelength :$.validator.format("<div class='tisyz'><i class='tisbefore'></i>请输入{0}位的放射源编号</div>"), verifySourceCodeUnit : "<div class='tisyz'><i class='tisbefore'></i>一二位是生产单位代码</div>", verifySourceCodeYear : "<div class='tisyz'><i c...
}
random_line_split
ESealedRadioactiveSourceDetail.js
//密封放射 var ESealedRadioactiveSourceDetail = (function() { return { init : function(){//初始化 // 区域 绑定删除事件 删除li的时候更新数据 $("#areaList1").click(function(e){ if(e.target.nodeName != "I"){//点击i的时候触发 return; } //获取i-> a-> li $(e.target).parent().parent().remove(); //所在院区 ...
)//光标切入移除 }); } //数组去重 Array.prototype.unique3 = function(){ var res = []; var json = {}; for(var i = 0; i < this.length; i++){ if(!json[this[i]]){ res.push(this[i]); json[this[i]] = 1; } } return res; }
cus().blur(
identifier_name
array.ts
import { Comparer, Predicate } from "./function" import { Nat, checkNat, isNat } from "./math" import { Option, exists, iff, optional } from "./option" import { Seq } from "./seq" /** Empty immutable array. Using this instead of a literal array `[]` to avoid allocating memory. */ export const empty: ReadonlyArray<neve...
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
import { Comparer, Predicate } from "./function" import { Nat, checkNat, isNat } from "./math" import { Option, exists, iff, optional } from "./option" import { Seq } from "./seq" /** Empty immutable array. Using this instead of a literal array `[]` to avoid allocating memory. */ export const empty: ReadonlyArray<neve...
(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
import { Comparer, Predicate } from "./function" import { Nat, checkNat, isNat } from "./math" import { Option, exists, iff, optional } from "./option" import { Seq } from "./seq" /** Empty immutable array. Using this instead of a literal array `[]` to avoid allocating memory. */ export const empty: ReadonlyArray<neve...
/** 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
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate libc; mod configuration; use configuration::ServerData; use configuration::ClientData; use std::sync::mpsc; use std::thread; use std::time; use std::time::SystemTime; use std::env; /*================================================...
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
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate libc; mod configuration; use configuration::ServerData; use configuration::ClientData; use std::sync::mpsc; use std::thread; use std::time; use std::time::SystemTime; use std::env; /*================================================...
(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
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate libc; mod configuration; use configuration::ServerData; use configuration::ClientData; use std::sync::mpsc; use std::thread; use std::time; use std::time::SystemTime; use std::env; /*================================================...
let mut threads = Vec::new(); let mut servers: Vec<Server> = Vec::new(); let mut clients: Vec<Client> = Vec::new(); info!("[T0] Inicializando servidores"); let server_data: Vec<ServerData> = configuration.get_server_dataset(); let mut server_count = 0; for d in server_data { server_count += 1; ...
random_line_split
main.rs
#[macro_use] extern crate log; extern crate fern; extern crate chrono; extern crate libc; mod configuration; use configuration::ServerData; use configuration::ClientData; use std::sync::mpsc; use std::thread; use std::time; use std::time::SystemTime; use std::env; /*================================================...
() -> 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
#!/usr/bin/env python # encoding: utf-8 ''' #-------------------------------------------------------------------# # CONFIDENTIAL --- CUSTOM STUDIOS # #-------------------------------------------------------------------# # ...
机页数 driver.find_element_by_xpath('//*[@id="company_list_input"]').send_keys(random.randint(5, 9)) # 点击跳转 driver.find_element_by_xpath('//*[@id="company_list_jump"]').click() time.sleep(2) try: driver.switch_to.frame('mainFrame') # 定位验证码图片位置 xi = driver.find_element_by_xpath('...
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
#!/usr/bin/env python # encoding: utf-8 ''' #-------------------------------------------------------------------# # CONFIDENTIAL --- CUSTOM STUDIOS # #-------------------------------------------------------------------# # ...
# 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
#!/usr/bin/env python # encoding: utf-8 ''' #-------------------------------------------------------------------# # CONFIDENTIAL --- CUSTOM STUDIOS # #-------------------------------------------------------------------# # ...
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
#!/usr/bin/env python # encoding: utf-8 ''' #-------------------------------------------------------------------# # CONFIDENTIAL --- CUSTOM STUDIOS # #-------------------------------------------------------------------# # ...
) >= 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
use std::string::ToString; fn main()
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
use std::string::ToString; fn main() { vectors(); strings(); hashmaps(); } 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...
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
use std::string::ToString; fn main() { vectors(); strings(); hashmaps(); } 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...
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
from twisted.internet.protocol import ClientFactory, Protocol, DatagramProtocol from twisted.internet import reactor, task import logging import struct from gbot.util import split_by from gbot.models import Account import time, json class LocalUDPInfo(DatagramProtocol): node_io_addr = ('0.0.0.0', 8124...
(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
from twisted.internet.protocol import ClientFactory, Protocol, DatagramProtocol from twisted.internet import reactor, task import logging import struct from gbot.util import split_by from gbot.models import Account import time, json class LocalUDPInfo(DatagramProtocol): node_io_addr = ('0.0.0.0', 8124...
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
from twisted.internet.protocol import ClientFactory, Protocol, DatagramProtocol from twisted.internet import reactor, task import logging import struct from gbot.util import split_by from gbot.models import Account import time, json class LocalUDPInfo(DatagramProtocol): node_io_addr = ('0.0.0.0', 8124...
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
from twisted.internet.protocol import ClientFactory, Protocol, DatagramProtocol from twisted.internet import reactor, task import logging import struct from gbot.util import split_by from gbot.models import Account import time, json class LocalUDPInfo(DatagramProtocol): node_io_addr = ('0.0.0.0', 8124...
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
package interval import ( "bitbucket.org/gofd/gofd/core" "fmt" "strings" ) // WeightedSum represents the constraint C1*X1+C2*X2+...+Cn*Xn=Z // Its propagate functions establish arc consistency (with bounds and arc // algorithms).
// 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
package interval import ( "bitbucket.org/gofd/gofd/core" "fmt" "strings" ) // WeightedSum represents the constraint C1*X1+C2*X2+...+Cn*Xn=Z // Its propagate functions establish arc consistency (with bounds and arc // algorithms). // The basic idea of WeightedSum is to substitute the WeightedSum equation to // many...
func (this *WeightedSum) GetOutCh() chan<- *core.ChangeEvent { return this.outCh } // XplusYneqZ represents the propagator for the constraint X + Y == Z type PseudoXmultCeqY struct { x, y core.VarId c int } func (this *PseudoXmultCeqY) Clone() *PseudoXmultCeqY { prop := new(PseudoXmultCeqY) prop.x, prop.c, ...
{ return this.inCh }
identifier_body
WeightedSum.go
package interval import ( "bitbucket.org/gofd/gofd/core" "fmt" "strings" ) // WeightedSum represents the constraint C1*X1+C2*X2+...+Cn*Xn=Z // Its propagate functions establish arc consistency (with bounds and arc // algorithms). // The basic idea of WeightedSum is to substitute the WeightedSum equation to // many...
if len(removeParts) != 0 { chEntry := core.CreateChangeEntryWithValues(firstOutVarId, core.CreateIvDomainDomParts(removeParts)) evt.AddChangeEntry(chEntry) } } // X*C=Y // ivfirstInMultSecondOutARC collect changes, when first variable has changed // e.g. Y=X/C, then X is first variable func ivfirstInMultSecond...
{ removeParts = append(removeParts, xPart.DIFFERENCE_MIN_MAX(minY, maxY)...) if xPart.GT(maxY) { removeParts = append(removeParts, firstOutDomain.GetParts()[i:]...) break } }
conditional_block
WeightedSum.go
package interval import ( "bitbucket.org/gofd/gofd/core" "fmt" "strings" ) // WeightedSum represents the constraint C1*X1+C2*X2+...+Cn*Xn=Z // Its propagate functions establish arc consistency (with bounds and arc // algorithms). // The basic idea of WeightedSum is to substitute the WeightedSum equation to // many...
() []core.Domain { return core.ValuesOfMapVarIdToIvDomain(this.GetAllVars(), this.varidToDomainMap) } func (this *WeightedSum) GetInCh() <-chan *core.ChangeEntry { return this.inCh } func (this *WeightedSum) GetOutCh() chan<- *core.ChangeEvent { return this.outCh } // XplusYneqZ represents the propagator for the ...
GetDomains
identifier_name
1505.js
// -------------- // 2017.03.20 增加cookie 记录dxl= & dxlm = 值 var dxlUrlValue = $.isUrlPar("dxl")||""; var dxlmUrlValue = $.isUrlPar("dxlm")||""; // 记录各自 cookie if(dxlUrlValue){ $.cookie("dxl", dxlUrlValue); }; if(dxlmUrlValue){ $.cookie("dxlm", dxlmUrlValue); }; //--------------- $(document...
-------------- 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
// -------------- // 2017.03.20 增加cookie 记录dxl= & dxlm = 值 var dxlUrlValue = $.isUrlPar("dxl")||""; var dxlmUrlValue = $.isUrlPar("dxlm")||""; // 记录各自 cookie if(dxlUrlValue){ $.cookie("dxl", dxlUrlValue); }; if(dxlmUrlValue){ $.cookie("dxlm", dxlmUrlValue); }; //--------------- $(document...
identifier_body
1505.js
// -------------- // 2017.03.20 增加cookie 记录dxl= & dxlm = 值 var dxlUrlValue = $.isUrlPar("dxl")||""; var dxlmUrlValue = $.isUrlPar("dxlm")||""; // 记录各自 cookie if(dxlUrlValue){ $.cookie("dxl", dxlUrlValue); }; if(dxlmUrlValue){ $.cookie("dxlm", dxlmUrlValue); }; //--------------- $(document)...
//动态取值 排序区域宽高 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
// -------------- // 2017.03.20 增加cookie 记录dxl= & dxlm = 值 var dxlUrlValue = $.isUrlPar("dxl")||""; var dxlmUrlValue = $.isUrlPar("dxlm")||""; // 记录各自 cookie if(dxlUrlValue){ $.cookie("dxl", dxlUrlValue); }; if(dxlmUrlValue){ $.cookie("dxlm", dxlmUrlValue); }; //--------------- $(document...
ata.coupon_putong_id ? '<span class="sale"></span>' : "") : '') + (data.fu_flag ? '<span class="fu"></span>' : '') + '</h3>' + '</div>' + '<div class="returnCash">' + '<p class="row1">' + '<span class="big">¥'; if (data.price_min == data.price_max) { //如果最低价格 和 最高价格一样,取其中一个 html +=...
*/ (d
identifier_name
udpopnet_random.py
# generate random fully connected networks # and evaluate their properties import time import copy import random import networkx as nx import numpy as np #import matplotlib.pyplot as plt #plt.ion() plotnet = 1 # 1 if plot network, 0 is no figure outfile = open("randomnetoutput.txt", "wb") outfile.write("Node"+"\t"+ "...
(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
# generate random fully connected networks # and evaluate their properties import time import copy import random import networkx as nx import numpy as np #import matplotlib.pyplot as plt #plt.ion() plotnet = 1 # 1 if plot network, 0 is no figure outfile = open("randomnetoutput.txt", "wb") outfile.write("Node"+"\t"+ "...
def eff(net, npop): # special case for a network of 2 populations if(npop == 2): return 1 else: # determine the distance between all popualtion pairs invert=[] 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 r...
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
# generate random fully connected networks # and evaluate their properties import time import copy import random import networkx as nx import numpy as np #import matplotlib.pyplot as plt #plt.ion() plotnet = 1 # 1 if plot network, 0 is no figure outfile = open("randomnetoutput.txt", "wb") outfile.write("Node"+"\t"+ "...
# 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
# generate random fully connected networks # and evaluate their properties import time import copy import random import networkx as nx import numpy as np #import matplotlib.pyplot as plt #plt.ion() plotnet = 1 # 1 if plot network, 0 is no figure outfile = open("randomnetoutput.txt", "wb") outfile.write("Node"+"\t"+ "...
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
#!/usr/bin/python import os, sys # Pages begin as follows: # <hr> # <A name=2></a>1<br> # Beginning at page 4, the second number is an increasing page number: # <hr> # <A name=4></a>1<br> # ... # <hr> # <A name=5></a>2<br> # This is the number printed in the top-right hand corner # of the ...
(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
#!/usr/bin/python import os, sys # Pages begin as follows: # <hr> # <A name=2></a>1<br> # Beginning at page 4, the second number is an increasing page number: # <hr> # <A name=4></a>1<br> # ... # <hr> # <A name=5></a>2<br> # This is the number printed in the top-right hand corner # of the ...
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
#!/usr/bin/python import os, sys # Pages begin as follows: # <hr> # <A name=2></a>1<br> # Beginning at page 4, the second number is an increasing page number: # <hr> # <A name=4></a>1<br> # ... # <hr> # <A name=5></a>2<br> # This is the number printed in the top-right hand corner # of the ...
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
#!/usr/bin/python import os, sys # Pages begin as follows: # <hr> # <A name=2></a>1<br> # Beginning at page 4, the second number is an increasing page number: # <hr> # <A name=4></a>1<br> # ... # <hr> # <A name=5></a>2<br> # This is the number printed in the top-right hand corner # of the ...
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
package controller import ( "encoding/json" "fmt" "time" daoConf "dao/conf" daoSql "dao/sql" . "global" apiIndex "http/api" "logic" "util" "github.com/labstack/echo" ) type OrderController struct{} // 注册路由 func (self OrderController) RegisterRoute(e *echo.Group) { e.Get("/order/list", echo.HandlerFunc(s...
} // 确认信息页 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
package controller import ( "encoding/json" "fmt" "time" daoConf "dao/conf" daoSql "dao/sql" . "global" apiIndex "http/api" "logic" "util" "github.com/labstack/echo" ) type OrderController struct{} // 注册路由 func (self OrderController) RegisterRoute(e *echo.Group) { e.Get("/order/list", echo.HandlerFunc(s...
er(ctx echo.Context) error { // 获取订单列表信息 uid := uint64(10) orderSn := ctx.FormValue("order_sn") stars := util.Atoi(ctx.FormValue("stars"), 8, false).(uint8) feedback := ctx.FormValue("feedback") err := logic.EvalOrder(uid, orderSn, stars, feedback) if nil != err { return util.Fail(ctx, 10, err.Error()) } re...
"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
package controller import ( "encoding/json" "fmt" "time" daoConf "dao/conf" daoSql "dao/sql" . "global" apiIndex "http/api" "logic" "util" "github.com/labstack/echo" ) type OrderController struct{} // 注册路由 func (self OrderController) RegisterRoute(e *echo.Group) { e.Get("/order/list", echo.HandlerFunc(s...
sonList = append(cancelReasonList, tmp) } cancel.CancelReason = cancelReasonList } return cancel }
cancelRea
identifier_name
order.go
package controller import ( "encoding/json" "fmt" "time" daoConf "dao/conf" daoSql "dao/sql" . "global" apiIndex "http/api" "logic" "util" "github.com/labstack/echo" ) type OrderController struct{} // 注册路由 func (self OrderController) RegisterRoute(e *echo.Group) { e.Get("/order/list", echo.HandlerFunc(s...
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
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may no...
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
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may no...
( symbolType: string, x: number, y: number, w: number, h: number, color?: ZRColor, // whether to keep the ratio of w/h, keepAspect?: boolean ) { // TODO Support image object, DynamicImage. const isEmpty = symbolType.indexOf('empty') === 0; if (isEmpty) { symbolType =...
createSymbol
identifier_name
symbol.ts
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may no...
}); // 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
use std::fmt; use std::collections::{VecDeque, HashSet}; use intcode::{Word, util::{parse_stdin_program, GameDisplay}, Program, Registers, ExecutionState}; fn main() { let mut robot = Robot::new(parse_stdin_program()); let mut gd: GameDisplay<Tile> = GameDisplay::default(); gd.insert(robot.position(), Til...
(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
use std::fmt; use std::collections::{VecDeque, HashSet}; use intcode::{Word, util::{parse_stdin_program, GameDisplay}, Program, Registers, ExecutionState}; fn main() { let mut robot = Robot::new(parse_stdin_program()); let mut gd: GameDisplay<Tile> = GameDisplay::default(); gd.insert(robot.position(), Til...
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
import logging import time import traceback import warnings 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...
# 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() def post_boot_env(config, env_helper, ...
devices.wlan_clients.register(client)
conditional_block
booting.py
import logging import time import traceback import warnings 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...
(actions_dict, actions_name, *args, **kwargs): logger.info(colored(f"{actions_name} ACTIONS", color="green", attrs=["bold"])) for key, func in actions_dict.items(): try: logger.info(colored(f"Action {key} start", color="green", attrs=["bold"])) start_time = time.time() ...
run_actions
identifier_name
booting.py
import logging
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
import logging import time import traceback import warnings 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...
def pre_boot_lan_clients(config, env_helper, devices): for x in devices.lan_clients: if isinstance(x, DebianLAN): logger.info(f"Configuring {x.name}") x.configure() def pre_boot_wlan_clients(config, env_helper, devices): for x in getattr(devices, "wlan_clients", []): ...
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
package factom import ( "bytes" "context" "crypto/sha256" "encoding/binary" "fmt" "time" "github.com/Factom-Asset-Tokens/factom/varintf" ) type FactoidTransaction struct { // TODO: The header is usually at the top level, is this ok? FactoidTransactionHeader FCTInputs []FactoidTransactionIO FCTOutputs []...
() 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
package factom import ( "bytes" "context" "crypto/sha256" "encoding/binary" "fmt" "time" "github.com/Factom-Asset-Tokens/factom/varintf" ) type FactoidTransaction struct { // TODO: The header is usually at the top level, is this ok? FactoidTransactionHeader FCTInputs []FactoidTransactionIO FCTOutputs []...
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
package factom import ( "bytes" "context" "crypto/sha256" "encoding/binary" "fmt" "time" "github.com/Factom-Asset-Tokens/factom/varintf" ) type FactoidTransaction struct { // TODO: The header is usually at the top level, is this ok? FactoidTransactionHeader FCTInputs []FactoidTransactionIO FCTOutputs []...
// 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
package factom import ( "bytes" "context" "crypto/sha256" "encoding/binary" "fmt" "time" "github.com/Factom-Asset-Tokens/factom/varintf" ) type FactoidTransaction struct { // TODO: The header is usually at the top level, is this ok? FactoidTransactionHeader FCTInputs []FactoidTransactionIO FCTOutputs []...
// 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
import sys import codecs import time import json from scipy.spatial.distance import cosine import code from models import BertMatch import torch import torch.nn as nn import torch.nn.functional as F import math import pkuseg from elmoformanylangs import Embedder import numpy as np from pytorch_transformers import Ber...
bestAnswer = set() maxScore = scoreReCal if scoreReCal == maxScore: bestAnswer.add(aCandidate) if debug: for ai in bestAnswer: for kb in kbDict[ai.sub]: if ai.pre in kb: print(ai.sub + ' ' +ai.pre +...
=True) if scoreReCal > maxScore:
conditional_block
core_bert.py
import sys import codecs import time import json from scipy.spatial.distance import cosine import code from models import BertMatch import torch import torch.nn as nn import torch.nn.functional as F import math import pkuseg from elmoformanylangs import Embedder import numpy as np from pytorch_transformers import Ber...
= '' 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
import sys import codecs import time import json from scipy.spatial.distance import cosine import code from models import BertMatch import torch import torch.nn as nn import torch.nn.functional as F import math import pkuseg from elmoformanylangs import Embedder import numpy as np from pytorch_transformers import Ber...
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
import sys import codecs import time import json from scipy.spatial.distance import cosine import code from models import BertMatch import torch import torch.nn as nn import torch.nn.functional as F import math import pkuseg from elmoformanylangs import Embedder import numpy as np from pytorch_transformers import Ber...
a list of iterables. ' 'Found non-iterable: ' + str(x)) if maxlen is None: maxlen = np.max(lengths) sample_shape = tuple() for s in sequences: if len(s) > 0: sample_shape = np.asarray(s).shape[1:] break is_dtype_str = np.issubdtype(...
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
#![allow(dead_code)] use super::pointer::*; use super::window::*; use crate::connection::ConnectionOps; use crate::os::wayland::inputhandler::InputHandler; use crate::os::wayland::output::OutputHandler; use crate::os::x11::keyboard::Keyboard; use crate::screen::{ScreenInfo, Screens}; use crate::spawn::*; use crate::{Ap...
_ => {} } 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.keyboard_event(event); } } Ok(()) } pub...
{ 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
#![allow(dead_code)] use super::pointer::*; use super::window::*; use crate::connection::ConnectionOps; use crate::os::wayland::inputhandler::InputHandler; use crate::os::wayland::output::OutputHandler; use crate::os::x11::keyboard::Keyboard; use crate::screen::{ScreenInfo, Screens}; use crate::spawn::*; use crate::{Ap...
( &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
#![allow(dead_code)] use super::pointer::*; use super::window::*; use crate::connection::ConnectionOps; use crate::os::wayland::inputhandler::InputHandler; use crate::os::wayland::output::OutputHandler; use crate::os::x11::keyboard::Keyboard; use crate::screen::{ScreenInfo, Screens}; use crate::spawn::*; use crate::{Ap...
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
#![allow(dead_code)] use super::pointer::*; use super::window::*; use crate::connection::ConnectionOps; use crate::os::wayland::inputhandler::InputHandler; use crate::os::wayland::output::OutputHandler; use crate::os::x11::keyboard::Keyboard; use crate::screen::{ScreenInfo, Screens}; use crate::spawn::*; use crate::{Ap...
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
use std::{cell::RefCell, default::Default, fmt}; use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult}; use crate::base::{ fixed::{FixedVec, FixedVecMap}, kind::ArcKind, symbol::Symbol, types::{self, ArcType, Flags, FlagsVisitor, Skolem, Type, TypeContext, Walker}, }; use crate::ty...
(&self, var: u32) -> Option<&T> { self.variables.get(var as usize) } pub fn find_type_for_var(&self, var: u32) -> Option<&T> { let mut union = self.union.borrow_mut(); if var as usize >= union.size() { return None; } let index = union.find(var as usize); ...
get_var
identifier_name
substitution.rs
use std::{cell::RefCell, default::Default, fmt}; use union_find::{QuickFindUf, Union, UnionByRank, UnionFind, UnionResult}; use crate::base::{ fixed::{FixedVec, FixedVecMap}, kind::ArcKind, symbol::Symbol, types::{self, ArcType, Flags, FlagsVisitor, Skolem, Type, TypeContext, Walker}, }; use crate::ty...
let mut union = self.union.borrow_mut(); union.get_mut(other as usize).level = level; } pub fn set_level(&self, var: u32, level: u32) { let mut union = self.union.borrow_mut(); union.get_mut(var as usize).level = level; } pub fn get_level(&self, mut var: u32) -> 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