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
simulation2_01.py
if distance[1] == True: x = (distance[0] * math.sin(azimuth * math.pi/180)) y = (distance[0] * math.cos(azimuth* math.pi/180)) #Convert back to degrees x /= 100 x *= 0.003297790480378 y /= 100 y *= 0.003297790480378 else: pass xarr[i][index] = x+xorigin yarr[i][index] = y+yorigin d...
for index in range(len(xarr[i])): #distance and coordinates distance, angle, elevation = calc_distance() azimuth = random_azimuth() Xcoordinate = distance * math.sin(azimuth * math.pi/180) #Conversion to radians Ycoordinate = distance * math.cos(azimuth* math.pi/180) #The WAC visible spectrum data is 10...
identifier_body
simulation2_01.py
.round_((gtinv[4] *xpt + gtinv[5] * ypt), decimals=0) try: dtmvector = dtm[ylin.astype(int),xsam.astype(int)] #Compute elevation of projectile from a plane at the origin height dtmvectormin = dtmvector.min() elevation -= abs(dtmvector[0]) #Compare the projectile elevation to the dtm dtmvector += abs(dtmve...
run
identifier_name
graph.go
return -1 } func (this *Graph) PrintAllCircle() { fmt.Println("打印环") for _, sli := range this.allCircle { fmt.Println(sli) } } // 遍历整个图使用深度优先算法 func (this *Graph) Dfs(v int) { if this.visted[v] == 1 { return } this.visted[v] = 1 edge := this.vertNode[v].edgeTableNode for edge != nil { this.Dfs(edge.i...
node := this.head this.head = this.head.next return node } type Queue struct { link *linkedList } func NewQueue() *Queue { return &Queue{link: NewLinkList()} } //加入队列 func (this *Queue) Put(value MapParent) { this.link.Add(value) } //pop出队列 func (this *Queue) Pop() *linkNode { return this.link.Delete() } ...
}
identifier_name
graph.go
tempNode.weight = weight tempNode.index = endVert tempNode.edgeTableNode = nil this.vertNode[startVert].edgeTableNode = tempNode continue } for edgeNode != nil { // 单链表尾插节点 if edgeNode.edgeTableNode == nil { tempNode := new(EdgeTableNode) tempNode.weight = weight tempNode.index = e...
.Itoa(i) fmt.Println(*vert) this.vertNode = append(this.vertNode, vert) } // 边初始化 var startVert int var endVert int var weight int var n int for i := 0; i < this.edgeNum; i++ { n, _ = fmt.Scanf("%d %d %d", &startVert, &endVert, &weight) fmt.Printf("%d %d %d\n", startVert, endVert, n) var edgeNode ...
identifier_body
graph.go
迭代的方式遍历 --栈结构 // func (this *Graph) DfsStatck() { var stack = CreateStack() for i := 0; i < this.vertNum; i++ { if this.visted[i] == 1 { continue } stack.Push(i) this.visted[i] = 1 for !stack.IsEmpty() { elemet := stack.Get() node := this.vertNode[elemet.(int)].edgeTableNode for node != nil ...
random_line_split
graph.go
return -1 } func (this *Graph) PrintAllCircle() { fmt.Println("打印环") for _, sli := range this.allCircle { fmt.Println(sli) } } // 遍历整个图使用深度优先算法 func (this *Graph) Dfs(v int) { if this.visted[v] == 1 { return } this.visted[v] = 1 edge := this.vertNode[v].edgeTableNode for edge != nil { this.Dfs(edge.i...
for !stack.IsEmpty() { elemet := stack.Get() node := this.vertNode[elemet.(int)].edgeTableNode for node != nil && this.visted[node.index] == 1 { node = node.edgeTableNode } if node != nil && this.visted[node.index] == 0 { this.visted[node.index] = 1 stack.Push(node.index) } else { ...
this.visted[i] = 1
conditional_block
lesson2-rf_interpretation.py
def get_scores(m, config=None): res = { 'config': [config], 'rmse_train': [rmse(m.predict(X_train), y_train)], 'rmse_dev': [rmse(m.predict(X_valid), y_valid)], 'r2_train': [m.score(X_train, y_train)], 'r2_dev': [m.score(X_valid, y_valid)], 'r2_oob': [None], ...
return math.sqrt(((x-y)**2).mean())
identifier_body
lesson2-rf_interpretation.py
m.fit(X_train, y_train) results = get_scores(m, 'baseline-subsample-tuning') results # We saw how the model averages predictions across the trees to get an estimate - but how can we know the confidence of the estimate? One simple way is to use the standard deviation of predictions, instead of just the mean. This tell...
def plot_pdp_old(feat, clusters=None, feat_name=None): feat_name = feat_name or feat p = pdp.pdp_isolate(m, x, feat) return pdp.pdp_plot(p, feat_name, plot_lines=True, cluster=clusters is not None, n_cluster_centers=clusters) def plot_pdp(feat, clusters = N...
x = get_sample(X_train[X_train.YearMade>1930], 500)
random_line_split
lesson2-rf_interpretation.py
(m, config=None): res = { 'config': [config], 'rmse_train': [rmse(m.predict(X_train), y_train)], 'rmse_dev': [rmse(m.predict(X_valid), y_valid)], 'r2_train': [m.score(X_train, y_train)], 'r2_dev': [m.score(X_valid, y_valid)], 'r2_oob': [None], 'n_trees':[m.n_e...
get_scores
identifier_name
lesson2-rf_interpretation.py
return pd.DataFrame(res) # - df_raw # # Confidence based on tree variance # For model interpretation, there's no need to use the full dataset on each tree - using a subset will be both faster, and also provide better interpretability (since an overfit model will not provide much variance across trees). set_r...
res['r2_oob'][0] = m.oob_score_
conditional_block
app.js
.title) { map.panTo(self.mapMarkers()[key].marker.position); map.setZoom(14); infowindow.setContent(self.mapMarkers()[key].content); infowindow.open(map, self.mapMarkers()[key].marker); map.panBy(0, -150); self.mobileShow(false); self.searchStatus(''); } ...
$.each(self.mapMarkers(), function(key, value) { value.marker.setMap(null); }); self.mapMarkers([]); }
identifier_body
app.js
map.panBy(0, -150); self.mobileShow(false); self.searchStatus(''); } } }; // AutoComplete input of city and state this.doAutoComplete = function() { var inputLocation = new google.maps.places.Autocomplete( (document.getElementById('autocomplete')), { types: ['geocode'] }...
random_line_split
app.js
’s value. if you do want to let the default action proceed, just return true from your event handler function.*/ return true; } // Handle the input given when user searches for events in a location this.processLocationSearch = function() { //Need to use a jQuery selector instead of KO binding becau...
self.searchStatus('Map is already centered.'); } e
conditional_block
app.js
('hide'); //Hold the current location's lat & lng - useful for re-centering map this.currentLat = ko.observable(37.39); this.currentLng = ko.observable(-122.40); // When an event on the list is clicked, go to corresponding marker and open its info window. this.goToMarker = function(clickedEvent) { var c...
ocation) { var meetupUrl = "https://api.meetup.com/find/groups?key=6f4c634b253677752b591d6a67327&"; var order = "&order=members"; var query = meetupUrl + location + order; $.ajax({ url: query, dataType: 'jsonp', success: function(data) { console.log(data); var le...
tMeetups(l
identifier_name
Router.js
'bundle-loader?lazy&name=alert!./pages/alert'; import modal from 'bundle-loader?lazy&name=modal!./pages/modal'; import message from 'bundle-loader?lazy&name=message!./pages/message'; import notification from 'bundle-loader?lazy&name=notification!./pages/notification'; import carousel from 'bundle-loader?lazy&name=caro...
te.locale) { this.setLocale(localStorage.getItem('WUI_LANG') || 'cn'); } }); } componentWillMount() { window.addEventL
identifier_body
Router.js
'bundle-loader?lazy&name=checkbox!./pages/checkbox'; import card from 'bundle-loader?lazy&name=card!./pages/card'; import select from 'bundle-loader?lazy&name=select!./pages/select'; import SwitchCom from 'bundle-loader?lazy&name=switch!./pages/switch'; import slider from 'bundle-loader?lazy&name=slider!./pages/slider...
if (routes) { return routes[3] || routes[4]; } return 'quick-start'; } const getLangName = () => localStorage.getItem('WUI_LANG') || 'cn'; const renderMenuLi = (item, idx) => { if (!item.path) return null; if (getPageName(window.location.href) === getPageName(item.path)) { return <li key={`${idx}`} ...
const getPageName = (location) => { const routes = location.match(/(?:\/(.+))?(\/(.+)\?|\/(.+))/);
random_line_split
Router.js
pages/progress'; import breadcrumb from 'bundle-loader?lazy&name=breadcrumb!./pages/breadcrumb'; import dropdown from 'bundle-loader?lazy&name=dropdown!./pages/dropdown'; import steps from 'bundle-loader?lazy&name=steps!./pages/steps'; import alert from 'bundle-loader?lazy&name=alert!./pages/alert'; import modal from '...
) {
identifier_name
Router.js
'bundle-loader?lazy&name=checkbox!./pages/checkbox'; import card from 'bundle-loader?lazy&name=card!./pages/card'; import select from 'bundle-loader?lazy&name=select!./pages/select'; import SwitchCom from 'bundle-loader?lazy&name=switch!./pages/switch'; import slider from 'bundle-loader?lazy&name=slider!./pages/slider...
const RoutersContainer = withRouter(({ history, location, ...props }) => { const prefixCls = 'w-docs'; return ( <div className={`${prefixCls}`}> <div className={`${prefixCls}-menu-warpper`}>
<ul key={`${e}`}> <li className="title">{getLang(`category.${e}`)}</li> {_obj[a][e].map((item, item_idx) => renderMenuLi(item, item_idx))} </ul> ) } } } } return html }
conditional_block
mod.rs
Subscriber> Layer<S> for FooLayer {} //! # impl<S: Subscriber> Layer<S> for BarLayer {} //! # impl FooLayer { //! # fn new() -> Self { Self {} } //! # } //! # impl BarLayer { //! # fn new() -> Self { Self {} } //! # } //! //! let subscriber = Registry::default() //! .with(FooLayer::new()) //! .with(BarLayer::n...
/// Returns a static reference to the span's metadata. pub fn metadata(&self) -> &'static Metadata<'static> { self.data.metadata() } /// Returns the span's name, pub fn name(&self) -> &'static str { self.data.metadata().name() } /// Returns a list of [fields] defined by the...
self.data.id() }
identifier_body
mod.rs
the `Layer` implementation will be guaranteed //! access to the [`Context`][ctx] methods, such as [`Context::span`][lookup], that //! require the root subscriber to be a registry. //! //! [`Layer`]: ../layer/trait.Layer.html //! [`Subscriber`]: //! https://docs.rs/tracing-core/latest/tracing_core/subscriber/trait....
tensions(&
identifier_name
mod.rs
Subscriber> Layer<S> for FooLayer {} //! # impl<S: Subscriber> Layer<S> for BarLayer {} //! # impl FooLayer { //! # fn new() -> Self { Self {} } //! # } //! # impl BarLayer { //! # fn new() -> Self { Self {} } //! # } //! //! let subscriber = Registry::default() //! .with(FooLayer::new()) //! .with(BarLayer::n...
pub use sharded::Registry; /// Provides access to stored span data. /// /// Subscribers which store span data and associate it with span IDs should /// implement this trait; if they do, any [`Layer`]s wrapping them can look up /// metadata via the [`Context`] type's [`span()`] method. /// /// [`Layer`]: ../layer/trait...
#[cfg_attr(docsrs, doc(cfg(feature = "registry")))]
random_line_split
manualtest.py
SCENARIO_TWO_DATA_FILE_KEY="Scenario Two" ANSWER_KEY_NAME="answer_key.yml" USER_ANSWER_CASE_A="A" USER_ANSWER_CASE_B="B" ANSWER_KEY_SCENARIO_ONE="scenario one" ANSWER_KEY_SCENARIO_TWO="scenario two" ANSWER_KEY_QUESTION_KEY="Q_" MAX_CASE_NUM=24 ADJUSTED_AUDIO_SUBDIR="adjusted_audio" SCENARIO_ONE_SUBDIR="scenario_one" SC...
except FileExistsError: logging.debug("Could not create test case directory at {} - encountered FileExistsError".format(test_case_path)) print("Could not create test case directory at {} - encountered FileExistsError".format(test_case_path))
random_line_split
manualtest.py
REFERENCE_KEY="user_preference_weight" USER_X_VALUE_KEY="user_X_value" USER_CONFIDENCE_KEY="user_answer_confidence" X_ANSWER_KEY="x_answer_alpha" A_VALUE_KEY="A_value" B_VALUE_KEY="B_value" TESTCASES_SUBDIR="testcases" A_CASE_NAME="A_" B_CASE_NAME="B_" X_CASE_NAME="X_" WNDWS_COPY_CMD="copy" AUDIO_TYPE=".wav" SCNEARIO_O...
(root_directory, scenario_one, scenario_two): logging.info("Enter: _create_temp_dir") # Will create exact copies of both directories specified so files may be altered later adjusted_file_path = os.path.join(root_directory, ADJUSTED_AUDIO_SUBDIR) scenario_one_temp = os.path.join(adjusted_file_path, SCENA...
_create_temp_dir
identifier_name
manualtest.py
REFERENCE_KEY="user_preference_weight" USER_X_VALUE_KEY="user_X_value" USER_CONFIDENCE_KEY="user_answer_confidence" X_ANSWER_KEY="x_answer_alpha" A_VALUE_KEY="A_value" B_VALUE_KEY="B_value" TESTCASES_SUBDIR="testcases" A_CASE_NAME="A_" B_CASE_NAME="B_" X_CASE_NAME="X_" WNDWS_COPY_CMD="copy" AUDIO_TYPE=".wav" SCNEARIO_O...
if case_num > MAX_CASE_NUM: logging.info("The amount of cases has exceeded 25. Please note that " "the accompanying excel sheet only has 25 answer slots and that it will need to " "be
""" Method to create A_B_X testing directories and return the corresponding answer key An A file is chosen from either the scenario one or two with a 50/50 probability. The B file is then from the scenario not chosen for A. An X file is then created with a 50/50 probability of being either a duplicate ...
identifier_body
manualtest.py
B_value" TESTCASES_SUBDIR="testcases" A_CASE_NAME="A_" B_CASE_NAME="B_" X_CASE_NAME="X_" WNDWS_COPY_CMD="copy" AUDIO_TYPE=".wav" SCNEARIO_ONE_DATA_FILE="output_data.yml" SCENARIO_ONE_DATA_FILE_KEY="Scenario One" SCENARIO_TWO_DATA_FILE="output_data.yml" SCENARIO_TWO_DATA_FILE_KEY="Scenario Two" ANSWER_KEY_NAME="answer_k...
logging.info("The amount of cases has exceeded 25. Please note that " "the accompanying excel sheet only has 25 answer slots and that it will need to " "be restructured") print("The amount of cases has exceeded 25. Please note that " "the accompanying excel sheet only ha...
conditional_block
docker_compose.rs
async_trait; use eyre::{eyre, Context, Result}; use std::ffi::OsStr; use std::fmt::Debug; use std::path::PathBuf; use std::process::Command; use std::process::Output; use url::Url; /// Each instance of this struct represents a particular FHIR Server implementation, where the implementation /// is launched and managed ...
(&self) -> Result<String> { let server_plugin = server_plugin_downcast(self); match run_docker_compose(server_plugin, &["logs", "--no-color"]).with_context(|| { format!( "Running '{} up --detach' failed.", server_plugin .server_script() ...
emit_logs
identifier_name
docker_compose.rs
_trait; use eyre::{eyre, Context, Result}; use std::ffi::OsStr; use std::fmt::Debug; use std::path::PathBuf; use std::process::Command; use std::process::Output; use url::Url; /// Each instance of this struct represents a particular FHIR Server implementation, where the implementation /// is launched and managed via D...
// Wait (up to a timeout) for the server to be ready. match wait_for_ready(app_state, &server_handle).await { Err(err) => { server_handle.emit_logs_info()?; Err(err) } Ok(_) => { let server_handle: Box<dyn ServerHandle> = Box::new(server_handle); ...
let server_handle = DockerComposeServerHandle { server_plugin: server_plugin.clone(), http_client, };
random_line_split
docker_compose.rs
_trait; use eyre::{eyre, Context, Result}; use std::ffi::OsStr; use std::fmt::Debug; use std::path::PathBuf; use std::process::Command; use std::process::Output; use url::Url; /// Each instance of this struct represents a particular FHIR Server implementation, where the implementation /// is launched and managed via D...
} /// Runs the specified Docker Compose subcommand with the specified argument, for the specified FHIR Server /// implementation. /// /// Parameters: /// * `server_plugin`: the [DockerComposeServerPlugin] that represents the FHIR Server implementation to run /// the command for/against /// * `args`: the Docker Comp...
{ launch_server(app_state, self).await }
identifier_body
common.go
erThumbprint provides a constant to capture our env variable "IMPORTER_THUMBPRINT" ImporterThumbprint = "IMPORTER_THUMBPRINT" // ImporterCurrentCheckpoint provides a constant to capture our env variable "IMPORTER_CURRENT_CHECKPOINT" ImporterCurrentCheckpoint = "IMPORTER_CURRENT_CHECKPOINT" // ImporterPreviousCheckp...
}
random_line_split
zsum_mulcov_rate.py
parent rates and subgroup covariate multipliers use a grid with # one point in age and two points in time. Thus there are six model variables # for each rate, two for the parent rates and four for the # covariate multipliers. # The resulting rates will be constant # in age and constant in time except between the two t...
{ # smooth_rate_subgroup 'name': 'smooth_rate_subgroup', 'age_id': [ 0 ], 'time_id': [ 0, 1 ], 'fun': fun_rate_subgroup },{ # smooth_rate_parent 'name': 'smooth_rate_p...
} ] # ---------------------------------------------------------------------- # smooth table smooth_table = [
random_line_split
zsum_mulcov_rate.py
rates and subgroup covariate multipliers use a grid with # one point in age and two points in time. Thus there are six model variables # for each rate, two for the parent rates and four for the # covariate multipliers. # The resulting rates will be constant # in age and constant in time except between the two time gri...
def fun_rate_parent(a, t) : return ('prior_rate_parent', None, 'prior_gauss_diff') import dismod_at # ---------------------------------------------------------------------- # age list age_list = [ 0.0, 50.0, 100.0 ] # # time list time_list = [ 1990.0, 2010.0 ] # # integrand ...
return ('prior_rate_subgroup', None, 'prior_gauss_diff')
identifier_body
zsum_mulcov_rate.py
rates and subgroup covariate multipliers use a grid with # one point in age and two points in time. Thus there are six model variables # for each rate, two for the parent rates and four for the # covariate multipliers. # The resulting rates will be constant # in age and constant in time except between the two time gri...
import dismod_at # # change into the build/example/user directory if not os.path.exists('build/example/user') : os.makedirs('build/example/user') os.chdir('build/example/user') # ------------------------------------------------------------------------ python_seed = int( time.time() ) random.seed( python_seed ) # --...
sys.path.insert(0, local_dir)
conditional_block
zsum_mulcov_rate.py
rates and subgroup covariate multipliers use a grid with # one point in age and two points in time. Thus there are six model variables # for each rate, two for the parent rates and four for the # covariate multipliers. # The resulting rates will be constant # in age and constant in time except between the two time gri...
(file_name) : def fun_rate_subgroup(a, t) : return ('prior_rate_subgroup', None, 'prior_gauss_diff') def fun_rate_parent(a, t) : return ('prior_rate_parent', None, 'prior_gauss_diff') import dismod_at # ---------------------------------------------------------------------- # age list age_...
example_db
identifier_name
lookup.rs
} else { high = mid; } } mid } /// Convert a [TValue] to a parametric `t`-value. pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 { match t { TValue::Parametric(t) => { assert!((0.0..=1.).contains(&t)); t } TValue::Euclidean(t) => { assert!((0.0..=1.).contains(&t))...
{ if ratio < error { return 0.; } if 1. - ratio < error { return 1.; } let mut low = 0.; let mut mid = 0.; let mut high = 1.; let total_length = self.length(None); while low < high { mid = (low + high) / 2.; let test_ratio = self.trim(TValue::Parametric(0.), TValue::Parametric(mid)).leng...
identifier_body
lookup.rs
(&self, ratio: f64, error: f64) -> f64 { if ratio < error { return 0.; } if 1. - ratio < error { return 1.; } let mut low = 0.; let mut mid = 0.; let mut high = 1.; let total_length = self.length(None); while low < high { mid = (low + high) / 2.; let test_ratio = self.trim(TValue::Parame...
euclidean_to_parametric
identifier_name
lookup.rs
} mid } /// Convert a [TValue] to a parametric `t`-value. pub(crate) fn t_value_to_parametric(&self, t: TValue) -> f64 { match t { TValue::Parametric(t) => { assert!((0.0..=1.).contains(&t)); t } TValue::Euclidean(t) => { assert!((0.0..=1.).contains(&t)); self.euclidean_to_parametri...
{ high = mid; }
conditional_block
lookup.rs
// Basis code based off of pseudocode found here: <https://pomax.github.io/bezierinfo/#explanation>. let t_squared = t * t; let one_minus_t = 1. - t; let squared_one_minus_t = one_minus_t * one_minus_t; match self.handles { BezierHandles::Linear => self.start.lerp(self.end, t), BezierHandles::Quadrati...
convergence_count += 1;
random_line_split
error_handle.py
while last: i+=1 tbo = last last = last.tb_next if i>100: print() return (1, "bad recursion") if not tbo: tbo = sys.last_traceback linum = sys.last_traceback.tb_lineno# first linum message += f'from line {s...
else: print() return (1, 'No error traceback found by sys module') if hasattr(sys, "last_type") and sys.last_type: error_type = str(sys.last_type) error_type = error_type.replace("<class '", "").replace("'>","") message = f'type {error_type}\n{message}' if hasattr(...
frame = '\n'.join(frame.split(', ')[1:3]) message += f'{frame}\n'
random_line_split
error_handle.py
while last: i+=1 tbo = last last = last.tb_next if i>100: print() return (1, "bad recursion") if not tbo: tbo = sys.last_traceback linum = sys.last_traceback.tb_lineno# first linum message += f'from line {s...
if not message : print() return (1, 'No message to display') if message and to_clipboad: bpy.context.window_manager.clipboard = message return (0, message) def get_traceback_stack(tb=None): if tb is None: tb = sys.last_traceback stack = [] if tb and tb.tb_fr...
print('use "last_value" line num') message += f'line {str(sys.last_value.lineno)}\n'
conditional_block
error_handle.py
(to_clipboad=False) -> Tuple[int, str]: '''Get last traceback error details summed in string return a tuple''' import sys message = '' linum = '' if hasattr(sys, "last_traceback") and sys.last_traceback: i = 0 last=sys.last_traceback.tb_next tbo = None while last...
get_last_traceback
identifier_name
error_handle.py
while last: i+=1 tbo = last last = last.tb_next if i>100: print() return (1, "bad recursion") if not tbo: tbo = sys.last_traceback linum = sys.last_traceback.tb_lineno# first linum message += f'from line {s...
if len(item) > 2 and item[2]: boxcol.label(text=item[2]) col.separator() row = layout.row() row.alignment = 'LEFT' row.operator('devtools.clear_last_traceback', text='Clear Traceback', icon='CANCEL') if self.error_desc: for l in self....
layout = self.layout col = layout.column() for item in self.error_list: path, line = item[0], item[1] # print(path, ' ', line) goto_line = f'{path}:{line}' box = col.box() boxcol = box.column() boxcol.alignment = '...
identifier_body
assembler.py
# - Negative immediate values must have a preceeding '-' with no space # - between it and the number. # # Language definition: # # LOAD D A - load from address A to destination D # LOADA D A - load using the address register from address A + RE to destination D # STORE S A - store value in S to address A # STOREA S...
#
random_line_split
assembler.py
_length() v = "00000000" v = v[0:8-l] + format( d, 'b' ) elif d == 0: v = "00000000" else: print 'Invalid address on line %d: value is negative' % (linenum) exit() return v # Tokenizes the input data, discarding white space and comments # returns the tokens as a list of lists, one list for each line. # ...
ass_txt+='0111'+table_d[token[1]]+'0000000000'
conditional_block
assembler.py
instructions # # Mkhanyisi Gamedze # CS232 Project 8 : Assembler # import sys # NO NEED TO CHANGE # converts d to an 8-bit 2-s complement binary value def dec2comp8( d, linenum ): try: if d > 0: l = d.bit_length() v = "00000000" v = v[0:8-l] + format( d, 'b') elif d < 0: dt = 128 + d l = dt.bit...
# split on white space words = uls.split() newwords = [] for word in words: newwords.append( word.lower() ) tokens.append( newwords ) print "done tokenizing\n" return tokens # reads through the file and returns a dictionary of all location # labels with their line numbers def pass1( tokens ): # fi...
tokens = [] # start of the file fp.seek(0) lines = fp.readlines() # strip white space and comments from each line for line in lines: ls = line.strip() uls = '' for c in ls: if c != '#': uls = uls + c else: break # skip blank lines if len(uls) == 0: continue
identifier_body
assembler.py
instructions # # Mkhanyisi Gamedze # CS232 Project 8 : Assembler # import sys # NO NEED TO CHANGE # converts d to an 8-bit 2-s complement binary value def dec2comp8( d, linenum ): try: if d > 0: l = d.bit_length() v = "00000000" v = v[0:8-l] + format( d, 'b') elif d < 0: dt = 128 + d l = dt.bit...
( d, linenum ): if d > 0: l = d.bit_length() v = "00000000" v = v[0:8-l] + format( d, 'b' ) elif d == 0: v = "00000000" else: print 'Invalid address on line %d: value is negative' % (linenum) exit() return v # Tokenizes the input data, discarding white space and comments # returns the tokens as a lis...
dec2bin8
identifier_name
agreement.rs
use untrusted; //! //! let rng = rand::SystemRandom::new(); //! //! let my_private_key = //! agreement::PrivateKey::<agreement::Ephemeral>::generate(&agreement::X25519, &rng)?; //! //! // Make `my_public_key` a byte slice containing my public key. In a real //! // application, this would be sent to the peer in an ...
/// The private key. pub fn private_key(&self) -> &PrivateKey<U> { &self.private_key } /// The public key. pub fn public_key(&self) -> &PublicKey { &self.public_key } /// Split the key pair apart. pub fn split(self) -> (PrivateKey<U>, PublicKey) { (self.private_key, self.public_key) } } ///...
{ // NSA Guide Step 1. let private_key = ec::PrivateKey::generate(&alg.curve, rng)?; let mut public_key = PublicKey { bytes: [0; PUBLIC_KEY_MAX_LEN], alg, }; private_key.compute_public_key(&alg.curve, &mut public_key.bytes)?; Ok(Self { ...
identifier_body
agreement.rs
algorithm. pub struct Algorithm { pub(crate) curve: &'static ec::Curve, pub(crate) ecdh: fn( out: &mut [u8], private_key: &ec::PrivateKey, peer_public_key: untrusted::Input, ) -> Result<(), error::Unspecified>, } derive_debug_via_self!(Algorithm, self.curve); impl Eq for Algorithm...
InputKeyMaterial
identifier_name
agreement.rs
use untrusted; //! //! let rng = rand::SystemRandom::new(); //! //! let my_private_key = //! agreement::PrivateKey::<agreement::Ephemeral>::generate(&agreement::X25519, &rng)?; //! //! // Make `my_public_key` a byte slice containing my public key. In a real //! // application, this would be sent to the peer in an ...
}; self.private_key .compute_public_key(&self.alg.curve, &mut public_key.bytes)?; Ok(public_key) } /// Performs a key agreement with an private key and the given public key. /// /// Since `self` is consumed, it will not be usable after calling `agree`. /// //...
alg: self.alg,
random_line_split
agreement.rs
what //! // algorithm was used to generate the peer's private key. Here, we know it //! // is X25519 since we just generated it. //! let peer_public_key_alg = &agreement::X25519; //! //! let input_keying_material = my_private_key.agree(peer_public_key_alg, peer_public_key)?; //! input_keying_material.derive(|_key_mate...
{ return Err(error::Unspecified); }
conditional_block
transformer_dynsparse.py
def embedding(self, x, src, compute_dense_grad=False, sparse_embeddings=False): # x[batch_size*sequence_length] -> x[batch_size*sequence_length, embedding_length] inshape = x.shape.as_list() assert len(inshape) == 2, f"Input to embedding lookup has shape {inshape}, but should be a 2D tensor" ...
self.encoder_k = None self.encoder_v = None # Dynsparse transformer is both a transformer and a sparse model Transformer.__init__(self, params, *args, **kwargs) SparseModel.__init__(self, params, *args, **kwargs)
identifier_body
transformer_dynsparse.py
params, *args, **kwargs) SparseModel.__init__(self, params, *args, **kwargs) def embedding(self, x, src, compute_dense_grad=False, sparse_embeddings=False): # x[batch_size*sequence_length] -> x[batch_size*sequence_length, embedding_length] inshape = x.shape.as_list() assert len(inshape) =...
compute_dense_grad, use_bias=self.include_projection_bias, disable_outlining=True) else: x = self.applySparseLinear(x, self.sparse_projection, self.target_vocab_length, ...
# The look-up table is shared with the dense embedding layer if sparse_embeddings: if self.exclude_embedding: x = self.sparseLinear(x, self.sparsity, self.target_vocab_length,
random_line_split
transformer_dynsparse.py
params, *args, **kwargs) SparseModel.__init__(self, params, *args, **kwargs) def embedding(self, x, src, compute_dense_grad=False, sparse_embeddings=False): # x[batch_size*sequence_length] -> x[batch_size*sequence_length, embedding_length] inshape = x.shape.as_list() assert len(inshape) =...
# Extract heads and transpose [B, S, heads, qkv_len] -> [B, heads, S, qkv_len] batch_size, sequence_length, _ = in_q.shape.as_list() with self.namescope('q'): q = tf.reshape(q, [batch_size, sequence_length, self.attention_heads, self.qkv_length]) q = tf.transpose(q, pe...
with self.namescope('qkv'): # Prepend (head) dimension in_qkv_r = tf.expand_dims(in_q, axis=-2) qkv = self.sparseLinear(in_qkv_r, self.sparsity, 3 * b_shape, compute_dense_grad, use_bias) # Extract q, k and v q, k, v = tf.split(qkv, 3, axis...
conditional_block
transformer_dynsparse.py
params, *args, **kwargs) SparseModel.__init__(self, params, *args, **kwargs) def embedding(self, x, src, compute_dense_grad=False, sparse_embeddings=False): # x[batch_size*sequence_length] -> x[batch_size*sequence_length, embedding_length] inshape = x.shape.as_list() assert len(inshape) =...
(self, x): # -> x with self.namescope('layernorm'): param_initializers = { "beta": tf.initializers.constant(0.0, x.dtype), "gamma": tf.initializers.constant(0.1, x.dtype) } x = ipu.normalization_ops.group_norm(x, groups=1, param_initializers=p...
norm
identifier_name
read.rs
parse::linebreak(&mut buf)?; name }; Some(solid_name) } else { None }; // In the binary case, we still need to skip the remaining header. let triangle_count = if is_binary { buf.skip(80 - buf.offset())?; ...
} impl<R: io::Read, U: UnifyingMarker> fmt::Debug for Reader<R, U> {
random_line_split
read.rs
fn check_length(&mut self) -> Result<CountMatch, Error>; } impl<R: io::Read> SeekHelper for R { default fn check_length(&mut self) -> Result<CountMatch, Error> { Ok(CountMatch::NoInfo) } } impl<R: io::Read + io::Seek> SeekHelper for R { ...
<F
read_raw_binary
identifier_name
read.rs
fn check_length(&mut self) -> Result<CountMatch, Error>; } impl<R: io::Read> SeekHelper for R { default fn check_length(&mut self) -> Result<CountMatch, Error> { Ok(CountMatch::NoInfo) } } impl<R: io::Read + io::Seek> SeekHelper for R { ...
// Read the all triangles into the raw result self.read_raw(|tri| { out.triangles.push(tri); Ok(()) })?; Ok(out) } /// Reads the whole file, passing each triangle to the `add_triangle` /// callback. /// /// This is a low level building bloc...
{ out.triangles.reserve(tri_count as usize); }
conditional_block
hostmon_server.go
("/host/"):] me := r.Method log.Printf("Got host %s (len=%d) with method %s\n", h, len(h), me) // We will key off r.Method = "GET" or "POST" // /host/ GET -> list all POST -> do nothing // /host/name GET -> list one POST -> update (or create) one switch me { case "GET": if (len(h) ==...
{ er = rs.Scan(&hh) if (er != nil) { log.Fatalf("Fatal compiling list for scan and notify") } htt = append(htt, hh) }
conditional_block
hostmon_server.go
() { //var bindaddr, conffile string var conffile string if (len(os.Args) != 5) { log.Fatalf("Usage: %s -b bindaddr -f configfile", os.Args[0]) } for i := 1; i < len(os.Args); i++ { switch os.Args[i] { //case "-b": //bindaddr = os.Args[i+1] case "-f": conffile = os.Args[i...
main
identifier_name
hostmon_server.go
MySQL will generate an ID // if (hostpi == 0) { dbCmd = "INSERT INTO hosts (host) VALUES ('" + m.Hostname + "');" _, dbExecErr = dbconn.Exec(dbCmd) if dbExecErr != nil { http.Error(w, "Failed executing host table INSERT for host " + m.Hostname, http.StatusInternalServerError) }...
{ eMailConn, eMailErr := smtp.Dial("localhost:25") if eMailErr != nil { log.Printf("SMTP server connection failure sending notification\n") } eMailConn.Mail(g_eMailFrom) eMailConn.Rcpt(g_eMailTo) wc, eMailErr := eMailConn.Data() if eMailErr != nil { log.Printf("Failure initiating DATA stage send...
identifier_body
hostmon_server.go
// // Read in the configuration file. // haveParam := make(map[string]bool) confFile, err := os.Open(conffile) if err != nil { log.Fatalf("Failed opening configuration file for reading\n") } inp := bufio.NewScanner(confFile) for inp.Scan() { line := inp.Text() if (len(line) > 0) { ...
} } log.Printf("Host monitor data server starting up\n")
random_line_split
index.ts
enterInitialLoadState() { overviewTable.addEventListener('click', (event) => this.handleTableEventClick(event)); overviewTable.addEventListener('save-edit', this); overviewTable.addEventListener('cancel-edit', this); itemDB.getAll().then(res => { if (res.length === 0)...
{ this.items = new Map(); }
identifier_body
index.ts
); } async addItemSubmit(event) { const addData: FormData = event.formData; const name = addData.get("item-name"); const sQty: string = addData.get("item-qty"); const qty = parseInt(sQty, 10); const sThreshold = addData.get("item-threshold"); const threshold = ...
fAddItem.querySelector('#add-name').focus(); // Setup form submission handling fAddItem.addEventListener('submit', e => { e.preventDefault(); new FormData(fAddItem); }, {once: true}); fAddItem.addEventListener('formdata', (e) => { this.handle...
// focus form name
random_line_split
index.ts
} async addItemSubmit(event) { const addData: FormData = event.formData; const name = addData.get("item-name"); const sQty: string = addData.get("item-qty"); const qty = parseInt(sQty, 10); const sThreshold = addData.get("item-threshold"); const threshold = par...
() { // hide add item form console.log('entered transition Setup -> Normal fn'); console.log(fAddItem); blankSetup.classList.add('hide'); this.enterNormalState(); } enterNormalState() { this.populateInitialTable(); addItem.addEventListener('click', e => ...
transitionFromSetupToNormal
identifier_name
index.ts
.classList.remove('hide'); // Setup the load existing data button loadDBFromFileSetupBtn.addEventListener('change', this.loadDataHandler.bind(this)); // Make form visible fAddItem.classList.remove('hide'); // Setup form submission handling fAddItem.addEventListener('su...
{ this.handleSaveEdit(e); }
conditional_block
setup_groupsched.py
For example, you can specify extra directories (CMake Binary Dir, kernel path) and force those arguments to be defined. The wrapped version also takes care of distutils causing errors when extra arguments are passed straight to the setup_<module-name>.py scripts. """ ###################################...
(): # Global level params class instance was # created before calling main(). We make it # global so that other code can access the set # of Parameters, simply by accessing the Params # instance. Here, however, we call the parse() # method to actually get the arguments, s...
main
identifier_name
setup_groupsched.py
For example, you can specify extra directories (CMake Binary Dir, kernel path) and force those arguments to be defined. The wrapped version also takes care of distutils causing errors when extra arguments are passed straight to the setup_<module-name>.py scripts. """ ###################################...
) # sdf_seq_module = Extension('_sdf_seq', # sources=[source_dir+'/libgsched/sdf_seq_wrap.c', # source_dir+'/libgsched/sdf_seq.c'], # include_dirs = [source_dir+'/include'], ...
libraries = ['gsched'], extra_compile_args = ['-fPIC'], library_dirs = [build_dir, source_dir],
random_line_split
setup_groupsched.py
For example, you can specify extra directories (CMake Binary Dir, kernel path) and force those arguments to be defined. The wrapped version also takes care of distutils causing errors when extra arguments are passed straight to the setup_<module-name>.py scripts. """ ###################################...
## ## if not Params.kernel_path: ## # Forcing a check for the kernel path variable. ## # Obvisouly used when making something that needs to compile ## # specifically against the kernel. ## # ## print "Must define the kernel path --kernel=<kernel-path>" ...
print "Must define the CMake binary directory --cbd=<build-dir>" sys.exit(1)
conditional_block
setup_groupsched.py
For example, you can specify extra directories (CMake Binary Dir, kernel path) and force those arguments to be defined. The wrapped version also takes care of distutils causing errors when extra arguments are passed straight to the setup_<module-name>.py scripts. """ ###################################...
dest="verbose_level", help="Turn on narrative output at level 1") self.p.add_option("-V", action="store", type ="int", dest="verbose_level", help="Turn on narrative output at level V...
USAGE = "usage: %prog [options]" def __init__(self): # Create the argument parser and then tell it # about the set of legal arguments for this # command. The parse() method of this class # calls parse_args of the optparse module self.p = optparse....
identifier_body
fs.go
fs.flushBalloc(op, blockA) ino.NBytes = newLen // TODO: leaves the inode dirty, caller must flush // // we should be able to flush it if we knew its inode number, potentially // relying on absorption within the transaction return true } func (fs Fs) shrinkInode(op *awol.Op, ino *inode, newLen uint64) { if !(ne...
{ op := fs.log.Begin() ino := fs.getInode(i) if ino.Kind != INODE_KIND_FILE { return false } for boff := off / disk.BlockSize; len(bs) > 0; boff++ { if off%disk.BlockSize != 0 { b := fs.inodeRead(ino, boff) byteOff := off % disk.BlockSize nBytes := disk.BlockSize - byteOff if uint64(len(bs)) < nByt...
identifier_body
fs.go
, due to inode size or running out of blocks) func (fs Fs) growInode(op *awol.Op, ino *inode, newLen uint64) bool { if !(ino.NBytes <= newLen) { panic("growInode requires a larger length") } oldBlks := divUp(ino.NBytes, disk.BlockSize) newBlks := divUp(newLen, disk.BlockSize) if newBlks > NumDirect { return fa...
{ b = b[:length] }
conditional_block
fs.go
sb *SuperBlock } func NewFs(log Log) Fs { sb := NewSuperBlock(uint64(log.Size())) blockA := balloc.Init(int(sb.NumBlockBitmaps)) op := log.Begin() op.Write(0, encodeSuperBlock(sb)) blockA.Flush(op, sb.blockAllocBase) log.Commit(op) op = log.Begin() op.Write(sb.inodeBase+(sb.rootInode-1), encodeInode(newI...
() balloc.Bitmap { bs := make([]disk.Block, fs.sb.NumBlockBitmaps) for i := 0; i < len(bs); i++ { bs[i] = fs.log.Read(fs.sb.blockAllocBase + uint64(i)) } return balloc.Open(bs) } func (fs Fs) flushBalloc(op *awol.Op, bm balloc.Bitmap) { bm.Flush(op, fs.sb.blockAllocBase) } // btoa translates an offset in an in...
readBalloc
identifier_name
fs.go
sb *SuperBlock } func NewFs(log Log) Fs { sb := NewSuperBlock(uint64(log.Size())) blockA := balloc.Init(int(sb.NumBlockBitmaps)) op := log.Begin() op.Write(0, encodeSuperBlock(sb)) blockA.Flush(op, sb.blockAllocBase) log.Commit(op) op = log.Begin() op.Write(sb.inodeBase+(sb.rootInode-1), encodeInode(newI...
de := decodeDirEnt(fs.inodeRead(dir, b)) if !de.Valid { continue } if de.Name == name { fs.inodeWrite(op, dir, b, encodeDirEnt(&DirEnt{ Valid: false, Name: "", I: 0, })) return true } } return false } func (fs Fs) isDirEmpty(dir *inode) bool { if dir.Kind != INODE_KIND_DIR { ...
panic("remove on non-dir inode") } blocks := dir.NBytes / disk.BlockSize for b := uint64(0); b < blocks; b++ {
random_line_split
pop-AP-var-v0.1.1-20190805.py
nd) ### # read into the amount of aboriginal peoples' population # with open(datadir+'\\'+'population-sum-ETL.csv', 'r', encoding='utf-8', newline='') as csvfile: df = pd.read_csv( csvfile, header = 0, usecols = ['日期', '身分', '區域別', '總計', '阿美族', '泰雅族', ...
wrong doing of input process print(ybeg, '~', ye
conditional_block
pop-AP-var-v0.1.1-20190805.py
(df): # trim whitespace from ends of each value across all series in dataframe trim_strings = lambda x: x.strip() if isinstance(x, str) else x return df.applymap(trim_strings) ### # set output figure and input data directories # pathdir = '.\\figure' # directory of output folder if not os.path.isdir(path...
trim_all_cells
identifier_name
pop-AP-var-v0.1.1-20190805.py
df = pd.read_csv( csvfile, header = 0, usecols = ['日期', '身分', '區域別', '總計', '阿美族', '泰雅族', '排灣族', '布農族', '魯凱族', '卑南族', '鄒族', '賽夏族', '雅美族', '邵族', '噶瑪蘭族', '太魯閣族', '撒奇萊雅族', '賽德克族', '拉阿魯哇族', '卡那卡那富族', ...
with open(datadir+'\\'+'population-sum-ETL.csv', 'r', encoding='utf-8', newline='') as csvfile:
random_line_split
pop-AP-var-v0.1.1-20190805.py
### # set output figure and input data directories # pathdir = '.\\figure' # directory of output folder if not os.path.isdir(pathdir): os.mkdir(pathdir) datadir = '.\\data' # directory of input data folder if not os.path.isdir(datadir): os.mkdir(datadir) ### # given the comparison period (from the year...
trim_strings = lambda x: x.strip() if isinstance(x, str) else x return df.applymap(trim_strings)
identifier_body
viastitching_dialog.py
return False for edge in self.board_edges: if edge.ShowShape() == 'Line': the_distance, _ = pnt2line(p1, edge.GetStart(), edge.GetEnd()) if the_distance <= clearance + via.GetWidth() / 2: return False if edge.ShowShape() == 'Ar...
self.x = float(point.x) self.y = float(point.y)
conditional_block
viastitching_dialog.py
Clearance", "0")) self.m_chkRandomize.SetValue(defaults.get("Randomize", False)) # Get default Vias dimensions via_dim_list = self.board.GetViasDimensionsList() if via_dim_list: via_dims = via_dim_list.pop() else: wx.MessageBox(_(u"Please set vi...
(self): """Collect overlapping items. Every bounding box of any item found is a candidate to be inspected for overlapping. """ area_bbox = self.area.GetBoundingBox() if hasattr(self.board, 'GetModules'): modules = self.board.GetModules() else: ...
GetOverlappingItems
identifier_name
viastitching_dialog.py
Clearance", "0")) self.m_chkRandomize.SetValue(defaults.get("Randomize", False)) # Get default Vias dimensions via_dim_list = self.board.GetViasDimensionsList() if via_dim_list: via_dims = via_dim_list.pop() else: wx.MessageBox(_(u"Please set vi...
if item.GetBoundingBox().Intersects(via.GetBoundingBox()): return True elif type(item) is pcbnew.PCB_TRACK: if item.GetBoundingBox().Intersects(via.GetBoundingBox()): width = item.GetWidth() dist, _ = pnt2line(v...
random_line_split
viastitching_dialog.py
Clearance", "0")) self.m_chkRandomize.SetValue(defaults.get("Randomize", False)) # Get default Vias dimensions via_dim_list = self.board.GetViasDimensionsList() if via_dim_list: via_dims = via_dim_list.pop() else: wx.MessageBox(_(u"Please set vi...
if the_distance < clearance: return False for i in range(corners): corner1 = area.GetCornerPosition(i) corner2 = area.GetCornerPosition((i + 1) % corners) pc1 = corner1.getWxPoint() pc2 = corner2.getWxPoint() the_di...
"""Check if position specified by p1 comply with given clearance in area. Parameters: p1 (wxPoint): Position to test area (pcbnew.ZONE_CONTAINER): Area clearance (int): Clearance value Returns: bool: True if p1 position comply with clearance valu...
identifier_body
difev_adversarial.py
_totensor(difev_vars.adv_image) # out = difev_vars.model.run(difev_vars.trans_adv_image) out = difev_vars.model.run(difev_vars.adv_image) # difev_vars.prob_adv = softmax(out.data.cpu().numpy()[0]) difev_vars.prob_adv = softmax(out) difev_vars.pred_adv = np.argmax(difev_vars.prob_adv) p = difev_v...
if k.find('color') == -1: new[k] = v
conditional_block
difev_adversarial.py
lasertoning', 'lentigo', 'leukemiacutis', 'leukocytoclasticvasculitis', 'lichenamyloidosis', 'lichennitidus', 'lichenoiddrugeruption', 'lichenplanus', 'lichensimplexchronicus', 'lichenstriatus', 'lipoma', 'lipomatosis', 'liv...
def get_basenames(self, img_path): basenames = [] dirname = os.path.dirname(img_path) for alias_ in self.list_alias: dirname = dirname.replace(alias_[0], alias_[1]) olddir = '' while dirname != '' and dirname != '/' and olddir != dirname: if ('lesion...
for j, dx_ in enumerate(self.main_dx): if dx_ == self.list_dx[i]: return self.main_dx2[j] return ""
identifier_body
difev_adversarial.py
# return self.loader1(image) def normalize_totensor(self, image): """ Input PIL image output cuda tensor """ x = self.loader2(image) x = x.repeat(1, 1, 1, 1) if is_cuda: x = x.cuda() return x def load_image(self, filename): # L...
# """
random_line_split
difev_adversarial.py
borrheic keratosis', 'Melanocytic nevus', 'Actinic keratosis', 'Dermatofibroma', 'Hemangioma', 'Wart', 'Lentigo'] self.main_dx = ['malignantmelanoma', 'basalcellcarcinoma', 'squamouscellcarcinoma', 'bowendisease', 'pyogenicgranuloma', ...
ColorAttack
identifier_name
rsync.rs
( rrdp_state: &RrdpState, changed: bool, config: &Config, ) -> Result<()> { // Check that there is a current snapshot, if not, there is no work if rrdp_state.snapshot_path().is_none() { return Ok(()); } // We can assume now that there is a snapshot and unwrap things for it let s...
update_from_rrdp_state
identifier_name
rsync.rs
_use_symlinks() { symlink_current_to_new_revision_dir(&new_revision, config)?; } else { rename_new_revision_dir_to_current(&new_revision, &rsync_state, config)?; } rsync_state.update_current(new_revision); } rsync_state.clean_old(config)?; rsync_state.persis...
"Renaming the rsync directory for previous revision to: {}", current_preserve_path.display() ); std::fs::rename(&current_path, &current_preserve_path).with_context(|| { format!( "Could not rename current rsync dir from '{}' to '...
random_line_split
rsync.rs
_name = file_ops::path_with_extension(&current_path, config::TMP_FILE_EXT); if tmp_name.exists() { std::fs::remove_file(&tmp_name).with_context(|| { format!( "Could not remove lingering temporary symlink for current rsync dir at '{}'", tmp_name.display() ...
{ // Try to parse this as a generic RPKI signed object SignedObject::decode(data, false).map(|signed| signed.cert().validity().not_before()) }
conditional_block
tcp.rs
out your //! specific `ulimit -n` settings and raise the max number of open files.) //! //! #### Avoid cross-thread communication //! This library uses no cross-thread communication via `std::sync` or `crossbeam`. All futures //! are executed on a `LocalPool`, and the number of OS threads used is user configurable. Th...
{ let addr = echo_server().unwrap(); let input = "test\n\r\n".as_bytes(); let want = input.len(); let result = async_std::task::block_on(async move { let mut stream = connect(&addr).await?; let mut read_buffer = [0u8; 1024]; let _ = write(&mut stream,...
identifier_body
tcp.rs
//! //! The pool of connections is created up front, and then connections begin sending requests //! to match the defined rate. (Or in the case of no defined, they start immediately.) In general //! we try to to limit significant allocations to startup rather than doing them on the fly. //! More specifically, you shou...
() { let result = async_std::task::block_on(async { let addr = echo_server().unwrap(); let result = connect(&addr).await; result }); assert!(result.is_ok()); } #[test] fn test_write() { let addr = echo_server().unwrap(); let inpu...
test_connect
identifier_name
tcp.rs
//! //! The pool of connections is created up front, and then connections begin sending requests //! to match the defined rate. (Or in the case of no defined, they start immediately.) In general //! we try to to limit significant allocations to startup rather than doing them on the fly. //! More specifically, you shou...
} #[cfg(test)] mod tests { use super::*; use crate::server::echo_server; #[test] fn test_connect() { let result = async_std::task::block_on(async { let addr = echo_server().unwrap(); let result = connect(&addr).await; result }); assert!(res...
// todo: Do something with the read_buffer? // todo: More verbose logging; dump to stdout, do post-run analysis on demand
random_line_split
epoll_file.rs
a host // file is ready, then it will be pushed into the ready list. Note // that this is the only way through which a host file can appear in // the ready list. This ensures that only the host files whose // events are update-to-date will be returned, reducing the chanc...
{ Some(self.host_file_epoller.host_fd()) }
identifier_body
epoll_file.rs
()); } return Ok(count); } // Wait for a while to try again later. let ret = waiter.wait_mut(timeout.as_mut()); if let Err(e) = ret { if e.errno() == ETIMEDOUT { return Ok(0); } else { ...
as_epoll_file
identifier_name
epoll_file.rs
Entries that are probably ready (having events happened). ready: SgxMutex<VecDeque<Arc<EpollEntry>>>, // All threads that are waiting on this epoll file. waiters: WaiterQueue, // A notifier to broadcast events on this epoll file. notifier: IoNotifier, // A helper to poll the events on the inter...
EpollCtl::Del(fd) => { self.del_interest(*fd)?; } EpollCtl::Mod(fd, event, flags) => { self.mod_interest(*fd, *event, *flags)?; } } Ok(()) } pub fn wait( &self, revents: &mut [MaybeUninit<EpollEvent...
{ self.add_interest(*fd, *event, *flags)?; }
conditional_block
epoll_file.rs
// process, then this EpollFile still has connection with the parent process's // file table, which is problematic. /// A file that provides epoll API. /// /// Conceptually, we maintain two lists: one consists of all interesting files, /// which can be managed by the epoll ctl commands; the other are for ready files, ...
// with the current process's file table by regitering itself as an observer // to the file table. But if an EpollFile is cloned or inherited by a child
random_line_split
lib.rs
::f128::BaseElement, FieldElement}, //! ExecutionTrace, //! }; //! //! pub fn build_do_work_trace(start: BaseElement, n: usize) -> ExecutionTrace<BaseElement> { //! // Instantiate the trace with a given width and length; this will allocate all //! // required memory for the trace //! let trace_width = 1...
//! # } //! # }
random_line_split
secrets.pb.go
0x11, 0xec, 0x14, 0xe1, 0x5e, 0x11, 0x1e, 0x14, 0xc1, 0x51, 0x11, 0x9e, 0x14, 0xc1, 0x59, 0x11, 0x5e, 0x14, 0xc1, 0x42, 0x13, 0x2c, 0x35, 0xe1, 0x9d, 0x26, 0xb8, 0xd7, 0x84, 0x0f, 0x9a, 0x60, 0xa5, 0x09, 0xd6, 0x9a, 0x70, 0xa3, 0x09, 0xb7, 0x9a, 0xf0, 0x1f, 0x0b, 0x84, 0x2d, 0x27, 0x5c, 0x4e, 0xc2, 0x38, 0xc8, 0xec...
} func (this *Secret) String() string { if this == nil {
random_line_split
secrets.pb.go
xc4, 0x5d, 0x49, 0xb8, 0x2f, 0x09, 0x0f, 0x25, 0xc1, 0xb1, 0x24, 0x38, 0x95, 0x04, 0xe7, 0x92, 0xe0, 0x52, 0x12, 0x2e, 0x14, 0xe1, 0x52, 0x11, 0xac, 0x14, 0xe1, 0x5a, 0x11, 0x6c, 0x14, 0xc1, 0x56, 0x11, 0xec, 0x14, 0xe1, 0x5e, 0x11, 0x1e, 0x14, 0xc1, 0x51, 0x11, 0x9e, 0x14, 0xc1, 0x59, 0x11, 0x5e, 0x14, 0xc1, 0x42, ...
Size
identifier_name
secrets.pb.go
00, } func (this *Secret) Equal(that interface{}) bool { if that == nil { return this == nil } that1, ok := that.(*Secret) if !ok { that2, ok := that.(Secret) if ok { that1 = &that2 } else { return false } } if that1 == nil { return this == nil } else if this == nil { return false } if th...
{ if shift >= 64 { return ErrIntOverflowSecrets } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ stringLen |= uint64(b&0x7F) << shift if b < 0x80 { break } }
conditional_block
secrets.pb.go
func init() { proto.RegisterType((*Secret)(nil), "ttn.lorawan.v3.Secret") golang_proto.RegisterType((*Secret)(nil), "ttn.lorawan.v3.Secret") } func init() { proto.RegisterFile("lorawan-stack/api/secrets.proto", fileDescriptor_8c9d796b7f7ca235) } func init() { golang_proto.RegisterFile("lorawan-stack/api/secrets.p...
{ if m != nil { return m.Value } return nil }
identifier_body
script.js
122.463701, 37.747683]) //-122.41, 37.79 .scale(width*200) .translate([width / 2, height / 2]); var path = d3.geo.path() .projection(projection); var ndx, yearDim, mhiDim, mgrDim, tractDim; var filterYear, filterMetric, sf_topojson; var parsed_data = []; var parsed_biz = []; var parsed_biz...
(evt) { var oldFilterMetric = filterMetric; filterMetric = evt.target.id; if (filterMetric !== "mhi" && filterMetric !== "mgr") { filterYear = +(filterMetric.split("_")[1]); filterMetric = oldFilterMetric; metricChange(true); var titleMetric = maptitle.innerHTML.split(" ").slice(0, 3); titleMe...
clickedOn
identifier_name