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
client.rs
AsyncContext, Context, Handler, StreamHandler, }; use actix_codec::{AsyncRead, AsyncWrite, Framed}; use futures::{ lazy, /* future::ok, */ stream::{SplitSink, Stream}, Future, }; use std::{ io, // str::FromStr, // time::Duration, sync::Arc, thread, // net, process, thre...
else { addr.do_send(ClientCommand(opt.msg)); sys.stop(); } }) })); }) // ).unwrap(); // sys.block_on( // ).unwrap(); // Arbiter::spawn( // TcpStream::connect(&addr) // .and_then(|stream| {...
{ addr.do_send(ClientCommand(read_stdin())); sys.stop(); }
conditional_block
base.py
DEFAULT_ROUTE = "%s/%s" % (environ.get('PATH_PREFIX', "/api"), environ.get('APP_NAME', "vulnerability")) IDENTITY_HEADER = "x-rh-identity" DEFAULT_PAGE_SIZE = 25 SKIP_ENTITLEMENT_CHECK = strtobool(environ.get('SKIP_ENTITLEMENT_CHECK', 'FALSE')) READ_ONLY_MODE = strtobool(environ.get('READ_ON...
(Exception): """manager is running in read-only mode""" def basic_auth(username, password, required_scopes=None): # pylint: disable=unused-argument """ Basic auth is done on 3scale level. """ raise MissingEntitlementException def auth(x_rh_identity, required_scopes=None): # pylint: disable=unu...
ReadOnlyModeException
identifier_name
base.py
DEFAULT_ROUTE = "%s/%s" % (environ.get('PATH_PREFIX', "/api"), environ.get('APP_NAME', "vulnerability")) IDENTITY_HEADER = "x-rh-identity" DEFAULT_PAGE_SIZE = 25 SKIP_ENTITLEMENT_CHECK = strtobool(environ.get('SKIP_ENTITLEMENT_CHECK', 'FALSE')) READ_ONLY_MODE = strtobool(environ.get('READ_ON...
if errors: raise ApplicationException({'errors': errors}, 400) return retval @classmethod def vmaas_call(cls, endpoint, data): """Calls vmaas and retrieves data from it""" headers = {'Content-type': 'application/json', 'Accept': 'application/json'...
retval[arg['arg_name']] = kwargs.get(arg['arg_name'], None) if retval[arg['arg_name']]: try: if arg['convert_func'] is not None: retval[arg['arg_name']] = arg['convert_func'](retval[arg['arg_name']]) except ValueError: ...
conditional_block
base.py
-name DEFAULT_ROUTE = "%s/%s" % (environ.get('PATH_PREFIX', "/api"), environ.get('APP_NAME', "vulnerability")) IDENTITY_HEADER = "x-rh-identity" DEFAULT_PAGE_SIZE = 25 SKIP_ENTITLEMENT_CHECK = strtobool(environ.get('SKIP_ENTITLEMENT_CHECK', 'FALSE')) READ_ONLY_MODE = strtobool(environ.get('RE...
@staticmethod def hide_satellite_managed(): """Parses hide-satellite-managed from headers""" try: return strtobool(connexion.request.headers.get('Hide-Satellite-Managed', 'false')) except ValueError: return False @staticmethod def _parse_arguments(kwarg...
"""Formats error message to desired format""" return {"errors": [{"status": str(status_code), "detail": text}]}, status_code
identifier_body
base.py
ITY_HEADER = "x-rh-identity" DEFAULT_PAGE_SIZE = 25 SKIP_ENTITLEMENT_CHECK = strtobool(environ.get('SKIP_ENTITLEMENT_CHECK', 'FALSE')) READ_ONLY_MODE = strtobool(environ.get('READ_ONLY_MODE', 'FALSE')) LOGGER.info("Access URL: %s", DEFAULT_ROUTE) # Prometheus support # Counter for all-the-get-calls, dealt with in Bas...
return cls.format_exception(str(exc), 503) except Exception: # pylint: disable=broad-except LOGGER.exception('Unhandled exception: ')
random_line_split
plot_inv_1_dcr_sounding.py
os import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import tarfile from discretize import TensorMesh from SimPEG import ( maps, data, data_misfit, regularization, optimization, inverse_problem, inversion, directives, utils, ) from SimPEG.electromagnetics...
# Define survey survey = dc.Survey(source_list) # Plot apparent resistivities on sounding curve as a function of Wenner separation # parameter. electrode_separations = 0.5 * np.sqrt( np.sum((survey.locations_a - survey.locations_b) ** 2, axis=1) ) fig = plt.figure(figsize=(11, 5)) mpl.rcParams.update({"font.siz...
M_locations = M_electrodes[k[ii] : k[ii + 1], :] N_locations = N_electrodes[k[ii] : k[ii + 1], :] receiver_list = [ dc.receivers.Dipole( M_locations, N_locations, data_type="apparent_resistivity", ) ] # AB electrode locations for source. Each is a (1,...
conditional_block
plot_inv_1_dcr_sounding.py
import os import numpy as np
from discretize import TensorMesh from SimPEG import ( maps, data, data_misfit, regularization, optimization, inverse_problem, inversion, directives, utils, ) from SimPEG.electromagnetics.static import resistivity as dc from SimPEG.utils import plot_1d_layer_model mpl.rcParams.upd...
import matplotlib as mpl import matplotlib.pyplot as plt import tarfile
random_line_split
ListBlock.js
geomicons').default , StreamConsumingBlock = require('./StreamConsumingBlock') , concat = [].concat.bind([]) const ListHeader = ({ start, shownItems, hide, items, limit, columns, shownColumns, prevPage, nextPage, firstPage, lastPage, updateOpts, }) => h(Flex, { bg: 'gray.1', p...
prevPage() { const limit = parseInt(this.props.limit) this.setState(prev => { let start = prev.start - limit if (start < 0) start = 0; return { start } }) } render() { const items = this.props.data , { shownColumns, sortBy, sortDirection, update...
}) }
random_line_split
ListBlock.js
geomicons').default , StreamConsumingBlock = require('./StreamConsumingBlock') , concat = [].concat.bind([]) const ListHeader = ({ start, shownItems, hide, items, limit, columns, shownColumns, prevPage, nextPage, firstPage, lastPage, updateOpts, }) => h(Flex, { bg: 'gray.1', p...
rops) { super(props); this.state = { start: withDefaults(props).start, } this.firstPage = this.firstPage.bind(this); this.lastPage = this.lastPage.bind(this); this.nextPage = this.nextPage.bind(this); this.prevPage = this.prevPage.bind(this); } componentWillR...
nstructor(p
identifier_name
main.rs
chart| GuitarPlaythrough::new(chart) .map_err(|s| String::from(s)))?; fn draw<T: sdl2::render::RenderTarget>(canvas: &mut sdl2::render::Canvas<T>, playthrough: &GuitarPlaythrough, time: f32) { canvas.set_draw_color(pixels::Color::RGB(0, 0, 0)); canvas.clear(); for i in 0..playt...
} } }); playthrough.update_time(song_time_ms)
random_line_split
main.rs
InputAction::Strum => Some(GuitarInputAction::Strum), } } } enum
{ Quit, GuitarEffect(GuitarGameEffect), } fn draw_fret<T: sdl2::render::RenderTarget>(canvas: &sdl2::render::Canvas<T>, enabled: bool, x: i16, y: i16, radius: i16, color: pixels::Color) -> Result<(), String> { if enabled { canvas.filled_circle(x, y, radius, color) } else { canvas.circl...
GameInputEffect
identifier_name
main.rs
InputAction::Strum => Some(GuitarInputAction::Strum), } } } enum GameInputEffect { Quit, GuitarEffect(GuitarGameEffect), } fn draw_fret<T: sdl2::render::RenderTarget>(canvas: &sdl2::render::Canvas<T>, enabled: bool, x: i16, y: i16, radius: i16, color: pixels::Color) -> Result<(), String>
enum FrameLimit { Vsync, Cap(u32), } fn main() -> Result<(), String> { let sdl_context = sdl2::init()?; /* joystick initialization */ let joystick_subsystem = sdl_context.joystick()?; let available = joystick_subsystem.num_joysticks() .map_err(|e| format!("can't enumerate joysticks...
{ if enabled { canvas.filled_circle(x, y, radius, color) } else { canvas.circle(x, y, radius, color) } }
identifier_body
script.js
); searchInput.value = bookTitle; searchBook(bookTitle); } else { window.location.replace('/'); } } } document.getElementById('searchBtn').addEventListener('click', searchBook); searchInput.addEventListener('keypre...
requestButton.addEventListener('click', toRequest); let bookingButtons = document.querySelectorAll('input[value="Забронировать"]'); if (bookingButtons.length > 0) { for (var i = 0; i < bookingButtons.length; i++) { ...
// Обработка кнопок для запроса и бронирования книги let requestButton = document.getElementById('toRequest'); if (requestButton != null)
random_line_split
script.js
} else { window.location.replace('/'); } } } document.getElementById('searchBtn').addEventListener('click', searchBook); searchInput.addEventListener('keypress',()=>{if(event.key==='Enter'){event.preventDefault();searchBook()}}); // поиск по Энтер...
if (link.classList.contains('timetableLinkClosed')) { link.classList.remove('timetableLinkClosed'); link.classList.add('timetableLinkOpened'); schedule.style.display = 'block'; } else { link.classList.remove('timetableLinkOpened'); link.classL
conditional_block
script.js
); searchInput.value = bookTitle; searchBook(bookTitle); } else { window.location.replace('/'); } } } document.getElementById('searchBtn').addEventListener('click', searchBook); searchInput.addEventListener('keypre...
t i = 0; i < timetableLinks.length; i++) { let timetableLink = timetableLinks[i]; timetableLink.addEventListener('click', { handleEvent: controlSchedule, link: timetableLink, ...
for (le
identifier_name
script.js
2 col-lg-10 offset-lg-1 col-xl-8 offset-xl-2"><div class="book"><div class="bookDesc"><h2>&nbsp;</h2><div class="details lead"> <span class="author">&nbsp;</span> <span class="publisher">&nbsp;</span> <span class="pages">&nbsp;</span></div></div></div></div></div><div class="row"><div class="col-sm-12 col-md-12 col-lg-...
d="M2,2 L8,8" class="closeBtn_p2"></path></svg>'; let aTimer=setTimeout(closeSearchAlert, 15000, alertID); document.querySelector('.closeBtn').addEventListen
identifier_body
elasticsearch.rs
_secs.unwrap_or(1); let index = if let Some(idx) = &config.index { Template::from(idx.as_str()) } else { Template::from("vector-%Y.%m.%d") }; let doc_type = config.clone().doc_type.unwrap_or("_doc".into()); let policy = FixedRetryPolicy::new( retry_attempts, Duratio...
{ Err(format!("Unexpected status: {}", response.status())) }
conditional_block
elasticsearch.rs
id_key: Option<String>, pub batch_size: Option<usize>, pub batch_timeout: Option<u64>, pub compression: Option<Compression>, // Tower Request based configuration pub request_in_flight_limit: Option<usize>, pub request_timeout_secs: Option<u64>, pub request_rate_limit_duration_secs: Option<...
maybe_set_id(id_key, &mut action, &event); assert_eq!(json!({}), action); } #[test] fn doesnt_set_id_when_not_configured() { let id_key: Option<&str> = None; let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("foo".int...
.insert_explicit("not_foo".into(), "bar".into()); let mut action = json!({});
random_line_split
elasticsearch.rs
_key: Option<String>, pub batch_size: Option<usize>, pub batch_timeout: Option<u64>, pub compression: Option<Compression>, // Tower Request based configuration pub request_in_flight_limit: Option<usize>, pub request_timeout_secs: Option<u64>, pub request_rate_limit_duration_secs: Option<u64...
#[test] fn doesnt_set_id_when_field_missing() { let id_key = Some("foo"); let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("not_foo".into(), "bar".into()); let mut action = json!({}); maybe_set_id(id_key, &mut action, &...
{ let id_key = Some("foo"); let mut event = Event::from("butts"); event .as_mut_log() .insert_explicit("foo".into(), "bar".into()); let mut action = json!({}); maybe_set_id(id_key, &mut action, &event); assert_eq!(json!({"_id": "bar"}), action); ...
identifier_body
elasticsearch.rs
, }; let batch_size = config.batch_size.unwrap_or(bytesize::mib(10u64) as usize); let batch_timeout = config.batch_timeout.unwrap_or(1); let timeout = config.request_timeout_secs.unwrap_or(60); let in_flight_limit = config.request_in_flight_limit.unwrap_or(5); let rate_limit_duration = config....
flush
identifier_name
session.go
管道满了会关闭连接 select { case <-s.CloseState: return false case s.SendChan <- packet: if wait := len(s.SendChan); wait > cap(s.SendChan)/10*5 && wait%20 == 0 { log.Warnf("session send process,waitChan:%d/%d,msg:%d,session:%d,remote:%s", wait, cap(s.SendChan), packet.MsgId, s.SessionId, s.RemoteAddr()) } ...
// encry
identifier_name
session.go
s.rpmInterval { // 提示操作太频繁三次后踢下线 //rpmMsgCount++ //if rpmMsgCount > 3 { // 发送频率过高的消息包 s.DirectSendAndClose(s.offLineMsg) log.Errorf("session rpm too high,%d/%s qps,session:%d,remote:%s", rpmCount, s.rpmInterval, s.SessionId, s.RemoteAddr()) return //} //// 发送频率过高的消息包 /...
.NewDoneChan(), } host, _, e
conditional_block
session.go
{MsgId: msgId, Data: payload[SEQ_ID_SIZE+MSG_ID_SIZE:], Session: s, ReceiveTime: time.Now()} //if s.readDelay > 0 { // if !delayTimer.Stop() { // select { // case <-delayTimer.C: // default: // } // } // delayTimer.Reset(s.readDelay) // if filter == nil { // select { // case s.ReadChan <- p...
identifier_body
session.go
} type NetConnIF interface { SetReadDeadline(t time.Time) error SetWriteDeadline(t time.Time) error Close() error SetWriteBuffer(bytes int) error SetReadBuffer(bytes int) error Write(b []byte) (n int, err error) RemoteAddr() net.Addr Read(p []byte) (n int, err error) } type TCPSession struct { //Conn *net.TC...
ReceiveTime time.Time
random_line_split
batcher.go
, r := range ba.reqs { var res Response if br != nil { resp := br.Responses[i].GetInner() if prevResps != nil { prevResp := prevResps[i] if cErr := roachpb.CombineResponses(prevResp, resp); cErr != nil { log.Fatalf(ctx, "%v", cErr) } resp = prevResp } if resume...
{ *r = request{} p.requestPool.Put(r) }
identifier_body
batcher.go
Error() } return nil } if !ba.sendDeadline.IsZero() { actualSend := send send = func(context.Context) error { return contextutil.RunWithTimeout( ctx, b.sendBatchOpName, timeutil.Until(ba.sendDeadline), actualSend) } } // Send requests in a loop to support pagination, which may be necessa...
batchRequest
identifier_name
batcher.go
sendDoneChan: make(chan struct{}), } b.sendBatchOpName = b.cfg.Name + ".sendBatch" if err := cfg.Stopper.RunAsyncTask(context.Background(), b.cfg.Name, b.run); err != nil { panic(err) } return b } func validateConfig(cfg *Config) { if cfg.Stopper == nil { panic("cannot construct a Batcher with a nil Stoppe...
{ return nil }
conditional_block
batcher.go
. MaxMsgsPerBatch int // MaxKeysPerBatchReq is the maximum number of keys that each batch is // allowed to touch during one of its requests. If the limit is exceeded, // the batch is paginated over a series of individual requests. This limit // corresponds to the MaxSpanRequestKeys assigned to the Header of each ...
// client is responsible for ensuring that the passed respChan has a buffer at // least as large as the number of responses it expects to receive. Using an // insufficiently buffered channel can lead to deadlocks and unintended delays // processing requests inside the RequestBatcher. func (b *RequestBatcher) SendWithCh...
} } // SendWithChan sends a request with a client provided response channel. The
random_line_split
lib.rs
/// Arguments passed in will be, in order, /// the number of frames analyzed, and the number of keyframes detected. /// /// This is generally useful for displaying progress, etc. pub progress_callback: Option<Box<dyn Fn(usize, usize)>>, } impl Default for DetectionOptions { fn default() -> Self...
let mut keyframes = BTreeSet::new(); let mut frameno = 0; loop { let mut next_input_frameno = frame_queue .keys() .last() .copied() .map(|key| key + 1) .unwrap_or(0); while next_input_frameno < frameno + opts.lookahead_distance { ...
let mut detector = SceneChangeDetector::new(bit_depth, chroma_sampling, &opts); let mut frame_queue = BTreeMap::new();
random_line_split
lib.rs
/// Arguments passed in will be, in order, /// the number of frames analyzed, and the number of keyframes detected. /// /// This is generally useful for displaying progress, etc. pub progress_callback: Option<Box<dyn Fn(usize, usize)>>, } impl Default for DetectionOptions { fn default() -> Self...
else { frame_queue.get(&(frameno - 1)) }, &frame_set, frameno, &mut keyframes, ); if frameno > 0 { frame_queue.remove(&(frameno - 1)); } frameno += 1; if let Some(ref progress_fn) = opts.progress_callb...
{ None }
conditional_block
lib.rs
: None, progress_callback: None, } } } /// Runs through a y4m video clip, /// detecting where scene changes occur. /// This is adjustable based on the `opts` parameters. /// /// Returns a `Vec` containing the frame numbers where the scene changes occur. pub fn detect_scene_changes<R: Read, T: P...
{ let lookahead_distance = cmp::min(self.opts.lookahead_distance, frame_subset.len() - 1); // Where A and B are scenes: AAAAAABBBAAAAAA // If BBB is shorter than lookahead_distance, it is detected as a flash // and not considered a scenecut. for j in 1..=lookahead_distance { ...
identifier_body
lib.rs
/// Arguments passed in will be, in order, /// the number of frames analyzed, and the number of keyframes detected. /// /// This is generally useful for displaying progress, etc. pub progress_callback: Option<Box<dyn Fn(usize, usize)>>, } impl Default for DetectionOptions { fn default() -> Self...
<'a> { /// Minimum average difference between YUV deltas that will trigger a scene change. threshold: u8, opts: &'a DetectionOptions, /// Frames that cannot be marked as keyframes due to the algorithm excluding them. /// Storing the frame numbers allows us to avoid looking back more than one frame. ...
SceneChangeDetector
identifier_name
debugger.rs
(event_handler: &'eh mut dyn DebugEventHandler) -> Self
pub fn spawn(&mut self, cmd: Command) -> Result<Child> { Ok(self.context.tracer.spawn(cmd)?) } pub fn wait(self, mut child: Child) -> Result<Output> { if let Err(err) = self.wait_on_stops() { // Ignore error if child already exited. let _ = child.kill(); ...
{ let context = DebuggerContext::new(); Self { context, event_handler, } }
identifier_body
debugger.rs
(event_handler: &'eh mut dyn DebugEventHandler) -> Self { let context = DebuggerContext::new(); Self { context, event_handler, } } pub fn spawn(&mut self, cmd: Command) -> Result<Child> { Ok(self.context.tracer.spawn(cmd)?) } pub fn wait(self, m...
#[cfg(target_arch = "aarch64")] let instruction_pointer = &mut regs.pc; // Compute what the last PC would have been _if_ we stopped due to a soft breakpoint. // // If we don't have a registered breakpoint, then we will not use this value. let pc = Address(instruction_po...
#[cfg(target_arch = "x86_64")] let instruction_pointer = &mut regs.rip;
random_line_split
debugger.rs
(event_handler: &'eh mut dyn DebugEventHandler) -> Self { let context = DebuggerContext::new(); Self { context, event_handler, } } pub fn spawn(&mut self, cmd: Command) -> Result<Child> { Ok(self.context.tracer.spawn(cmd)?) } pub fn
(self, mut child: Child) -> Result<Output> { if let Err(err) = self.wait_on_stops() { // Ignore error if child already exited. let _ = child.kill(); return Err(err); } // Currently unavailable on Linux. let status = None; let stdout = if let...
wait
identifier_name
debugger.rs
(event_handler: &'eh mut dyn DebugEventHandler) -> Self { let context = DebuggerContext::new(); Self { context, event_handler, } } pub fn spawn(&mut self, cmd: Command) -> Result<Child> { Ok(self.context.tracer.spawn(cmd)?) } pub fn wait(self, m...
// Cannot panic due to initial length check. let first = &maps[0]; let path = if let MMapPath::Path(path) = &first.pathname { FilePath::new(path.to_string_lossy())? } else { bail!("module image mappings must be file-backed"); }; for map in &map...
{ bail!("no executable mapping for module image"); }
conditional_block
lib.rs
protected access //! to actor state, which also guarantees at compile-time that no //! actor can directly access any other actor. //! //! By default a cut-down ref-counting implementation is used instead //! of `Rc`, which saves around one `usize` per [`Actor`] or [`Fwd`] //! instance. //! //! With default features, o...
//! //! If no inter-thread operations are active, then **Stakker** will //! never do locking or any atomic operations, nor block for any //! reason. So the code can execute at full speed without triggering //! any CPU memory fences or whatever. Usually the only thing that //! blocks would be the external I/O poller w...
//! provided with arguments. These are also efficient due to //! inlining. In this case two chunks of inlined code are generated //! for each by the compiler: the first which accepts arguments and //! pushes the second one onto the queue.
random_line_split
decisiontree.rs
store the block // of each branch if it was already codegen'd. let mut branches: Vec<_> = vec![None; match_expr.branches.len()]; self.builder.position_at_end(starting_block); // Then codegen the decisiontree itself that will eventually lead to each branch. self.codegen_subtree(...
} } /// When creating a decision tree, any match all case is always last in the case list. fn has_match_all_case(&self, cases: &[Case]) -> bool {
random_line_split
decisiontree.rs
id, typ), value_to_match); } let starting_block = self.current_block(); let ending_block = self.insert_into_new_block("match_end"); // Create the phi value to merge the value of all the match branches let match_type = match_expr.typ.as_ref().unwrap(); let llvm_type = se...
<'c>(&mut self, tag: &VariantTag, cache: &mut ModuleCache<'c>) -> Option<BasicValueEnum<'g>> { match tag { VariantTag::True => Some(self.bool_value(true)), VariantTag::False => Some(self.bool_value(false)), VariantTag::Unit => Some(self.unit_value()), // TODO: Re...
get_constructor_tag
identifier_name
decisiontree.rs
_on, cases, branches, phi, match_end, match_expr, cache); let mut switch_cases = vec![]; for case in cases.iter() { self.codegen_case(case, value_to_switch_on, &mut switch_cases, branches, phi, match_end...
{ for id in field { let typ = self.follow_bindings(cache.definition_infos[id.0].typ.as_ref().unwrap(), cache); self.definitions.insert((*id, typ), value); } }
identifier_body
main.rs
in each key is the correctly spelled // word (or possible words) with their // count included to determine which // of the possible words is more likely. use std::collections::HashMap; // word == word // score == word priority // higher number == higher priority #[derive(Debug, Clone)] struct Word { word: String...
new_set.insert(word.to_string(), ()); x.clear(); for j in new_set.keys() { x.push(j.to_string()); } } else { self.error_map .insert( i.clone(), vec![wor...
{ // Vec<String> // Must only contain inserts of // correct words let permuted_keys = self.permutations_of(word); for i in permuted_keys { // if error key exists if let Some(x) = self.error_map.get_mut(&i) { let mut new_set: HashMap<String,...
identifier_body
main.rs
_map: HashMap<String, Vec<String>>, error_distance: u8 } // UNIMPLEMENTED YET // only counts in word_map are measured to // determined probable match // only counts in word_map are incremented // and check when inserting a new word. // counts in error_map are ignored. // only necessary for word_map, // only word_m...
io::stdin().read_line(&mut word).expect("no work... >:("); println!("value? "); io::stdin().read_line(&mut value).expect("no work... >:("); d.insert_with_permutations_and_count(word.trim().as_ref(), value.trim().parse().expect("not a number")); } else {
random_line_split
main.rs
in each key is the correctly spelled // word (or possible words) with their // count included to determine which // of the possible words is more likely. use std::collections::HashMap; // word == word // score == word priority // higher number == higher priority #[derive(Debug, Clone)] struct Word { word: String...
() -> Dictionary { Dictionary { word_map: HashMap::new(), error_map: HashMap::new(), error_distance: 2 } } fn insert(&mut self, word: &str) { if let Some(x) = self.word_map.get_mut(word) { x.score += 1; } else { self.wo...
new
identifier_name
main.rs
in each key is the correctly spelled // word (or possible words) with their // count included to determine which // of the possible words is more likely. use std::collections::HashMap; // word == word // score == word priority // higher number == higher priority #[derive(Debug, Clone)] struct Word { word: String...
else if let Some(x) = self.error_map.get(word) { if x.len() > 1 { Some(self.find_best_match(x.to_vec())) } else { Some(x[0].clone()) } } else { None } }; if let Some(x) = fin...
{ Some(x.word.clone()) }
conditional_block
consumer.rs
second one. /// /// # Safety /// /// All items are initialized. Elements must be removed starting from the beginning of first slice. /// When all items are removed from the first slice then items must be removed from the beginning of the second slice. /// /// *This method must be followed b...
<'a, C: Consumer> { target: &'a C, slices: (&'a [MaybeUninit<C::Item>], &'a [MaybeUninit<C::Item>]), len: usize, } impl<'a, C: Consumer> PopIter<'a, C> { pub fn new(target: &'a mut C) -> Self { let slices = target.occupied_slices(); Self { len: slices.0.len() + slices.1.len()...
PopIter
identifier_name
consumer.rs
_read_index(count) }; count } fn into_iter(self) -> IntoIter<Self> { IntoIter::new(self) } /// Returns an iterator that removes items one by one from the ring buffer. fn pop_iter(&mut self) -> PopIter<'_, Self> { PopIter::new(self) } /// Returns a front-to-back ite...
self.base_mut().as_mut_slices() }
random_line_split
consumer.rs
second one. /// /// # Safety /// /// All items are initialized. Elements must be removed starting from the beginning of first slice. /// When all items are removed from the first slice then items must be removed from the beginning of the second slice. /// /// *This method must be followed b...
}; unsafe { self.advance_read_index(count) }; count } fn into_iter(self) -> IntoIter<Self> { IntoIter::new(self) } /// Returns an iterator that removes items one by one from the ring buffer. fn pop_iter(&mut self) -> PopIter<'_, Self> { PopIter::new(self) ...
{ unsafe { write_uninit_slice(elems.get_unchecked_mut(..right.len()), right) }; right.len() }
conditional_block
v4.rs
& Structs //---------------------------------------------------------------------------// /// This struct represents a Schema File in memory, ready to be used to decode versioned PackedFiles. #[derive(Clone, PartialEq, Eq, Debug, Serialize, Deserialize)] pub struct SchemaV4 { /// It stores the structural version...
om(l
identifier_name
v4.rs
std::path::Path; use crate::error::Result; use crate::schema::Schema as SchemaV5; use crate::schema::Definition as DefinitionV5; use crate::schema::FieldType as FieldTypeV5; use crate::schema::Field as FieldV5; //---------------------------------------------------------------------------// // ...
Some((name, definitions)) } e
conditional_block
v4.rs
version of Loc files decoded (currently, only version `1`). Loc(Vec<DefinitionV4>), /// It stores a `Vec<Definition>` with the definitions for each version of MatchedCombat files decoded. MatchedCombat(Vec<DefinitionV4>), } /// This struct contains all the data needed to decode a specific version of a ve...
random_line_split
service.go
validatorsManager validatorsmanager.Service domainProvider eth2client.DomainProvider farFutureEpoch phase0.Epoch currentEpochProvider chaintime.Service wallets map[string]e2wtypes.Wallet walletsMutex sync.RWMutex } // module-wide log. var log zerolog.Logger // New creates a n...
accountsMu.Unlock() log.Trace().Dur("elapsed", time.Since(started)).Int("accounts", len(walletAccounts)).Msg("Imported accounts") }(ctx, sem, &wg, i, &accountsMu) } wg.Wait() log.Trace().Int("accounts", len(accounts)).Msg("Obtained accounts") if len(accounts) == 0 && len(s.accounts) != 0 { log.Warn().Msg...
accounts[k] = v }
conditional_block
service.go
validatorsManager validatorsmanager.Service domainProvider eth2client.DomainProvider farFutureEpoch phase0.Epoch currentEpochProvider chaintime.Service wallets map[string]e2wtypes.Wallet walletsMutex sync.RWMutex } // module-wide log. var log zerolog.Logger // New creates a n...
if len(endpointParts) != 2 { log.Warn().Str("endpoint", endpoint).Msg("Malformed endpoint") continue } port, err := strconv.ParseUint(endpointParts[1], 10, 32) if err != nil { log.Warn().Str("endpoint", endpoint).Err(err).Msg("Malformed port") continue } if port == 0 { log.Warn().Str("endpoin...
parameters, err := parseAndCheckParameters(params...) if err != nil { return nil, errors.Wrap(err, "problem with parameters") } // Set logging. log = zerologger.With().Str("service", "accountmanager").Str("impl", "dirk").Logger() if parameters.logLevel != log.GetLevel() { log = log.Level(parameters.logLevel...
identifier_body
service.go
eth2client "github.com/attestantio/go-eth2-client" api "github.com/attestantio/go-eth2-client/api/v1" "github.com/attestantio/go-eth2-client/spec/phase0" "github.com/attestantio/vouch/services/chaintime" "github.com/attestantio/vouch/services/metrics" "github.com/attestantio/vouch/services/validatorsmanager" "gi...
"time"
random_line_split
service.go
atorsManager validatorsmanager.Service domainProvider eth2client.DomainProvider farFutureEpoch phase0.Epoch currentEpochProvider chaintime.Service wallets map[string]e2wtypes.Wallet walletsMutex sync.RWMutex } // module-wide log. var log zerolog.Logger // New creates a new dir...
ctx context.Context) error { // Create the relevant wallets. wallets := make([]e2wtypes.Wallet, 0, len(s.accountPaths)) pathsByWallet := make(map[string][]string) for _, path := range s.accountPaths { pathBits := strings.Split(path, "/") var paths []string var exists bool if paths, exists = pathsByWallet[p...
efreshAccounts(
identifier_name
pinhole.go
z := math.Inf(-1), math.Inf(-1), math.Inf(-1) for ; i < len(p.lines); i++ { if p.lines[i].x1 < minx { minx = p.lines[i].x1 } if p.lines[i].x1 > maxx { maxx = p.lines[i].x1 } if p.lines[i].y1 < miny { miny = p.lines[i].y1 } if p.lines[i].y1 > maxy { maxy = p.lines[i].y1 } if p.lines[i].z1 ...
if imax[i] < jmax[i] { return i != 2 } if imin[i] > jmin[i] { return i == 2 } if imin[i] < jmin[i] { return i != 2 } } return false } func (a byDistance) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (p *Pinhole) Image(width, height int, opts *ImageOptions) *image.RGBA { if opts == nil { ...
{ return i == 2 }
conditional_block
pinhole.go
() []float64 { min, max := l.Rect() return []float64{ (max[0] + min[0]) / 2, (max[1] + min[1]) / 2, (max[2] + min[2]) / 2, } } type Pinhole struct { lines []*line stack []int } func New() *Pinhole { return &Pinhole{} } func (p *Pinhole) Begin() { p.stack = append(p.stack, len(p.lines)) } func (p *Pinhole...
Center
identifier_name
pinhole.go
{ if i == circleSteps { p.DrawLine(lx, ly, lz, fx, fy, fz) } else { p.DrawLine(lx, ly, lz, dx, dy, dz) } line := p.lines[len(p.lines)-1] line.nocaps = true line.circle = true if first == nil { first = line } line.cfirst = first line.cprev = prev if prev != nil { prev.cn...
c.CubicTo(ax1, ay1, ax2, ay2, dx2, dy2) } else {
random_line_split
pinhole.go
type Pinhole struct { lines []*line stack []int } func New() *Pinhole { return &Pinhole{} } func (p *Pinhole) Begin() { p.stack = append(p.stack, len(p.lines)) } func (p *Pinhole) End() { if len(p.stack) > 0 { p.stack = p.stack[:len(p.stack)-1] } } func (p *Pinhole) Rotate(x, y, z float64) { var i int if l...
{ min, max := l.Rect() return []float64{ (max[0] + min[0]) / 2, (max[1] + min[1]) / 2, (max[2] + min[2]) / 2, } }
identifier_body
Tools.py
lines = f.readlines(); f.close(); f = open(errorFile, "r"); errors = f.readlines(); f.close(); newUsers = []; existingUsers = []; for i in range(1, len(lines)): addToExisting = False; for j in range(len(errors)): seperator = " "; if "...
def __repr__(self): return "ord:%d\t|\tchr:%s\t|\tline:%d\t|\tcolumn:%d\t\n" % (self.ordNumber, self.ordCharacter, self.lineOccurence, self.colOccurence); f = open(fileName, "r"); lines = f.readlines(); f.close(); errorArray = [] for i in range(len(lines)...
turn self.sourceLine;
identifier_body
Tools.py
lines = f.readlines(); f.close(); f = open(errorFile, "r"); errors = f.readlines(); f.close(); newUsers = []; existingUsers = []; for i in range(1, len(lines)): addToExisting = False; for j in range(len(errors)): seperator = " "; if "...
elf): return self.ordNumber; def getOrdCharacter(self): return self.ordCharacter; def getLineOccurence(self): return self.lineOccurence; def getColOccurence(self): return self.colOccurence; def getSourceL...
tOrdNumber(s
identifier_name
Tools.py
lines = f.readlines(); f.close(); f = open(errorFile, "r"); errors = f.readlines(); f.close(); newUsers = []; existingUsers = []; for i in range(1, len(lines)): addToExisting = False; for j in range(len(errors)): seperator = " "; if "...
fNew.close(); sortOrder = lines[0]; exVarIndex1 = sortOrder.split(";").index("username"); exVarIndex2 = sortOrder.split(";").index("grouphand"); fExisting = open(newFile + "_existing" + ".txt", "w"); fExisting.write(lines[0].split(";")[exVarIndex1] + ";" + lines[0].split...
fNew.write(newUser);
conditional_block
Tools.py
"_existing" + ".txt", "w"); fExisting.write(lines[0].split(";")[exVarIndex1] + ";" + lines[0].split(";")[exVarIndex2] + "\n"); for existingUser in existingUsers: split = existingUser.split(";"); fExisting.write(split[exVarIndex1] + ";" + split[exVarIndex2] + "\n"); #TODO: (minor) d...
waitForInCourseId();
random_line_split
traits.rs
!("by {}", self.author) } } impl NewsArticle { // You can't define this function in the "impl Summary for NewsArticle" block // because it's not a function of the NewsArticle trait! pub fn get_headline(&self) -> &String { &self.headline } } pub struct Tweet { pub username: String, ...
pub struct Cow {} impl Animal for Cow {
random_line_split
traits.rs
Sheep { fn is_naked(&self) -> bool { self.naked } pub fn shear(&mut self) { if self.is_naked() { // You can call the trait method "name()" here because Sheep implements // the Animal trait. println!("{} is already naked...", self.name()); } else ...
= sel
identifier_name
traits.rs
} // Default implementations can call other methods in the same trait, even if those other // methods don’t have a default implementation. In this way, a trait can provide a lot of // useful functionality and only require implementors to specify a small part of it. // This is the "template pattern"...
ent any trait on any type, as long as either the trait or the type is /// introduced in the current crate. This means that any time you want to add a method to any type, /// you can use a trait to do it. This is called an "extension trait". pub trait IsEmoji { fn is_emoji(&self) -> bool; } impl IsEmoji for char { ...
t lets you implem
conditional_block
traits.rs
IsEmoji { fn is_emoji(&self) -> bool; } impl IsEmoji for char { fn is_emoji(&self) -> bool { unimplemented!() } } /// We said earlier that when you implement a trait, either the trait or the type must be new in /// the current crate. This is called the "coherence rule". It helps Rust ensure that ...
} } struct Published {} impl
identifier_body
message.rs
en.bitcoin.it/wiki/Protocol_documentation#pong) Pong( /// The nonce from the [`Ping`] message this was in response to. Nonce, ), /// A `reject` message. /// /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#reject) Reject { /// Type of message rej...
from
identifier_name
message.rs
/// Note that although this is called `version` in Bitcoin, its role is really /// analogous to a `ClientHello` message in TLS, used to begin a handshake, and /// is distinct from a simple version number. /// /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#version) Version...
}, /// A `headers` message. /// /// Returns block headers in response to a getheaders packet. /// /// [Bitcoin reference](https://en.bitcoin.it/wiki/Protocol_documentation#headers) // Note that the block headers in this packet include a // transaction count (a var_int, so there can be m...
/// /// Set to zero to get as many blocks as possible (500). hash_stop: BlockHeaderHash,
random_line_split
openqabot.py
(self): if self.ibs: self.check_suse_incidents() # first calculate the latest build number for current jobs self.gather_test_builds() started = [] # then check progress on running incidents for req in self.requests: jobs = self.request_get_openq...
check_requests
identifier_name
openqabot.py
= incident.replace('_', '.').split('.')[1] req = self.is_incident_in_testing(incident) # without release request it's in staging if not req: continue # skip kgraft patches from aggregation req_ = osc.core.Request() ...
groups[gl]['passed'] = groups[gl]['passed'] + 1 continue
conditional_block
openqabot.py
code for SUSE Maintenance workflow
def calculate_incidents(self, incidents): """ get incident numbers from SUSE:Maintenance:Test project returns dict with openQA var name : string with numbers """ self.logger.debug("calculate_incidents: {}".format(pformat(incidents))) l_incidents = [] for kin...
project = 'SUSE:Maintenance:{}'.format(incident) xpath = "(state/@name='review') and (action/source/@project='{}' and action/@type='maintenance_release')".format(project) res = osc.core.search(self.apiurl, request=xpath)['request'] # return the one and only (or None) return res.find('re...
identifier_body
openqabot.py
code for SUSE Maintenance workflow project = 'SUSE:Maintenance:{}'.format(incident) xpath = "(state/@name='review') and (action/source/@project='{}' and action/@type='maintenance_release')".format(project) res = osc.core.search(self.apiurl, request=xpath)['request'] # return the one an...
types = {a.type for a in req.actions} if 'maintenance_release' in types: src_prjs = {a.src_project for a in req.actions} if len(src_prjs) != 1: raise Exception("can't handle maintenance_release from different incidents") build = src_prjs.pop() ...
def request_get_openqa_jobs(self, req, incident=True, test_repo=False): ret = None
random_line_split
all.js
clearInterval(this.timer); //关闭move中的定时器, 让敌机停止移动 //爆炸动画 var self = this; var index = 0; var dieTimer = setInterval(function(){ if (index >= self.dieImgs.length) { clearInterval(dieTimer); //关闭定时器 gameEngine.ele.removeChild(self.ele); //移除敌机 delete gameEngine.enemys[self.id]; //将当前的敌机对象从...
alert("Game Over!"); location.reload(); }); } } }, 30); }, //显示分数 showScore: function() { this.scoreNode = document.createElement("div"); this.scoreNode.className = "score"; this.scoreNode.innerHTML = "0"; gameEngine
identifier_body
all.js
- obj1.offsetHeight/2; var downSide = obj2.offsetTop + obj2.offsetHeight + obj1.offsetHeight/2; var x = obj1.offsetLeft+obj1.offsetWidth/2; var y = obj1.offsetTop + obj1.offsetHeight/2; if(x > leftSide && x < rightSide && y > upSide && y < downSide){ return true; } } return false; } ...
tSide = obj2.offsetLeft+obj2.offsetWidth+obj1.offsetWidth/2; var upSide = obj2.offsetTop
conditional_block
all.js
} return false; } //敌机: 类(构造函数) function Enemy(type) { //属性: this.ele = document.createElement("div"); this.hp = 0; //血量 this.speed = 0; //速度 this.dieImgs = []; //爆炸时的图片数组 //当前敌机所在gameEngine.enemys对象中的id this.id = parseInt(Math.random()*100000) + ""; this.score = 0; //分数 //方法: this.i...
} }, 30); } //受到一点伤害 this.hurt = function() { this.hp--; //掉一点血 if (this.hp == 0) { //当血量为0时 this.boom(); //爆炸 //把分数添加 gameEngine.scoreNode.innerHTML = (gameEngine.scoreNode.innerHTML-0) + this.score; } } //爆炸 this.boom = function() { clearInterval(this.timer); //关闭move中的定时器, 让敌机停止移动 ...
self.ele.style.top = self.ele.offsetTop + self.speed + "px";
random_line_split
all.js
eight + obj1.offsetHeight/2; var x = obj1.offsetLeft+obj1.offsetWidth/2; var y = obj1.offsetTop + obj1.offsetHeight/2; if(x > leftSide && x < rightSide && y > upSide && y < downSide){ return true; } } return false; } //敌机: 类(构造函数) function Enemy(type) { //属性: this.ele = document.crea...
offsetH
identifier_name
main.rs
, true); flags.set(OpenFlags::SQLITE_OPEN_READ_WRITE, true); flags.set(OpenFlags::SQLITE_OPEN_SHARED_CACHE, self.shared_cache); flags } } impl Database { pub fn create<P: AsRef<Path>>(path: P, options: &DbOptions) -> Self { let path: &Path = path.as_ref(); if path.exist...
else { "
{ "" }
conditional_block
main.rs
, true); flags.set(OpenFlags::SQLITE_OPEN_READ_WRITE, true); flags.set(OpenFlags::SQLITE_OPEN_SHARED_CACHE, self.shared_cache); flags } } impl Database { pub fn create<P: AsRef<Path>>(path: P, options: &DbOptions) -> Self { let path: &Path = path.as_ref(); if path.exist...
pub fn seed(&mut self) -> std::io::Result<Vec<u16>> { let mut transaction = self .conn .transaction() .expect("Could not open DB transaction"); transaction.set_drop_behavior(DropBehavior::Commit); let mut query = transaction .prepare( ...
{ if options.wal { self.conn .pragma_update(None, "journal_mode", &"WAL".to_owned()) .expect("Error applying WAL journal_mode"); } self.conn .execute( r#" CREATE TABLE "kv" ( "key" INTEGER NOT NULL, "value" BLOB NOT NULL,...
identifier_body
main.rs
{ conn: rusqlite::Connection, } #[derive(Copy, Clone, Debug)] struct DbOptions { wal: bool, shared_cache: bool, } impl DbOptions { fn db_flags(&self) -> rusqlite::OpenFlags { use rusqlite::OpenFlags; let mut flags = OpenFlags::empty(); flags.set(OpenFlags::SQLITE_OPEN_CREATE,...
Database
identifier_name
main.rs
_CREATE, true); flags.set(OpenFlags::SQLITE_OPEN_READ_WRITE, true); flags.set(OpenFlags::SQLITE_OPEN_SHARED_CACHE, self.shared_cache); flags } } impl Database { pub fn create<P: AsRef<Path>>(path: P, options: &DbOptions) -> Self { let path: &Path = path.as_ref(); if pat...
let key = rng.get_u16(); let timer = Instant::now(); let _guard; if USE_RWLOCK { _guard = rwlock.write().expect("Cannot unlock for read!"); } let rows_updated = query .execute(params![key, value]) .expect("Failed to issue update query!...
rng.fill_bytes(&mut value); while !stop.load(Ordering::Relaxed) {
random_line_split
lib.rs
gfx bits //! mut device, //! mut factory, //! mut color_view, //! mut depth_view, //! .. //! } = old_school_gfx_glutin_ext::window_builder(&event_loop, window_builder) //! .build::<ColorFormat, DepthFormat>()?; //! //! # let new_size = winit::dpi::PhysicalSize::new(1, 1); //! // Update gfx view...
} /// Recreate and replace gfx views if the dimensions have changed. pub fn resize_views<Color: RenderFormat, Depth: DepthFormat>( new_size: winit::dpi::PhysicalSize<u32>, color_view: &mut RenderTargetView<R, Color>, depth_view: &mut DepthStencilView<R, Depth>, ) { if let Some((cv, dv)) = resized_view...
{ Init { window: self.window, gl_config: self.gl_config, gl_surface: self.gl_surface, gl_context: self.gl_context, device: self.device, factory: self.factory, color_view: Typed::new(self.color_view), depth_view: Type...
identifier_body
lib.rs
Builder, ) -> Builder<'_, T> { Builder { event_loop, winit, surface_attrs: <_>::default(), ctx_attrs: <_>::default(), config_attrs: <_>::default(), sample_number_pref: <_>::default(), } } /// Builder for initialising a winit window, glutin context & gfx views. #[...
default
identifier_name
lib.rs
// gfx bits //! mut device, //! mut factory, //! mut color_view, //! mut depth_view, //! .. //! } = old_school_gfx_glutin_ext::window_builder(&event_loop, window_builder) //! .build::<ColorFormat, DepthFormat>()?; //! //! # let new_size = winit::dpi::PhysicalSize::new(1, 1); //! // Update gfx v...
.with_stencil_size(stencil_bits); let mut no_suitable_config = false; let (window, gl_config) = glutin_winit::DisplayBuilder::new() .with_window_builder(Some(self.winit)) .build(self.event_loop, config_attrs, |configs| { let mut configs: Vec<_> = conf...
.config_attrs .with_alpha_size(alpha_bits) .with_depth_size(depth_total_bits - stencil_bits)
random_line_split
__init___.py
user = current_user status = False if user.status == 'Listo': status = True files = {'Acta': user.acta, 'Credencial': user.cred, 'Foto': user.foto} files_status = {'acta': user.status_acta, 'cred': user.status_credencial, 'foto': user.status_foto} # return str(files2)...
if current_user.admin != 1: return redirect(url_for('index')) users = User.query.filter_by(admin=0).all() return render_template('lista.html', usuarios=users, admin=1) @app.route('/datos/<estudiante>', methods=['GET']) @login_required def datos(estudiante): if current_user.admin != 1: retur...
identifier_name
__init___.py
user = current_user status = False if user.status == 'Listo': status = True files = {'Acta': user.acta, 'Credencial': user.cred, 'Foto': user.foto} files_status = {'acta': user.status_acta, 'cred': user.status_credencial, 'foto': user.status_foto} # return str(files2)...
if item[1] == "1": aceptados.append(doc) with engine.connect() as connection: engine.execute("update users set status_"+doc+"=1 where email ='"+u.email+"'") else: rechazados.append(doc) with engine.connect() as connection: e...
doc = item[0].split('_')[1] revisados.append(doc.title())
random_line_split
__init___.py
@login_manager.user_loader def load_user(user_id): return User.query.get(unicode(user_id)) @app.route('/inicio/<success>') @login_required def inicio(success): user = current_user status = False if user.status == 'Listo': status = True files = {'Acta': user.acta, 'Credencial': user.cred,...
return "Acceso no autorizado, favor de iniciar sesión.".decode('utf8'), 401
identifier_body
__init___.py
user = current_user status = False if user.status == 'Listo': status = True files = {'Acta': user.acta, 'Credencial': user.cred, 'Foto': user.foto} files_status = {'acta': user.status_acta, 'cred': user.status_credencial, 'foto': user.status_foto} # return str(files2)...
w = engine.execute("select status_acta, status_credencial, status_foto from users where email='"+u.email+"'") estados = tuple(row.fetchone()) # return "<script type=\"text/javascript\">\ # alert(\""+str(estados)+"\");\ # window.location.href = '/admin'\ # </script>" if l...
em[0].split('_')[1] revisados.append(doc.title()) if item[1] == "1": aceptados.append(doc) with engine.connect() as connection: engine.execute("update users set status_"+doc+"=1 where email ='"+u.email+"'") else: rechazados.append(doc) ...
conditional_block
ply_loader.rs
a.unwrap() }; // Make new descriptor let elem_index = element_vec.len() as u32; current_element = Some(PlyElementDescriptor::new(elem_index, elem_name, num_entries)); } // Property descriptor else if line.starts_with("property") { // Check that we are actually in an elem...
let a = a.parse::<u32>(); if a.is_err() { return ply_err("Invalid element descriptor"); }
random_line_split
ply_loader.rs
// too small. // NOTE: This discards the internal buffer of the buffered reader so this // is fcking stupid, but without implementing it myself there is no other way let initial_stream_pos = match self.buf_reader.seek(SeekFrom::Current(0)) { Ok(pos) => pos, Err(err) => return Err(PlyReadError::Other(Box:...
fmt
identifier_name
ply_loader.rs
let mut split_line = line.split_ascii_whitespace(); let _ = split_line.next(); // Skip 'property' token let prop_type = { let a = split_line.next(); if a.is_none() { return ply_err("Invalid property descriptor"); } let a = a.unwrap(); if a.eq("list") { ...
{ s }
conditional_block
main.rs
o, timestamp) .get_reply() .ok()?; match info.connection() as u32 { xrandr::CONNECTION_CONNECTED => { let crtc = xrandr::get_crtc_info(&conn, info.crtc(), timestamp) .get_reply() .ok()?; Some(crtc.as_rect()) } _ => None, } ...
let pct = DisplayPercentageSpaceRect::new( DisplayPercentageSpacePoint::new(self.x.value(), self.y.value()), DisplayPercentageSpaceSize::new(self.w.value(), self.h.value()), ); let new_rect = pct .to_rect(display_frame) .inner_rect(geom.active_window_insets); dbg!(&new_rect); ...
let display_frame = get_output_available_rect(&conn)?; let geom = get_geometry(&conn)?;
random_line_split
main.rs
{ num: f32, denom: f32, } impl Fract { fn value(&self) -> f32 { self.num / self.denom } } impl std::str::FromStr for Fract { type Err = Error; fn from_str(s: &str) -> Result<Fract, Error> { let parts = s.split('/').collect::<Vec<_>>(); Ok(Fract { num: f32::from_str(parts[0])?, denom: f3...
Fract
identifier_name
lib.rs
vec.set(*b as usize, true); } Self::Decoded(vec) } /// Sets bit at bit index provided pub fn set(&mut self, bit: u64) { match self { BitField::Encoded { set, unset, .. } => { unset.remove(&bit); set.insert(bit); } ...
BitField::Decoded(bv) => { if let Some(true) = bv.get(index as usize) { Ok(true) } else { Ok(false) } } } } /// Retrieves the index of the first set bit, and error if invalid encoding or no ...
{ if set.contains(&index) { return Ok(true); } if unset.contains(&index) { return Ok(false); } // Check in encoded for the given bit // This can be changed to not flush changes ...
conditional_block
lib.rs
() -> Self { Self::Decoded(BitVec::new()) } } impl BitField { pub fn new() -> Self { Self::default() } /// Generates a new bitfield with a slice of all indexes to set. pub fn new_from_set(set_bits: &[u64]) -> Self { let mut vec = match set_bits.iter().max() { So...
default
identifier_name
lib.rs
vec.set(*b as usize, true); } Self::Decoded(vec) } /// Sets bit at bit index provided pub fn set(&mut self, bit: u64) { match self { BitField::Encoded { set, unset, .. } => { unset.remove(&bit); set.insert(bit); } ...
// TODO this probably should not require mut self and RLE decode bits pub fn get(&mut self, index: u64) -> Result<bool> { match self { BitField::Encoded { set, unset, .. } => { if set.contains(&index) { return Ok(true); } i...
random_line_split
lib.rs
vec.set(*b as usize, true); } Self::Decoded(vec) } /// Sets bit at bit index provided pub fn set(&mut self, bit: u64) { match self { BitField::Encoded { set, unset, .. } => { unset.remove(&bit); set.insert(bit); } ...
/// Intersection of two bitfields and assigns to self (equivalent of bit AND `&`) pub fn intersect_assign(&mut self, other: &Self) -> Result<()> { match other { BitField::Encoded { bv, set, unset } => { *self.as_mut_flushed()? &= decode_and_apply_cache(bv, set, unset)? ...
{ self.intersect_assign(other)?; Ok(self) }
identifier_body
pymines.py
66], 7: [0, 0, .33], 8: [0, 0, 0]} # Pre-defined levels (level: [width, height, mines]) levels = {0: [8, 8, 10], 1: [16, 16, 40], 2: [30, 16, 99]} # Aliases for the levels level_aliases = {**dict.fromkeys(['beginner', 'b', '0', 0], 0), **dict.fromkeys(['intermediate', 'i', '1', 1],...
def count_neighbor_flags(self, i, j): """ Counts the number of flags in the neighboring cells """ return np.count_nonzero(self.flags[(i-1 if i > 0 else 0):i+2, (j-1 if j > 0 else 0):j+2]) def update_revealed(self, i, j): """ Updates revealed cells by checking i,...
"" Counts the number of mines in the neighboring cells """ n_neighbor_mines = -1 if not self.mines[i, j]: n_neighbor_mines = np.count_nonzero( self.mines[(i-1 if i > 0 else 0):i+2, (j-1 if j > 0 else 0):j+2]) return n_neighbor_mines
identifier_body
pymines.py
_press) self.ax.format_coord = _CoordsFormatter(self.width, self.height) # Title text: number of flags/total mines self.title_txt = self.ax.set_title( '{}/{}'.format(np.count_nonzero(self.flags), self.n_mines)) self.refresh_canvas() def initialize(self, i, j): ...
mport argparse parser = argparse.ArgumentParser() parser.add_argument('-l', metavar='level (b, i, e)', default='beginner', help='level, i.e., ' 'beginner (8 x 8, 10 mines), intermediate (16 x 16, 40 mines), expert (30 ' 'x 16, 99 mines)') parser.add_argument(...
conditional_block
pymines.py
: """ Minesweeper Parameters ---------- width : int Width of minefield height : int Height of minefield n_mines : int Number of mines show : bool (optional) If True, displays game when initialized """ # Colormap object used for showing wrong cell...
Mines
identifier_name
pymines.py
.66], 7: [0, 0, .33], 8: [0, 0, 0]} # Pre-defined levels (level: [width, height, mines]) levels = {0: [8, 8, 10], 1: [16, 16, 40], 2: [30, 16, 99]} # Aliases for the levels level_aliases = {**dict.fromkeys(['beginner', 'b', '0', 0], 0), **dict.fromkeys(['intermediate', 'i', '1', 1...
# number of mines in the neighboring cells self.mines_count = np.full((self.height, self.width), 0, dtype=int) self.flags = np.full((self.height, self.width), False, dtype=bool) # mine flags self.revealed = np.full((self.height, self.width), False, dtype=bool) # revealed cells ...
self.mines = np.full((self.height, self.width), False, dtype=bool) # boolean, mine or not
random_line_split