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
http.go
== nil { keyVals[k] = int(i) } else if f, err := t.Float64(); err == nil { keyVals[k] = f } else { keyVals[k] = t.String() } } } return keyVals, err } // Key-val format: key=val,key2=val2, ... for _, kv := range strings.Split(headers.Get(headerName), ";") { if kv != "" { kvS...
frame = qf.ReadCSV(r.Body, configFns...) case contentTypeJson: configFns, err := headersToJsonConfig(r.Header) if err != nil { a.badRequest(w, err.Error()) return } frame = qf.ReadJSON(r.Body, configFns...) default: a.badRequest(w, "Unknown content type: %s", contentType) return } if frame.Er...
{ statsProbe := statistics.NewStoreProbe(r.Context()) defer r.Body.Close() vars := mux.Vars(r) key := vars["key"] var frame qf.QFrame contentType, charset := parseContentType(r.Header.Get("Content-Type")) if charset != "" && charset != "utf-8" { a.badRequest(w, "Unsupported charset: %s", charset) return } ...
identifier_body
http.go
err == nil { keyVals[k] = int(i) } else if f, err := t.Float64(); err == nil { keyVals[k] = f } else { keyVals[k] = t.String() } } } return keyVals, err } // Key-val format: key=val,key2=val2, ... for _, kv := range strings.Split(headers.Get(headerName), ";") { if kv != "" { ...
(msg string, params ...interface{}) string { result := fmt.Sprintf(msg, params...) a.logger.Printf(result) return result } func (a *application) logError(source string, err error) { if err != nil { a.logger.Printf("Error %s: %v", source, err) } } func (a *application) badRequest(w http.ResponseWriter, msg stri...
log
identifier_name
http.go
string) { result := strings.Split(h, ";") if len(result) == 1 { return strings.TrimSpace(h), "" } if len(result) >= 2 { contentType, charset := strings.TrimSpace(result[0]), "" match := charsetRegex.FindStringSubmatch(result[1]) if len(match) > 1 { charset = match[1] } return contentType, charset ...
{ r.HandleFunc(root+"/dataset/{key}", mw(app.newDataset)).Methods("POST") r.HandleFunc(root+"/dataset/{key}/q", mw(app.queryDatasetPost)).Methods("POST") r.HandleFunc(root+"/dataset/{key}", mw(app.queryDatasetGet)).Methods("GET") r.HandleFunc(root+"/statistics", mw(app.statistics)).Methods("GET") r.HandleFunc...
conditional_block
http.go
err == nil { keyVals[k] = int(i) } else if f, err := t.Float64(); err == nil { keyVals[k] = f } else { keyVals[k] = t.String() } } } return keyVals, err } // Key-val format: key=val,key2=val2, ... for _, kv := range strings.Split(headers.Get(headerName), ";") { if kv != "" { ...
func (a *application) log(msg string, params ...interface{}) string { result := fmt.Sprintf(msg, params...) a.logger.Printf(result) return result } func (a *application) logError(source string, err error) { if err != nil { a.logger.Printf("Error %s: %v", source, err) } } func (a *application) badRequest(w http...
}
random_line_split
HeaderCell.ts
from './HeaderRow'; import Cell, {IOptions as ICellOptions} from './Cell'; export interface IOptions<T> extends ICellOptions<T> { shadowVisibility?: string; backgroundStyle?: string; sorting?: string; cellPadding?: IItemPadding; } const DEFAULT_CELL_TEMPLATE = 'Controls/gridNew:HeaderContent'; const...
} return contentClasses; } protected _getContentSeparatorClasses(theme: string): string { let headerEndRow = this._$owner.getBounds().row.end; const isMultiLineHeader = this._$owner.isMultiline(); let classes = ''; if (isMultiLineHeader) { if (this._$...
} if (this._$align) { contentClasses += ` controls-Grid__header-cell_justify_content_${this._$align}`;
random_line_split
HeaderCell.ts
from './HeaderRow'; import Cell, {IOptions as ICellOptions} from './Cell'; export interface IOptions<T> extends ICellOptions<T> { shadowVisibility?: string; backgroundStyle?: string; sorting?: string; cellPadding?: IItemPadding; } const DEFAULT_CELL_TEMPLATE = 'Controls/gridNew:HeaderContent'; const...
// todo <<< START >>> compatible with old gridHeaderModel get column(): IHeaderCell { return this._$column; } // todo <<< END >>> isLastColumn(): boolean { const isMultilineHeader = this._$owner.isMultiline(); if (isMultilineHeader) { let headerEndColumn = this._$ow...
}
identifier_name
HeaderCell.ts
from './HeaderRow'; import Cell, {IOptions as ICellOptions} from './Cell'; export interface IOptions<T> extends ICellOptions<T> { shadowVisibility?: string; backgroundStyle?: string; sorting?: string; cellPadding?: IItemPadding; } const DEFAULT_CELL_TEMPLATE = 'Controls/gridNew:HeaderContent'; const...
ht_theme-${theme}`; } else { wrapperClasses += ` controls-Grid__header-cell_min-height_theme-${theme}`; } if (!isStickySupport) { wrapperClasses += ' controls-Grid__header-cell_static'; } if (!this.isMultiSelectColumn()) { wrapperClasses += ' ...
tWrapperPaddingClasses(theme)}` + ` ${this._getColumnSeparatorClasses(theme)}` + ` controls-background-${backgroundColorStyle || style}_theme-${theme}`; const isMultilineHeader = this._$owner.isMultiline(); const isStickySupport = this._$owner.isStick...
identifier_body
HeaderCell.ts
Row from './HeaderRow'; import Cell, {IOptions as ICellOptions} from './Cell'; export interface IOptions<T> extends ICellOptions<T> { shadowVisibility?: string; backgroundStyle?: string; sorting?: string; cellPadding?: IItemPadding; } const DEFAULT_CELL_TEMPLATE = 'Controls/gridNew:HeaderContent'; co...
}`; } } return classes; } getTemplate(): TemplateFunction|string { return this._$column.template || DEFAULT_CELL_TEMPLATE; } getCaption(): string { // todo "title" - is deprecated property, use "caption" return this._$column.caption || this._$column....
.startRow === 1) { classes += ` controls-Grid__cell_header-content_border-bottom_theme-${theme
conditional_block
util.py
ils(shape): npts = shape.shape[0] if npts == 29: dist_pupils = np.linalg.norm(shape[7-1,:] - shape[16-1,:]) elif npts == 68: left_eye_4 = [38 - 1, 39 - 1, 41 - 1, 42 - 1] right_eye_4 = [44 - 1, 45 - 1, 47 - 1, 48 - 1] left_center = np.mean(shape(left_eye_4, :), 0) ...
refshape_new = np.mean(alignedShapes, 0) diff = np.abs(np.max(refshape - refshape_new)) refshape = refshape_new print('MeanShape finished in {} iterations.\n'.format(iters)) return refshape.reshape(-1, 2) def alignShape(s1, s0): npts = len(s1)/2 s1 = s1.reshape(npt...
alignedShapes(i,:) = alignShape(alignedShapes(i,:), refshape)
conditional_block
util.py
(data_path): number_files = len(os.listdir(data_path)) / 4 # because for a image we have 4 related files train_set = [] for i in range(number_files): if i % 50 == 0: print('Samples loaded {} / {} ...'.format(i, number_files)) img = cv2.imread(data_path + 'image_%04d.png'%...
loadTrainData
identifier_name
util.py
ils(shape): npts = shape.shape[0] if npts == 29: dist_pupils = np.linalg.norm(shape[7-1,:] - shape[16-1,:]) elif npts == 68: left_eye_4 = [38 - 1, 39 - 1, 41 - 1, 42 - 1] right_eye_4 = [44 - 1, 45 - 1, 47 - 1, 48 - 1] left_center = np.mean(shape(left_eye_4, :), 0) ...
M_diff_rho[:,f] = features[k,f].rho_m - features[k,f].rho_n updateMat = evaluateFern_batch(M_diff_rho, ferns[k]) print('fern %d/%d\tmax(Y) = %.6g, min(Y) = %.6g'%(k
ferns.append(trainFern(features[-1], Y, M_rho, beta)) # update the normalized target M_diff_rho = np.zeros(nsamples, F) for f in range(F):
random_line_split
util.py
def estimateTransform(source_shape, target_shape): n, m = source_shape.shape mu_source = mean(source_shape, 0) mu_target = mean(target_shape, 0) d_source = source_shape - tile(mu_source, (n, 1)) sig_source2 = np.sum(d_source*d_source)/n d_target = target_shape - repmat(mu_target, n, ...
Lfp = Y.shape[1] nbins = len(bins) outputs = np.zeros(nbins, Lfp) for i in range(nbins): if bins[i].size == 0: # empty bin continue outputs[i,:] = sum(Y[bins[i], :]) ni = len(bins[i]) factor = 1.0 / ((1 + beta/ni)*ni) outputs[i,:] = outputs[i,:]...
identifier_body
request_error.pb.go
RESOURCE_NOT_FOUND", 7: "INVALID_PAGE_TOKEN", 8: "EXPIRED_PAGE_TOKEN", 22: "INVALID_PAGE_SIZE", 9: "REQUIRED_FIELD_MISSING", 11: "IMMUTABLE_FIELD", 13: "TOO_MANY_MUTATE_OPERATIONS", 14: "CANNOT_BE_EXECUTED_BY_MANAGER_ACCOUNT", 15: "CANNOT_MODIFY_FOREIGN_FIELD", 18: "INVALID_ENUM_VALUE", 19: "DEVELOPER_TOKE...
func (m *RequestErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_RequestErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_RequestErrorEnum proto.InternalMessageInfo func init() { proto.RegisterType((*RequestErrorEnum)(nil), "google.ads.googleads.v1.errors.RequestErrorEnum") proto.RegisterEnum("google.ads.googlea...
{ return xxx_messageInfo_RequestErrorEnum.Size(m) }
identifier_body
request_error.pb.go
22: "INVALID_PAGE_SIZE", 9: "REQUIRED_FIELD_MISSING", 11: "IMMUTABLE_FIELD", 13: "TOO_MANY_MUTATE_OPERATIONS", 14: "CANNOT_BE_EXECUTED_BY_MANAGER_ACCOUNT", 15: "CANNOT_MODIFY_FOREIGN_FIELD", 18: "INVALID_ENUM_VALUE", 19: "DEVELOPER_TOKEN_PARAMETER_MISSING", 20: "LOGIN_CUSTOMER_ID_PARAMETER_MISSING", 21: "VAL...
6: "RESOURCE_NOT_FOUND", 7: "INVALID_PAGE_TOKEN", 8: "EXPIRED_PAGE_TOKEN",
random_line_split
request_error.pb.go
RESOURCE_NOT_FOUND", 7: "INVALID_PAGE_TOKEN", 8: "EXPIRED_PAGE_TOKEN", 22: "INVALID_PAGE_SIZE", 9: "REQUIRED_FIELD_MISSING", 11: "IMMUTABLE_FIELD", 13: "TOO_MANY_MUTATE_OPERATIONS", 14: "CANNOT_BE_EXECUTED_BY_MANAGER_ACCOUNT", 15: "CANNOT_MODIFY_FOREIGN_FIELD", 18: "INVALID_ENUM_VALUE", 19: "DEVELOPER_TOKE...
(src proto.Message) { xxx_messageInfo_RequestErrorEnum.Merge(dst, src) } func (m *RequestErrorEnum) XXX_Size() int { return xxx_messageInfo_RequestErrorEnum.Size(m) } func (m *RequestErrorEnum) XXX_DiscardUnknown() { xxx_messageInfo_RequestErrorEnum.DiscardUnknown(m) } var xxx_messageInfo_RequestErrorEnum proto.Int...
XXX_Merge
identifier_name
http_server_utils.go
Params map[string]*HttpParam ErrorCodes []string Errors []error postJson map[string]interface{} body []byte } type HttpParam struct { Name string InvalidErrorCode string DataType HttpParamDataType Type HttpParamType Required bool MinLength int MaxLength int Post bool Value interface{} Raw string Vali...
{ param.Raw = retrieveParamValue(ctx, param).(string) if len(param.Raw) == 0 && param.Required { appendInvalidErrorCode(ctx, param) return } if len(param.Raw) == 0 { return } if val, err := strconv.ParseBool(param.Raw); err != nil { appendInvalidErrorCode(ctx, param) } else { param.setPresentValue(val...
identifier_body
http_server_utils.go
HttpContext struct { Response http.ResponseWriter Request *http.Request Params map[string]*HttpParam ErrorCodes []string Errors []error postJson map[string]interface{} body []byte } type HttpParam struct { Name string InvalidErrorCode string DataType HttpParamDataType Type HttpParamType Required bool M...
for _, param := range self.Params { switch param.DataType { case HttpIntParam: validateIntParam(self, param) case HttpStringParam: validateStringParam(self, param) case HttpFloatParam: validateFloatParam(self, param) case HttpBoolParam: validateBoolParam(self, param) case HttpObjectIdParam: validate...
{ return true }
conditional_block
http_server_utils.go
HttpContext struct { Response http.ResponseWriter Request *http.Request Params map[string]*HttpParam ErrorCodes []string Errors []error postJson map[string]interface{} body []byte } type HttpParam struct { Name string InvalidErrorCode string DataType HttpParamDataType Type HttpParamType Required bool M...
func (self *HttpContext) ParamObjectId(name string) *bson.ObjectId { return self.Params[name].ObjectId() } func (self *HttpContext) ParamJson(name string) map[string]interface{} { return self.Params[name].Json() } func (self *HttpContext) ParamJsonArray(name string) []interface{} { return self.Params[name].JsonArray...
func (self *HttpContext) ParamBool(name string) bool { return self.Params[name].Bool() }
random_line_split
http_server_utils.go
HttpContext struct { Response http.ResponseWriter Request *http.Request Params map[string]*HttpParam ErrorCodes []string Errors []error postJson map[string]interface{} body []byte } type HttpParam struct { Name string InvalidErrorCode string DataType HttpParamDataType Type HttpParamType Required bool M...
() *bson.ObjectId { if self.Value != nil { return self.Value.(*bson.ObjectId) } else { return nil } } func (self *HttpParam) Json() map[string]interface{} { if self.Value == nil { return nil } else { return self.Value.(map[string]interface{}) } } func (self *HttpParam) JsonArray() []interface{} { if self.Value == nil...
ObjectId
identifier_name
mod.rs
Handle raft ready to process the side affect and send IO tasks to //! background threads //! - Receive IO tasks completion and update the raft state machine //! //! There two steps can be processed concurrently. mod async_writer; use engine_traits::{KvEngine, RaftEngine}; use error_code::ErrorCodeExt; use kvproto:...
/// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if !self.is_leader() { self.entry_storage_mut().clean_async_fetch_res(low); return...
{ self.raft_group_mut().tick() }
identifier_body
mod.rs
- Handle raft ready to process the side affect and send IO tasks to //! background threads //! - Receive IO tasks completion and update the raft state machine //! //! There two steps can be processed concurrently. mod async_writer; use engine_traits::{KvEngine, RaftEngine}; use error_code::ErrorCodeExt; use kvprot...
_take_committed_entries: Vec<raft::prelude::Entry>, ) { unimplemented!() } /// Processing the ready of raft. A detail description of how it's handled /// can be found at https://docs.rs/raft/latest/raft/#processing-the-ready-state. /// /// It's should be called at the end of eve...
random_line_split
mod.rs
- Handle raft ready to process the side affect and send IO tasks to //! background threads //! - Receive IO tasks completion and update the raft state machine //! //! There two steps can be processed concurrently. mod async_writer; use engine_traits::{KvEngine, RaftEngine}; use error_code::ErrorCodeExt; use kvprot...
(&mut self) -> bool { self.raft_group_mut().tick() } /// Callback for fetching logs asynchronously. pub fn on_fetched_logs(&mut self, fetched_logs: FetchedLogs) { let FetchedLogs { context, logs } = fetched_logs; let low = logs.low; if !self.is_leader() { self.en...
tick
identifier_name
gl_scene.py
8: (0.4, 0.4, 0.4), 9: (0.0, 0.0, 0.0), } def make_plane(): glNewList(G_OBJ_PLANE, GL_COMPILE) glBegin(GL_LINES) glColor3f(0, 0, 0) for i in range(41): glVertex3f(-10.0 + 0.5 * i, 0, -10) glVertex3f(-10.0 + 0.5 * i, 0, 10) glVertex3f(-10.0, 0, -10 + 0.5 * i) glVert...
List() def init_primitives(): """ 初始化所有的图元渲染函数列表 """ make_plane() make_sphere() make_cube() def translation(displacement): """ 生成平移矩阵 """ t = numpy.identity(4) t[0, 3] = displacement[0] t[1, 3] = displacement[1] t[2, 3] = displacement[2] return t def scaling(scale): """...
0], normals[i][1], normals[i][2]) for j in range(4): glVertex3f(vertices[i][j][0], vertices[i][j][1], vertices[i][j][2]) glEnd() glEnd
conditional_block
gl_scene.py
0.5, -0.5))] normals = [(-1.0, 0.0, 0.0), (0.0, 0.0, -1.0), (1.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, -1.0, 0.0), (0.0, 1.0, 0.0)] glBegin(GL_QUADS) for i in range(6): glNormal3f(normals[i][0], normals[i][1], normals[i][2]) for j in range(4): glVertex3f(vertices[i][j][0], vertices...
视野范围到
identifier_name
gl_scene.py
0, 0, -10 + 0.5 * i) # Axes glEnd() glLineWidth(5) glBegin(GL_LINES) glColor3f(0.5, 0.7, 0.5) glVertex3f(0.0, 0.0, 0.0) glVertex3f(5, 0.0, 0.0) glEnd() glBegin(GL_LINES) glColor3f(0.5, 0.7, 0.5) glVertex3f(0.0, 0.0, 0.0) glVertex3f(0.0, 5, 0.0) glEnd() glBegin...
ld_nodes[1].scale(0.8) self.child_nodes[2].transl
identifier_body
gl_scene.py
MIN_COLOR = 0 COLORS = { # RGB Colors 0: (1.0, 1.0, 1.0), 1: (0.05, 0.05, 0.9), 2: (0.05, 0.9, 0.05), 3: (0.9, 0.05, 0.05), 4: (0.9, 0.9, 0.0), 5: (0.1, 0.8, 0.7), 6: (0.7, 0.2, 0.7), 7: (0.7, 0.7, 0.7), 8: (0.4, 0.4, 0.4), 9: (0.0, 0.0, 0.0), } def make_plane(): glNewList...
G_OBJ_CUBE = 3 MAX_COLOR = 9
random_line_split
driver.rs
(previous) = &previous { (previous)(sess, lint_store); } let conf = clippy_lints::read_conf(&[], &sess); clippy_lints::register_plugins(&mut lint_store, &sess, &conf); clippy_lints::register_pre_expansion_lints(&mut lint_store, &conf); clippy_...
.or_else(|_| std::env::var("MULTIRUST_HOME")) .ok(); let toolchain = std::env::var("RUSTUP_TOOLCHAIN")
random_line_split
driver.rs
.map(|group| group.len()) .map(|len| len + "clippy::".len()) .max() .unwrap_or(0), ); let padded_group = |x: &str| { let mut s = " ".repeat(max_group_name_len - x.chars().count()); s.push_str(x); s }; println!("Lint groups provide...
{ Some(s.to_string()) }
conditional_block
driver.rs
() { let args = &["--bar=bar", "--foobar", "123", "--foo"]; assert_eq!(arg_value(&[] as &[&str], "--foobar", |_| true), None); assert_eq!(arg_value(args, "--bar", |_| false), None); assert_eq!(arg_value(args, "--bar", |_| true), Some("bar")); assert_eq!(arg_value(args, "--bar", |p| p == "bar"), Som...
test_arg_value
identifier_name
matrix_invert.rs
= matrix_a[idx] - 3.0; // just do it!!! // make a unit matrix let mut matrix_i = vec![0f32; nxy]; for r in 0..nx { matrix_i[r * nx + r] = 1.0; } println!("orignal matrix_a: "); print_matrix(&matrix_a, nx, nx); println!("orignal matrix_i: "); print_matrix(&matrix_i, nx...
// calculate the inverse and compare with expected result let inv = matrix_invert_cpu(&m).unwrap(); assert_eq!(expected, inv); println!("orignal: {}", m); println!("inverted: {}", inv); } #[derive(Debug, PartialEq, Clone)] pub struct Matrix { data: Vec<f32>, rows: usize, cols: usize, } ...
expected.set(2, 2, 1.0);
random_line_split
matrix_invert.rs
= matrix_a[idx] - 3.0; // just do it!!! // make a unit matrix let mut matrix_i = vec![0f32; nxy]; for r in 0..nx { matrix_i[r * nx + r] = 1.0; } println!("orignal matrix_a: "); print_matrix(&matrix_a, nx, nx); println!("orignal matrix_i: "); print_matrix(&matrix_i, nx...
(rows: usize, cols: usize) -> Matrix { Matrix { rows: rows, cols: cols, data: vec![0.0; cols * rows], } } pub fn identiy(rows: usize) -> Matrix { let mut m = Matrix::zero(rows, rows); for i in 0..rows { m.set(i, i, 1.0); } ...
zero
identifier_name
matrix_invert.rs
= matrix_a[idx] - 3.0; // just do it!!! // make a unit matrix let mut matrix_i = vec![0f32; nxy]; for r in 0..nx { matrix_i[r * nx + r] = 1.0; } println!("orignal matrix_a: "); print_matrix(&matrix_a, nx, nx); println!("orignal matrix_i: "); print_matrix(&matrix_i, nx...
// apply all transformations to the identiy matrix as well cols = 2 * mat_a.cols; let mut tmp: f32 = 0.0;
{ if mat_a.rows != mat_a.cols { return Err(MathError::MatrixNotInvertableNotSquare); } let rows = mat_a.rows; let mut cols = mat_a.cols; // helper matrix for inverting let mut dummy = Matrix::zero(rows, 2 * cols); // copy matrix a to dummy (left half of dummy) for row in 0..row...
identifier_body
classifier.py
h_pool2 = max_pool_2x2(h_conv2) # Fully connected layer 1 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # Dropout h...
print(max_steps, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) save_path = saver.save(sess, "results/cnn_classifier-med-train/checkpoint/model.ckpt") # print('Test Acc', sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob...
batch_xs, batch_ys = mnist.train.next_batch(50) # 0 ~ 1 # batch_xs = batch_xs*2-1 # -1 ~ 1, bad results if (step % 10) == 0: print(step, sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0})) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_y...
conditional_block
classifier.py
def cnn_classifier(x_image, keep_prob, name="classifier", reuse=True): with tf.variable_scope(name, reuse=reuse): # Convolutional layer 1 W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool...
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
identifier_body
classifier.py
(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(...
weight_variable
identifier_name
classifier.py
h_pool2 = max_pool_2x2(h_conv2) # Fully connected layer 1 h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # Dropout h...
# Fully connected layer 2 (Output layer) W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) y = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='y') return y def main(): from tensorflow.examples.tutorials.mnist import input_data mnist = input_data...
random_line_split
replica.go
create_and_lock(USERLIST_FILENAME) // lock userlist file for editing defer lock_for_files_map[USERLIST_FILENAME].Unlock() file, open_err := os.OpenFile(USERLIST_FILENAME, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0600) defer file.Close() if open_err != nil { return fmt.Sprintf("error: Server open error%s\n", E...
{ removed = true //didn't add scanned_name to sublist continue }
conditional_block
replica.go
delete user from server memory user_map_lock.Lock() delete(user_map, uname) user_map_lock.Unlock() err := rewrite_userlist() //delete user from user list file if err != nil { return fmt.Sprintf("error: Server rewrite uselist error%s\n", END_TAG), false } //delete user message file filename := uname + ".txt" ...
{ if err != nil { panic(err) } }
identifier_body
replica.go
data, so it should not be using locks. This function directs to other function that will lock files for read/write. Pre-Condition: Request will be in the form of "queryname: arg1: arg2: ..." Post Condition: complete request and return the response, along with bool saying if there was an update returns (response, i...
} else { return sub_feed(uname, num_messages) } } return fmt.Sprintf("error: unknown error.%s\n", END_TAG), false } //========================================================================================== //Functions that respond to queries, used by Evalute //==============================================...
random_line_split
replica.go
.Sprintf("error: Server rewrite uselist error%s\n", END_TAG), false } //delete user message file filename := uname + ".txt" create_and_lock(filename) // lock the file we want to delete defer lock_for_files_map[filename].Unlock() os.Remove(filename) //repond sucess return fmt.Sprintf("success: Deleted user %s.%...
create_and_lock
identifier_name
upb.rs
NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // ...
// SAFETY: // - `upb_Arena_Realloc` promises that if the return pointer is non-null, it is // dereferencable for the new `size` in bytes until the arena is destroyed. // - `[MaybeUninit<u8>]` has no alignment requirement, and `ptr` is aligned to a // `UPB_MALLOC_ALIGN` boun...
{ alloc::handle_alloc_error(new); }
conditional_block
upb.rs
eref; use std::ptr::{self, NonNull}; use std::slice; /// See `upb/port/def.inc`. const UPB_MALLOC_ALIGN: usize = 8; /// A wrapper over a `upb_Arena`. /// /// This is not a safe wrapper per se, because the allocation functions still /// have sharp edges (see their safety docs for more info). /// /// This is an owning ...
self.msg } }
random_line_split
upb.rs
, RawMessage}; use std::alloc; use std::alloc::Layout; use std::cell::UnsafeCell; use std::fmt; use std::marker::PhantomData; use std::mem::MaybeUninit; use std::ops::Deref; use std::ptr::{self, NonNull}; use std::slice; /// See `upb/port/def.inc`. const UPB_MALLOC_ALIGN: usize = 8; /// A wrapper over a `upb_Arena`. ...
new
identifier_name
upb.rs
NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // ...
} impl Drop for Arena { #[inline] fn drop(&mut self) { unsafe { upb_Arena_Free(self.raw); } } } /// Serialized Protobuf wire format data. /// /// It's typically produced by `<Message>::serialize()`. pub struct SerializedData { data: NonNull<u8>, len: usize, // The...
{ debug_assert!(new.align() <= UPB_MALLOC_ALIGN); // SAFETY: // - `self.raw` is a valid UPB arena // - `ptr` was allocated by a previous call to `alloc` or `realloc` as promised // by the caller. let ptr = unsafe { upb_Arena_Realloc(self.raw, ptr, old.size(), new.size()...
identifier_body
Content.js
_createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else...
() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } } /** @jsx jsx */ import React...
_isNativeReflectConstruct
identifier_name
Content.js
'../styled/Content'; import Footer from './Footer'; import Header from './Header'; function getInitialState() { return { showFooterKeyline: false, showHeaderKeyline: false, showContentFocus: false, tabbableElements: [] }; } function mergeRefs(refs) { return function (value) { refs.forEach(f...
}); export { Content as default };
random_line_split
Content.js
createSuper(Derived)
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return fals...
{ var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply...
identifier_body
Content.js
createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else {...
} }, { key: "componentWillUnmount", value: function componentWillUnmount() { this._isMounted = false; document.removeEventListener('keydown', this.handleKeyDown, false); document.removeEventListener('keyup', this.handleKeyUp, false); if (this.scrollContainer) { var captur...
{ this.handleStackChange(nextProps.stackIndex); }
conditional_block
datascraper_whoscored.py
.whoscored.com%s" % link) time.sleep(2) # let the link load soup = BeautifulSoup(driver.page_source, 'lxml') date = soup.find_all('dd')[4] # [3].find('dl').find_all('dd') score = soup.find_all('dd')[2] scores = [int(s) for s in score.text.split() if s.isdigit()] teams = [] teams_link = sou...
match_report_stat.append(span.text) return match_report_stat if len(sys.argv) == 3: # Parameters to write the data to links_csv = sys.argv[1] # "data/whoscored/match-links.csv" filepath = sys.argv[2] # leaguename = 'premierleague' # filepath = 'data/whoscored/%s-%d.csv' % (l...
soup = BeautifulSoup(driver.page_source, 'lxml') info_div = soup.find('div', id=info_panel_id) for stat in info_div.find_all('div', class_='stat'): for span in stat.find_all('span', class_='stat-value'): match_report_stat.append(span.text) clickable_fields = driver.find_elements_by_xpat...
identifier_body
datascraper_whoscored.py
.whoscored.com%s" % link) time.sleep(2) # let the link load soup = BeautifulSoup(driver.page_source, 'lxml') date = soup.find_all('dd')[4] # [3].find('dl').find_all('dd') score = soup.find_all('dd')[2] scores = [int(s) for s in score.text.split() if s.isdigit()] teams = [] teams_link = sou...
return match_report_stat if len(sys.argv) == 3: # Parameters to write the data to links_csv = sys.argv[1] # "data/whoscored/match-links.csv" filepath = sys.argv[2] # leaguename = 'premierleague' # filepath = 'data/whoscored/%s-%d.csv' % (leaguename, 20182019) chromepath = "chromedriver...
match_report_stat.append(span.text)
conditional_block
datascraper_whoscored.py
.whoscored.com%s" % link) time.sleep(2) # let the link load soup = BeautifulSoup(driver.page_source, 'lxml') date = soup.find_all('dd')[4] # [3].find('dl').find_all('dd') score = soup.find_all('dd')[2] scores = [int(s) for s in score.text.split() if s.isdigit()] teams = [] teams_link = sou...
(match_report_stat, info_panel_id, clickable_xpath): # Get the page and now scrap the data from the bottom panel soup = BeautifulSoup(driver.page_source, 'lxml') info_div = soup.find('div', id=info_panel_id) for stat in info_div.find_all('div', class_='stat'): for span in stat.find_all('span', c...
extract_report_data
identifier_name
datascraper_whoscored.py
.whoscored.com%s" % link) time.sleep(2) # let the link load soup = BeautifulSoup(driver.page_source, 'lxml') date = soup.find_all('dd')[4] # [3].find('dl').find_all('dd') score = soup.find_all('dd')[2] scores = [int(s) for s in score.text.split() if s.isdigit()] teams = [] teams_link = sou...
"home total shots", "away total shots", "home woodwork", "away woodwork", "home shots on target", "away shots on target", "home shots off target", "away shots off target", "home shots blocked", "away shots blocked", "home possession", "away possession", "home ...
random_line_split
function.go
// Use StaticReturnType if the function's return type does not vary // depending on its arguments. Type TypeFunc // Impl is the ImplFunc that implements the function's behavior. // // Functions are expected to behave as pure functions, and not create // any visible side-effects. // // If a TypeFunc is also pro...
if val.IsNull() && !spec.AllowNull { return cty.Type{}, NewArgErrorf(i, "argument must not be null") } // AllowUnknown is ignored for type-checking, since we expect to be // able to type check with unknown values. We *do* still need to deal // with DynamicPseudoType here though, since the Type function ...
{ // During type checking we just unmark values and discard their // marks, under the assumption that during actual execution of // the function we'll do similarly and then re-apply the marks // afterwards. Note that this does mean that a function that // inspects values (rather than just types) in its T...
conditional_block
function.go
// Use StaticReturnType if the function's return type does not vary // depending on its arguments. Type TypeFunc // Impl is the ImplFunc that implements the function's behavior. // // Functions are expected to behave as pure functions, and not create // any visible side-effects. // // If a TypeFunc is also pro...
if val.Type() == cty.DynamicPseudoType { if !spec.AllowDynamicType { return cty.DynamicPseudoType, nil } } else if errs := val.Type().TestConformance(spec.Type); errs != nil { // For now we'll just return the first error in the set, since // we don't have a good way to return the whole list here. ...
// AllowUnknown is ignored for type-checking, since we expect to be // able to type check with unknown values. We *do* still need to deal // with DynamicPseudoType here though, since the Type function might // not be ready to deal with that.
random_line_split
function.go
// Use StaticReturnType if the function's return type does not vary // depending on its arguments. Type TypeFunc // Impl is the ImplFunc that implements the function's behavior. // // Functions are expected to behave as pure functions, and not create // any visible side-effects. // // If a TypeFunc is also pro...
// ReturnType returns the return type of a function given a set of candidate // argument types, or returns an error if the given types are unacceptable. // // If the caller already knows values for at least some of the arguments // it can be better to call ReturnTypeForValues, since certain functions may // determine...
{ return func([]cty.Value) (cty.Type, error) { return ty, nil } }
identifier_body
function.go
// Use StaticReturnType if the function's return type does not vary // depending on its arguments. Type TypeFunc // Impl is the ImplFunc that implements the function's behavior. // // Functions are expected to behave as pure functions, and not create // any visible side-effects. // // If a TypeFunc is also pro...
(ty cty.Type) TypeFunc { return func([]cty.Value) (cty.Type, error) { return ty, nil } } // ReturnType returns the return type of a function given a set of candidate // argument types, or returns an error if the given types are unacceptable. // // If the caller already knows values for at least some of the argumen...
StaticReturnType
identifier_name
index.js
return currentState; }); } callback = (data) => { console.log('%ccallback', 'color: #47AAAC; font-weight: bold; font-size: 13px;'); // eslint-disable-line no-console console.log(data); // eslint-disable-line no-console this.setState({ selector: data.type === 'tooltip:before' ? data.st...
}; onOpenNotification = (id) => { this.onOpenChat(id); }; onRateUser =(obj) => { const { email } = this.getEmail(); this.props.rating({ ...obj, userId: email }); }; onRemove =() => { this.props.remove(); }; onSubmit = (evt) => { evt.preventDefault(); const { data } = this.pr...
{ this.props.addChat('abcd', this.props.users.allUsers[id], id); }
conditional_block
index.js
return currentState; }); } callback = (data) => { console.log('%ccallback', 'color: #47AAAC; font-weight: bold; font-size: 13px;'); // eslint-disable-line no-console console.log(data); // eslint-disable-line no-console this.setState({ selector: data.type === 'tooltip:before' ? data.st...
onDateValidation = (date) => date.match(/^\d{4}([./-])\d{2}\1\d{2}$/g); onPresentDateValidation = (dateString) => new Date(dateString) > new Date(); onPhoneNumberValidation = (number) => number.match(/[+](\d+)/g); onChangeOffence = (evt, id) => { let { value } = evt.target; if (value === '--clear--'...
random_line_split
index.js
extends Component { constructor(props) { super(props); this.state = { collapse: '', joyrideOverlay: true, joyrideType: 'continuous', isReady: false, isRunning: false, stepIndex: 0, steps: [], selector: '', open: '', }; } componentWillMount() { ...
Dashboard
identifier_name
index.js
}; onCloseNotification = () => { }; onFileChange = (evt) => { const { name, files } = evt.target; this.props.updateFields(name, files); }; onLogout = (e) => { e.preventDefault(); const logout = window.confirm('Are you sure you want to logout'); if (logout) { AuthService.logout(...
{ return { addChat: (id, value, userId) => dispatch(addChat(id, value, userId)), addUser: (user) => dispatch(addUser(user)), approveUsers: (id) => dispatch(approveUsers(id)), addChatMessage: (message) => dispatch(addChatMessage(message)), addErrorMessage: (msg) => dispatch(addErrorMessages(msg)), ...
identifier_body
more.rs
libc::c_char) -> libc::c_int; #[no_mangle] fn die_if_ferror_stdout(); #[no_mangle] fn fflush_all() -> libc::c_int; #[no_mangle] fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE; #[no_mangle] fn fopen_for_read(path: *const libc::c_char) -> *mut FILE; #[no_ma...
) -> libc::c_int; #[no_mangle] fn set_termios_to_raw(fd: libc::c_int, oldterm: *mut termios, flags: libc::c_int) -> libc::c_int; #[no_mangle] static mut bb_common_bufsiz1: [libc::c_char; 0]; } pub type C2RustUnnamed = libc::c_uint; pub const BB_FATAL_SIGS: C2RustUnnamed = 117503054; #[derive(Copy, Clone)] ...
fn get_terminal_width_height( fd: libc::c_int, width: *mut libc::c_uint, height: *mut libc::c_uint,
random_line_split
more.rs
libc::c_char) -> libc::c_int; #[no_mangle] fn die_if_ferror_stdout(); #[no_mangle] fn fflush_all() -> libc::c_int; #[no_mangle] fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE; #[no_mangle] fn fopen_for_read(path: *const libc::c_char) -> *mut FILE; #[no_ma...
unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' as i32 as libc::c_char); /* for compiler */ tcsetattr_tty_TCSANOW(&mut (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).initial_settings)...
{ tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); }
identifier_body
more.rs
libc::c_char) -> libc::c_int; #[no_mangle] fn die_if_ferror_stdout(); #[no_mangle] fn fflush_all() -> libc::c_int; #[no_mangle] fn fopen_or_warn(filename: *const libc::c_char, mode: *const libc::c_char) -> *mut FILE; #[no_mangle] fn fopen_for_read(path: *const libc::c_char) -> *mut FILE; #[no_ma...
(mut settings: *mut termios) { tcsetattr( (*(bb_common_bufsiz1.as_mut_ptr() as *mut globals)).tty_fileno, 0i32, settings, ); } unsafe extern "C" fn gotsig(mut _sig: libc::c_int) { /* bb_putchar_stderr doesn't use stdio buffering, * therefore it is safe in signal handler */ bb_putchar_stderr('\n' ...
tcsetattr_tty_TCSANOW
identifier_name
point_cloud.rs
&path.as_ref())); let mut config = String::new(); config_file .read_to_string(&mut config) .expect(&format!("Unable to read config file {:?}", &path.as_ref())); let params_files = YamlLoader::load_from_str(&config).unwrap(); PointCloud::<M>::from_yaml(&params_f...
{ if let Some(schema_map) = schema_yaml.as_hash() { for (k, v) in schema_map.iter() { let key = k.as_str().unwrap().to_string(); match v.as_str().unwrap() { "u32" => label_scheme.add_u32(key), "f32" => label_scheme.add_f32(key), "i32" =...
identifier_body
point_cloud.rs
::new(); let mut indexes_to_names: IndexMap<PointIndex, PointName> = IndexMap::new(); let mut current_count: u64 = 0; let mut data_sources = Vec::new(); let mut label_sources = Vec::new(); for (i,(dp,lp)) in data_path.iter().zip(labels_path).enumerate() { let new_data...
(&self) -> usize { self.data_sources.iter().fold(0, |acc, mm| acc + mm.len()) } /// Dimension of the data in the point cloud pub fn dim(&self) -> usize { self.data_dim } /// The names of the data are currently a shallow wrapper around a usize. pub fn reference_indexes(&self) ->...
len
identifier_name
point_cloud.rs
-> PointCloudResult<PointCloud<M>> { assert!(data.len() / data_dim == labels.len() / labels_dim); let list = MetadataList::simple_vec(labels, labels_dim); PointCloud::<M>::from_ram(data, data_dim, list) } /// Total number of points in the point cloud pub fn len(&self) -> usize { ...
random_line_split
machinedeployment_webhook.go
8s.io,resources=machinedeployments,versions=v1beta1,name=default.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 var _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} var _ webhook.Validator = &MachineDeployment{} // MachineDeploymentDefaulter creates a new CustomDefault...
() (admission.Warnings, error) { return nil, m.validate(nil) } // ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (m *MachineDeployment) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { oldMD, ok := old.(*MachineDeployment) if !ok { return nil, apierr...
ValidateCreate
identifier_name
machinedeployment_webhook.go
-k8s.io,resources=machinedeployments,versions=v1beta1,name=default.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 var _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} var _ webhook.Validator = &MachineDeployment{} // MachineDeploymentDefaulter creates a new CustomDefau...
), ) } // MachineSet preflight checks that should be skipped could also be set as annotation on the MachineDeployment // since MachineDeployment annotations are synced to the MachineSet. if feature.Gates.Enabled(feature.MachineSetPreflightChecks) { if err := validateSkippedMachineSetPreflightChecks(m); err ...
allErrs, field.Forbidden( specPath.Child("template", "metadata", "labels"), fmt.Sprintf("must match spec.selector %q", selector.String()),
random_line_split
machinedeployment_webhook.go
8s.io,resources=machinedeployments,versions=v1beta1,name=default.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 var _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} var _ webhook.Validator = &MachineDeployment{} // MachineDeploymentDefaulter creates a new CustomDefault...
} if m.Spec.Strategy.RollingUpdate.MaxUnavailable != nil { if _, err := intstr.GetScaledValueFromIntOrPercent(m.Spec.Strategy.RollingUpdate.MaxUnavailable, total, true); err != nil { allErrs = append( allErrs, field.Invalid(specPath.Child("strategy", "rollingUpdate", "maxUnavailable"), m.Sp...
{ allErrs = append( allErrs, field.Invalid(specPath.Child("strategy", "rollingUpdate", "maxSurge"), m.Spec.Strategy.RollingUpdate.MaxSurge, fmt.Sprintf("must be either an int or a percentage: %v", err.Error())), ) }
conditional_block
machinedeployment_webhook.go
8s.io,resources=machinedeployments,versions=v1beta1,name=default.machinedeployment.cluster.x-k8s.io,sideEffects=None,admissionReviewVersions=v1;v1beta1 var _ webhook.CustomDefaulter = &machineDeploymentDefaulter{} var _ webhook.Validator = &MachineDeployment{} // MachineDeploymentDefaulter creates a new CustomDefault...
// ValidateUpdate implements webhook.Validator so a webhook will be registered for the type. func (m *MachineDeployment) ValidateUpdate(old runtime.Object) (admission.Warnings, error) { oldMD, ok := old.(*MachineDeployment) if !ok { return nil, apierrors.NewBadRequest(fmt.Sprintf("expected a MachineDeployment but...
{ return nil, m.validate(nil) }
identifier_body
day_15.rs
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() } fn neighbor_dist() -> usize { 1 } fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) } } type CavernPathfinder = Pathfinder<CavernWorld>; #[derive(Copy, Clone, Eq, PartialEq)] enum Team { Elf, ...
let b_dest = *b.last().unwrap(); // sort first by shortest paths... match a.len().cmp(&b.len()) { // then by origin pos in reading order Ordering::Equal => Point::cmp_reading_order(a_dest, b_dest), dest_order => ...
{ let mut paths = Vec::new(); let origin_points = fighter.pos.neighbors_reading_order() .filter(|p| self.is_free_space(*p)); let mut path = Vec::new(); for origin in origin_points { for &dest in &dests { let free_tile_...
conditional_block
day_15.rs
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() } fn neighbor_dist() -> usize { 1 } fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) } } type CavernPathfinder = Pathfinder<CavernWorld>; #[derive(Copy, Clone, Eq, PartialEq)] enum Team { Elf, ...
match a.hp.cmp(&b.hp) { Ordering::Equal => Point::cmp_reading_order(a.pos, b.pos), hp_order => hp_order, } }); if let Some(j) = target_index { let attack_power = match self.fighters[i].team { Team::E...
{ let neighbors = self.fighters[i].pos.neighbors_reading_order(); let target_index = neighbors .filter_map(|neighbor| { self.fighters.iter().enumerate() .filter_map(|(j, f)| { if f.pos == neighbor && f.h...
identifier_body
day_15.rs
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() } fn neighbor_dist() -> usize { 1 } fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) } } type CavernPathfinder = Pathfinder<CavernWorld>; #[derive(Copy, Clone, Eq, PartialEq)] enum Team { Elf, ...
(&self, i: usize, targets: &mut Vec<usize>) { targets.clear(); let fighter = &self.fighters[i]; targets.extend(self.fighters.iter().enumerate() .filter(|(_, other)| other.hp > 0) .filter_map(|(j, other)| if other.team != fighter.team { Some(j) ...
find_targets
identifier_name
day_15.rs
fn neighbors(origin: &Point) -> Neighbors { origin.neighbors_reading_order() } fn neighbor_dist() -> usize { 1 } fn point_order(a: &Point, b: &Point) -> Ordering { Point::cmp_reading_order(*a, *b) } } type CavernPathfinder = Pathfinder<CavernWorld>; #[derive(Copy, Clone, Eq, PartialEq)] enum Team { El...
for (y, line) in s.lines().enumerate() { height += 1; width = line.len(); // assume all lines are the same length for (x, char) in line.chars().enumerate() { let point = Point::new(x as isize, y as isize); match char { '#' ...
let mut fighters = Vec::new(); let mut tiles = Vec::new();
random_line_split
main.go
for { if commandLine, err := line.Prompt("BaiduPCS-Go > "); err == nil { line.AppendHistory(commandLine) cmdArgs := args.GetArgs(commandLine) if len(cmdArgs) == 0 { continue } s := []string{os.Args[0]} s = append(s, cmdArgs...) closeLiner(line) c.App.Run(s) ...
Name: "chuser", Usage: "切换已登录的百度帐号", Description: fmt.Sprintf("%s\n 示例:\n\n %s\n %s\n", "如果运行该条命令没有提供参数, 程序将会列出所有的百度帐号, 供选择切换", app.Name+" chuser --uid=123456789", app.Name+" chuser", ), Category: "百度帐号操作", Before: reloadFn, After: reloadFn, Action: func(c *cli.Cont...
{
random_line_split
main.go
() { // change work directory folderPath, err := osext.ExecutableFolder() if err != nil { folderPath, err = filepath.Abs(filepath.Dir(os.Args[0])) if err != nil { folderPath = filepath.Dir(os.Args[0]) } } os.Chdir(folderPath) } func main() { app := cli.NewApp() app.Name = "baidupcs_go" app.Author = "i...
init
identifier_name
main.go
for { if commandLine, err := line.Prompt("BaiduPCS-Go > "); err == nil { line.AppendHistory(commandLine) cmdArgs := args.GetArgs(commandLine) if len(cmdArgs) == 0 { continue } s := []string{os.Args[0]} s = append(s, cmdArgs...) closeLiner(line) c.App.Run(s) ...
{ app := cli.NewApp() app.Name = "baidupcs_go" app.Author = "iikira/BaiduPCS-Go: https://github.com/iikira/BaiduPCS-Go" app.Usage = fmt.Sprintf("百度网盘工具箱 %s/%s GoVersion %s", runtime.GOOS, runtime.GOARCH, runtime.Version()) app.Description = `baidupcs_go 使用 Go语言编写, 为操作百度网盘, 提供实用功能. 具体功能, 参见 COMMANDS 列表 特色: 网盘内...
identifier_body
main.go
for { if commandLine, err := line.Prompt("BaiduPCS-Go > "); err == nil { line.AppendHistory(commandLine) cmdArgs := args.GetArgs(commandLine) if len(cmdArgs) == 0 { continue } s := []string{os.Args[0]} s = append(s, cmdArgs
命令 %s help 获取帮助\n", c.Args().Get(0), app.Name) } } app.Commands = []cli.Command{ { Name: "login", Usage: "使用百度BDUSS登录百度账号", Description: fmt.Sprintf("\n 示例: \n\n %s\n\n %s\n\n %s\n\n %s\n\n %s\n", app.Name+" login --bduss=123456789", app.Name+" login", "百度BDUSS获取方法: ...
...) closeLiner(line) c.App.Run(s) line = newLiner() } else if err == liner.ErrPromptAborted || err == io.EOF { break } else { log.Print("Error reading line: ", err) continue } } } else { fmt.Printf("未找到命令: %s\n运行
conditional_block
driver_suite_test.go
odes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" fakedyn "k8s.io/client-go/dynamic/fake" "k8s....
return origDriverHelper.GetClaimValue(claims, key) } func (dv *fakeDriverHelper) MarshaljSON(v interface{}) ([]byte, error) { if dv.errorOnAction == "marshaljson" { return nil, fmt.Errorf("fake error") } return origDriverHelper.MarshaljSON(v) } func (dv *fakeDriverHelper) UnMarshaljSON(data []byte, v interface{...
func (dv *fakeDriverHelper) GetClaimValue(claims jwt.MapClaims, key string) (string, error) {
random_line_split
driver_suite_test.go
" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" fakedyn "k8s.io/client-go/dynamic/fake" "k8s.io/c...
return origDriverHelper.MkdirAll(path, perm) } func (dv *fakeDriverHelper) WriteFile(name, content string, flag int, perm os.FileMode) error { if dv.errorOnAction == "Writefile" { return fmt.Errorf("fake error") } return origDriverHelper.WriteFile(name, content, flag, perm) } func (dv *fakeDriverHelper) FileSt...
{ return fmt.Errorf("fake error") }
conditional_block
driver_suite_test.go
odes" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" fakedyn "k8s.io/client-go/dynamic/fake" "k8s....
(targetPath string) []string { return origDriverHelper.GetDatasetDirectoryNames(targetPath) } func (dv *fakeDriverHelper) CleanMountPoint(targetPath string) error { if dv.errorOnAction == "cleanmountpoint" { return fmt.Errorf("fake error") } return os.Remove(targetPath) } func (dv *fakeDriverHelper) MkdirAll(pa...
GetDatasetDirectoryNames
identifier_name
driver_suite_test.go
" "google.golang.org/grpc/status" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/client-go/dynamic" fakedyn "k8s.io/client-go/dynamic/fake" "k8s.io/c...
func (dv *fakeDriverHelper) WriteFile(name, content string, flag int, perm os.FileMode) error { if dv.errorOnAction == "Writefile" { return fmt.Errorf("fake error") } return origDriverHelper.WriteFile(name, content, flag, perm) } func (dv *fakeDriverHelper) FileStat(path string) (os.FileInfo, error) { if dv.er...
{ if dv.errorOnAction == "mkdirall" { return fmt.Errorf("fake error") } return origDriverHelper.MkdirAll(path, perm) }
identifier_body
libvirt.go
DomainCreateFlagStartValidate ) // RebootFlags specifies domain reboot methods type RebootFlags uint32 const ( // RebootAcpiPowerBtn - send ACPI event RebootAcpiPowerBtn RebootFlags = 1 << iota // RebootGuestAgent - use guest agent RebootGuestAgent // RebootInitctl - use initctl RebootInitctl // RebootSign...
}
random_line_split
libvirt.go
KB). DomainMemoryStatTagActualBalloon // DomainMemoryStatTagRss - Resident Set Size of the process running the domain (in KB). DomainMemoryStatTagRss // DomainMemoryStatTagUsable - How much the balloon can be inflated without pushing the guest system // to swap, corresponds to 'Available' in /proc/meminfo Doma...
XML
identifier_name
libvirt.go
NoAutostart // pools by type StoragePoolsFlagDir StoragePoolsFlagFS StoragePoolsFlagNETFS StoragePoolsFlagLogical StoragePoolsFlagDisk StoragePoolsFlagISCSI StoragePoolsFlagSCSI StoragePoolsFlagMPATH StoragePoolsFlagRBD StoragePoolsFlagSheepdog StoragePoolsFlagGluster StoragePoolsFlagZFS ) // DomainCreat...
{ d, err := l.lookup(dom) if err != nil { return nil, err } payload := struct { Domain Domain Command []byte Flags uint32 }{ Domain: d, Command: cmd, Flags: 0, } buf, err := encode(&payload) if err != nil { return nil, err }
identifier_body
libvirt.go
PoolsFlagMPATH StoragePoolsFlagRBD StoragePoolsFlagSheepdog StoragePoolsFlagGluster StoragePoolsFlagZFS ) // DomainCreateFlags specify options for starting domains type DomainCreateFlags uint32 const ( // DomainCreateFlagPaused creates paused domain. DomainCreateFlagPaused = 1 << iota // DomainCreateFlagAutoD...
{ return nil, decodeError(res.Payload) }
conditional_block
global-network.js
.preventDefault(); $('.network-filter').hide(); //Hide all dropdowns }); //Live Search Global Network $("input#network-search").keyup(function(){ // Retrieve the input field text and reset the count to zero var filter = $(this).val(); // Loop through grid items $(".network-grid .network-grid-it...
//========= PLUGIN ADD ON FOR MIXITUP ===================== // To keep our code clean and modular, all custom functionality will be contained inside a single object literal called "checkboxFilter". var checkboxFilter = { // Declare any variables we will need as properties of the object $filters: null, $reset...
{ var active = []; $('.checkbox input:checked').each(function() { active.push($(this).attr('data-filter')); }); var filtered = active.join(", "); if(filtered !== '') $('.filtered-list').html(filtered); else{ $('.filtered-list').html('All'); } }
identifier_body
global-network.js
(); $('.network-filter').hide(); //Hide all dropdowns }); //Live Search Global Network $("input#network-search").keyup(function(){ // Retrieve the input field text and reset the count to zero var filter = $(this).val(); // Loop through grid items $(".network-grid .network-grid-item").each(funct...
//URL FILTERS var filter = getParameterByName('filter'); //check if url filter is present - initialize mixitup and prefilter if(filter !==''){ $("input[value='" + filter + "']").prop('checked', true); $('#network-grid').mixItUp('filter', filter, GetActiveString); $(".network-filter-status").slid...
random_line_split
global-network.js
e.preventDefault(); $('.network-filter').hide(); //Hide all dropdowns }); //Live Search Global Network $("input#network-search").keyup(function(){ // Retrieve the input field text and reset the count to zero var filter = $(this).val(); // Loop through grid items $(".network-grid .network-grid-...
(profile_id) { var is_loading = false; if (is_loading == false) { is_loading = true; $('#loader').show(); var data = { action: 'getSingleProfile', profile_id: profile_id }; jQuery.post(ajaxurl, data, function(response) { // appen...
loadProfile
identifier_name
global-network.js
}); //Clost all filter sections $('.close-filter').click(function(e) { e.preventDefault(); $('.network-filter').hide(); //Hide all dropdowns }); //Live Search Global Network $("input#network-search").keyup(function(){ // Retrieve the input field text and reset the count to zero var filter = $(thi...
{ initialize(); }
conditional_block
handler.go
[string]interface{} json.Unmarshal(bodyBytes, &response) dict, _ := json.Marshal(response["response"]) var bots []Bot json.Unmarshal(dict, &bots) log.Println(bots) return bots } func msgHandler() gin.HandlerFunc { return func(c *gin.Context) { var botResponse msg if c.BindJSON(&botResponse) == nil { bots...
func getStats(season string, week string) map[int]map[string]float32 { url := "https://api.sleeper.app/v1/stats/nfl/regular/" + season + "/" + week resp, _ := http.Get(url) defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) var stats map[int]map[string]float32 json.Unmarshal(bodyBytes, &stats) ...
{ url := "https://api.sleeper.app/v1/league/" + league + "/users" resp, _ := http.Get(url) defer resp.Body.Close() bodyBytes, _ := ioutil.ReadAll(resp.Body) var users []map[string]interface{} json.Unmarshal(bodyBytes, &users) return users }
identifier_body
handler.go
") { sendPost("I am your chat bot.\nType `!coin` to flip a coin.\nType `!smack @someone` to talk trash.\nType `!suckup @someone` to show admiration.\nType `!stats player season week` for stats.\nType `!draft` for draft info.\nType `!standings` for league standings.", botId) } else { sendPost("I am your ch...
sendStandings
identifier_name
handler.go
[string]interface{} json.Unmarshal(bodyBytes, &response) dict, _ := json.Marshal(response["response"]) var bots []Bot json.Unmarshal(dict, &bots) log.Println(bots) return bots } func msgHandler() gin.HandlerFunc { return func(c *gin.Context) { var botResponse msg if c.BindJSON(&botResponse) == nil { bots...
else if fields[0] == "!stats" { if len(fields) <= 3 || len(fields) >= 6 { c.JSON(http.StatusOK, nil) return } name := fields[1] + " " + fields[2] season := fields[3] week := "" if len(fields) == 5 { week = fields[4] } player, err := queryPlayer(name) if err != nil { ...
{ sendStandings(botId) }
conditional_block
handler.go
map[string]interface{} json.Unmarshal(bodyBytes, &response) dict, _ := json.Marshal(response["response"]) var bots []Bot json.Unmarshal(dict, &bots) log.Println(bots) return bots } func msgHandler() gin.HandlerFunc { return func(c *gin.Context) { var botResponse msg if c.BindJSON(&botResponse) == nil { ...
} log.Println(botId) log.Println(fields) if len(fields) == 0 { c.JSON(http.StatusOK, nil) return } if fields[0] == "!help" { if botResponse.GroupId == os.Getenv("htown") { sendPost("I am your chat bot.\nType `!coin` to flip a coin.\nType `!smack @someone` to talk trash.\nType `!suc...
}
random_line_split
install.rs
("S") .long(OPT_SUFFIX) .help("(unimplemented) override the usual backup suffix") .value_name("SUFFIX") ) .arg( // TODO implement flag Arg::with_name(OPT_TARGET_DIRECTORY) .short("t") .long(OPT_TARGET...
0 } } ///
conditional_block
install.rs
short("S") .long(OPT_SUFFIX) .help("(unimplemented) override the usual backup suffix") .value_name("SUFFIX") ) .arg( // TODO implement flag Arg::with_name(OPT_TARGET_DIRECTORY) .short("t") .long(OPT_T...
copy(file, &target, b).is_err() { 1 } else { 0 } } /// Co
identifier_body
install.rs
static OPT_STRIP_PROGRAM: &str = "strip-program"; static OPT_SUFFIX: &str = "suffix"; static OPT_TARGET_DIRECTORY: &str = "target-directory"; static OPT_NO_TARGET_DIRECTORY: &str = "no-target-directory"; static OPT_VERBOSE: &str = "verbose"; static OPT_PRESERVE_CONTEXT: &str = "preserve-context"; static OPT_CONTEXT: &s...
(matches: &ArgMatches) -> Result<Behavior, i32> { let main_function = if matches.is_present("directory") { MainFunction::Directory } else { MainFunction::Standard }; let considering_dir: bool = MainFunction::Directory == main_function; let specified_mode: Option<u32> = if matches.i...
behavior
identifier_name
install.rs
/// Create directories Directory, /// Install files to locations (primary functionality) Standard, } impl Behavior { /// Determine the mode for chmod after copy. pub fn mode(&self) -> u32 { match self.specified_mode { Some(x) => x, None => DEFAULT_MODE, }...
random_line_split
modules.go
.AllPermissions, } cliToken, err := jwt.Sign(&p, jwt.NewHS256(sk)) if err != nil { return nil, err } if err := cfg.LocalStorage().SetAPIToken(cliToken); err != nil { return nil, err } return (*types2.APIAlg)(jwt.NewHS256(sk)), nil } //storage func StorageAuth(ctx MetricsCtx, ca api.Common) (sectorstorage...
(ma types2.MinerAddress) (types2.MinerID, error) { id, err := address.IDFromAddress(address.Address(ma)) return types2.MinerID(id), err } func MinerAddress(metaDataService *service.MetadataService) (types2.MinerAddress, error) { ma, err := metaDataService.GetMinerAddress() return types2.MinerAddress(ma), err } fu...
MinerID
identifier_name
modules.go
.AuthNew(ctx, []auth.Permission{"admin"}) if err != nil { return nil, xerrors.Errorf("creating storage auth header: %w", err) } headers := http.Header{} headers.Add("Authorization", "Bearer "+string(token)) return sectorstorage.StorageAuth(headers), nil } func MinerID(ma types2.MinerAddress) (types2.MinerID, e...
{ return xerrors.Errorf("getting sector info: %w", err) }
conditional_block