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
gardenView.js
this.grid = { userDimensions: { width: width, length: length }, sizeMeter: ($(`#${this.containerSelector}`).width() - SCROLLBAR_WIDTH) / width, horizontalLines: [], verticalLines: [] }; $(`#${this.containerSelector}`).empty().append(` <div class="row"> ...
} const scoreInput = new ScoreInput(plants, plantModels, { sizeMeter: this.grid.sizeMeter }); // Call score process by dispatching save event with plants data this.actionDispatcher.dispatch({type: actions.SCORE, data: { input: scoreInput, }}); } /* Add a plant on grid, by put...
plantModels[plant.id] = plant; }
conditional_block
csv_test.py
(SPREADSHEETS_DIR, LOGFILE)): to_del.append(LOGFILE) for f in to_del: remove(join(SPREADSHEETS_DIR,f)) if to_del: print('Deleted',len(to_del),'files in', SPREADSHEETS_DIR) def files_to_check(): etalons = { f for f in listdir(ETALON_DIR) if f.endswith(EXTENSION) } tocomps = { f f...
create_header
identifier_name
csv_test.py
Dump CSV, with type info in the column # NaN as NaN string # Remove all exit() from sg2ps executable, throw test_finished exception? # Test failures can be tested as well # #------------------------------------------------------------------------------- _errors = { } def main(extra_msg = ''): ...
def check_rowlength(lines, expected_len): # Returns error message on error, None otherwise. # The first row is the header, and error messages use base 1 indices indices = [i for i, row in enumerate(lines, 2) if len(row)!=expected_len] if indices: return 'row length error in rows (header is row...
if len(header)==0: return None, 'missing' col_types = [ TO_TYPE.get(col[-1:], None) for col in header ] for i, typ in enumerate(col_types): if typ is None: msg = 'unrecognized type in column {}: "{}"'.format(i+1, header[i]) return None, msg assert len(col_types)==len(...
identifier_body
csv_test.py
Dump CSV, with type info in the column # NaN as NaN string # Remove all exit() from sg2ps executable, throw test_finished exception? # Test failures can be tested as well # #------------------------------------------------------------------------------- _errors = { } def main(extra_msg = ''): ...
mismatch = compare_values(etalon, tocomp) if mismatch: log_error(filename, 'mismatch, excel sheet written') write_mismatch(filename, etalon, tocomp, mismatch) return return True def log_error(filename, msg): assert filename not in _errors, (filename, _errors[filename]) _err...
msg = 'number of rows: {}!={}'.format(etalon_len, tocomp_len) log_error(filename, msg) return
conditional_block
csv_test.py
Dump CSV, with type info in the column # NaN as NaN string # Remove all exit() from sg2ps executable, throw test_finished exception? # Test failures can be tested as well # #------------------------------------------------------------------------------- _errors = { } def main(extra_msg = ''): ...
with open(filename, 'r') as f: header = extract_first_line(f) lines = [ split(line) for line in f ] print('Read {} lines'.format( bool(header) + len(lines) )) return header, lines def extract_first_line(f): header = next(f, None) return split(header) if header else [ ] def split(li...
return return header, table def read_csv(filename): print('Trying to read file "{}"'.format(filename))
random_line_split
list_view.rs
<'t> ListViewCell<'t> { pub fn new(con: String, style: &'t CompoundStyle) -> Self { let width = con.chars().count(); Self { con, style, width } } } impl<'t, T> ListViewColumn<'t, T> { pub fn new( title: &str, min_width: usize, max_width: usize, extract: Box<d...
else { self.area.height } } /// return an option which when filled contains /// a tupple with the top and bottom of the vertical /// scrollbar. Return none when the content fits /// the available space. #[inline(always)] pub fn scrollbar(&self) -> Option<(u16, u16)> {...
{ self.area.height - 2 }
conditional_block
list_view.rs
impl<'t> ListViewCell<'t> { pub fn new(con: String, style: &'t CompoundStyle) -> Self { let width = con.chars().count(); Self { con, style, width } } } impl<'t, T> ListViewColumn<'t, T> { pub fn new( title: &str, min_width: usize, max_width: usize, extract: B...
self.row_order = Some(sort); } /// return the height which is available for rows #[inline(always)] pub const fn tbody_height(&self) -> u16 { if self.area.height > 2 { self.area.height - 2 } else { self.area.height } } /// return an option w...
/// set a comparator for row sorting #[allow(clippy::type_complexity)] pub fn sort(&mut self, sort: Box<dyn Fn(&T, &T) -> Ordering>) {
random_line_split
list_view.rs
<'t> ListViewCell<'t> { pub fn new(con: String, style: &'t CompoundStyle) -> Self { let width = con.chars().count(); Self { con, style, width } } } impl<'t, T> ListViewColumn<'t, T> { pub fn new( title: &str, min_width: usize, max_width: usize, extract: Box<d...
(&mut self, data: T) { let stick_to_bottom = self.row_order.is_none() && self.do_scroll_show_bottom(); let displayed = match &self.filter { Some(fun) => fun(&data), None => true, }; if displayed { self.displayed_rows_count += 1; } if st...
add_row
identifier_name
lib.rs
the expected amount of data [Expected {}, Actual {}]", actual, expected) } Fetch { description("While reading message") display("While reading message") } InvalidTransport(t: String) { description("Transport not valid") ...
get_file
identifier_name
lib.rs
<'a> { fn read<T: Read + 'a>(mut stream: T) -> Result<Self> { //Get the length of the name let name_len = try!(stream.read_u32::<BigEndian>()); //Get the name from the stream let mut name_buff = Vec::with_capacity(name_len as usize); //@Expansion: Here we have the 32-bit again. ...
{ bail!(ErrorKind::FileExists(new_path)); }
conditional_block
lib.rs
and cause will // forward to the description and cause of the original error. // // Optionally, some attributes can be added to a variant. // // This section can be empty. foreign_links { Io(io::Error) #[cfg(unix)]; } // Define additional `Er...
}; } pub fn present(&self, t: &Transport) -> Result<String> { let parts = (t.max_state() as f64).log(self.dict_entries as f64).ceil() as u32; let mut part_representation: Vec<&str> = Vec::with_capacity(parts as usize); let mut remainder = t.state(); for _ in 0..parts {...
dictionary: dictionary, dict_entries: dict_entries,
random_line_split
lib.rs
description and cause will // forward to the description and cause of the original error. // // Optionally, some attributes can be added to a variant. // // This section can be empty. foreign_links { Io(io::Error) #[cfg(unix)]; } // Define ad...
fn from_transport<T: PartialTransport>(t: T) -> Result<Self> { return Ok(std::net::Ipv4Addr::from(t.state())); } } #[derive(Clone)] pub struct FileInfo{
{ return Ok(ServerTransport::new(u32::from(self.clone()), std::u32::MAX)); }
identifier_body
bulk.rs
_block, read_indexed_blockhashes}; use crate::metrics::Metrics; use crate::signal::Waiter; use crate::store::{DbStore, Row, WriteStore}; use crate::util::{spawn_thread, HeaderList, SyncChannel}; struct Parser { magic: u32, current_headers: HeaderList, indexed_blockhashes: Mutex<HashSet<BlockHash>>, cas...
(blob: Vec<u8>, magic: u32) -> Result<Vec<Block>> { let mut cursor = Cursor::new(&blob); let mut blocks = vec![]; let max_pos = blob.len() as u64; while cursor.position() < max_pos { let offset = cursor.position(); match u32::consensus_decode(&mut cursor) { Ok(value) => { ...
parse_blocks
identifier_name
bulk.rs
ed_block, read_indexed_blockhashes}; use crate::metrics::Metrics; use crate::signal::Waiter; use crate::store::{DbStore, Row, WriteStore}; use crate::util::{spawn_thread, HeaderList, SyncChannel}; struct Parser { magic: u32, current_headers: HeaderList, indexed_blockhashes: Mutex<HashSet<BlockHash>>, c...
let chan = SyncChannel::new(0); let blobs = chan.sender(); let handle = spawn_thread("bulk_read", move || -> Result<()> { for path in blk_files { blobs .send((parser.read_blkfile(&path)?, path)) .expect("failed to send blk*.dat contents"); } ...
type JoinHandle = thread::JoinHandle<Result<()>>; type BlobReceiver = Arc<Mutex<Receiver<(Vec<u8>, PathBuf)>>>; fn start_reader(blk_files: Vec<PathBuf>, parser: Arc<Parser>) -> (BlobReceiver, JoinHandle) {
random_line_split
bulk.rs
_block, read_indexed_blockhashes}; use crate::metrics::Metrics; use crate::signal::Waiter; use crate::store::{DbStore, Row, WriteStore}; use crate::util::{spawn_thread, HeaderList, SyncChannel}; struct Parser { magic: u32, current_headers: HeaderList, indexed_blockhashes: Mutex<HashSet<BlockHash>>, cas...
bytes_read: metrics.histogram(prometheus::HistogramOpts::new( "electrscash_parse_bytes_read", "# of bytes read (from blk*.dat)", )), })) } fn last_indexed_row(&self) -> Row { // TODO: use JSONRPC for missing blocks, and don't use 'L' row...
{ Ok(Arc::new(Parser { magic: daemon.disk_magic(), current_headers: load_headers(daemon)?, indexed_blockhashes: Mutex::new(indexed_blockhashes), cashaccount_activation_height, duration: metrics.histogram_vec( prometheus::HistogramOpts::...
identifier_body
chapter12.py
f from keras import backend as K #import tensorflow.keras.backend as K #from tensorflow.python.keras import backend as K def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1 err = y_pred - y_true return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 ) #-------------------- BRAIN ------------------------...
) model.add(Dense(self.layer1_para, kernel_initializer='lecun_uniform', input_shape=(self.stateCnt,))) model.add(Activation('relu')) #model.add(Dropout(0.2)) I'm not using dropout, but maybe you wanna give it a try? model.add(Dense(self.layer2_para, kernel_initializer='lecun_unifor...
Sequential(
identifier_name
chapter12.py
f.VERSION) ## 1.14.0 print(tf.keras.__version__) ## 2.2.4-tf from keras import backend as K #import tensorflow.keras.backend as K #from tensorflow.python.keras import backend as K def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1 err = y_pred - y_true return K.mean( K.sqrt(1+K.square(err))-1, axi...
dataIdx = idx - self.capacity + 1 return (idx, self.tree[idx], self.data[dataIdx]) import tensorflow as tf print(t
identifier_body
chapter12.py
f from keras import backend as K #import tensorflow.keras.backend as K #from tensorflow.python.keras import backend as K def hubert_loss(y_true, y_pred): # sqrt(1+a^2)-1 err = y_pred - y_true return K.mean( K.sqrt(1+K.square(err))-1, axis=-1 ) #-------------------- BRAIN ------------------------...
n based on our eperience self.steps += 1 self.epsilon = MIN_EPSILON + (MAX_EPSILON - MIN_EPSILON) * math.exp(-LAMBDA * self.steps) def _getTargets(self, batch): no_state = numpy.zeros(self.stateCnt) states = numpy.array([ o[1][0] for o in batch ]) states_ = numpy.ar...
# slowly decrease Epsilo
conditional_block
chapter12.py
, s, target=False): if target: return self.model_.predict(s) else: return self.model.predict(s) def predictOne(self, s, target=False): return self.predict(s.reshape(1, self.stateCnt), target=target).flatten() def updateTargetModel(self): self.m...
#plt.plot(u0,close20,'og') ####################################
random_line_split
userlist.js
({el: 'startDate'}).children('#startDate');//.val(minusMonth(6)); $('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd')); //查询按钮 $('#queryBtn').on('click', function (e) { $('#page').val(1); $('#rows').val(10) $('#subAccount').va...
nth() + 1) + '-' + addzero(date.getDate() + 1); return s; } //月份
identifier_body
userlist.js
Date().getTime() + '&hisArr=' + hisArr.toString() + '&subUserId=' + userId + '&queryMap=' + queryMapFormat( JSON.stringify(queryMap)); }, openTeam: function (userId, account) { hisArr.push($("#subAccount").val());//把上一次放入历史操作数组 window.location.href = '/page/user-center/agent...
} catch (e) { } if (responseText.code === 'UC/TOKEN_INVALID') { alert('网络连接超时,请重新登陆!'); $.cookie('token', null, {path: '/'}); window.location.href = '/views/main.html'; } }); return account; } function cleanQueryForm() { $('#account').val(null); $('#moneyF...
seText);
identifier_name
userlist.js
new Date().getTime() + '&hisArr=' + hisArr.toString() + '&subUserId=' + userId + '&queryMap=' + queryMapFormat( JSON.stringify(queryMap)); }, openTeam: function (userId, account) { hisArr.push($("#subAccount").val());//把上一次放入历史操作数组 window.location.href = '/page/user-center/a...
$('#startDatePicker').datepicker({el: 'startDate'}).children('#startDate');//.val(minusMonth(6)); $('#endDatePicker').datepicker({el: 'endDate'}).children('#endDate');//.val($.dateformat(new Date(), 'yyyy-MM-dd')); //查询按钮 $('#queryBtn').on('click', function (e) { $('#page').val(1); $('#rows')....
account = loadCurrAccount();//初始隐藏currAccount值 //设置默认查询时间 最近半年
conditional_block
userlist.js
+ queryMapFormat( JSON.stringify(queryMap)); }, openBill: function (userId) { hisArr.push($("#subAccount").val());//把上一次放入历史操作数组 window.location.href = '/page/user-center/report/bill_report.html?' + new Date().getTime() + '&hisArr=' + hisArr.toString() + '&subUserI...
return false; };
random_line_split
gcm.go
is not constant-time. // An exception is when the underlying Block was created by aes.NewCipher // on systems with hardware support for AES. See the crypto/aes package documentation for details. func newGCM(cipher goCipher.Block) (aeadIf, error) { return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTagS...
e) { ciphertext := make([]byte, len(g.block)) g.counterCrypt(ciphertext, g.block, &g.counter) g.block = nil g.counter = [gcmBlockSize]byte{} g.len.ct += len(ciphertext) g.update(&g.tagaccum, ciphertext) tag := make([]byte, g.tagSize) g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask) g.tagmask ...
yte, []byt
identifier_name
gcm.go
(&g.tagaccum, g.block) g.counterCrypt(plaintext, g.block, &g.counter) g.block = nil g.counter = [gcmBlockSize]byte{} tag := make([]byte, g.tagSize) g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask) g.tagmask = [gcmBlockSize]byte{} g.tagaccum = gcmFieldElement{} g.len.aad = 0 g.len.ct = 0 retur...
identifier_body
gcm.go
6 multiples of |key|. However, when we do lookups // into this table we'll be using bits from a field element and // therefore the bits will be in the reverse order. So normally one // would expect, say, 4*key to be in index 4 of the table but due to // this bit ordering it will actually be in index 0010 (base 2) =...
BlockSize]byte copy(partialBlock[:], data[fullBlocks:]) g.updateBlocks(y, partialBlock[:]) } } // gcmInc32 treats th
conditional_block
gcm.go
CM is not constant-time. // An exception is when the underlying Block was created by aes.NewCipher // on systems with hardware support for AES. See the crypto/aes package documentation for details. func newGCM(cipher goCipher.Block) (aeadIf, error) { return newGCMWithNonceAndTagSize(cipher, gcmStandardNonceSize, gcmTa...
g.block = nil g.counter = [gcmBlockSize]byte{} tag := make([]byte, g.tagSize) g.authFinal(tag, g.tagaccum, g.len.aad, g.len.ct, &g.tagmask) g.tagmask = [gcmBlockSize]byte{} g.tagaccum = gcmFieldElement{} g.len.aad = 0 g.len.ct = 0 return plaintext, subtle.ConstantTimeCompare(tag, expectedTag) == 1 } // re...
g.update(&g.tagaccum, g.block) g.counterCrypt(plaintext, g.block, &g.counter)
random_line_split
lib.rs
/cursive/latest/cursive/struct.Cursive.html //! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html //! [`html2text`]: https://docs.rs/html2text/latest/html2text/ //! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html //! [`Convert...
/// [`set_maximum_width`][] method. /// /// [`RenderedDocument`]: struct.RenderedDocument.html /// [`Renderer`]: trait.Renderer.html /// [`render`]: trait.Renderer.html#method.render /// [`on_link_select`]: #method.on_link_select /// [`on_link_focus`]: #method.on_link_focus /// [`set_maximum_width`]: #method.set_maximu...
/// /// You can also limit the available width by setting a maximum line width with the
random_line_split
lib.rs
/cursive/latest/cursive/struct.Cursive.html //! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html //! [`html2text`]: https://docs.rs/html2text/latest/html2text/ //! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html //! [`Convert...
fn layout(&mut self, constraint: cursive_core::XY<usize>) { self.render(constraint); } fn required_size(&mut self, constraint: cursive_core::XY<usize>) -> cursive_core::XY<usize> { self.render(constraint) } fn take_focus(&mut self, direction: cursive_core::direction::Direction) -> ...
let doc = &self.doc.as_ref().expect("layout not called before draw"); for (y, line) in doc.lines.iter().enumerate() { let mut x = 0; for element in line { let mut style = element.style; if let Some(link_idx) = element.link_idx { ...
identifier_body
lib.rs
/cursive/latest/cursive/struct.Cursive.html //! [`ScrollView`]: https://docs.rs/cursive/latest/cursive/views/struct.ScrollView.html //! [`html2text`]: https://docs.rs/html2text/latest/html2text/ //! [`TextDecorator`]: https://docs.rs/html2text/latest/html2text/render/text_renderer/trait.TextDecorator.html //! [`Convert...
text: String, style: theme::Style, link_target: Option<String>, } #[derive(Clone, Debug, Default)] struct RenderedElement { text: String, style: theme::Style, link_idx: Option<usize>, } #[derive(Clone, Debug, Default)] struct LinkHandler { links: Vec<Link>, focus: usize, } #[derive(C...
ement {
identifier_name
ed_glob.py
ID_PREF_TABS = wx.NewId() ID_PREF_UNINDENT = wx.NewId() ID_PREF_TABW = wx.NewId() ID_PREF_INDENTW = wx.NewId() ID_PREF_FHIST = wx.NewId() ID_PREF_WSIZE = wx.NewId() ID_PREF_WPOS = wx.NewId() ID_PREF_ICON = wx.NewId() ID_PREF_ICONSZ = wx.NewId() ID_PREF_MODE = wx.NewId() ID_PREF_TABICON = w...
EOLModeMap
identifier_name
ed_glob.py
Plugin Dir 'SYSPIX_DIR' : "", # Editras non user graphics 'THEME_DIR' : "", # Theme Directory 'LANG_DIR' : "", # Locale Data Directory 'SYS_PLUGIN_DIR' : "", # Editra base plugin dir 'SYS_STYLES_DIR' : "", # Editra base style sheets 'TEST_DIR' ...
ID_READONLY = wx.NewId() ID_NEW_FOLDER = wx.NewId()
random_line_split
ed_glob.py
.NewId() ID_PREF_ICONSZ = wx.NewId() ID_PREF_MODE = wx.NewId() ID_PREF_TABICON = wx.NewId() ID_PRINT_MODE = wx.NewId() ID_TRANSPARENCY = wx.NewId() ID_PREF_SPOS = wx.NewId() ID_PREF_UPDATE_BAR = wx.NewId() ID_PREF_VIRT_SPACE = wx.NewId() ID_PREF_CARET_WIDTH = wx.NewId() ID_PREF_WARN_EOL = wx.NewId() ID_S...
"""Get the eol mode map""" # Maintenance Note: ints must be kept in sync with EDSTC_EOL_* in edstc return { EOL_MODE_CR : _("Old Machintosh (\\r)"), EOL_MODE_LF : _("Unix (\\n)"), EOL_MODE_CRLF : _("Windows (\\r\\n)")}
identifier_body
ed_glob.py
_ABOUT', 'ID_HOMEPAGE', 'ID_CONTACT', 'ID_BUG_TRACKER', 'ID_DOCUMENTATION', 'ID_COMMAND', 'ID_USE_SOFTTABS', 'ID_DUP_LINE', 'ID_TRANSLATE', 'I18N_PAGE', 'ID_GOTO_MBRACE', 'ID_HLCARET_LINE', 'ID_SHOW_SB', 'ID_REVERT_FILE', 'ID_RELOAD_ENC', 'ID_DOCPROP', 'ID_PASTE_AFTER', ...
ID_QUICK_FIND = wx.NewId() ID_PREF = wx.ID_PREFERENCES # Preference Dlg Ids ID_PREF_LANG = wx.NewId() ID_PREF_AALIAS = wx.NewId() ID_PREF_AUTOBKUP = wx.NewId() ID_PREF_AUTO_RELOAD = wx.NewId() ID_PREF_AUTOCOMPEX = wx.NewId() ID_PREF_AUTOTRIM = wx.NewId() ID_PREF_CHKMOD = wx.NewId() ID_PREF_CHKUPDA...
ID_FIND = wx.NewId() ID_FIND_REPLACE = wx.NewId()
conditional_block
spec.rs
_state.get().iter() { db.note_non_null_account(address); account.insert_additional( &mut *factories.accountdb.create( db.as_hash_db_mut(), keccak(address), ), &factories.trie, ); } let start_nonce = engine.account_start_nonce(0); let mut state = State::from_existing(db, root, start_nonce, fa...
else { Machine::regular(params, builtins) } } /// Convert engine spec into a arc'd Engine of the right underlying type. /// TODO avoid this hard-coded nastiness - use dynamic-linked plugin framework instead. fn engine( spec_params: SpecParams, engine_spec: ethjson::spec::Engine, params: CommonParams, ...
{ Machine::with_ethash_extensions(params, builtins, ethash.params.clone().into()) }
conditional_block
spec.rs
-> fmt::Result { writeln!(f, "{{")?; writeln!(f, r#"header": "{:?},"#, self.header)?; writeln!(f, r#"total_difficulty": "{:?},"#, self.total_difficulty)?; writeln!(f, r#"chts": {:#?}"#, self.chts.iter().map(|x| format!(r#"{}"#, x)).collect::<Vec<_>>())?; writeln!(f, "}}") } } /// Load from JSON object. fn ...
let params = CommonParams::from(s.params); Spec::machine(&s.engine, params, builtins)
random_line_split
spec.rs
_state.get().iter() { db.note_non_null_account(address); account.insert_additional( &mut *factories.accountdb.create( db.as_hash_db_mut(), keccak(address), ), &factories.trie, ); } let start_nonce = engine.account_start_nonce(0); let mut state = State::from_existing(db, root, start_nonce, fa...
( spec_params: SpecParams, engine_spec: ethjson::spec::Engine, params: CommonParams, builtins: BTreeMap<Address, Builtin>, ) -> Arc<dyn Engine> { let machine = Self::machine(&engine_spec, params, builtins); match engine_spec { ethjson::spec::Engine::Null(null) => Arc::new(NullEngine::new(null.params.in...
engine
identifier_name
spec.rs
} impl<'a, T: AsRef<Path>> From<&'a T> for SpecParams<'a> { fn from(path: &'a T) -> Self { Self::from_path(path.as_ref()) } } /// given a pre-constructor state, run all the given constructors and produce a new state and /// state root. fn run_constructors<T: Backend>( genesis_state: &PodState, constructors: &[...
{ SpecParams { cache_dir: path, optimization_setting: Some(optimization), } }
identifier_body
language.go
.app/definitions/crazy/"}, {Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read more information abo...
d, ensure its bounded as it should. if !strings.Contains(word.Filter, " ") { word.Filter = fmt.Sprintf("(?:^|\\W)%s(?:$|[^\\w+])", word.Filter) } word.regex, _ = regexp.Compile(word.Filter) } if word.regex.MatchString(text) { word.Reply += conductLinks return &word } } return nil }
conditional_block
language.go
://www.selfdefined.app/definitions/crazy/"}, {Filter: "insane", Reply: "The word *insane* is considered by some to be insensitive to sufferers of mental illness. Perhaps you mean *outrageous*, *unthinkable*, *nonsensical*, *incomprehensible*? Have you considered a different adjective like *ridiculous*? You can read mo...
:= transform.Chain(norm.NFD, runes.Remove(runes.In(unicode.Mn)), norm.NFC) text, _, _ := transform.String(t, strings.ToLower(input)) filters := append(inclusiveFilters, extraFilters...) for _, word := range filters { if word.regex == nil { // If it's just one word, ensure its bounded as it should. if !strin...
identifier_body
language.go
"unicode" "golang.org/x/text/runes" "golang.org/x/text/transform" "golang.org/x/text/unicode/norm" ) type InclusiveFilter struct { Filter string // Supports regex Reply string regex *regexp.Regexp // do not fill. Just used for caching the regex once compiled. } var conductLinks = "\nIn case of doubts please...
import ( "fmt" "regexp" "strings"
random_line_split
language.go
ronyms, _especially_ when they are already marginalized. See: en.wikipedia.org/wiki/Underrepresented_group`}, {Filter: "URG", Reply: `Underrepresented group(s). But please consider using the full term "members of traditionally underrepresented groups" or similar; people don't like to be made into acronyms, _especially...
*Incl
identifier_name
dynamic_scene.rs
HashMap; #[cfg(feature = "serialize")] use crate::serde::SceneSerializer; use bevy_ecs::reflect::ReflectResource; #[cfg(feature = "serialize")] use serde::Serialize; /// A collection of serializable resources and dynamic entities. /// /// Each dynamic entity in the collection contains its own run-time defined set of ...
use crate::dynamic_scene_builder::DynamicSceneBuilder; #[test] fn components_not_defined_in_scene_should_not_be_affected_by_scene_entity_map() { // Testing that scene reloading applies EntityMap correctly to MapEntities components. // First, we create a simple world with a parent and a chi...
use bevy_hierarchy::{AddChild, Parent}; use bevy_utils::HashMap;
random_line_split
dynamic_scene.rs
; #[cfg(feature = "serialize")] use crate::serde::SceneSerializer; use bevy_ecs::reflect::ReflectResource; #[cfg(feature = "serialize")] use serde::Serialize; /// A collection of serializable resources and dynamic entities. /// /// Each dynamic entity in the collection contains its own run-time defined set of compone...
} Ok(()) } /// Write the resources, the dynamic entities, and their corresponding components to the given world. /// /// This method will return a [`SceneSpawnError`] if a type either is not registered /// in the world's [`AppTypeRegistry`] resource, or doesn't reflect the ///...
{ map_entities_reflect.map_entities(world, entity_map, &entities); }
conditional_block
dynamic_scene.rs
; #[cfg(feature = "serialize")] use crate::serde::SceneSerializer; use bevy_ecs::reflect::ReflectResource; #[cfg(feature = "serialize")] use serde::Serialize; /// A collection of serializable resources and dynamic entities. /// /// Each dynamic entity in the collection contains its own run-time defined set of compone...
#[cfg(test)] mod tests { use bevy_ecs::{reflect::AppTypeRegistry, system::Command, world::World}; use bevy_hierarchy::{AddChild, Parent}; use bevy_utils::HashMap; use crate::dynamic_scene_builder::DynamicSceneBuilder; #[test] fn components_not_defined_in_scene_should_not_be_affected_by_scene...
{ let pretty_config = ron::ser::PrettyConfig::default() .indentor(" ".to_string()) .new_line("\n".to_string()); ron::ser::to_string_pretty(&serialize, pretty_config) }
identifier_body
dynamic_scene.rs
; #[cfg(feature = "serialize")] use crate::serde::SceneSerializer; use bevy_ecs::reflect::ReflectResource; #[cfg(feature = "serialize")] use serde::Serialize; /// A collection of serializable resources and dynamic entities. /// /// Each dynamic entity in the collection contains its own run-time defined set of compone...
{ /// The identifier of the entity, unique within a scene (and the world it may have been generated from). /// /// Components that reference this entity must consistently use this identifier. pub entity: Entity, /// A vector of boxed components that belong to the given entity and /// implement ...
DynamicEntity
identifier_name
bank.rs
= mig.add_ingredient("credits", &["acct_id", "total"], Aggregation::SUM.over(transfers, 2, &[1])); // add join of credits and debits; this is a hack as we don't currently have multi-parent // aggregations or arithmetic on column...
fn client(i: usize, mut transfers_put: Box<Putter>, balances_get: Box<Getter>, naccounts: i64, start: time::Instant, runtime: time::Duration, verbose: bool, cdf: bool, audit: bool, transactions: &mut Vec<(i64, i64, i64)>) ...
{ // prepopulate non-transactionally (this is okay because we add no accounts while running the // benchmark) println!("Connected. Setting up {} accounts.", naccounts); { // let accounts_put = bank.accounts.as_ref().unwrap(); let mut money_put = transfers_put.transfer(); for i in...
identifier_body
bank.rs
= mig.add_ingredient("credits", &["acct_id", "total"], Aggregation::SUM.over(transfers, 2, &[1])); // add join of credits and debits; this is a hack as we don't currently have multi-parent // aggregations or arithmetic on column...
(naccounts: i64, transfers_put: &mut Box<Putter>) { // prepopulate non-transactionally (this is okay because we add no accounts while running the // benchmark) println!("Connected. Setting up {} accounts.", naccounts); { // let accounts_put = bank.accounts.as_ref().unwrap(); let mut mone...
populate
identifier_name
bank.rs
transactionally (this is okay because we add no accounts while running the // benchmark) println!("Connected. Setting up {} accounts.", naccounts); { // let accounts_put = bank.accounts.as_ref().unwrap(); let mut money_put = transfers_put.transfer(); for i in 0..naccounts { ...
}) }) .collect::<Vec<_>>();
random_line_split
HiddenEye.py
BE CAPTURED ] _______________________________________________________________ {1}'''.format(GREEN, DEFAULT, CYAN)) if 256 != system('which php'): #Checking if user have PHP print (" -----------------------".format(CYAN, DEFAULT)) print ("[PHP INSTALLATION FOU...
custom
identifier_name
HiddenEye.py
checkNgrok() def end(): #Message when HiddenEye exit system('clear') print ('''{1}THANK YOU FOR USING ! JOIN DARKSEC TEAM NOW (github.com/DarkSecDevelopers).{1}'''.format(RED, DEFAULT, CYAN)) print ('''{1}WAITING FOR YOUR CONTRIBUTION. GOOD BYE !.{1}'''.format(RED, DEFAULT, CYAN)) def loadModule(module):...
if path.isfile('Server/ngrok') == False: print('[*] Downloading Ngrok...') if 'Android' in str(check_output(('uname', '-a'))): filename = 'ngrok-stable-linux-arm.zip' else: ostype = systemos().lower() if architecture()[0] == '64bit': filename =...
identifier_body
HiddenEye.py
elif option2 == '1' and page == 'Google': copy_tree("WebPages/google_standard/", "Server/www/") elif option2 == '2' and page == 'Google': copy_tree("WebPages/google_advanced_poll/", "Server/www/") elif option2 == '3' and page == 'Google': copy_tree("WebPages/google_advanced_web/", "S...
else: matchObj = re.match('^(.*?),(.*)$', ipinfo['loc']) latitude = matchObj.group(1) longitude = matchObj.group(2) log('======================================================================'.format(RED, DEFAULT)) ...
log('======================================================================'.format(RED, DEFAULT)) log(' \n{0}[ VICTIM IP BONUS ]{1}:\n {0}%s{1}'.format(GREEN, DEFAULT) % lines)
conditional_block
HiddenEye.py
}[ LIVE VICTIM ATTACK INFORMATION ] {0}[ LIVE KEYSTROKES CAN BE CAPTURED ] _______________________________________________________________ {1}'''.format(GREEN, DEFAULT, CYAN)) if 256 != system('which php'): #Checking if user have PHP print (" --------------...
random_line_split
lib.rs
: {}", config_filename); let f = match File::open(&config_filename) { Ok(file) => file, Err(_) => return Err("Unable to open configuration file."), }; // Decode RON format of configuration file let config: Config = match from_reader(f) { Ok(x) => x, ...
/// Calculates the cross power spectrum of the given 3D grids (note if the same /// grid is given twice then this is the auto power spectrum). /// /// # Examples /// /// ``` /// let output: Output = correlate(&config, grid1, grid2).unwrap(); /// ``` pub fn correlate( config: &Config, out1: AlignedVec<c64>, ...
{ let mut out = AlignedVec::new(ngrid3); match plan.c2c(&mut grid, &mut out) { Ok(_) => (), Err(_) => return Err("Failed to FFT grid."), }; Ok(out) }
identifier_body
lib.rs
: {}", config_filename); let f = match File::open(&config_filename) { Ok(file) => file, Err(_) => return Err("Unable to open configuration file."), }; // Decode RON format of configuration file let config: Config = match from_reader(f) { Ok(x) => x, ...
} /// Performs FFT on grids /// /// # Examples /// /// ``` /// let output: Output = correlate(&config, grid1, grid2).unwrap(); /// ``` pub fn perform_fft( config: &Config, grid1: AlignedVec<c64>, grid2: AlignedVec<c64>, ) -> Result<(AlignedVec<c64>, AlignedVec<c64>), &'static str> { println!("\nPerform...
}); Ok(grid)
random_line_split
lib.rs
: {}", config_filename); let f = match File::open(&config_filename) { Ok(file) => file, Err(_) => return Err("Unable to open configuration file."), }; // Decode RON format of configuration file let config: Config = match from_reader(f) { Ok(x) => x, ...
(config: &Config, num: usize) -> Result<AlignedVec<c64>, &'static str> { let filename = match num { 1 => &config.grid1_filename, 2 => &config.grid2_filename, _ => return Err("Need to load either grid 1 or 2!"), }; println!("\nOpening grid from file: {}", filename); let ngrid: usi...
load_grid
identifier_name
jwt.go
= "token" ) // Opts holds constructor params type Opts struct { SecretReader Secret ClaimsUpd ClaimsUpdater SecureCookies bool TokenDuration time.Duration CookieDuration time.Duration DisableXSRF bool DisableIAT bool // disable IssuedAt claim // optional (custom) names for cookies and headers ...
(opts Opts) *Service { res := Service{Opts: opts} setDefault := func(fld *string, def string) { if *fld == "" { *fld = def } } setDefault(&res.JWTCookieName, defaultJWTCookieName) setDefault(&res.JWTHeaderKey, defaultJWTHeaderKey) setDefault(&res.XSRFCookieName, defaultXSRFCookieName) setDefault(&res.XS...
NewService
identifier_name
jwt.go
j *Service) Token(claims Claims) (string, error) { // make token for allowed aud values only, rejects others // update claims with ClaimsUpdFunc defined by consumer if j.ClaimsUpd != nil { claims = j.ClaimsUpd.Update(claims) } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) if j.SecretReader == n...
{ return f(aud) }
identifier_body
jwt.go
type Claims struct { jwt.StandardClaims User *User `json:"user,omitempty"` // user info SessionOnly bool `json:"sess_only,omitempty"` Handshake *Handshake `json:"handshake,omitempty"` // used for oauth handshake NoAva bool `json:"no-ava,omitempty"` // disable avatar, always use i...
Opts } // Claims stores user info for token and state & from from login
random_line_split
jwt.go
= "token" ) // Opts holds constructor params type Opts struct { SecretReader Secret ClaimsUpd ClaimsUpdater SecureCookies bool TokenDuration time.Duration CookieDuration time.Duration DisableXSRF bool DisableIAT bool // disable IssuedAt claim // optional (custom) names for cookies and headers ...
} secret, err := j.SecretReader.Get(aud) if err != nil { return Claims{}, fmt.Errorf("can't get secret: %w", err) } token, err := parser.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("u...
{ return Claims{}, fmt.Errorf("can't retrieve audience from the token") }
conditional_block
helper.js
}); return R.sortWith(colItems, data); }; // data grouping // * 특정컬럼들을 추출하여 grouping 하여 array JSON 형식으로 리턴 // ex) dGroup(["AColumn", "BColumn"], arrayJson); // ex2) dGroup(["AColumn", "BColumn"], arrayJson, ["AColumn"]); // return => [{"AColumn": 5, "BColumn": 6}, {"AColumn": 4, "BColumn": 2}, {"AColumn": 3, "BCol...
f (appendText) rtnText = rtnText + appendText; return rtnText; } return text; }; // Blob -> String 변환 export const parseBlob = async (file) => { const reader = new FileReader(); reader.readAsText(file); return await new Promise((resolve, reject) => { reader.onload = function (event) { resolve(...
); let rtnText = maskingArray.join(''); i
conditional_block
helper.js
}); return R.sortWith(colItems, data); }; // data grouping // * 특정컬럼들을 추출하여 grouping 하여 array JSON 형식으로 리턴 // ex) dGroup(["AColumn", "BColumn"], arrayJson); // ex2) dGroup(["AColumn", "BColumn"], arrayJson, ["AColumn"]); // return => [{"AColumn": 5, "BColumn": 6}, {"AColumn": 4, "BColumn": 2}, {"AColumn": 3, "BCol...
let p = point; while (node) { p = p + node.textContent.length; text = isPre ? node.textContent + text : text + node.textContent; node = getNode(parent, node, isPre, point); } // 문자열 앞뒤 공백 OR 문자열 확인 const firstWord = isPre ? text.substring(p - 1, p) : text.slice(0, 1); const wordCheck = firstW...
random_line_split
api_op_CreateFileSystem.go
ProvisionedThroughputInMibps *float64 // Use to create one or more tags associated with the file system. Each tag is a // user-defined key-value pair. Name your file system on creation by including a // "Key":"Name","Value":"{value}" key-value pair. Each key must be unique. For more // information, see Tagging Am...
{ if m.tokenProvider == nil { return next.HandleInitialize(ctx, in) } input, ok := in.Parameters.(*CreateFileSystemInput) if !ok { return out, metadata, fmt.Errorf("expected middleware input to be of type *CreateFileSystemInput ") } if input.CreationToken == nil { t, err := m.tokenProvider.GetIdempotencyT...
identifier_body
api_op_CreateFileSystem.go
111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab . // - Key alias - A previously created display name for a key, for example // alias/projectKey1 . // - Key alias ARN - An ARN for a key alias, for example // arn:aws:kms:us-west-2:444455556666:alias/projectKey1 . // If you use KmsKeyId , you must set t...
{ return err }
conditional_block
api_op_CreateFileSystem.go
provisioned , you must // also set a value for ProvisionedThroughputInMibps . After you create the file // system, you can decrease your file system's throughput in Provisioned Throughput // mode or change between the throughput modes, with certain time restrictions. For // more information, see Specifying through...
ID
identifier_name
api_op_CreateFileSystem.go
in every Amazon Web Services account. AvailabilityZoneId *string // Describes the Amazon Web Services Availability Zone in which the file system is // located, and is valid only for file systems using One Zone storage classes. For // more information, see Using EFS storage classes (https://docs.aws.amazon.com/efs...
// and override the value set at client initialization time. ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) } ctx = awsmiddleware.SetSigningName(ctx, signingName)
random_line_split
lifa.py
货方电话', 'ERP_no': 'ERP销货单号', 'express_no': '货运单号', 'notice_date': '通知时间', 'send_date': '发货日期', 'order_detail': '订单明细' } # not_null_response(1001, **param_not_null) # print(readxlsx()) # a = public_db.Get_SeqNo("MEETING_ROOM") # print(a) # print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').d...
# # for i in v: # # sum_value += i[1] # sum_value = sum(x[1] for x in v) # lc[k] = sum_value print(lc) s = {} for k, v in itertools.groupby(l1, lambda x: x[0]): s[k] = sum(x[1] for x in v) print(s) class nation(): def __init__(self, key1, value1): ...
c = itertools.groupby(l1, lambda x: x[0]) lc = {} for k, v in c: print(list(v)[0]) # # sum_value = 0
conditional_block
lifa.py
+管理费+运输+利润)*13%", "amount_tax": "", "remark_market_price": "", "market_price": "", "remark_suggest_price": "BOM材料成本+生产辅材+人工成本+水电+折旧+损耗+管理+运输+税费+利润", "suggest_price": "", "remark_confirm_price": "/", "confirm_price": "", "tab_man": "", "confirm_man": "", "check_man": "" } # list_p...
"key": 3, "value": "3-产假"
random_line_split
lifa.py
unit": "联桥科技有限公司", "rec_unit": "", "supply_address": "许昌市中原电气谷森尼瑞节能产业园四楼", "rec_address": "", "sp_contact": "", "rec_contact": "", "supply_phone": "", "rec_phone": "", "ERP_no": "", "express_no": "", "notice_date": "2021-04-16 14:36:55", "send_date": "", "order_detail": [...
temp = form_var # temp = eval(form_var) for k in param: if not temp.get(k): respcode, respmsg = str(temp_code), param.get(k) + '不可为空' # respinfo = HttpResponse(public.setrespinfo()) return respcode, respmsg form_var = { "supply_
identifier_body
lifa.py
货方电话', 'ERP_no': 'ERP销货单号', 'express_no': '货运单号', 'notice_date': '通知时间', 'send_date': '发货日期', 'order_detail': '订单明细' } # not_null_response(1001, **param_not_null) # print(readxlsx()) # a = public_db.Get_SeqNo("MEETING_ROOM") # print(a) # print(datetime.datetime.strptime('2022-01-07', '%Y-%m-%d').d...
uments\a.json" lx = [] with(open(file_path, encoding='utf-8')) as f: for line in f: # temp_row = 'key:'+line[:line.index(',')] mz = nation(line[:line.index(',')], line[line.index(',') + 1:-1]) lx.append(mz.__dict__) print(lx) def auto_generate_sql(input): te...
er\Doc
identifier_name
jenkins-mod-main.rs
extern crate toml; use hyper::client::{Client, RedirectPolicy}; use serde_json::{Map, Value}; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; use structopt::StructOpt; mod errors { error_chain! { errors { } } } use errors::*; #[d...
// write the body here let mut client = Client::new(); client.set_redirect_policy(RedirectPolicy::FollowAll); let mut resp = client.get(&config.update_center_url).send().chain_err(|| { format!( "Unable to perform HTTP request with URL string '{}'", config.update_center_u...
})?; info!("Completed configuration initialization!");
random_line_split
jenkins-mod-main.rs
crate toml; use hyper::client::{Client, RedirectPolicy}; use serde_json::{Map, Value}; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; use structopt::StructOpt; mod errors { error_chain! { errors { } } } use errors::*; #[derive(...
None => Ok(()), } }; create_parent_dir_if_present(config.modified_json_file_path.parent())?; create_parent_dir_if_present(config.url_list_json_file_path.parent())?; } let mut json_file = File::create(&config.modified_json_file_path) .chain_err(|| "...
{ info!("Creating directory chain: {:?}", dir); fs::create_dir_all(dir) .chain_err(|| format!("Unable to create directory chain: {:?}", dir)) }
conditional_block
jenkins-mod-main.rs
extern crate toml; use hyper::client::{Client, RedirectPolicy}; use serde_json::{Map, Value}; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::path::{Path, PathBuf}; use std::process; use structopt::StructOpt; mod errors { error_chain! { errors { } } } use errors::*; #[d...
<S: Into<String>>( resp_outer_map: &mut MapStrVal, connection_check_url_change: S, ) -> Result<()> { let connection_check_url = match resp_outer_map.get_mut(CONNECTION_CHECK_URL_KEY) { Some(connection_check_url) => connection_check_url, None => bail!(format!( "Unable to find '{}'...
change_connection_check_url
identifier_name
mod.rs
> { let mut index = 0; for line in &self.buffer[..] { if &tag == &line.tag { return Ok(index); } index += 1; } Err(NO_MATCH) } fn get_matching(&self, pattern: &str, curr_line: usize, backwards: bool) -> Result<usize, &'static str> { verify_index(self, curr_line)?; use reg...
; // If there is no newline at the end, join next line if !after.ends_with('\n') { if tail.len() > 0 { after.push_str(&tail.remove(0).text); } else { after.push('\n'); } } // Split on newlines and add all lines to the buffer for line in after.lines() { s...
{ regex.replace(&tmp.text, pattern.1).to_string() }
conditional_block
mod.rs
{ if regex.is_match(&(self.buffer[curr_line - 1 - index].text)) { return Ok(curr_line - 1 - index) } } else { if regex.is_match(&(self.buffer[curr_line + index + 1].text)) { return Ok(curr_line + index + 1) } } } Err(NO_MATCH) } // For macro ...
write_to
identifier_name
mod.rs
buffer: Vec::new(), clipboard: Vec::new(), } } } impl Buffer for VecBuffer { // Index operations, get and verify fn len(&self) -> usize { self.buffer.len() } fn get_tag(&self, tag: char) -> Result<usize, &'static str> { let mut index = 0; for line in &self.buffer[..] { ...
saved: true,
random_line_split
simple_xia2_to_shelxcde_new.py
(name, cell, wavelengths, sg, find, ntry=1000): print("SHELXC") print("======") cell_round = tuple(map(lambda x: isinstance(x, float) and round(x, 2) or x, cell)) keywords = [] for w in wavelengths: label = w['label'] sca = os.path.relpath(w['sca']) keywords.append("{0} {1}\n".format(label, sca)...
simpleSHELXC
identifier_name
simple_xia2_to_shelxcde_new.py
".format(find)) keywords.append("NTRY {0}\n".format(ntry)) result = procrunner.run(["shelxc", name], stdin="".join(keywords).encode('utf-8'), print_stdout=True) # for w in wavelengths: # label = w["name"] # sca = os.path.relpath(w['sca']) # # k...
else: if not os.path.exists(args.xia2dir): raise RuntimeError('%s does not exist' % args.xia2dir) if args.atom is None: print("Defaulting to --atom Se") args.atom = "Se" if args.ntry is None: print("Defaulting to --ntry 1000") args.ntry = 1000 ########################################...
raise RuntimeError('Need to specify the path to the xia2 processing directory')
conditional_block
simple_xia2_to_shelxcde_new.py
".format(find)) keywords.append("NTRY {0}\n".format(ntry)) result = procrunner.run(["shelxc", name], stdin="".join(keywords).encode('utf-8'), print_stdout=True) # for w in wavelengths: # label = w["name"] # sca = os.path.relpath(w['sca']) # # k...
"-q"]) #print_stdout=True) if inverse_hand: msg = msg.format("inverse") print(msg) print("=" * len(msg)) result = procrunner.run(["shelxe", name, fa, ...
fa = name + '_fa' solvent = "-s{0}".format(round(solvent_frac), 4) m_value = "-m" h_value = "-h{0}".format(find) z_value = "-z{0}".format(find) msg = "SHELXE - {0} hand" if not inverse_hand: msg = msg.format("original") print(msg) print("=" * len(msg)) result = procrunner.run(["shelxe"...
identifier_body
simple_xia2_to_shelxcde_new.py
".format(find)) keywords.append("NTRY {0}\n".format(ntry)) result = procrunner.run(["shelxc", name], stdin="".join(keywords).encode('utf-8'), print_stdout=True) # for w in wavelengths: # label = w["name"] # sca = os.path.relpath(w['sca']) # # k...
shutil.copy(w['sca'], '.') w['sca'] = os.path.abspath(f) return wavelengths if __name__ == '__main__': ######################################################################## ### receive command line arguments ######################################################################## parser = argparse.Arg...
def copy_sca_locally(wavelengths): '''Copy .sca files locally to work around problem at DLS where SHELX fails to find the files''' for w in wavelengths: f = os.path.basename(w['sca'])
random_line_split
day24b.rs
wall: false, .. }, 1) => self.blizzards[0], (MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => { char::from_digit(nblizzards as u32, 10).unwrap() } _ => 'X', } } } impl Map { /// Create a new empty Map with the specified dimensions. p...
} fn main() { env_logger::Builder::from_env(Env::default().default_filter_or("info")) .format_timestamp(None) .init(); let args = Args::parse(); let nways: usize = match args.part { 1 => 1, // start-exit 2 => 3, // start-exit-start-exit part @ _ => panic!("Don't kno...
)) .collect::<String>() .trim_end() ) }
random_line_split
day24b.rs
} impl Map { /// Create a new empty Map with the specified dimensions. pub fn empty((nrows, ncols): (usize, usize)) -> Map { let start = (1, 0); let exit = (ncols - 2, nrows - 1); Map { grid: (0..nrows) .map(|nrow| { (0..ncols) ...
{ let nblizzards = self.blizzards.len(); match (self, nblizzards) { (MapPos { wall: true, .. }, _) => '#', (MapPos { wall: false, .. }, 0) => '.', (MapPos { wall: false, .. }, 1) => self.blizzards[0], (MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 ...
identifier_body
day24b.rs
: false, .. }, 1) => self.blizzards[0], (MapPos { wall: false, .. }, 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9) => { char::from_digit(nblizzards as u32, 10).unwrap() } _ => 'X', } } } impl Map { /// Create a new empty Map with the specified dimensions. pub fn...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "\n{}", self.grid .iter() .enumerate() .map(|(rownum, row)| format!( "{}\n", row.iter() .enumerate()...
fmt
identifier_name
interface.rs
{ DLL_HANDLE = hinstance }; // set up logging #[cfg(feature = "debug")] if let Ok(mut path) = get_module_path(hinstance) { let stem = path.file_stem().map_or_else( || "debug.log".to_string(), |s| s.to_string_lossy().into_owned(...
} winerror::CLASS_E_CLASSNOTAVAILABLE } /// Add in-process server keys into registry. /// /// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver #[no_mangle] extern "system" fn DllRegisterServer() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = mat...
random_line_split
interface.rs
DLL_HANDLE = hinstance }; // set up logging #[cfg(feature = "debug")] if let Ok(mut path) = get_module_path(hinstance) { let stem = path.file_stem().map_or_else( || "debug.log".to_string(), |s| s.to_string_lossy().into_owned(),...
winerror::CLASS_E_CLASSNOTAVAILABLE } /// Add in-process server keys into registry. /// /// See: https://docs.microsoft.com/en-us/windows/win32/api/olectl/nf-olectl-dllregisterserver #[no_mangle] extern "system" fn DllRegisterServer() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = match ge...
{ log::warn!("Unsupported class: {}", class_guid); }
conditional_block
interface.rs
DLL_HANDLE = hinstance }; // set up logging #[cfg(feature = "debug")] if let Ok(mut path) = get_module_path(hinstance) { let stem = path.file_stem().map_or_else( || "debug.log".to_string(), |s| s.to_string_lossy().into_owned(),...
/// Convert Win32 GUID pointer to Guid struct. const fn guid_from_ref(clsid: *const guiddef::GUID) -> Guid { Guid { 0: unsafe { *clsid }, } } /// Get path to loaded DLL file. fn get_module_path(hinstance: win::HINSTANCE) -> Result<PathBuf, Error> { use std::ffi::OsString; use std::os::windows...
{ match wslscript_common::registry::remove_server_from_registry() { Ok(_) => (), Err(e) => { log::error!("Failed to unregister server: {}", e); return winerror::E_UNEXPECTED; } } winerror::S_OK }
identifier_body
interface.rs
{ DLL_HANDLE = hinstance }; // set up logging #[cfg(feature = "debug")] if let Ok(mut path) = get_module_path(hinstance) { let stem = path.file_stem().map_or_else( || "debug.log".to_string(), |s| s.to_string_lossy().into_owned(...
() -> HRESULT { let hinstance = unsafe { DLL_HANDLE }; let path = match get_module_path(hinstance) { Ok(p) => p, Err(_) => return winerror::E_UNEXPECTED, }; log::debug!("DllRegisterServer for {}", path.to_string_lossy()); match wslscript_common::registry::add_server_to_registry(&path...
DllRegisterServer
identifier_name
gbc.go
.io.GetScreenOutputChannel()) gbc.setupBoot() err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose) if err != nil { log.Fatalln("io init failure\n\t", err) } log.Println("Completed setup") log.Println(strings.Repeat("*", 120)) return gbc, nil } func (gbc *GomeboyColor) Run(frameRunnerWra...
func (gbc *GomeboyColor) doFrameWithDebug() { for gbc.cpuClockAcc < FRAME_CYCLES { if gbc.cpu.PC == gbc.debugOptions.breakWhen { gbc.pause() } if gbc.config.DumpState && !gbc.cpu.Halted { fmt.Println("\t ", gbc.cpu) } gbc.Step() } } func (gbc *GomeboyColor) setupBoot() { if gbc.config.SkipBoot { ...
{ for gbc.cpuClockAcc < FRAME_CYCLES { gbc.Step() } }
identifier_body
gbc.go
.io.GetScreenOutputChannel()) gbc.setupBoot() err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose) if err != nil { log.Fatalln("io init failure\n\t", err) } log.Println("Completed setup") log.Println(strings.Repeat("*", 120)) return gbc, nil } func (gbc *GomeboyColor) Run(frameRunnerWra...
else { frameRunnerWrapper(gbc.doFrameWithDebug) } gbc.cpuClockAcc = 0 } } func (gbc *GomeboyColor) RunIO() { gbc.io.Run() } func (gbc *GomeboyColor) Step() { cycles := 0x00 if gbc.hDMA.IsRunning() { gbc.hDMA.Step() } else { cycles = gbc.cpu.Step() } //GPU is unaffected by CPU speed changes gbc.gp...
{ frameRunnerWrapper(gbc.doFrame) }
conditional_block
gbc.go
.io.GetScreenOutputChannel()) gbc.setupBoot() err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose) if err != nil { log.Fatalln("io init failure\n\t", err) } log.Println("Completed setup") log.Println(strings.Repeat("*", 120)) return gbc, nil } func (gbc *GomeboyColor) Run(frameRunnerWra...
//Determine if ColorGB hardware should be enabled func (gbc *GomeboyColor) setHardwareMode(isColor bool) { if isColor { gbc.cpu.R.A = 0x11 gbc.gpu.RunningColorGBHardware = gbc.mmu.IsCartridgeColor() gbc.mmu.RunningColorGBHardware = true } else { gbc.cpu.R.A = 0x01 gbc.gpu.RunningColorGBHardware = false gb...
} } }
random_line_split
gbc.go
.io.GetScreenOutputChannel()) gbc.setupBoot() err = gbc.io.Init(gbc.config.Title, gbc.config.ScreenSize, gbc.onClose) if err != nil { log.Fatalln("io init failure\n\t", err) } log.Println("Completed setup") log.Println(strings.Repeat("*", 120)) return gbc, nil } func (gbc *GomeboyColor) Run(frameRunnerWra...
() { gbc.inBootMode = true gbc.mmu.WriteByte(0xFF50, 0x00) } func (gbc *GomeboyColor) checkBootModeStatus() { //value in FF50 means gameboy has finished booting if gbc.inBootMode { if gbc.mmu.ReadByte(0xFF50) != 0x00 { gbc.cpu.PC = 0x0100 gbc.mmu.SetInBootMode(false) gbc.inBootMode = false //put the...
setupWithBoot
identifier_name
server.rs
self.app_state.log, "failed to register DTrace USDT probes: {}", msg ); ProbeRegistration::Failed(msg) } } } else { debug!( self.app_state.log, "DTrace USDT probes compiled ou...
} /** * Return the result of registering the server's DTrace USDT probes. * * See [`ProbeRegistration`] for details. */ pub fn probe_registration(&self) -> &ProbeRegistration { &self.probe_registration } } /* * For graceful termination, the `close()` function is preferred...
{ Ok(()) }
conditional_block
server.rs
self.app_state.log, "failed to register DTrace USDT probes: {}", msg ); ProbeRegistration::Failed(msg) } } } else { debug!( self.app_state.log, "DTrace ...
} Err(e) => { let msg = e.to_string(); error!(
random_line_split
server.rs
This function returns a * Result that either represents a valid HTTP response or an error (which will * also get turned into an HTTP response). */ async fn http_request_handle_wrap<C: ServerContext>( server: Arc<DropshotState<C>>, remote_addr: SocketAddr, request: Request<Body>, ) -> Result<Response<Bo...
handler
identifier_name
kflash.rs
0x{:08x}", entry); boot(&mut self.serial, entry as u32).await?; // Now, pass the channel to the caller Ok(Box::pin(Demux::new(&mut self.serial)) as _) }) } } #[derive(Debug)] enum BootCmd { Dtr(bool), Rts(bool), Delay, } const ISP_BOOT_CMDS: &[(&str, &[Boot...
read_to_end_and_discard
identifier_name
kflash.rs
_and_get_output( &mut self, exe: &Path, ) -> Pin<Box<dyn Future<Output = Result<DynAsyncRead<'_>>> + '_>> { let exe = exe.to_owned(); Box::pin(async move { // Extract loadable sections let LoadableCode { regions, entry } = read_elf(&exe).await....
BadDataChecksum, InvalidCommand,
random_line_split
modes.go
different versions [Conformance]", "[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] Burst scaling should run to completion even with unhealthy pods [Slow] [Conformance]", `[sig-node] Probing container should be restarted with a exec "cat /tmp/health" liveness probe [NodeConformance] [Conf...
{ return s }
conditional_block
modes.go
"[sig-auth] ServiceAccounts ServiceAccountIssuerDiscovery should support OIDC discovery of service account issuer [Conformance]", "[sig-network] DNS should provide DNS for services [Conformance]", "[sig-network] DNS should resolve DNS of partial qualified names for services [LinuxOnly] [Conformance]", "[sig-apps...
NewCmdModes
identifier_name
modes.go
Endpoints and EndpointSlices for Pods matching a Service [Conformance]", "[sig-api-machinery] CustomResourcePublishOpenAPI [Privileged:ClusterAdmin] works for multiple CRDs of same group and version but different kinds [Conformance]", "[sig-auth] ServiceAccounts ServiceAccountIssuerDiscovery should support OIDC di...
{ quoted := make([]string, len(liteSkips)) for i, v := range liteSkips { quoted[i] = regexp.QuoteMeta(v) // Quotes will cause the regexp to explode; easy to just change them to wildcards without an issue. quoted[i] = strings.ReplaceAll(quoted[i], `"`, ".") } return strings.Join(quoted, "|") }
identifier_body
modes.go
\]` quickFocus = "Pods should be submitted and removed" E2eModeConformanceLite = "conformance-lite" ) var ( liteSkips = []string{ "Serial", "Slow", "Disruptive", "[sig-apps] StatefulSet Basic StatefulSet functionality [StatefulSetBasic] should have a working scale subresource [Conformance]", "[sig...
},
random_line_split