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
gulpfile.js
server: { baseDir: settings.dist }, ghostMode: { clicks: true, location: true, forms: true, scroll: true }, open: "external", injectChanges: true, // inject CSS changes (false force a reload) browser: ["google chrome"], scrollPro...
gulp.watch([settings.dist + '**']).on('change', function(){browserSync.reload({});notify({ message: 'Reload browser' });}); return browserSync({
random_line_split
gulpfile.js
settings.liveReload = true; // first, delete the index.html from the dist folder as we will copy it later del([settings.dist + 'index.html']); // add livereload script to the index.html gulp.src([settings.src + 'index.html']) .pipe(gulpif(argv.dev, replace(/app.min.js/g, 'app.js'))) .pipe(gulpif(argv.no...
{ // TODO log error with gutil notify.onError(function (error) { return error.message; }); this.emit('end'); }
identifier_body
transaction.rs
tokens paid for processing and storage of this transaction. pub fee: u64, /// Keys identifying programs in the instructions vector. pub program_ids: Vec<Pubkey>, /// Programs that will be executed in sequence and commited in one atomic transaction if all /// succeed. pub instructions: Vec<Inst...
<T: Serialize>( from_keypair: &Keypair, transaction_keys: &[Pubkey], program_id: Pubkey, userdata: &T, last_id: Hash, fee: u64, ) -> Self { let program_ids = vec![program_id]; let accounts = (0..=transaction_keys.len() as u8).collect(); let ins...
new
identifier_name
transaction.rs
of tokens paid for processing and storage of this transaction. pub fee: u64, /// Keys identifying programs in the instructions vector. pub program_ids: Vec<Pubkey>, /// Programs that will be executed in sequence and commited in one atomic transaction if all /// succeed. pub instructions: Vec<I...
data.extend_from_slice(&fee_data); let program_ids = serialize(&self.program_ids).expect("serialize program_ids"); data.extend_from_slice(&program_ids); let instructions = serialize(&self.instructions).expect("serialize instructions"); data.extend_from_slice(&instructions); ...
data.extend_from_slice(&last_id_data); let fee_data = serialize(&self.fee).expect("serialize fee");
random_line_split
transaction.rs
} /// An atomic transaction #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] pub struct Transaction { /// A digital signature of `account_keys`, `program_ids`, `last_id`, `fee` and `instructions`, signed by `Pubkey`. pub signature: Signature, /// The `Pubkeys` that are executing this transa...
{ let userdata = serialize(userdata).unwrap(); Instruction { program_ids_index, userdata, accounts, } }
identifier_body
getqf.py
= symbol_string.split(",") symbol_file.close() path = file.split('/') name = path[len(path)-1] name = name.split('.') index_lists[name[0]] = symbol_list return index_lists def get_data(symbollist, index_name, ext = ''): """ Takes a list of symbols, and requests the key ...
if index in keystatrows: stat_atom = stat.get_text() if stat_atom is None or stat_atom == 'N/A': stat_atom = 'NaN' table_data_list.append(stat_atom) if len(table_data_list) < 2: print full_sym...
symbol = param[0] data_lists = param[1] index = param[2] url = "http://finance.yahoo.com/q/ks?s={}+Key+Statistics".format(symbol) try: resp = urllib2.urlopen(url, timeout = 10) if resp.getcode() == 200: htmltext = BeautifulSoup(resp.read()) data_table_pattern = "...
identifier_body
getqf.py
(symbolfilepaths, csvdelim = ","): """ Takes a list of symbol file paths to respective csv files, and loads their content into a \ dictionary of file-paths to lists containing the content of the csv. The delimeter of the csv files \ defaults to a ','. """ index_lists = {} for file in symbolfilepaths: ...
load_files
identifier_name
getqf.py
and requests the key statistics page from yahoo for that company. \ Searches for all the table data for that company and returns a dictionary of symbols for keys mapped to\ a list of statistical data for that information. """ data_lists = {} for index, symbol in enumerate(symbollist): symbollist[i...
if index == 'tsxvct' or index == 'tsxvog': qfindexdict[index] = get_data(symbollist, index, '.V') elif index == 'tsxct' or index == 'tsxog': qfindexdict[index] = get_data(symbollist, index, '.TO') else: qfindexdict[index] = get_data(symbollist, index)
conditional_block
getqf.py
= symbol_string.split(",") symbol_file.close() path = file.split('/') name = path[len(path)-1] name = name.split('.') index_lists[name[0]] = symbol_list return index_lists def get_data(symbollist, index_name, ext = ''): """ Takes a list of symbols, and requests the key ...
# testindexlist = load_files(testlist) # ##end here## ##Get the data and store it in a dict of indexes to company symbols to lists of values ## qfindexdict = {} for index, symbollist in indexlist.iteritems(): if index == 'tsxvct' or index == 'tsxvog': qfindex
# # ##test grab## # testlist = ['dataFiles/nsdqct.csv']
random_line_split
main.rs
= Options::new(); // Create the file argument opts.optopt("d", "", "Specify destination file", "NAME"); // Create help flag (-h or --help) opts.optflag("h", "help", "Print this help menu"); // Create version l opts.optflag("v", "version", "Check the version you're running"); // Use th...
match file.write_all(&x) { Err(why) => { panic!("couldn't write to {}: {}", display, why.description()) }, Ok(_) => (), } } println!("successfully wrote to {}", display); } fn extract_file_name_if_empty_string(fullpath:...
for x in &finally {
random_line_split
main.rs
// https://doc.rust-lang.org/std/macro.panic.html let matches = match opts.parse(&commandline_args[1..]){ Ok(m) => { m } Err(f) => {panic!(f.to_string())} }; // Handle help flags if matches.opt_present("h"){ let brief = format!("Usage: {} FILE [options]", program); print!("...
{ const VERSION: Option<&'static str> = option_env!("CARGO_PKG_VERSION"); pretty_env_logger::init().unwrap(); // Using args() instead of args_os(), cause they never panic let commandline_args: Vec<_> = env::args().collect(); let program = commandline_args[0].clone(); // Use the getopts package Options str...
identifier_body
main.rs
= Options::new(); // Create the file argument opts.optopt("d", "", "Specify destination file", "NAME"); // Create help flag (-h or --help) opts.optflag("h", "help", "Print this help menu"); // Create version l opts.optflag("v", "version", "Check the version you're running"); // Use th...
(url: hyper::Uri, destination: &str){ let mut core = tokio_core::reactor::Core::new().unwrap(); let client = Client::configure().connector(::hyper_tls::HttpsConnector::new(4, &core.handle()).unwrap()).build(&core.handle()); let work = client.get(url); let reponse = core.run(work).unwrap(); let buf2 =...
https_download_single_file
identifier_name
update_webhook_message.rs
( self, ) -> ( UpdateWebhookMessageErrorType, Option<Box<dyn Error + Send + Sync>>, ) { (self.kind, self.source) } } impl Display for UpdateWebhookMessageError { fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult { match &self.kind { UpdateWebhookMessa...
into_parts
identifier_name
update_webhook_message.rs
embeds: Option<NullableField<&'a [Embed]>>, #[serde(skip_serializing_if = "Option::is_none")] payload_json: Option<&'a [u8]>, } /// Update a message created by a webhook. /// /// A webhook's message must always have at least one embed or some amount of /// content. If you wish to delete a webhook's message...
{ self.fields.payload_json = Some(payload_json); self }
identifier_body
update_webhook_message.rs
ContentInvalid => { f.write_str("message content is invalid") } UpdateWebhookMessageErrorType::EmbedTooLarge { .. } => { f.write_str("length of one of the embeds is too large") } UpdateWebhookMessageErrorType::TooManyEmbeds => { ...
/// of the original message is unaffected and only the embed(s) are /// modified. /// /// ```no_run /// # use twilight_http::Client; /// use twilight_embed_builder::EmbedBuilder; /// use twilight_model::id::{MessageId, WebhookId}; /// /// # #[tokio::main] async fn main() -> Result<()...
/// Create an embed and update the message with the new embed. The content
random_line_split
update_webhook_message.rs
Invalid => { f.write_str("message content is invalid") } UpdateWebhookMessageErrorType::EmbedTooLarge { .. } => { f.write_str("length of one of the embeds is too large") } UpdateWebhookMessageErrorType::TooManyEmbeds => { f....
self.fields.components = Some(NullableField(components)); Ok(self) } /// Set the content of the message. /// /// Pass `None` if you want to remove the message content. /// /// Note that if there is are no embeds then you will not be able to remove /// the content of the m...
{ validate_inner::components(components).map_err(|source| { let (kind, inner_source) = source.into_parts(); match kind { ComponentValidationErrorType::ComponentCount { count } => { UpdateWebhookMessageError { ...
conditional_block
131. Custom Exceptions - Coding.py
# %% ''' Now someone using our library can expect to trap **any** exception we raise by catching the `WebScraperException` type, or anything more specific if they prefer: ''' # %% try: raise PingTimeoutException('Ping to www.... timed out') except HTTPException as ex: print(repr(ex)) # %% ''' or more broadly...
"""General database exception""" http_status = HTTPStatus.INTERNAL_SERVER_ERROR internal_err_msg = "Database exception." user_err_msg = "We are sorry. An unexpected error occurred on our end."
identifier_body
131. Custom Exceptions - Coding.py
HTTPStatus.OK, {"id": account.account_id, "type": account.account_type} # %% ''' Now when we call our end point with different account numbers: ''' # %% get_account('abc') # %% get_account(50) # %% get_account(150) # %% get_account(250) # %% get_account(350) # %% ''' As you can see this was quite a lot of excep...
raise NegativeIntegerError('age cannot be negative')
conditional_block
131. Custom Exceptions - Coding.py
class TimeoutException(HTTPException): """Indicates a general timeout exception in http connectivity""" class PingTimeoutException(TimeoutException): """Ping time out""" class LoadTimeoutException(TimeoutException): """Page load time out""" class ParserException(WebScraperException): ...
"""Base API exception""" http_status = HTTPStatus.INTERNAL_SERVER_ERROR internal_err_msg = 'API exception occurred.' user_err_msg = "We are sorry. An unexpected error occurred on our end." def __init__(self, *args, user_err_msg = None): if args: self.internal_err_msg = ...
random_line_split
131. Custom Exceptions - Coding.py
(HTTPException): """Indicates the url is invalid (dns lookup fails)""" class TimeoutException(HTTPException): """Indicates a general timeout exception in http connectivity""" class PingTimeoutException(TimeoutException): """Ping time out""" class LoadTimeoutException(TimeoutException): ""...
InvalidUrlException
identifier_name
mode.rs
spawn(move || get_default_modes(verbose)); let currents = currents_handle.join().unwrap()?; let defaults = defaults_handle.join().unwrap()?; let displays = match d { Some(disps) => disps, None => { let mut tmp: Vec<String> = Vec::with_capacity(currents.len()); for mod...
cmd.arg("--newmode")
random_line_split
mode.rs
if default.display == disp { if verbose { println!("Switching to default mode to allow updating of the current mode"); } switch_mode(&default.name, &disp, verbose)?; // switch the display to its default mode to enable deletion of in-use mod...
{ let mut cmd = process::Command::new("xrandr"); cmd.arg("--newmode") .arg(&mode.name) .arg(&mode.clock) .arg(&mode.h_disp) .arg(&mode.h_sync_start) .arg(&mode.h_sync_end) .arg(&mode.h_total) .arg(&mode.v_disp) .arg(&mode.v_sync_start) .arg...
identifier_body
mode.rs
String, v_sync_start: String, v_sync_end: String, v_total: String, flags: String, } impl CvtMode { pub fn get_name(&self) -> &str { &self.name } /* pub fn new_empty() -> CvtMode { CvtMode { name: String::new(), clock: String::new(), h...
(w: Option<&str>, h: Option<&str>, r: Option<&str>, d: Option<&str>, n: Option<&str>, t: Option<&str>, f: Option<&str>, test: bool, save: bool, verbose: bool) -> Result<(),Error> { let current_modes = get_current_modes(verbose)?; // Use first current display mode for parameters not supplied // and as the fa...
add_mode
identifier_name
model.py
=Event) # Store underlying data model self._data_types = ('image', 'coords') self._data_type = None # Save the line style params self._width = width self._color = color self._colors = get_color_names() # averaging and length attributes self._ave...
else: self.name = name self._qt_properties = QtVectorsLayer(self) # ====================== Property getter and setters ===================== @property def _original_data(self) -> np.ndarray: return self._raw_data @_original_data.setter def _original_data(self,...
self.name = 'vectors'
conditional_block
model.py
=Event) # Store underlying data model self._data_types = ('image', 'coords') self._data_type = None # Save the line style params self._width = width self._color = color self._colors = get_color_names() # averaging and length attributes self._ave...
self.events.averaging() self._update_avg() self.refresh() def _update_avg(self): """Method for calculating average Implemented ONLY for image-like vector data """ if self._data_type == 'coords': # default averaging is supported only for 'matrix'...
Parameters ---------- value : int that defines (int, int) kernel """ self._averaging = value
random_line_split
model.py
=Event) # Store underlying data model self._data_types = ('image', 'coords') self._data_type = None # Save the line style params self._width = width self._color = color self._colors = get_color_names() # averaging and length attributes self._ave...
(self): """Method for calculating average Implemented ONLY for image-like vector data """ if self._data_type == 'coords': # default averaging is supported only for 'matrix' dataTypes return elif self._data_type == 'image': x, y = self._averagi...
_update_avg
identifier_name
model.py
averaging=Event) # Store underlying data model self._data_types = ('image', 'coords') self._data_type = None # Save the line style params self._width = width self._color = color self._colors = get_color_names() # averaging and length attributes ...
xspace = np.linspace(0, stride_x*xdim, 2 * xdim, endpoint=False) yspace = np.linspace(0, stride_y*ydim, ydim, endpoint=False) xv, yv = np.meshgrid(xspace, yspace) # assign coordinates (pos) to all pixels pos[:, 0] = xv.flatten() pos[:, 1] = yv.flatten() # pixel ...
"""To convert an image-like array with elements (y-proj, x-proj) into a position list of coordinates Every pixel position (n, m) results in two output coordinates of (N,2) Parameters ---------- vect : np.ndarray of shape (N, M, 2) """ xdim = vect.shape[0] ...
identifier_body
draw_trans_pixel_cihea.py
('--block_fnam',default=BLOCK_FNAM,help='Block shape file (%default)') parser.add_option('--trans_fnam',default=TRANS_FNAM,help='Transplanting tiff file (%default)') parser.add_option('--mask_fnam',default=MASK_FNAM,help='Mask file (%default)') parser.add_option('--output_fnam',default=OUTPUT_FNAM,help='Output figure n...
(longitude,latitude): utm_zone = (int(1+(longitude.mean()+180.0)/6.0)) is_northern = (1 if latitude.mean() > 0 else 0) utm_coordinate_system = osr.SpatialReference() utm_coordinate_system.SetWellKnownGeogCS('WGS84') # Set geographic coordinate system to handle lat/lon utm_coordinate_system.SetUTM(ut...
transform_wgs84_to_utm
identifier_name
draw_trans_pixel_cihea.py
('--block_fnam',default=BLOCK_FNAM,help='Block shape file (%default)') parser.add_option('--trans_fnam',default=TRANS_FNAM,help='Transplanting tiff file (%default)') parser.add_option('--mask_fnam',default=MASK_FNAM,help='Mask file (%default)') parser.add_option('--output_fnam',default=OUTPUT_FNAM,help='Output figure n...
if opts.add_tmax: if not tmax in values: if ds > 1.0: values.append(tmax) labels.append(dmax.strftime('%Y-%m')) else: values.append(tmax) labels.append(dmax.strftime('%m/%d')) torg = date2num(datetime(dmin.year,1,1)) twid = 365.0*2.0 newcolors = mymap...
if not tmin in values: if ds > 1.0: values.append(tmin) labels.append(dmin.strftime('%Y-%m')) else: values.append(tmin) labels.append(dmin.strftime('%m/%d'))
conditional_block
draw_trans_pixel_cihea.py
('--block_fnam',default=BLOCK_FNAM,help='Block shape file (%default)') parser.add_option('--trans_fnam',default=TRANS_FNAM,help='Transplanting tiff file (%default)') parser.add_option('--mask_fnam',default=MASK_FNAM,help='Mask file (%default)') parser.add_option('--output_fnam',default=OUTPUT_FNAM,help='Output figure n...
if opts.batch: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm as cm from matplotlib.colors import ListedColormap,LinearSegmentedColormap,to_rgba from matplotlib.dates import date2num,num2date from matplotlib.path import Path def transform_wgs84_to_utm(longitude,la...
if not opts.debug: warnings.simplefilter('ignore')
random_line_split
draw_trans_pixel_cihea.py
('--block_fnam',default=BLOCK_FNAM,help='Block shape file (%default)') parser.add_option('--trans_fnam',default=TRANS_FNAM,help='Transplanting tiff file (%default)') parser.add_option('--mask_fnam',default=MASK_FNAM,help='Mask file (%default)') parser.add_option('--output_fnam',default=OUTPUT_FNAM,help='Output figure n...
if opts.add_coords: center_x = 107.268 center_y = -6.839 lon = np.arange(107+10/60,107+23/60,2.0/60.0) lat = np.arange(-6-56/60,-6.756,2.0/60.0) xg,yg = np.meshgrid(lon,lat) x,y,z = transform_wgs84_to_utm(xg,yg) ind_x = np.argmin(np.abs(lon-center_x)) ind_y = np.argmin(np.abs(lat-cente...
utm_zone = (int(1+(longitude.mean()+180.0)/6.0)) is_northern = (1 if latitude.mean() > 0 else 0) utm_coordinate_system = osr.SpatialReference() utm_coordinate_system.SetWellKnownGeogCS('WGS84') # Set geographic coordinate system to handle lat/lon utm_coordinate_system.SetUTM(utm_zone,is_northern) wg...
identifier_body
base.py
', 'required']: return MODE_REQUIRED elif mode in ['auto', 'automatic']: return MODE_AUTOMATIC else: if mode not in ['off', 'disable', 'disabled']: logger.warning("Watchdog mode {0} not recognized, disabling watchdog".format(mode)) return MODE_OFF def synchronized(f...
(self: 'Watchdog', *args: Any, **kwargs: Any) -> Any: with self.lock: return func(self, *args, **kwargs) return wrapped class WatchdogConfig(object): """Helper to contain a snapshot of configuration""" def __init__(self, config: Config) -> None: watchdog_config = config.get("wa...
wrapped
identifier_name
base.py
', 'required']: return MODE_REQUIRED elif mode in ['auto', 'automatic']: return MODE_AUTOMATIC else: if mode not in ['off', 'disable', 'disabled']: logger.warning("Watchdog mode {0} not recognized, disabling watchdog".format(mode)) return MODE_OFF def synchronized(f...
return True def _set_timeout(self) -> Optional[int]: if self.impl.has_set_timeout(): self.impl.set_timeout(self.config.timeout) # Safety checks for watchdog implementations that don't support configurable timeouts actual_timeout = self.impl.get_timeout() if se...
logger.error("Configuration requires watchdog, but watchdog could not be activated") return False
conditional_block
base.py
', 'required']: return MODE_REQUIRED elif mode in ['auto', 'automatic']: return MODE_AUTOMATIC else: if mode not in ['off', 'disable', 'disabled']: logger.warning("Watchdog mode {0} not recognized, disabling watchdog".format(mode)) return MODE_OFF def synchronized(f...
# Safety checks for watchdog implementations that don't support configurable timeouts actual_timeout = self.impl.get_timeout() if self.impl.is_running and actual_timeout < self.config.loop_wait: logger.error('loop_wait of {0} seconds is too long for watchdog {1} second timeout' ...
self.impl.set_timeout(self.config.timeout)
random_line_split
base.py
) -> None: watchdog_config = config.get("watchdog") or {'mode': 'automatic'} self.mode = parse_mode(watchdog_config.get('mode', 'automatic')) self.ttl = config['ttl'] self.loop_wait = config['loop_wait'] self.safety_margin = watchdog_config.get('safety_margin', 5) self.d...
"""Returns the current keepalive timeout in effect."""
identifier_body
db_viewer.go
:= listCourses(s) for _, c := range courses { lang, err := strconv.Atoi(string(c.Code[1])) if err != nil { log.Printf("Couldn't get language digit, %v", err) continue } var equiv string if lang < 5 && lang >= 0 { equiv = c.Id[:4] + strconv.Itoa(lang+4) + c.Id[5:] } else if lang >= 5 && lang < 10 ...
random_line_split
db_viewer.go
} defer func() { err := store.Close() if err != nil { log.Printf("Error closing dskvs: %v", err) } }() if *flagCourse { for _, c := range listCourses(store) { log.Printf("len(c.Id)=%d, c.Id=\"%s\"", len(c.Id), c.Id) fmt.Printf("%+v\n", c) } } if *valCourse != "" { key := COURSE_COLL + dskv...
readDegreeUrlList
identifier_name
db_viewer.go
json:"extra"` LastUpdated time.Time `json:"updated"` } func main() { flagCourse := flag.Bool( "courses", false, "print courses in the datastore", ) flagTopic := flag.Bool( "topics", false, "print topics in the datastore", ) flagDegree := flag.Bool( "degrees", false, "print degrees in the dat...
var degrees []Degree for _, b := range results { d := Degree{} if err := json.Unmarshal(b, &d); err != nil { log.Printf("Couldn't unmarshal degrees from store, %v", err) continue } degrees = append(degrees, d) } return degrees } func doDegreeBackfill(s *dskvs.Store) { degreeChan := make(chan Degree...
{ log.Printf("Couldn't query back saved degrees, %v", err) return nil }
conditional_block
db_viewer.go
_, d := range listDegrees(store) { fmt.Printf("%+v\n", d) } } if *valDegree != "" { key := DEGREE_COLL + dskvs.CollKeySep + *valDegree val, ok, err := store.Get(key) if !ok { log.Printf("Not found : %v", key) } else if err != nil { log.Printf("Error %v", err) } else { log.Printf(string(val))...
{ deg := Degree{Url: DEGREE_URL + degreePage, LastUpdated: time.Now()} t0 := time.Now() doc, err := goquery.NewDocument(deg.Url) if err != nil { log.Printf("Error getting degree doc %s, %v", degreePage, err) return deg, err } log.Printf("readDegreePage Reading <%s> done in %s\n", deg.Url, time.Since(t0))...
identifier_body
ic4164.rs
The 4164 is 1-bit memory that is stored /// in a 256x256 matrix internally, but we don't have either u1 or u256 types (bools /// don't count; they actually take up much more than 1 bit of memory space). Instead we /// pack the bits into an array of 2048 u32s, which we then address through a function //...
{ float!(self.pins[Q]); self.col = None; self.data = None; }
conditional_block
ic4164.rs
= (col & 0b1110_0000) >> 5; let bit_index = col & 0b0001_1111; (row_index | col_index, bit_index) } /// Retrieves a single bit from the memory array and sets the level of the Q pin to the /// value of that bit. fn read(&self) { let (index, bit) = self.resolve(); let va...
clear!(tr[WE]);
random_line_split
ic4164.rs
, vcc, vss]; let addr_pins = RefVec::with_vec( IntoIterator::into_iter(PA_ADDRESS) .map(|pa| clone_ref!(pins[pa])) .collect::<Vec<PinRef>>(), ); let device: DeviceRef = new_ref!(Ic4164 { pins, addr_pins, memory: [0;...
read_write_one_bit
identifier_name
ic4164.rs
bit_index) } /// Retrieves a single bit from the memory array and sets the level of the Q pin to the /// value of that bit. fn read(&self) { let (index, bit) = self.resolve(); let value = (self.memory[index] & (1 << bit)) >> bit; set_level!(self.pins[Q], Some(value as f64)) ...
{ let (_, tr, _) = before_each(); // Write is happening at 0x0000, so we don't need to set addresses at all set!(tr[D]); clear!(tr[RAS]); clear!(tr[CAS]); // in read mode, Q should be 0 because no data has been written to 0x0000 yet assert!( low!(tr[Q...
identifier_body
main_demo.py
def change_infor_money(self,name,money): self.infor_conf.set(name,'余额',str(money)) self.infor_conf.write(open("information.conf","w")) def close_window(self): self.video_btn = 3 self.show_camera()
#self.sources = 'rtsp://admin:5417010101xx@59.70.132.250/Streaming/Channels/1' #self.source = 'shishi-nini.mp4' self.source = conf.get('image_config', 'capture_source') if self.source == '0': self.source = 0 else : self.source = str(self.source) ...
infor_sql.update_infor() self.close() def show_camera(self): #展示摄像头画面并进行人脸识别的功能
identifier_body
main_demo.py
', '顾客'+peopleName+'余额不足 支付失败') else : self.name_money[peopleName] = remain_money self.change_infor_money(peopleName,remain_money) self.deduct_money = 0 ...
print('更改余额',search_name,age2) self.conf.set(search_name,'余额',age2) button2=1 if sex2!='' and (sex2=='男' or sex2=='女'):
random_line_split
main_demo.py
if self.deduct_money != 0 and peopleName!='Unknown': # 判断是否扣钱 remain_money = self.name_money[peopleName] - self.deduct_money if remain_money < 0: QMessageBox.about(self, 'warning', '顾客'+pe...
and str.isdi
identifier_name
main_demo.py
Num): peopleName = "Unknown" ra = detectedFaces.faceRect[face] faceID = detectedFaces.faceID[face] faceid_list.append(faceID) left = int(ra.left * (1 / SET_SIZE)) # 坐标变大 top = int(ra.top * (1...
ame,'余额')) self.lineEdit_18.setPlaceholderText(se
conditional_block
field.py
# Read the string offset table offset = stringTableOffset offset += 2 # the first two bytes are supposed to indicate the number of strings, but this is totally unreliable firstOffset = struct.unpack_from("<H", data, offset)[0] numStrings = firstOffset / 2 - 1 # determine the ...
if self.scriptCode[codeOffset] == Op.RET and self.scriptCode[codeOffset + 1] == Op.RET: entry = codeOffset + self.scriptBaseAddress + 2 if entry not in self.scriptEntryAddresses: self.actorScripts[i].append(entry) s...
conditional_block
field.py
), ("chmph", 3), # 0xf8..0xff ("pmvie", 1), ("movie", 0), ("mvief", 2), ("mvcam", 1), ("fmusc", 1), ("cmusc", 5), ("chmst", 2), ("gmovr", 0), ] # Mnemonic and operand length for SPCAL sub-opcodes specialOpcodes = { 0xf5: ("arrow", 1), 0xf6: ("pname", 4), 0xf7: ("gmspd", 2), 0xf8: ("sm...
random_line_split
field.py
(self, event): data = event.getData() # Align section size to multiple of four if len(data) % 4: data += '\0' * (4 - len(data) % 4) self.sections[Section.EVENT] = data # Write the map to a file object, truncating the file. def writeToFile(self, fileobj): ma...
setEventSection
identifier_name
field.py
# Write the map to a file object, truncating the file. def writeToFile(self, fileobj): mapData = "" # Create the pointer table pointer = self.basePointer for data in self.sections: mapData += struct.pack("<L", pointer) pointer += len(data) # Ap...
data = event.getData() # Align section size to multiple of four if len(data) % 4: data += '\0' * (4 - len(data) % 4) self.sections[Section.EVENT] = data
identifier_body
trainer.py
2]) for x in open('tmp', 'r').readlines()] os.remove('tmp') return np.argmax(memory_available) return 0 def get_device(model): """ Extract the device to run on from the model. :param model: The model to train. :return: String. The name of the device. """ if next(model.parameters()).is_cuda:
else: return 'cpu' def prepare_batch(batch, device=None, non_blocking=False): """ Move the batch to the provided device. :param batch: The batch to prepare. :param device: The device to move to (e.g. cpu or gpu). :param non_blocking: Bool. Whether it should be blocking or not. :return: The prepared batch. ...
return 'cuda:{}'.format(torch.cuda.current_device())
conditional_block
trainer.py
2]) for x in open('tmp', 'r').readlines()] os.remove('tmp') return np.argmax(memory_available) return 0 def get_device(model): """ Extract the device to run on from the model. :param model: The model to train. :return: String. The name of the device. """ if next(model.parameters()).is_cuda: return 'cuda:...
(model_type, lr, lr_decay_step, epochs, dilation, validate, batch_size, log_dir, data_dir, csv_file, use_adam, checkpoint_dir, resume_checkpoint): """ Train the model with the given parameters. :param model_type: The type of the model to train. :param lr: Float or Array[Float]. The learning rate. :param ...
train
identifier_name
trainer.py
()[2]) for x in open('tmp', 'r').readlines()] os.remove('tmp') return np.argmax(memory_available) return 0 def get_device(model): """ Extract the device to run on from the model. :param model: The model to train. :return: String. The name of the device. """ if next(model.parameters()).is_cuda: return 'cu...
avg_fps = list(range(1, 26)) avg_fps.append(0.5) avg_fps.sort() tags = ['froc_{}fp'.format(fp) for fp in avg_fps] for avg_fp, tag in zip(avg_fps, tags): FROC([avg_fp], iou_threshold=0.5).attach(self, tag) # tqdm ProgressBar(persist=True).attach(self) # Tensorboard logging tb_logger.attach(self, ...
# FROC
random_line_split
trainer.py
def get_device(model): """ Extract the device to run on from the model. :param model: The model to train. :return: String. The name of the device. """ if next(model.parameters()).is_cuda: return 'cuda:{}'.format(torch.cuda.current_device()) else: return 'cpu' def prepare_batch(batch, device=None, non_bl...
""" Scan the system for available GPUs' and return the one with the most memory available. NOTE: Only available for linux systems! :return: Integer. The index of the GPU. """ os.system('nvidia-smi -q -d Memory |grep -A4 GPU|grep Free >tmp') if os.path.exists('tmp'): memory_available = [int(x.split()[2]) for x i...
identifier_body
vet.go
false, nil } // Upgrades reports if the are any upgrades for any direct and indirect dependencies. // It returns true if upgrades are needed. // Rule: gomodvet-002 func Upgrades(verbose bool) (bool, error) { mods, err := buildlist.ResolveUpgrades() if err != nil { return false, err } flagged := false...
return flagged, nil } // MultipleMajor reports if the current module has any dependencies with multiple major versions. // For example, if the current module is 'foo', it reports if there is a 'bar' and 'bar/v3' as dependencies of 'foo'. // It returns true if multiple major versions are found. // Note that th...
{ if verbose { fmt.Printf("gomodvet: upgrades: module %s: %+v\n", mod.Path, mod) } if mod.Update != nil { fmt.Println("gomodvet-002: dependencies have available updates: ", mod.Path, mod.Update.Version) flagged = true } }
conditional_block
vet.go
odvet-002: dependencies have available updates: ", mod.Path, mod.Update.Version) flagged = true } } return flagged, nil } // MultipleMajor reports if the current module has any dependencies with multiple major versions. // For example, if the current module is 'foo', it reports if there is a 'bar' and '...
{ mods, err := buildlist.Resolve() if err != nil { return false, fmt.Errorf("prerelease: %v", err) } flagged := false for _, mod := range mods { if verbose { fmt.Printf("gomodvet: prerelease: module %s: %+v\n", mod.Path, mod) } if isPrerelease(mod.Version) { fmt.Printf("gomodvet-006: a m...
identifier_body
vet.go
return false, nil } // Upgrades reports if the are any upgrades for any direct and indirect dependencies. // It returns true if upgrades are needed. // Rule: gomodvet-002 func Upgrades(verbose bool) (bool, error) { mods, err := buildlist.ResolveUpgrades() if err != nil { return false, err } flagged :...
// ExcludedVersion reports if the current module or any dependencies are using a version excluded by a dependency. // It returns true if so. // Currently requires main module's go.mod being in a consistent state (e.g., after a 'go list' or 'go build'), such that // the main module does not have a go.mod file using s...
} } return flagged, nil }
random_line_split
vet.go
%s", require) } // Probably not needed, but might as well use the canonical semver version. That strips "+incompatible", // which we need to preserve. Thus, we check here for "+incompatible" and add it back if needed. if semver.Build(version) == "+incompatible" { paths[path] = append(paths[path], sem...
isBeforeV1
identifier_name
dldata.py
logger = logging.getLogger('animethemes-dl') FILENAME_BAD = set('#%&{}\\<>*?/$!\'":@+`|') FILENAME_BANNED = set('<>:"/\\|?*') FILENAME_ALLOWEDASCII = set(string.printable).difference(FILENAME_BANNED) # this regex is for getting metadata from a song name, might be straight up wrong FEATURED_RE = re.compile(r"""^ (.*?)...
(**kwargs) -> Dict[str,str]: """ Generates a formatter dict used for formatting filenames. Takes in kwargs of Dict[str,Any]. Does not keep lists, dicts and bools. Automatically filters out` .endswith('ated_at')` for animethemes-dl. Also adds `{video_filetype:webm,anime_filename:...}`. """ ...
get_formatter
identifier_name
dldata.py
logger = logging.getLogger('animethemes-dl') FILENAME_BAD = set('#%&{}\\<>*?/$!\'":@+`|') FILENAME_BANNED = set('<>:"/\\|?*') FILENAME_ALLOWEDASCII = set(string.printable).difference(FILENAME_BANNED) # this regex is for getting metadata from a song name, might be straight up wrong FEATURED_RE = re.compile(r"""^ (.*...
return video_path,audio_path def pick_best_entry(theme: AnimeThemeTheme) -> Optional[Tuple[AnimeThemeEntry,AnimeThemeVideo]]: """ Returns the best entry and video based on OPTIONS. Returns None if no entry/video is wanted """ # picking best entry entries = [] for entry in theme['e...
audio_path = None
conditional_block
dldata.py
logger = logging.getLogger('animethemes-dl') FILENAME_BAD = set('#%&{}\\<>*?/$!\'":@+`|') FILENAME_BANNED = set('<>:"/\\|?*') FILENAME_ALLOWEDASCII = set(string.printable).difference(FILENAME_BANNED) # this regex is for getting metadata from a song name, might be straight up wrong FEATURED_RE = re.compile(r"""^ (.*...
def generate_path( anime: AnimeThemeAnime, theme: AnimeThemeTheme, entry: AnimeThemeEntry, video: AnimeThemeVideo) -> ( Tuple[Optional[PathLike],Optional[PathLike]]): """ Generates a path with animethemes api returns. Returns `(videopath|None,audiopath|None)` """ formatter = get_f...
""" Generates a formatter dict used for formatting filenames. Takes in kwargs of Dict[str,Any]. Does not keep lists, dicts and bools. Automatically filters out` .endswith('ated_at')` for animethemes-dl. Also adds `{video_filetype:webm,anime_filename:...}`. """ formatter = {} for t,d in k...
identifier_body
dldata.py
logger = logging.getLogger('animethemes-dl') FILENAME_BAD = set('#%&{}\\<>*?/$!\'":@+`|') FILENAME_BANNED = set('<>:"/\\|?*') FILENAME_ALLOWEDASCII = set(string.printable).difference(FILENAME_BANNED) # this regex is for getting metadata from a song name, might be straight up wrong FEATURED_RE = re.compile(r"""^ (.*...
""" for k in ('spoiler','nsfw'): v = OPTIONS['filter'][k] if v is not None and entry[k] ^ v: return False return True def is_video_wanted(video: AnimeThemeVideo) -> bool: """ Determines wheter all the tags in the entry are the same as in OPTIONS """ for k in ('nc...
random_line_split
securitygroup.go
type SecurityGroupPolicy struct { region *SRegion PolicyIndex int // 安全组规则索引号。 Protocol string // 协议, 取值: TCP,UDP, ICMP。 Port string // 端口(all, 离散port, range)。 ServiceTemplate ServiceTemplateSpecification...
"yunion.io/x/onecloud/pkg/cloudprovider" "yunion.io/x/onecloud/pkg/multicloud" )
random_line_split
securitygroup.go
offset int, limit int) ([]SSecurityGroup, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(name) > 0 { params["Filters.0.Name"] = "security-group-name" params["Filters.0...
Rules() []cloudprovider.SecurityRule { result := []cloudprovider.SecurityRule{} rule := cloudprovider.SecurityRule{ ExternalId: fmt.Sprintf("%d", self.PolicyIndex), SecurityRule: secrules.SecurityRule{ Action: secrules.SecurityRuleAllow, Protocol: secrules.PROTO_ANY, Direction: secrules.TSecurityRule...
roupPolicy) to
identifier_name
securitygroup.go
ip := range address[0].AddressSet { rule.ParseCIDR(ip) result = append(result, rule) } return result, nil } func (self *SSecurityGroup) GetRules() ([]cloudprovider.SecurityRule, error) { secgroup, err := self.region.GetSecurityGroupDetails(self.SecurityGroupId) if err != nil { return nil, err } for i := 0...
ddress-template-group-id"
conditional_block
securitygroup.go
int, limit int) ([]SSecurityGroup, int, error) { if limit > 50 || limit <= 0 { limit = 50 } params := make(map[string]string) params["Limit"] = fmt.Sprintf("%d", limit) params["Offset"] = fmt.Sprintf("%d", offset) if len(name) > 0 { params["Filters.0.Name"] = "security-group-name" params["Filters.0.Values...
ressIndex := -1, -1 for _, rule := range rules { policyIndex := 0 switch rule.Direction { case secrules.DIR_IN: ingressIndex++ policyIndex = ingressIndex case secrules.DIR_OUT: egressIndex++ policyIndex = egressIndex default: return fmt.Errorf("Unknown rule direction %v for secgroup %s", rule,...
roupRules(self.SecurityGroupId, rules) } func (self *SRegion) syncSecgroupRules(secgroupid string, rules []cloudprovider.SecurityRule) error { err := self.deleteAllRules(secgroupid) if err != nil { return errors.Wrap(err, "deleteAllRules") } egressIndex, ing
identifier_body
ext-all-extend.js
= r - 1; newF = -1; } else if (f == "down") { var cm = this.grid.colModel, clen = cm.getColumnCount(), ds = this.grid.store, rlen = ds.getCount(); newR = r + 1; if (newR >= rlen) { newR = 0; newC = c + 1; } } var newCell = this.grid...
random_line_split
ext-all-extend.js
Reader({ root: "rows", totalProperty: 'totalcount' }, [ {name: "menuId"}, {name: "name"} ]) }); ds.on("load", function(){ var totalcount = ds.getCount(); for (var i = 0; i < totalcount; i++) { var menuId = ds.getAt(i).data.menuId; var sArray = menuId.split("."); var funcId =...
on=getSubFuncs&menuId=" + menuId}), reader: new Ext.data.Json
conditional_block
ext-all-extend.js
menu.items, menuCls = this.headerMenuOpenCls; this.hdCtxIndex = index; Ext.fly(header).addClass(menuCls); menuItems.get('asc').setDisabled(!sortable); menuItems.get('desc').setDisabled(!sortable); ...
ndNodes = fn; se.activeNode = fn.length > 0 ? fn[0].id : undefined; return se; } }); Ext.Ajax.on('requestexception', function(conn, response, options){ try { var error = Ext.decode(response.responseText); if (!error)
identifier_body
ext-all-extend.js
('x-grid3-hd-btn')) { e.stopEvent(); var colModel = this.cm, header = this.findHeaderCell(target), index = this.getCellIndex(header), sortable = colModel.isSortable(index), menu = this.hmenu, ...
key);
identifier_name
corebuilder.rs
, minimum_separation: 100, read_distance: 8000, write_distance: 8000, separation: Separation::Random(100), warriors: Vec::new(), logger: None, } } } impl CoreBuilder { /// Creates a new instance of CoreBuilder with default paramete...
self.separation = separation; self } /// This is the range available for warriors to write information /// to core. Attempts to write outside the limits of this range /// result in writing within the local writable range. The range /// is centered on the current instruction. Thus...
/// warrior to the first instruction of the next warrior. /// Separation can be set to `Random`, meaning separations will be /// chosen randomly from those larger than the minimum separation. pub fn separation(&mut self, separation: Separation) -> &mut Self {
random_line_split
corebuilder.rs
minimum_separation: 100, read_distance: 8000, write_distance: 8000, separation: Separation::Random(100), warriors: Vec::new(), logger: None, } } } impl CoreBuilder { /// Creates a new instance of CoreBuilder with default parameters...
(&mut self, warriors: &[Warrior]) -> Result<&mut Self, CoreError> { for warrior in warriors { if warrior.len() > self.instruction_limit { return Err(CoreError::WarriorTooLong( warrior.len(), self.instruction_limit, warrior.m...
load_warriors
identifier_name
corebuilder.rs
minimum_separation: 100, read_distance: 8000, write_distance: 8000, separation: Separation::Random(100), warriors: Vec::new(), logger: None, } } } impl CoreBuilder { /// Creates a new instance of CoreBuilder with default parameters...
/// Each warrior can spawn multiple additional tasks. This variable sets the maximum /// number of tasks allowed per warrior. In other words, this is the size of each warrior's task queue. pub fn maximum_number_of_tasks(&mut self, maximum_number_of_tasks: usize) -> &mut Self { self.maximum_number_...
{ self.instruction_limit = instruction_limit; self }
identifier_body
corebuilder.rs
minimum_separation: 100, read_distance: 8000, write_distance: 8000, separation: Separation::Random(100), warriors: Vec::new(), logger: None, } } } impl CoreBuilder { /// Creates a new instance of CoreBuilder with default parameters...
if warrior.is_empty() { return Err(CoreError::EmptyWarrior( warrior.metadata.name().unwrap_or("Unnamed").to_owned(), )); }; } self.warriors = warriors.to_vec(); Ok(self) } /// Use a `Logger` to log the battle...
{ return Err(CoreError::WarriorTooLong( warrior.len(), self.instruction_limit, warrior.metadata.name().unwrap_or("Unnamed").to_owned(), )); }
conditional_block
exec_plan9.go
} for b := buf[:n]; len(b) > 0; { var s []byte s, b = gdirname(b) if s == nil { return nil, ErrBadStat } names = append(names, string(s)) } } return } // name of the directory containing names and control files for all open file descriptors var dupdev, _ = BytePtrFromString("#d") // forkAndEx...
r1, _, _ = RawSyscall(SYS_DUP, uintptr(fd[i]), uintptr(nextfd), 0) if int32(r1) == -1 { goto childerror } fd[i] = nextfd nextfd++ } } // Pass 2: dup fd[i] down onto i. for i = 0; i < len(fd); i++ { if fd[i] == -1 { RawSyscall(SYS_CLOSE, uintptr(i), 0, 0) continue } if fd[i] == int(...
if fd[i] >= 0 && fd[i] < int(i) { if nextfd == pipe { // don't stomp on pipe nextfd++ }
random_line_split
exec_plan9.go
(ss []string) []*byte { bb := make([]*byte, len(ss)+1) for i := 0; i < len(ss); i++ { bb[i] = StringBytePtr(ss[i]) } bb[len(ss)] = nil return bb } // SlicePtrFromStrings converts a slice of strings to a slice of // pointers to NUL-terminated byte arrays. If any string contains // a NUL byte, it returns (nil, EI...
StringSlicePtr
identifier_name
exec_plan9.go
0666)) if int32(r1) == -1 { goto childerror } envfd = int(r1) r1, _, _ = RawSyscall6(SYS_PWRITE, uintptr(envfd), uintptr(unsafe.Pointer(envv[i].value)), uintptr(envv[i].nvalue), ^uintptr(0), ^uintptr(0), 0) if int32(r1) == -1 || int(r1) != envv[i].nvalue { goto childerror } r1, _, ...
{ type forkRet struct { pid int err error } forkc := make(chan forkRet, 1) go func() { runtime.LockOSThread() var ret forkRet ret.pid, ret.err = forkExec(argv0, argv, attr) // If fork fails there is nothing to wait for. if ret.err != nil || ret.pid == 0 { forkc <- ret return } waitc := ma...
identifier_body
exec_plan9.go
0 && fd[i] < int(i) { if nextfd == pipe { // don't stomp on pipe nextfd++ } r1, _, _ = RawSyscall(SYS_DUP, uintptr(fd[i]), uintptr(nextfd), 0) if int32(r1) == -1 { goto childerror } fd[i] = nextfd nextfd++ } } // Pass 2: dup fd[i] down onto i. for i = 0; i < len(fd); i++ { if fd[i]...
{ i++ }
conditional_block
ha-state.go
if c.leaf == nil { log.Panicf("cert TLS called with nil leaf!") } return c.leaf } // GlobalHaState is the consensus state shared by all members of // a consensus cluster. type GlobalHaState struct { // LoadBalanced indicates that an external service is responsible for // routing traffic destined to VirtAddr to ...
return nil } // TLS converts the Cert into a TLS compatible certificate. func (c *Cert) TLS() *tls.Certificate {
random_line_split
ha-state.go
Enabled is set, the cluster is using the synchronous replication // protocol with manual failover. Enabled bool // ConsensusEnabled indicates that this cluster is operating on the Raft // based replication protocol with automatic failover. ConsensusEnabled bool // ConsensusJoin is the API URL of the current acti...
return fmt.Errorf("Must specify an IP address for the consensus address") } for _, ourAddr := range ourAddrs { if ourAddr.(*net.IPNet).IP.String() == consensusAddr { cAddrOk = true break } } if !cAddrOk { return fmt.Errorf("Consensus address %s is not present on the system", consensusAddr) ...
{ // Validate HA args. if !cOpts.Enabled { return nil } ourAddrs, err := net.InterfaceAddrs() if err != nil { return err } consensusAddr := "" consensusPort := "" if cOpts.ConsensusAddr != "" { consensusAddr, consensusPort, err = net.SplitHostPort(cOpts.ConsensusAddr) if err != nil { return err ...
identifier_body
ha-state.go
Enabled is set, the cluster is using the synchronous replication // protocol with manual failover. Enabled bool // ConsensusEnabled indicates that this cluster is operating on the Raft // based replication protocol with automatic failover. ConsensusEnabled bool // ConsensusJoin is the API URL of the current acti...
(template *x509.Certificate, parentCert *tls.Certificate) (*tls.Certificate, error) { var err error var priv ed25519.PrivateKey var public ed25519.PublicKey public, priv, err = ed25519.GenerateKey(rand.Reader) if err != nil { return nil, err } var parent *x509.Certificate var parentPriv ed25519.PrivateKey if...
makeCert
identifier_name
ha-state.go
Enabled is set, the cluster is using the synchronous replication // protocol with manual failover. Enabled bool // ConsensusEnabled indicates that this cluster is operating on the Raft // based replication protocol with automatic failover. ConsensusEnabled bool // ConsensusJoin is the API URL of the current acti...
} if !lbAddrOk { return fmt.Errorf("Virt address %s is present on the system, not permitted when load balanced", cOpts.VirtAddr) } } else { if cOpts.VirtAddr == "" { return fmt.Errorf("Error: HA must specify a VIP in CIDR format that DRP will move around") } // In HA mode with a VIP, force everythin...
{ lbAddrOk = false break }
conditional_block
nbd.rs
( Code::Internal, "no such bdev exists".to_string(), )); } let nbd_disk = nbd_disk.unwrap(); if let Some(mount) = match_mount( Some(&nbd_disk.nbd_device), Some(&target_path), fal...
num_devices
identifier_name
nbd.rs
9, 10, 11, 12, 14, 15]); } #[derive(Clone, Copy)] pub struct NbdDevInfo { instance: u32, major: u64, minor: u64, } impl fmt::Display for NbdDevInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "/dev/nbd{}", self.instance) } } impl fmt::Debug for NbdDevInfo { fn f...
else { let msg = format!( "Failed to stop nbd device {} for {}", nbd_disk.nbd_device, nbd_disk.bdev_name ); error!("{}", msg); Box::new(err(Status::new(Code::Internal, msg))) ...
{ info!( "Stopped NBD device {} with bdev {}", nbd_disk.nbd_device, nbd_disk.bdev_name ); NbdDevInfo::from(nbd_disk.nbd_device).put_back(); Box::new(ok(Response::new(Null {}))) ...
conditional_block
nbd.rs
9, 10, 11, 12, 14, 15]); } #[derive(Clone, Copy)] pub struct NbdDevInfo { instance: u32, major: u64, minor: u64, } impl fmt::Display for NbdDevInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result
} impl fmt::Debug for NbdDevInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "nbd{} ({}:{})", self.instance, self.major, self.minor) } } pub fn nbd_stage_volume( socket: String, msg: &NodeStageVolumeRequest, filesystem: Fs, mnt_opts: Vec<String>, ) -> Box< d...
{ write!(f, "/dev/nbd{}", self.instance) }
identifier_body
nbd.rs
} let nbd_disk = nbd_disk.unwrap(); if let Some(mount) = match_mount( Some(&nbd_disk.nbd_device), Some(&target_path), false, ) { if mount.source == nbd_disk.nbd_device && mount.dest == t...
random_line_split
sidebar.js
[0]); Sidebar.shadowRoot.appendChild($sidebar[0]); }; Sidebar.initShadowDOM = function () { // Note: shadowDOM doesn't support adding <script> tag through innerHTML, but only through appendChild. // Moreover, unlike with stylesheets, shadowDOM doesn't act as a sandbox for Javascript code (use iframe fo...
else if (Sidebar.hide()) { } } Sidebar.show = function ($sidebar) { var $sidebar = $(Sidebar.shadowRoot.querySelector('#sidebar')); var isShown = false; if ($sidebar.hasClass("collapsed")) { $sidebar.removeClass("collapsed"); isShown = true; } return isShown; } Sideb...
{ }
conditional_block
sidebar.js
; return sidebarToggler; }; Sidebar.getSidebarHTML = function () { var buttons = [ { id: "copier", label: 'Copy to clipboard', classes: 'fas fa-copy' }, { id: "saver", label: 'Save', classes: 'fas fa-save' }, { id: "flipper", label: 'Change sidebar position', classes: 'fas fa-comp...
random_line_split
basic_statements.py
StatementNoArgs, ParsedStatementDef, ParsedStatementPrint from basic_parsing import ParsedStatementGo, ParsedStatementDim from basic_parsing import ParsedStatementInput, ParsedStatementNext from basic_lexer import get_lexer from basic_types import NUMBERS, LETTERS from basic_expressions import Expression from basic_uti...
executor.put_symbol(var, value, SymbolType.VARIABLE, None) else: break # Break the while, if we did NOT get an invalid number (break from for) def stmt_on(executor, stmt): var = stmt._expression op = stmt._op result = eval_expression(executor._symbols, var) assert_sy...
executor.do_print(prompt, end='') result = executor.do_input() if result is None: print("Bad response from trekbot") result = result.split(",") if len(result) != len(stmt._input_vars): print(F"Mismatched number of inputs. Expected {len(stmt._input_vars)} got {len(...
conditional_block
basic_statements.py
StatementNoArgs, ParsedStatementDef, ParsedStatementPrint from basic_parsing import ParsedStatementGo, ParsedStatementDim from basic_parsing import ParsedStatementInput, ParsedStatementNext from basic_lexer import get_lexer from basic_types import NUMBERS, LETTERS from basic_expressions import Expression from basic_uti...
def get_exec(self): return self._exec class Keywords(Enum): CLEAR = KB(stmt_clear, ParsedStatement) # Some uses of clear take arguments, which we ignore. DEF = KB(stmt_def, ParsedStatement
return self._parser
identifier_body
basic_statements.py
from basic_parsing import ParsedStatement, ParsedStatementIf, ParsedStatementFor, ParsedStatementOnGoto from basic_parsing import ParsedStatementLet, ParsedStatementNoArgs, ParsedStatementDef, ParsedStatementPrint from basic_parsing import ParsedStatementGo, ParsedStatementDim from basic_parsing import ParsedStatementI...
from basic_dialect import UPPERCASE_INPUT from basic_types import BasicSyntaxError, assert_syntax, is_valid_identifier from basic_types import SymbolType, RunStatus
random_line_split
basic_statements.py
StatementNoArgs, ParsedStatementDef, ParsedStatementPrint from basic_parsing import ParsedStatementGo, ParsedStatementDim from basic_parsing import ParsedStatementInput, ParsedStatementNext from basic_lexer import get_lexer from basic_types import NUMBERS, LETTERS from basic_expressions import Expression from basic_uti...
(executor, stmt): executor.do_return() def stmt_width(executor, stmt): """ The WIDTH statement is only for compatibility with some versions of BASIC. It set the width of the screen. Ignored. :param executor: :param stmt: :return: """ pass class KB: def __init__(self, exec, p...
stmt_return
identifier_name
ViewCreater3d.ts
, ViewQueryParams, IModelReadRpcInterface, ViewDefinition3dProps, CategorySelectorProps, ModelSelectorProps, ViewDefinitionProps, DisplayStyle3dProps, CameraProps, IModelError, } from "@bentley/imodeljs-common"; import { Environment, IModelConnection, SpatialViewState, ViewState...
}, environment: options !== undefined && options.skyboxOn !== undefined && options.skyboxOn ? new Environment({ sky: { display: true } }).toJSON() : undefined, }, }, }; const viewStateProps: ViewStatePr...
backgroundMap: this._imodel.isGeoLocated,
random_line_split
ViewCreater3d.ts
, ViewQueryParams, IModelReadRpcInterface, ViewDefinition3dProps, CategorySelectorProps, ModelSelectorProps, ViewDefinitionProps, DisplayStyle3dProps, CameraProps, IModelError, } from "@bentley/imodeljs-common"; import { Environment, IModelConnection, SpatialViewState, ViewState...
( options?: ViewCreator3dOptions, modelIds?: string[] ): Promise<ViewState> { const models = modelIds ? modelIds : await this._getAllModels(); if (models === undefined || models.length === 0) throw new IModelError( IModelStatus.BadModel, "ViewCreator3d.createDefaultView: ...
createDefaultView
identifier_name
expenv.py
.gridsz[X], self.gridsz[Y], NUM_LAYERS)) put(st, start_box, agentLayer, True) put(st, flavor_loc, goalLayer, True) put_all(st, mobile_locs, mobileLayer, True) put_all(st, block_locs, immobileLayer, True) self.start_states.append( { 'flavo...
centr_pos = (3,3) dx, dy = aloc[0]-centr_pos[0], aloc[1]-centr_pos[1] state_mat = np.roll(state_mat, shift=dx, axis=0) state_mat = np.roll(state_mat, shift=dy, axis=1)
conditional_block
expenv.py
): for p in pos_list: put(mat, p, lyr, v) #------#------#------#------#------#------#------#------#------#------#------#-- #*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#* #*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#*$#* # # Experiment API class: # ...
'''Public method: query the location of the agent. (<0,0> is NW corner.)''' return self._get_loc(state,targ='agent')
identifier_body
expenv.py
# except: # return tuple([i+m for i in Iterable]) def addvec(Iterable, m, optn=None): try: m[0] except: if m>80: m = DVECS[m] else: m = DVECS[INDICES_TO_CARDINAL_ACTIONS[m]] return tuple([i+m for i,m in zip(Iterable,m)]) def multvec(Iterable, m, o...
#def addvec(Iterable, m, optn=None): # try: # return tuple([i+m for i,m in zip(Iterable,m)])
random_line_split
expenv.py
return tuple([int(i*m) for i in Iterable]) return tuple([i*m for i in Iterable]) def at(mat, pos, lyr): return mat[pos[X], pos[Y], lyr] def empty(mat, pos): return np.any(mat[pos[X], pos[Y], :]) def what(mat, pos): return np.array([at(mat, pos, lyr) for lyr in OLAYERS]) def put(mat, pos, lyr, v): mat[pos[X], po...
get_all_starting_states
identifier_name
main.rs
::convert::TryInto; use std::env; use std::fs; use std::fs::File; use std::io::prelude::*; use std::str; use uuid::Uuid; static mut USER_TOKEN: Vec<(String, String)> = Vec::new(); static mut USER_CHALLENGE: Vec<(String, u64)> = Vec::new(); #[derive(Debug)] struct User { username: String, salt: Salt, passw...
// récupère le code dans le header let input_code: &str = req.headers().get("Code").unwrap().to_str().unwrap(); if !auth.verify_code(&user.secret, &input_code, 0, 0) { println!("Mauvais code."); return HttpResponse::Unauthorized().finish(); } // si ok, un token est envoyé à l'utili...
} };
random_line_split