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
image_processor_2.0.py
_color = (255,0,0) possible_target_color = (0,255,0) #used to judge whether a polygon side is near vertical or near horizontal, for filtering out shapes that don't match expected target characteristics vert_threshold = math.tan(math.radians(90-20)) horiz_threshold = math.tan(math.radia...
if self.img_path is None: rval, self.img = self.vc.read() #might set to None else: self.img = imread(self.img_path) def process(self): if enable_dashboard: self.camera_saturation = int(SmartDashboard.GetNumber(camera_saturation_title) self.angle_to_ro...
self.process()
conditional_block
image_processor_2.0.py
# degrees_camera_pitch = 21.0 # degrees_sighting_offset = -1.55 def __init__(self, img_path): self.img_path = img_path self.layout_result_windows(self.h,self.s,self.v) self.vc = VideoCapture(0)...
random_line_split
App.js
are good with the object this.props.dispatch(markerSelect(filterKeplerObject)); this.setState({filterKeplerObject}, () => this.addEventListeners()); }); } }; getConfigSheetSummaryData = selectedSheet => { // get sheet information this.state.selectedSheet should be syncronized with se...
{ log(`%c this.state.isSplash=true}`, 'color: purple'); return ( <div className="splashScreen" style={{padding: 5}}> <SplashScreen configure={this.configure} title="Kepler.gl within Tableau" desc="Leverage the brilliance of Kepler.gl functionality, dire...
conditional_block
App.js
.updateAndSave', 'background: red; color: white' ); TableauSettings.updateAndSave(kv, settings => { this.setState({ tableauSettings: settings }); }); } else { tableauExt.settings.set(event.target.name, event.target.value); tableauExt.settings.saveAsync...
{ window.addEventListener('resize', this.resize, true); this.resize(); tableauExt.initializeAsync({configure: this.configure}).then(() => { // console.log('tableau config', configJson); // default tableau settings on initial entry into the extension // we know if we haven't done anything ...
identifier_body
App.js
.state.stepIndex === 2) { this.customCallBack('configuration'); } else { this.setState((previousState, currentProps) => { return {stepIndex: previousState.stepIndex + 1}; }); } }; onPrevStep = () => { this.setState((previousState, currentProps) => { return {stepIndex: pr...
} else { log( '%c getConfigSheetSummaryData TableauSettings.ShouldUse false',
random_line_split
App.js
) tableauExt.settings.saveAsync().then(() => { this.setState({ tableauSettings: tableauExt.settings.getAll() }); }); } }; customCallBack = confSetting => { log('in custom call back', confSetting); if (TableauSettings.ShouldUse) { log( '%c customCallBa...
render
identifier_name
hubtype-service.js
(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clam...
return target; } var _WEBCHAT_PUSHER_KEY_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef typeof WEBCHAT_PUSHER_KEY !== 'undefined' && WEBCHAT_PUSHER_KEY, 'WEBCHAT_PUSHER_KEY', '434ca667c8e6cb3f641c'); var _HUBTYPE_API_URL_ = (0, _utils.getWebpackEnvVar)( // eslint-disable-next-line no-undef typ...
{ var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { (0, _defineProperty2["default"])(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ...
conditional_block
hubtype-service.js
onEvent = _ref.onEvent, unsentInputs = _ref.unsentInputs, server = _ref.server; (0, _classCallCheck2["default"])(this, HubtypeService); this.appId = appId; this.user = user || {}; this.lastMessageId = lastMessageId; this.lastMessageUpdateDate = lastMessageUpdateDate; this.onEven...
case 13:
random_line_split
hubtype-service.js
"])(HubtypeService, [{ key: "resolveServerConfig", value: function resolveServerConfig() { if (!this.server) { return { activityTimeout: ACTIVITY_TIMEOUT, pongTimeout: PONG_TIMEOUT }; } return { activityTimeout: this.server.activityTimeout || ACTIVI...
{ return _resendUnsentInputs.apply(this, arguments); }
identifier_body
hubtype-service.js
this.init(); } } (0, _createClass2["default"])(HubtypeService, [{ key: "resolveServerConfig", value: function resolveServerConfig() { if (!this.server) { return { activityTimeout: ACTIVITY_TIMEOUT, pongTimeout: PONG_TIMEOUT }; } return { a...
resendUnsentInputs
identifier_name
main_test_xgb.py
= np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction # Firing data for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float') for i in xrange(adrien_data['ADn'].shape...
# TUNING CURVE ##################################################################### X = data['ang'].values Yall = data[[i for i in list(data) if i.split(".")[0] in ['Pos', 'ADn']]].values tuningc = {targets[i]:tuning_curve(X, Yall[:,i], nb_bins = 100) for i in xrange(Yall.shape[1])} sys.exit() ######################...
random_line_split
main_test_xgb.py
= np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction # Firing data for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float') for i in xrange(adrien_data['ADn'].shape...
(features, targets, learners = ['glm_pyglmnet', 'nn', 'xgb_run', 'ens']): X = data[features].values Y = np.vstack(data[targets].values) Models = {method:{'PR2':[],'Yt_hat':[]} for method in learners} learners_ = list(learners) # print learners_ for i in xrange(Y.shape[1]): y = Y[:,i] # TODO : make sure that...
test_features
identifier_name
main_test_xgb.py
= np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction # Firing data for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float') for i in xrange(adrien_data['ADn'].shape...
def tuning_curve(x, f, nb_bins): bins = np.linspace(x.min(), x.max()+1e-8, nb_bins+1) index = np.digitize(x, bins).flatten() tcurve = np.array([np.mean(f[index == i]) for i in xrange(1, nb_bins+1)]) x = bins[0:-1] + (bins[1]-bins[0])/2. return (x, tcurve) def test_features(features, targets, learners = ...
n = len(trees.get_dump()) thr = {} for t in xrange(n): gv = xgb.to_graphviz(trees, num_trees=t) body = gv.body for i in xrange(len(body)): for l in body[i].split('"'): if 'f' in l and '<' in l: tmp = l.split("<") if thr.has_key(tmp[0]): thr[tmp[0]].append(float(tmp[1])) else: ...
identifier_body
main_test_xgb.py
'] = np.cos(adrien_data['Ang'].flatten()) # cosinus of angular direction data['sin'] = np.sin(adrien_data['Ang'].flatten()) # sinus of angular direction # Firing data for i in xrange(adrien_data['Pos'].shape[1]): data['Pos'+'.'+str(i)] = adrien_data['Pos'][:,i].astype('float') for i in xrange(adrien_data['ADn'].sha...
##################################################################### # plot 11 (2.1) ##################################################################### order = ['Pos.8', 'Pos.9', 'Pos.10', 'ADn.9', 'ADn.10', 'ADn.11'] rcParams.update({ 'backend':'pdf', 'savefig.pad_inches':0.1, ...
thresholds[i][j] = extract_tree_threshold(bsts[i][j])
conditional_block
tls.go
"cr", the Kubernetes Service "Service", and the CertConfig "config". // // GenerateCert creates and manages TLS key and cert and CA with the following: // CA creation and management: // - If CA is not given: // - A unique CA is generated for the CR. // - CA's key is packaged into a Secret as shown below. // ...
{ return nil, nil, nil, err }
conditional_block
tls.go
CA's cert is packaged in a ConfigMap as shown below. // - The CA Secret and ConfigMap are created on the k8s cluster in the CR's namespace before // returned to the user. The CertGenerator manages the CA Secret and ConfigMap to ensure it's // unqiue per CR. // - If CA is given: // - CA's key is packaged i...
verifyConfig
identifier_name
tls.go
import ( "crypto/rsa" "crypto/x509" "errors" "fmt" "io/ioutil" "strings" "k8s.io/api/core/v1" apiErrors "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes" ) // CertType defin...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tlsutil
random_line_split
tls.go
used to generate and sign the TLS cert. // - The signing process uses the passed in "service" to set the Subject Alternative Names(SAN) // for the certificate. We assume that the deployed applications are typically communicated // with via a Kubernetes Service. The SAN is set to the FQDN of the service // `<...
{ se, err := kubeClient.CoreV1().Secrets(namespace).Get(name, metav1.GetOptions{}) if err != nil && !apiErrors.IsNotFound(err) { return nil, err } if apiErrors.IsNotFound(err) { return nil, nil } return se, nil }
identifier_body
universal.rs
Right pub const VPRE: u8 = 22; // VOWEL_PRE / VOWEL_PRE_ABOVE / VOWEL_PRE_ABOVE_POST / VOWEL_PRE_POST pub const VMABV: u8 = 37; // VOWEL_MOD_ABOVE pub const VMBLW: u8 = 38; // VOWEL_MOD_BELOW pub const VMPST: u8 = 39; // VOWEL_MOD_POST pub const VMPRE: u8 = 23; // VOWEL_MOD_PRE...
{ let universal_plan = plan.data::<UniversalShapePlan>(); let mask = universal_plan.rphf_mask; if mask == 0 { return; } let mut start = 0; let mut end = buffer.next_syllable(0); while start < buffer.len { // Mark a substituted repha as USE_R. for i in start..end { ...
identifier_body
universal.rs
&[u8; 4] = bytemuck::cast_ref(&self.var2); v[2] } fn set_use_category(&mut self, c: Category) { let v: &mut [u8; 4] = bytemuck::cast_mut(&mut self.var2); v[2] = c; } fn is_halant_use(&self) -> bool { matches!(self.use_category(), category::H | category::HVM) && !self.i...
} else {
random_line_split
universal.rs
_POST pub const VMPRE: u8 = 23; // VOWEL_MOD_PRE pub const SMABV: u8 = 41; // SYM_MOD_ABOVE pub const SMBLW: u8 = 42; // SYM_MOD_BELOW pub const FMABV: u8 = 45; // CONS_FINAL_MOD UIPC = Top pub const FMBLW: u8 = 46; // CONS_FINAL_MOD UIPC = Bottom pub const FMPST: u8 = 47; ...
insert_dotted_circles
identifier_name
api_op_CreateScan.go
ns, c.addOperationCreateScanMiddlewares) if err != nil { return nil, err } out := result.(*CreateScanOutput) out.ResultMetadata = metadata return out, nil } type CreateScanInput struct { // The identifier for an input resource used to create a scan. // // This member is required. ResourceId types.Resource...
if err = addIdempotencyToken_opCreateScanMiddleware(stack, options); err != nil { return err } if err = addOpCreateScanValidationMiddleware(stack); err != nil { return err } if err = stack.Initialize.Add(newServiceMetadataMiddleware_opCreateScan(options.Region), middleware.Before); err != nil { return err ...
{ return err }
conditional_block
api_op_CreateScan.go
ns, c.addOperationCreateScanMiddlewares) if err != nil { return nil, err } out := result.(*CreateScanOutput) out.ResultMetadata = metadata return out, nil } type CreateScanInput struct { // The identifier for an input resource used to create a scan. // // This member is required. ResourceId types.Resource...
(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsRestjson1_serializeOpCreateScan{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsRestjson1_deserializeOpCreateScan{}, middleware.After) if err != nil { return err } if err = addlegacyEndpoi...
addOperationCreateScanMiddlewares
identifier_name
api_op_CreateScan.go
Fns, c.addOperationCreateScanMiddlewares) if err != nil { return nil, err } out := result.(*CreateScanOutput) out.ResultMetadata = metadata return out, nil } type CreateScanInput struct { // The identifier for an input resource used to create a scan. // // This member is required. ResourceId types.Resourc...
// The type of analysis you want CodeGuru Security to perform in the scan, either // Security or All . The Security type only generates findings related to // security. The All type generates both security findings and quality findings. // Defaults to Security type if missing. AnalysisType types.AnalysisType //...
random_line_split
api_op_CreateScan.go
ScanName *string // The current state of the scan. Returns either InProgress , Successful , or // Failed . // // This member is required. ScanState types.ScanState // The ARN for the scan name. ScanNameArn *string // Metadata pertaining to the operation's result. ResultMetadata middleware.Metadata noSmith...
{ return stack.Serialize.Insert(&opCreateScanResolveEndpointMiddleware{ EndpointResolver: options.EndpointResolverV2, BuiltInResolver: &builtInResolver{ Region: options.Region, UseDualStack: options.EndpointOptions.UseDualStackEndpoint, UseFIPS: options.EndpointOptions.UseFIPSEndpoint, Endpo...
identifier_body
stocker.py
l.get('%s/%s' % (exchange, ticker)) except Exception as e: print('Error Retrieving Data.') print(e) return # Set the index to a column called Date stock = stock.reset_index(level=0) # Columns required for prophet stock['ds'] = stock['Date'] ...
# Find max and min prices and dates on which they occurred self.max_price = np.max(self.stock['y']) self.min_price = np.min(self.stock['y']) self.min_price_date = self.stock[self.stock['y'] == self.min_price]['Date'] self.min_price_date = self.min_price_date[self.min_price_date....
random_line_split
stocker.py
l.get('%s/%s' % (exchange, ticker)) except Exception as e: print('Error Retrieving Data.') print(e) return # Set the index to a column called Date stock = stock.reset_index(level=0) # Columns required for prophet stock['ds'] = stock['Date'] ...
else: valid_start = False valid_end = False while (not valid_start) & (not valid_end): start_date, end_date = self.handle_dates(start_date, end_date) # No round dates, if either data not in, print message and return if (star...
if (end_in) & (start_in): trim_df = df[(df['Date'] >= start_date) & (df['Date'] <= end_date)] else: # If only start is missing, round start if (not start_in): trim_df = df[(df['Date'] > s...
conditional_block
stocker.py
(self, ticker, exchange='WIKI'): # Enforce capitalization ticker = ticker.upper() # Symbol is used for labeling plots self.symbol = ticker # Use Personal Api Key quandl.ApiConfig.api_key = 'U-m-xTvejNiPHWNa8SzH' # Retrieval the financial data try: ...
__init__
identifier_name
stocker.py
.get('%s/%s' % (exchange, ticker)) except Exception as e: print('Error Retrieving Data.') print(e) return # Set the index to a column called Date stock = stock.reset_index(level=0) # Columns required for prophet stock['ds'] = stock['Date'] ...
# Calculate and plot profit from buying and holding shares for specified date range def buy_and_hold(self, start_date=None, end_date=None, nshares=1): start_date, end_date = self.handle_dates(start_date, end_date) # Find starting and ending price of stock start_price = float(self.sto...
dataframe = dataframe.reset_index(drop=True) weekends = [] # Find all of the weekends for i, date in enumerate(dataframe['ds']): if (date.weekday()) == 5 | (date.weekday() == 6): weekends.append(i) # Drop the weekends dataframe = dataframe.drop(week...
identifier_body
main.go
.Flags() | log.Lshortfile) flag.Parse() var r RiceLa if err := r.run(); err != nil { log.Fatalf("%+v", err) } } type ClimateState struct { InsideTemp float64 `json:"inside_temp"` OutsideTemp float64 `json:"outside_temp"` DriverTempSetting float64 `json:"driver_temp_s...
SeatHeaterRearLeftBack int `json:"seat_heater_rear_left_back"` SmartPreconditioning bool `json:"smart_preconditioning"` } type VehicleData struct { UserID int64 `json:"user_id"` VehicleID int64 `json:"vehicle_id"` VIN string `json:"vin"` State string `json:"online"` ChargeStat...
SeatHeaterRearRightBack int `json:"seat_heater_rear_right_back"`
random_line_split
main.go
.Flags() | log.Lshortfile) flag.Parse() var r RiceLa if err := r.run(); err != nil { log.Fatalf("%+v", err) } } type ClimateState struct { InsideTemp float64 `json:"inside_temp"` OutsideTemp float64 `json:"outside_temp"` DriverTempSetting float64 `json:"driver_temp_s...
func (r *RiceLa) charging() bool { r.mu.Lock() defer r.mu.Unlock() return r.mu.charging } func (r *RiceLa) monitorVehicle(ctx context.Context, v *tesla.Vehicle) error { var data, prevData *VehicleData for { b := backoff.NewExponentialBackOff() b.MaxElapsedTime = 1 * time.Minute if err := backoff.Retry(fu...
{ r.mu.Lock() defer r.mu.Unlock() r.mu.charging = charging }
identifier_body
main.go
.Flags() | log.Lshortfile) flag.Parse() var r RiceLa if err := r.run(); err != nil { log.Fatalf("%+v", err) } } type ClimateState struct { InsideTemp float64 `json:"inside_temp"` OutsideTemp float64 `json:"outside_temp"` DriverTempSetting float64 `json:"driver_temp_s...
return count case float64: r.setCounter(key, v) return 1 case int: r.setCounter(key, float64(v)) return 1 case int64: r.setCounter(key, float64(v)) return 1 case int32: r.setCounter(key, float64(v)) return 1 case float32: r.setCounter(key, float64(v)) return 1 case bool: if v { r.setCo...
{ key := key + ":" + k count += r.processCounter(key, v) }
conditional_block
main.go
.Flags() | log.Lshortfile) flag.Parse() var r RiceLa if err := r.run(); err != nil { log.Fatalf("%+v", err) } } type ClimateState struct { InsideTemp float64 `json:"inside_temp"` OutsideTemp float64 `json:"outside_temp"` DriverTempSetting float64 `json:"driver_temp_s...
(key string, v interface{}) int { switch v := v.(type) { case map[string]interface{}: count := 0 for k, v := range v { key := key + ":" + k count += r.processCounter(key, v) } return count case float64: r.setCounter(key, v) return 1 case int: r.setCounter(key, float64(v)) return 1 case int64:...
processCounter
identifier_name
norace_test.go
nil { t.Fatalf("Error on connect: %v", err) } defer nc1.Close() nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) if err != nil { t.Fatalf("Error on connect: %v", err) } defer nc2.Close() data := make([]byte, 1024*1024) // 1MB payload rand.Read(data) expected := int32(500) re...
// Reduce socket buffer to increase reliability of data backing up in the server destined // for our subscribed client. c.(*net.TCPConn).SetReadBuffer(128) url := fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port) sender, err := nats.Connect(url) if err != nil { t.Fatalf("Error
{ t.Fatalf("Error sending protocols to server: %v", err) }
conditional_block
norace_test.go
!= nil { t.Fatalf("Error on connect: %v", err) } defer nc1.Close() nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) if err != nil { t.Fatalf("Error on connect: %v", err) } defer nc2.Close() data := make([]byte, 1024*1024) // 1MB payload rand.Read(data) expected := int32(500) ...
(t *testing.T) { opts := DefaultOptions() opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip. opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here. s := RunServer(opts) defer s.Shutdown() c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*...
TestNoRaceClosedSlowConsumerWriteDeadline
identifier_name
norace_test.go
!= nil { t.Fatalf("Error on connect: %v", err) } defer nc1.Close() nc2, err := nats.Connect(fmt.Sprintf("nats://%s:%d", opts.Host, opts.Port)) if err != nil { t.Fatalf("Error on connect: %v", err) } defer nc2.Close() data := make([]byte, 1024*1024) // 1MB payload rand.Read(data) expected := int32(500) ...
sender, err := nats.Connect(url) if err != nil { t.Fatalf("Error on connect: %v", err) } defer sender.Close() payload := make([]byte, 1024*1024) for i := 0; i < 100; i++ { if err := sender.Publish("foo", payload); err != nil { t.Fatalf("Error on publish: %v", err) } } // Flush sender connection to en...
{ opts := DefaultOptions() opts.WriteDeadline = 10 * time.Millisecond // Make very small to trip. opts.MaxPending = 500 * 1024 * 1024 // Set high so it will not trip here. s := RunServer(opts) defer s.Shutdown() c, err := net.DialTimeout("tcp", fmt.Sprintf("%s:%d", opts.Host, opts.Port), 3*time.Second) i...
identifier_body
norace_test.go
// http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing ...
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at //
random_line_split
bootstrap.go
.TrustedProxy { if ip := net.ParseIP(trustedProxy); ip != nil { bs.config.Config.TrustedProxyIPs = append(bs.config.Config.TrustedProxyIPs, &ip) continue } if _, ipNet, errParseCIDR := net.ParseCIDR(trustedProxy); errParseCIDR == nil { bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedPr...
{ return nil, err }
conditional_block
bootstrap.go
func (bs *bootstrap) Config() *Config { return bs.config } // Managers returns bootstrapped identity-managers. func (bs *bootstrap) Managers() *managers.Managers { return bs.managers } // Boot is the main entry point to bootstrap the service after validating the // given configuration. The resulting Bootstrap struc...
// Config returns the bootstap configuration.
random_line_split
bootstrap.go
if err != nil { return nil, err } err = bs.setup(ctx, settings) if err != nil { return nil, err } return bs, nil } // initialize, parsed parameters from commandline with validation and adds them // to the associated Bootstrap data. func (bs *bootstrap) initialize(settings *Settings) error { logger := bs....
{ // NOTE(longsleep): Ensure to use same salt length as the hash size. // See https://www.ietf.org/mail-archive/web/jose/current/msg02901.html for // reference and https://github.com/golang-jwt/jwt/v4/issues/285 for // the issue in upstream jwt-go. for _, alg := range []string{jwt.SigningMethodPS256.Name, jwt.Sign...
identifier_body
bootstrap.go
Proxy); errParseCIDR == nil { bs.config.Config.TrustedProxyNets = append(bs.config.Config.TrustedProxyNets, ipNet) continue } } if len(bs.config.Config.TrustedProxyIPs) > 0 { logger.Infoln("trusted proxy IPs", bs.config.Config.TrustedProxyIPs) } if len(bs.config.Config.TrustedProxyNets) > 0 { logger.Inf...
setupGuest
identifier_name
source.rs
/// ``` pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> { snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace())) } /// Gets a snippet of the indentation of the line of a span pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> { ...
else { " ".repeat(indent - x) + l } }) .collect::<Vec<String>>() .join("\n") } /// Converts a span to a code snippet if available, otherwise returns the default. /// /// This is useful if you want to provide suggestions for your lint or more generally, if you want /...
{ l.split_at(x - indent).1.to_owned() }
conditional_block
source.rs
/// ``` pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> { snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace())) } /// Gets a snippet of the indentation of the line of a span pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> { ...
/// Converts a span to a code snippet if available, otherwise returns the default. /// /// This is useful if you want to provide suggestions for your lint or more generally, if you want /// to convert a given `Span` to a `str`. To create suggestions consider using /// [`snippet_with_applicability`] to ensure that the a...
}
random_line_split
source.rs
<'a, T: LintContext>( cx: &T, expr: &Expr<'_>, option: Option<String>, default: &'a str, indent_relative_to: Option<Span>, ) -> Cow<'a, str> { let code = snippet_block(cx, expr.span, default, indent_relative_to); let string = option.unwrap_or_default(); if expr.span.from_expansion() { ...
expr_block
identifier_name
source.rs
/// ``` pub fn indent_of<T: LintContext>(cx: &T, span: Span) -> Option<usize> { snippet_opt(cx, line_span(cx, span)).and_then(|snip| snip.find(|c: char| !c.is_whitespace())) } /// Gets a snippet of the indentation of the line of a span pub fn snippet_indent<T: LintContext>(cx: &T, span: Span) -> Option<String> { ...
/// Same as `snippet`, but should only be used when it's clear that the input span is /// not a macro argument. pub fn snippet_with_macro_callsite<'a, T: LintContext>(cx: &T, span: Span, default: &'a str) -> Cow<'a, str> { snippet(cx, span.source_callsite(), default) } /// Converts a span to a code snippet. Retu...
{ if *applicability != Applicability::Unspecified && span.from_expansion() { *applicability = Applicability::MaybeIncorrect; } snippet_opt(cx, span).map_or_else( || { if *applicability == Applicability::MachineApplicable { *applicability = Applicability::HasPlaceh...
identifier_body
ogre_unit.py
IS.py""" import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugins.cfg')] for path in paths: if os.p...
class quiet_logListener_class(ogre.LogListener): def messageLogged(self, message, level, debug, logName): '''Called by Ogre instead of logging.''' pass #print message def quiet_log(): '''Replace log with quiet version. Useful for unit test. Return logManager and logList...
random_line_split
ogre_unit.py
(): """Return the absolute path to a valid plugins.cfg file. Copied from sf_OIS.py""" import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), ...
getPluginPath
identifier_name
ogre_unit.py
IS.py""" import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugins.cfg')] for path in paths: if os.p...
def setup_root(plugins_path = getPluginPath(), resources_path = 'resources.cfg'): '''Return new root, sceneManager.''' root = ogre.Root(plugins_path) root.setFrameSmoothingPeriod(5.0) setup_resources(resources_path) sceneManager = root.createSceneManager(ogre.ST_GENERIC,"Example...
'''Load resources, such as from 'resources.cfg'.''' config = ogre.ConfigFile() config.load(resources_path) section_iter = config.getSectionIterator() while section_iter.hasMoreElements(): section_name = section_iter.peekNextKey() settings = section_iter.getNext() for item ...
identifier_body
ogre_unit.py
IS.py""" import sys import os import os.path paths = [os.path.join(os.getcwd(), 'plugins.cfg'), '/etc/OGRE/plugins.cfg', os.path.join(os.path.dirname(os.path.abspath(__file__)), 'plugins.cfg')] for path in paths:
sys.stderr.write("\n" "** Warning: Unable to locate a suitable plugins.cfg file.\n" "** Warning: Please check your ogre installation and copy a\n" "** Warning: working plugins.cfg file to the current directory.\n\n") raise ogre.Exception(0, "can't locate the 'plugins.cfg' file", ...
if os.path.exists(path): return path
conditional_block
data_loader.py
# self.paths = path is not None and librosa.util.find_files(path) with open(path) as f: self.paths = f.readlines() self.sample_rate = sample_rate self.noise_levels = noise_levels def inject_noise(self, data): noise_info_dic = json.loads(np.random.choice(self.path...
return data class SpectrogramParser(AudioParser): def __init__(self, audio_conf, speed_volume_perturb=False, reverberation=False): """ Parses audio file into spectrogram with optional normalization and various augmentations :param...
noise_energy = np.sqrt(noise_dst.dot(noise_dst) / noise_dst.size) data_energy = np.sqrt(data.dot(data) / data.size) data += noise_level * noise_dst * data_energy / noise_energy
conditional_block
data_loader.py
60.0): """ Dataset that loads tensors via a csv containing file paths to audio files and transcripts separated by a comma. Each new line is a different sample. Example below: /path/to/audio.wav,/path/to/audio.txt ... :param audio_conf: Dictionary containing the sample r...
""" Picks tempo and gain uniformly, applies it to the utterance by using sox utility. Returns the augmented utterance. """ low_tempo, high_tempo = tempo_range tempo_value = np.random.uniform(low=low_tempo, high=high_tempo) low_gain, high_gain = gain_range gain_value = np.random.uniform(low=l...
identifier_body
data_loader.py
# self.paths = path is not None and librosa.util.find_files(path) with open(path) as f: self.paths = f.readlines() self.sample_rate = sample_rate self.noise_levels = noise_levels def inject_noise(self, data): noise_info_dic = json.loads(np.random.choice(self.path...
(self, transcript_path): raise NotImplementedError class SpectrogramDataset(Dataset, SpectrogramParser): def __init__(self, audio_conf, manifest_filepath, labels, word_form, speed_volume_perturb=False, re...
parse_transcript
identifier_name
data_loader.py
# self.paths = path is not None and librosa.util.find_files(path) with open(path) as f: self.paths = f.readlines() self.sample_rate = sample_rate self.noise_levels = noise_levels def inject_noise(self, data): noise_info_dic = json.loads(np.random.choice(self.pat...
add_reverb = np.random.binomial(1, self.reverb_prob) if add_reverb: y = self.reverb.add_reverb(y) # sf.write('wav/bbbb_{}'.format(os.path.basename(audio_path)), y, self.sample_rate) if self.noiseInjector: add_noise = np.random.binomial(1, self.nois...
y = load_randomly_augmented_audio(audio_path, self.sample_rate) # sf.write('wav/aaaa_{}'.format(os.path.basename(audio_path)), y, self.sample_rate) else: y = load_audio(audio_path) if self.reverberation:
random_line_split
IMMA2nc1.py
ME','CHE','AM','AH','UM','UH','SBI','SA','RI') attachment['95'] = 'REANALYSES QC/FEEDBACK ATTACHMENT' parameters['95'] = ('ICNR','FNR','DPRO','DPRP','UFR','MFGR','MFGSR','MAR','MASR','BCR','ARCR','CDR','ASIR') attachment['96'] = 'ICOADS VALUE-ADDED DATABASE ATTACHMENT' parameters['96'] = ('ICNI','FNI','JVAD','VAD','IVA...
print('%s: check IMMA version' %out_file)
conditional_block
IMMA2nc1.py
19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO') attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT' parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM'...
(out_file,data, **kwargs): def duration(seconds): t= [] for dm in (60, 60, 24, 7): seconds, m = divmod(seconds, dm) t.append(m) t.append(seconds) return ''.join('%d%s' % (num, unit) for num, unit in zip(t[::-1], 'W DT H M S'.split()) if num) def get_keywords(data): keywords = [] for var in dat...
save
identifier_name
IMMA2nc1.py
19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO') attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT' parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM'...
return keywords def Add_gattrs(ff): lon_min = min(data['LON']) lon_max = max(data['LON']) lat_min = min(data['LAT']) lat_max = max(data['LAT']) start_time = min(data.data['Julian']) end_time = max(data.data['Julian']) dur_time = (end_time-start_time)*24.0*3600.0 start_time = jdutil.jd_to_datetime(start_ti...
def duration(seconds): t= [] for dm in (60, 60, 24, 7): seconds, m = divmod(seconds, dm) t.append(m) t.append(seconds) return ''.join('%d%s' % (num, unit) for num, unit in zip(t[::-1], 'W DT H M S'.split()) if num) def get_keywords(data): keywords = [] for var in data.data.keys(): if var in a...
identifier_body
IMMA2nc1.py
I19','QI20','QI21','HDG','COG','SOG','SLL','SLHH','RWD','RWS','QI22','QI23','QI24','QI25','QI26','QI27','QI28','QI29','RH','RHI','AWSI','IMONO') attachment['06'] = 'MODEL QUALITY CONTROL ATTACHMENT' parameters['06'] = ('CCCC','BUID','FBSRC','BMP','BSWU','SWU','BSWV','SWV','BSAT','BSRH','SRH','BSST','MST','MSH','BY','BM...
def save(out_file,data, **kwargs): def duration(seconds): t= [] for dm in (60, 60, 24, 7): seconds, m = divmod(seconds, dm) t.append(m) t.append(seconds) return ''.join('%d%s' % (num, unit) for num, unit in zip(t[::-1], 'W DT H M S'.split()) if num) def get_keywords(data): keywords = [] for va...
return parameters["%02d" % i]
random_line_split
JsPopup.js
Id); $(this).after(miSign); miSign.click(function(){ $(this).removeClass('shake'); }); }); var clearAbleObjs = container.find('.clear_able'); clearAbleObjs.each(function(){ var inputId = _pad_check_temp_id_to_jobj($(this)); var miGroup = _pad_check_input_...
nd(close_btn);
identifier_name
JsPopup.js
0,1)!='#') containerId = '#' + containerId; var container = $(containerId); container.attr('content_url',''); //不去掉就没法设置pageSize //container.removeAttr(_pad_grid_page_size); container.removeAttr('pageNo'); container.removeData(_pad_adv_filter_id); container.removeData(_pad_search_pa...
} } mapop.css('height', p_height); }else{ mapop.css('height', p_height+50); } if(!isNaN(position.left)){ mapop.css('left',position.left); }else if(!isNaN(position.right)){ var width = mapop.outerWidth(); ...
identifier_body
JsPopup.js
+ containerId; var container = $(containerId); container.attr('content_url',''); //不去掉就没法设置pageSize //container.removeAttr(_pad_grid_page_size); container.removeAttr('pageNo'); container.removeData(_pad_adv_filter_id); container.removeData(_pad_search_params_id); container.removeData(_...
if(top<0){ top = 0;
conditional_block
JsPopup.js
异常 if(html.err_text){ alert(html.err_text); _hide_top_loading(); } return; } _pad_add_pageInfo_to_loadPageHtml(html, pageContainerId, url);
if(tempIdx1!=-1){ tempIdx1 = tempIdx1 + 6; var tempIdx2 = html.indexOf('>',tempIdx1); var tempIdx3 = html.indexOf('table',tempIdx1); if(tempIdx3!=-1 && tempIdx3< tempIdx2){ //尝试准确的定位"table.table:first"的table ...
//处理如果html中有grid,为grid加上containerId var tempIdx1 = html.indexOf('<table');
random_line_split
plot_utils.py
(disp, scanline_index, color, title): coords = get_disparity_plot_coords(disp, scanline_index = scanline_index) plt.plot(coords) def get_disparity_plot_coords(disp, scanline_index=0): current = next = disp[0,0] current_plot_coords = [0,0] for j in range ((disp.shape[1])): next = disp[scanli...
plot_disp_line
identifier_name
plot_utils.py
#if it is brighter? if(next>current): return (np.abs(next-current)+1, 1) #if it is darker? return (1,np.abs(next - current)+1) def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"): if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'): data = pd...
return (1,1)
conditional_block
plot_utils.py
_OR_DATAFRAME.__class__.__name__ == 'str'): data = pd.read_csv(FILE_PATH_OR_DATAFRAME) data.columns = np.array([str.strip(col) for col in data.columns]) else: data = FILE_PATH_OR_DATAFRAME x,y,z = data[x_label], data[y_label], data[metrix] fig = plt.figure() ax = fig.gca(projec...
def bar_3d_by_scenes(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, occl_counted=False): if (FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'): data = pd.read_csv(FILE_PATH_OR_DATAFRAME) data.columns = np.array([str.strip(col) for col in data.columns]) else: data = FILE_PATH_OR_DATA...
random_line_split
plot_utils.py
def scatter_3d_results(x_label, y_label, metrix, FILE_PATH_OR_DATAFRAME, cmm="viridis"): if(FILE_PATH_OR_DATAFRAME.__class__.__name__ == 'str'): data = pd.read_csv(FILE_PATH_OR_DATAFRAME) data.columns = np.array([str.strip(col) for col in data.columns]) else: data = FILE_PATH_OR_DATAF...
if next==0: return (1,0) if(current==next): return (1,1) #if it is brighter? if(next>current): return (np.abs(next-current)+1, 1) #if it is darker? return (1,np.abs(next - current)+1)
identifier_body
gui.py
() == '': return 0 return 1 def apply(self): print("apply hit") print(str(self.new_course_ID.get())) # self.parent.withdraw() # TODO: Save this to the actual course data. Then draw window. course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip()) class New_...
except ValueError: return 0 if self.last_name_entry.get().strip() == '' or self.first_name_entry.get().strip() == '': return 0 return 1 def apply(self): print("apply hit") self.last_name = self.last_name_entry.get().strip() self.first_name = self.first_name_entry.get().strip(...
value = int(entry.get().strip()) if value > 100 or value < 0: return 0
conditional_block
gui.py
() == '': return 0 return 1 def apply(self): print("apply hit") print(str(self.new_course_ID.get())) # self.parent.withdraw() # TODO: Save this to the actual course data. Then draw window. course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip()) class New_...
(self): print("apply hit") self.last_name = self.last_name_entry.get().strip() self.first_name = self.first_name_entry.get().strip() self.att_avg = 100 # reports back as percentage att_sum = 0 for i in self.att_entry: att_sum += int(i.get().strip()) print(att_sum) self.att_...
apply
identifier_name
gui.py
() == '': return 0 return 1 def apply(self): print("apply hit") print(str(self.new_course_ID.get())) # self.parent.withdraw() # TODO: Save this to the actual course data. Then draw window. course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip()) class New_...
tkinter.Label(master, text="Last Name").grid( column=0, row=0, sticky='w') tkinter.Label(master, text="First Name:").grid( column=0, row=1) self.last_name_entry = tkinter.Entry(master) self.first_name_entry = tkinter.Entry(master) self.last_name_entry.grid(column=1, row=0) self...
super().__init__(parent, title="Enter Student Information:") def body(self, master):
random_line_split
gui.py
() == '': return 0 return 1 def apply(self): print("apply hit") print(str(self.new_course_ID.get())) # self.parent.withdraw() # TODO: Save this to the actual course data. Then draw window. course_window(self.new_course_ID.get().strip(), self.new_course_name.get().strip()) class New_...
class Section_Tree(ttk.Treeview): #table view. possibly rewrite with inheritance def __init__(self, master, section=Course('MAC000', 'test_000').sectionList[0]): # self.section_tree = section_tree self.section = section self.master = master self.student_grade_list = self.section.student_grade_list...
print("apply hit") self.last_name = self.last_name_entry.get().strip() self.first_name = self.first_name_entry.get().strip()
identifier_body
txn.go
} } txn.queuing = queueDuration(h, txn.start) } txn.attrs.agent.HostDisplayName = txn.Config.HostDisplayName return txn } func (txn *txn) txnEventsEnabled() bool { return txn.Config.TransactionEvents.Enabled && txn.Reply.CollectAnalyticsEvents } func (txn *txn) errorEventsEnabled() bool { return txn...
{ txn := &txn{ txnInput: input, start: time.Now(), name: name, isWeb: nil != input.Request, attrs: newAttributes(input.attrConfig), } if nil != txn.Request { h := input.Request.Header txn.attrs.agent.RequestMethod = input.Request.Method txn.attrs.agent.RequestAcceptHeader = h.Get("Accept...
identifier_body
txn.go
("Host") txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent") txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer")) if cl := h.Get("Content-Length"); "" != cl { if x, err := strconv.Atoi(cl); nil == err { txn.attrs.agent.RequestContentLength = x } } txn.queuing = que...
} txn.attrs.agent.ResponseCode = statusCodeLookup[code] if txn.attrs.agent.ResponseCode == "" { txn.attrs.agent.ResponseCode = strconv.Itoa(code) } if responseCodeIsError(&txn.Config, code) { e := txnErrorFromResponseCode(code) e.stack = getStackTrace(1) txn.noticeErrorInternal(e) } } func (txn *txn) H...
if val := h.Get("Content-Length"); "" != val { if x, err := strconv.Atoi(val); nil == err { txn.attrs.agent.ResponseHeadersContentLength = x }
random_line_split
txn.go
.isWeb, duration: txn.duration, exclusive: exclusive, name: txn.finalName, zone: txn.zone, apdexThreshold: txn.apdexThreshold, errorsSeen: txn.errorsSeen, }, h.metrics) if txn.queuing > 0 { h.metrics.addDuration(queueMetric, "", txn.queuing, txn.queuing, forced) } ...
StartSegment
identifier_name
txn.go
("Host") txn.attrs.agent.RequestHeadersUserAgent = h.Get("User-Agent") txn.attrs.agent.RequestHeadersReferer = safeURLFromString(h.Get("Referer")) if cl := h.Get("Content-Length"); "" != cl { if x, err := strconv.Atoi(cl); nil == err { txn.attrs.agent.RequestContentLength = x } } txn.queuing = que...
else { metrics.addSingleCount(errorsBackground, forced) } metrics.addSingleCount(errorsPrefix+args.name, forced) } } func (txn *txn) mergeIntoHarvest(h *harvest) { exclusive := time.Duration(0) children := tracerRootChildren(&txn.tracer) if txn.duration > children { exclusive = txn.duration - children }...
{ metrics.addSingleCount(errorsWeb, forced) }
conditional_block
tools.py
self.encoder(batch_image_tensors) class KeyPointHeatmapEncoder(nn.Module): def __init__(self, layer_params, input_channel_num=1): # layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]} super(KeyPointHeatmapEncoder, self).__init__() ...
class GraphReadOut(nn.Module): """ that's the readout function input: all nodes final hidden state output: readout vector representing the graph """ def __init__(self, input_dim, node_num, output_dim): super(GraphReadOut, self).__init__() self.input_dim = input_dim # 1024 ...
""" # for n graph instances # given edge index number # this connected_msgs_list contains all connnected edges msg, say m connected edges # connected_msgs_list: m items, each item is n*msg_dim matrix # return n*msg_dim matrix, representing next step msg of this edge index ...
identifier_body
tools.py
self.encoder(batch_image_tensors) class
(nn.Module): def __init__(self, layer_params, input_channel_num=1): # layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]} super(KeyPointHeatmapEncoder, self).__init__() layers = [] layer_params['filter num'] = [input_channe...
KeyPointHeatmapEncoder
identifier_name
tools.py
self.encoder(batch_image_tensors) class KeyPointHeatmapEncoder(nn.Module): def __init__(self, layer_params, input_channel_num=1): # layer_params {'filter num': [1, 2], 'operator':['conv2d','max_pool'], 'kernel sizes': [3, 3], 'strides': [1, 2]} super(KeyPointHeatmapEncoder, self).__init__() ...
else: layers.append(nn.MaxPool2d(kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i])) layers.append(View(-1, )) self.encoder_conv = nn.Sequential(*layers) def forward(self, batch_heatmap_tensor): return self.encoder_conv(batch_heatmap...
layers.append(nn.Conv2d(layer_params['filter num'][i], layer_params['filter num'][i + 1], kernel_size=layer_params['kernel sizes'][i], stride=layer_params['strides'][i])) layers.append(nn.BatchNorm2d(layer_params['filter num'][i+1])) layers.append(...
conditional_block
tools.py
def __init__(self, size): super(View, self).__init__() self.size = size def forward(self, tensor): return tensor.view(self.size) ######################################################### # image encoders # "Any image encoders could replace my implementation here" ####################...
random_line_split
Project4.py
hide_zeroes: cell = cell if float(cm[i, j]) != 0 else empty_cell if hide_diagonal: cell = cell if i != j else empty_cell if hide_threshold: cell = cell if cm[i, j] > hide_threshold else empty_cell print(cell, end=" ") print() ...
regex = re.compile('[\.|\-|\,|\?|\_|\:|\"|\)|\(\)\/|\\|\>|\<]') text = text.lower() # Turn everything to lower case text = regex.sub(' ', text).strip() out = re.sub(' +', ' ', text) # Reduce whitespace down to one return out ##################################################################...
random_line_split
Project4.py
uni_ex_var) print('Reduced Shape of Unigram Data:',reduced_uni_train.shape) with open('reduced_uni_train', 'wb') as f: pickle.dump(reduced_uni_train, f) with open('reduced_uni_validation', 'wb') as f: pickle.dump(reduced_uni_validation, f) with open('reduced_uni_test', 'wb') as f: pickle.dump(reduce...
Computes a weighted average attention mechanism """ def __init__(self, return_attention=False, **kwargs): self.init = initializers.get('uniform') self.supports_masking = True self.return_attention = return_attention super(AttentionWeightedAverage, self).__init__(** kwargs) ...
identifier_body
Project4.py
hide_zeroes: cell = cell if float(cm[i, j]) != 0 else empty_cell if hide_diagonal: cell = cell if i != j else empty_cell if hide_threshold: cell = cell if cm[i, j] > hide_threshold else empty_cell print(cell, end=" ") print() ...
(Callback): def on_train_begin(self, logs={}): self.val_f1s = [] self.val_recalls = [] self.val_precisions = [] def on_epoch_end(self, epoch, logs={}): val_predict = (np.asarray(self.model.predict(self.validation_data[0]))).round() val_targ = self.validation_data...
Metrics
identifier_name
Project4.py
(_val_f1) self.val_recalls.append(_val_recall) self.val_precisions.append(_val_precision) print(' — val_f1: %f — val_precision: %f — val_recall %f' %(_val_f1, _val_precision, _val_recall)) print() return metrics = Metrics() def Dense_Layer(input_tensor, n_neurons, l1_rat...
ue t
conditional_block
transformer.go
{"result"}) feastFeatureStatus = promauto.NewCounterVec(prometheus.CounterOpts{ Namespace: transformer.PromNamespace, Name: "feast_feature_status_count", Help: "Feature status by feature", }, []string{"feature", "status"}) feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{ Names...
for _, val := range vals { entities = append(entities, feast.Row{ configEntity.Name: val, }) } } else { newEntities := []feast.Row{} for _, entity := range entities { for _, val := range vals { newFeastRow := feast.Row{} for k, v := range entity { newFeastRow[k] = v }...
random_line_split
transformer.go
feastValType) if err != nil { logger.Warn(fmt.Sprintf("invalid default value for %s : %v, %v", f.Name, f.DefaultValue, err)) continue } defaultValues[f.Name] = defVal } } } compiledJsonPath := make(map[string]*jsonpath.Compiled) compiledUdf := make(map[string]*vm.Program) for _, ft := r...
{ entityNames := make([]string, 0) for _, n := range entities { entityNames = append(entityNames, n.Name) } return strings.Join(entityNames, "_") }
identifier_body
transformer.go
compiledJsonPath map[string]*jsonpath.Compiled compiledUdf map[string]*vm.Program } // NewTransformer initializes a new Transformer. func NewTransformer(feastClient feast.Client, config *transformer.StandardTransformerConfig, options *Options, logger *zap.Logger) (*Transformer, error) { defaultValues := make(...
getFloatValue
identifier_name
transformer.go
Help: "Feature status by feature", }, []string{"feature", "status"}) feastFeatureSummary = promauto.NewSummaryVec(prometheus.SummaryOpts{ Namespace: transformer.PromNamespace, Name: "feast_feature_value", Help: "Summary of feature value", AgeBuckets: 1, }, []string{"feature"}) ) // Option...
{ var row []interface{} for _, column := range columns { featureStatus := status[i][column] switch featureStatus { case serving.GetOnlineFeaturesResponse_PRESENT: rawValue := feastRow[column] featVal, err := getFeatureValue(rawValue) if err != nil { return nil, err } row = append(r...
conditional_block
start.py
, anchor_ratios) # for inference , the batch size is 1, the model output shape is [1, N, 4], # so we expand dim for anchors to [1, anchor_num, 4] anchors_exp = np.expand_dims(anchors, axis=0) id2class = {0: 'Mask', 1: 'NoMask'} # 人脸对齐方法 def inference(image, conf_thresh=0.5, iou_...
for filename in os.listdir(videos_dir): logger.info('All files:{}'.format(filename)) for filename in os.listdir(videos_dir): suffix = filename.split('.')[1] if suffix != 'mp4' and suffix != 'avi': # you can specify more video formats if you need continue video_name =...
s_dir output_path = args.output_path no_display = args.no_display detect_interval = args.detect_interval # 间隔一帧检测一次 margin = args.margin # 脸边距(默认10) scale_rate = args.scale_rate # 检测图像的尺寸设置 show_rate = args.show_rate # 展示图像的尺寸设置 face_score_threshold = args.face_score_threshold # 人脸判别阈值 ...
identifier_body
start.py
_sizes, anchor_ratios) # for inference , the batch size is 1, the model output shape is [1, N, 4], # so we expand dim for anchors to [1, anchor_num, 4] anchors_exp = np.expand_dims(anchors, axis=0) id2class = {0: 'Mask', 1: 'NoMask'} # 人脸对齐方法 def inference(image, conf_thresh=0.5, ...
:param image: 3D numpy array of image :param conf_thresh: the min threshold of classification probabity. :param iou_thresh: the IOU threshold of NMS :param target_shape: the model input size. :param draw_result: whether to daw bounding box to the image. :param show_result: whether to display the...
show_result=True ): ''' Main function of detection inference
random_line_split
start.py
anchor_ratios) # for inference , the batch size is 1, the model output shape is [1, N, 4], # so we expand dim for anchors to [1, anchor_num, 4] anchors_exp = np.expand_dims(anchors, axis=0) id2class = {0: 'Mask', 1: 'NoMask'} # 人脸对齐方法 def inference(image,
nf_thresh=0.5, iou_thresh=0.4, target_shape=(160, 160), draw_result=True, show_result=True ): ''' Main function of detection inference :param image: 3D numpy array of image :param conf_thresh: the min threshold of classification proba...
co
identifier_name
start.py
anchor_ratios) # for inference , the batch size is 1, the model output shape is [1, N, 4], # so we expand dim for anchors to [1, anchor_num, 4] anchors_exp = np.expand_dims(anchors, axis=0) id2class = {0: 'Mask', 1: 'NoMask'} # 人脸对齐方法 def inference(image, conf_thresh=0.5, iou_t...
# if c % detect_interval == 0: # img_size = np.asarray(frame.shape)[0:2] # faces = inference(r_g_b_frame, show_result=True, target_shape=(260, 260)) with tf.Graph().as_default(): with tf.Session(config=tf.ConfigProto(gpu_options=tf.GPUOptions(allow_growth=Tru...
cv2.COLOR_BGR2RGB) # 间隔取帧,默认每帧都取
conditional_block
h5t.go
_t dtype_id, size_tsize ) func (t *DataType) SetSize(sz int) error { err := C.H5Tset_size(t.id, C.size_t(sz)) return togo_err(err) } // --------------------------------------------------------------------------- // array data type type ArrayType struct { DataType } func new_array_type(id C.hid_t) *ArrayType { t ...
{ f := t.Field(i) var field_dt *DataType = nil field_dt = new_dataTypeFromType(f.Type) offset := int(f.Offset + 0) if field_dt == nil { panic(fmt.Sprintf("pb with field [%d-%s]", i, f.Name)) } field_name := string(f.Tag) if len(field_name) == 0 { field_name = f.Name } err = cdt.Ins...
conditional_block
h5t.go
.hid_t, rt reflect.Type) *DataType { t := &DataType{id: id, rt: rt} //runtime.SetFinalizer(t, (*DataType).h5t_finalizer) return t } // Creates a new datatype. // hid_t H5Tcreate( H5T_class_t class, size_tsize ) func CreateDataType(class TypeClass, size int) (t *DataType, err error) { t = nil err = nil hid := C...
{ c_tag := C.CString(tag) defer C.free(unsafe.Pointer(c_tag)) err := C.H5Tset_tag(t.id, c_tag) return togo_err(err) }
identifier_body
h5t.go
32(0)) _go_uint64_t reflect.Type = reflect.TypeOf(uint64(0)) _go_float32_t reflect.Type = reflect.TypeOf(float32(0)) _go_float64_t reflect.Type = reflect.TypeOf(float64(0)) _go_array_t reflect.Type = reflect.TypeOf([1]int{0}) _go_slice_t reflect.Type = reflect.TypeOf([]int{0}) _go_struct_t reflect.Type = refle...
() { err := t.Close() if err != nil { panic(fmt.Sprintf("error closing datatype: %s", err)) } } // Releases a datatype. // herr_t H5Tclose( hid_t dtype_id ) func (t *DataType) Close() error { if t.id > 0 { fmt.Printf("--- closing dtype [%d]...\n", t.id) err := togo_err(C.H5Tclose(t.id)) t.id = 0 return ...
h5t_finalizer
identifier_name
h5t.go
T_TIME: nil, T_STRING: _go_string_t, T_BITFIELD: nil, T_OPAQUE: nil, T_COMPOUND: _go_struct_t, T_REFERENCE: _go_ptr_t, T_ENUM: _go_int_t, T_VLEN: _go_slice_t, T_ARRAY: _go_array_t, } ) func new_dtype(id C.hid_t, rt reflect.Type) *DataType { t := &DataType{id: id, rt: rt} ...
random_line_split
ai.py
between two angles. """ import math import pymunk from pymunk import Vec2d import gameobjects
def angle_between_vectors(vec1, vec2): """ Since Vec2d operates in a cartesian coordinate space we have to convert the resulting vector to get the correct angle for our space. """ vec = vec1 - vec2 vec = vec.perpendicular() return vec.angle def periodic_difference_of_angles(angle1,...
from collections import defaultdict, deque MIN_ANGLE_DIF = math.radians(5)
random_line_split
ai.py
between two angles. """ import math import pymunk from pymunk import Vec2d import gameobjects from collections import defaultdict, deque MIN_ANGLE_DIF = math.radians(5) def angle_between_vectors(vec1, vec2): """ Since Vec2d operates in a cartesian coordinate space we have to convert the resulti...
elif isinstance(res.shape.parent, gameobjects.Box): if res.shape.parent.boxmodel.destructable is True: bullet = self.tank.shoot(self.space) if bullet is not None: self.game_objects_list.a...
bullet = self.tank.shoot(self.space) if bullet is not None: self.game_objects_list.append(bullet)
conditional_block
ai.py
between two angles. """ import math import pymunk from pymunk import Vec2d import gameobjects from collections import defaultdict, deque MIN_ANGLE_DIF = math.radians(5) def angle_between_vectors(vec1, vec2): """ Since Vec2d operates in a cartesian coordinate space we have to convert the resulti...
angle_tank = self.tank.body.angle target_angle = \ angle_between_vectors(Vec2d(self.tank.body.position), next_coord) yield self.tank.accelerate() while not self.correct_pos(next_coord, self.last...
""" A generator that iteratively goes through all the required steps to move to our goal. """ while True: self.update_grid_pos() path = self.find_shortest_path("without_metalbox") if not path: path = self.find_shortest_path("met...
identifier_body
ai.py
between two angles. """ import math import pymunk from pymunk import Vec2d import gameobjects from collections import defaultdict, deque MIN_ANGLE_DIF = math.radians(5) def angle_between_vectors(vec1, vec2): """ Since Vec2d operates in a cartesian coordinate space we have to convert the resulti...
(self, coord): """ Filter for all the tiles around the tank, metalboxes included. This filter removes the immovable stones so we don't count those tiles to find the shortest path. """ coord = coord.int_tuple if coord[1] <= self.MAX_Y and coord[0] <=
filter_tile_neighbors_metalbox
identifier_name
mole.go
struct { Conf *Configuration Tunnel *tunnel.Tunnel sigs chan os.Signal } // New initializes a new mole's client. func New(conf *Configuration) *Client { cli = &Client{ Conf: conf, sigs: make(chan os.Signal, 1), } return cli } // Start kicks off mole's client, establishing the tunnel and its channels /...
createTunnel
identifier_name
mole.go
configuration. type Client struct { Conf *Configuration Tunnel *tunnel.Tunnel sigs chan os.Signal } // New initializes a new mole's client. func New(conf *Configuration) *Client { cli = &Client{ Conf: conf, sigs: make(chan os.Signal, 1), } return cli } // Start kicks off mole's client, establishing th...
{ for _, f := range fs { if flag == f { return true } } return false }
identifier_body
mole.go
KeepAliveInterval time.Duration `json:"keep-alive-interval" mapstructure:"keep-alive-interva" toml:"keep-alive-interval"` ConnectionRetries int `json:"connection-retries" mapstructure:"connection-retries" toml:"connection-retries"` WaitAndRetry time.Duration `json:"wait-and-retry" mapstructur...
cntxt := &daemon.Context{ PidFileName: pfp, } d, err := cntxt.Search() if err != nil { return err } if c.Conf.Detach { err = os.RemoveAll(pfp) if err != nil { return err } } else { d, err := fsutils.InstanceDir(c.Conf.Id) if err != nil { return err } err = os.RemoveAll(d.Dir) if er...
{ return fmt.Errorf("no instance of mole with id %s is running", c.Conf.Id) }
conditional_block