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
texture.rs
112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, ...
new
identifier_name
texture.rs
204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, ...
} impl TextureMapping2D for UVMapping2D { fn map(&self, si: &SurfaceInteraction, dstdx: &mut Vector2f, dstdy: &mut Vector2f) -> Point2f { // Compute texture differentials for sphere (u, v) mapping *dstdx = Vector2f::new(self.su * si.dudx.get() , self.sv * si.dvdx.get()); *dstdy ...
{ Self { su, sv, du, dv } }
identifier_body
batches.rs
author(crate_authors!("\n")) .about("Handles the maintance work for karmator") .subcommand( Command::new("runs") .about("Detect runs of votes") .arg( Arg::new("min") .short('m') .help("Min cou...
compact
identifier_name
batches.rs
_version!()) .author(crate_authors!("\n")) .about("Handles the maintance work for karmator") .subcommand( Command::new("runs") .about("Detect runs of votes") .arg( Arg::new("min") .short('m') ...
fn delete_set(all: &HashSet<OsString>, keep: Vec<&HashSet<OsString>>) -> HashSet<OsString> { let mut delete = all.clone(); for hs in keep { let out = delete.difference(&hs).map(|e| e.clone()).collect(); delete = out; }
{ glob(&(directory.to_string() + glob_str)).unwrap() .flatten() .map(|e| e.into_os_string()) .collect::<HashSet<OsString>>() }
identifier_body
batches.rs
_version!()) .author(crate_authors!("\n")) .about("Handles the maintance work for karmator") .subcommand( Command::new("runs") .about("Detect runs of votes") .arg( Arg::new("min") .short('m') ...
let delete = m.contains_id("delete"); run(filename, *min, delete) }, Some(("prune", m)) => { let directory = m.get_one::<String>("BACKUPS").unwrap(); let delete = m.contains_id("delete"); let skip = m.contains_id("skip"); prune(di...
let filename = m.get_one::<String>("FILE").unwrap(); let min = m.get_one::<u32>("min").unwrap();
random_line_split
batches.rs
} _ => { println!("meh do --help yourself"); Ok(()) }, }.unwrap(); } #[derive(Debug, Clone)] struct Vote { id: i32, by_whom_name: String, for_what_name: String, amount: i8, } impl PartialEq for Vote { fn eq(&self, other: &Self) -> bool { (self.by...
{ std::fs::remove_file(path)?; }
conditional_block
reconcile_keyspaces.go
planetscalev2 "planetscale.dev/vitess-operator/pkg/apis/planetscale/v2" "planetscale.dev/vitess-operator/pkg/operator/lockserver" "planetscale.dev/vitess-operator/pkg/operator/reconciler" "planetscale.dev/vitess-operator/pkg/operator/rollout" "planetscale.dev/vitess-operator/pkg/operator/update" "planetscale.dev/v...
(key client.ObjectKey, vtk *planetscalev2.VitessKeyspace, vt *planetscalev2.VitessCluster, parentLabels map[string]string, keyspace *planetscalev2.VitessKeyspaceTemplate) { newKeyspace := newVitessKeyspace(key, vt
updateVitessKeyspaceInPlace
identifier_name
reconcile_keyspaces.go
planetscalev2 "planetscale.dev/vitess-operator/pkg/apis/planetscale/v2" "planetscale.dev/vitess-operator/pkg/operator/lockserver" "planetscale.dev/vitess-operator/pkg/operator/reconciler" "planetscale.dev/vitess-operator/pkg/operator/rollout" "planetscale.dev/vitess-operator/pkg/operator/update" "planetscale.dev/v...
sort.Strings(status.Cells) vt.Status.Keyspaces[curObj.Spec.Name] = status }, OrphanStatus: func(key client.ObjectKey, obj runtime.Object, orphanStatus *planetscalev2.OrphanStatus) { curObj := obj.(*planetscalev2.VitessKeyspace) vt.Status.OrphanedKeyspaces[curObj.Spec.Name] = *orphanStatus }, Prepa...
{ status.Cells = append(status.Cells, cell) }
conditional_block
reconcile_keyspaces.go
planetscalev2 "planetscale.dev/vitess-operator/pkg/apis/planetscale/v2" "planetscale.dev/vitess-operator/pkg/operator/lockserver" "planetscale.dev/vitess-operator/pkg/operator/reconciler" "planetscale.dev/vitess-operator/pkg/operator/rollout" "planetscale.dev/vitess-operator/pkg/operator/update" "planetscale.dev/...
newObj := obj.(*planetscalev2.VitessKeyspace) if *vt.Spec.UpdateStrategy.Type == planetscalev2.ImmediateVitessClusterUpdateStrategyType { // In this case we should use UpdateInPlace for all updates. return } updateVitessKeyspace(key, newObj, vt, labels, keyspaceMap[key]) }, Status: func(key clie...
return } updateVitessKeyspaceInPlace(key, newObj, vt, labels, keyspaceMap[key]) }, UpdateRollingInPlace: func(key client.ObjectKey, obj runtime.Object) {
random_line_split
reconcile_keyspaces.go
) runtime.Object { return newVitessKeyspace(key, vt, labels, keyspaceMap[key]) }, UpdateInPlace: func(key client.ObjectKey, obj runtime.Object) { newObj := obj.(*planetscalev2.VitessKeyspace) if *vt.Spec.UpdateStrategy.Type == planetscalev2.ImmediateVitessClusterUpdateStrategyType { updateVitessKeyspac...
{ var differentKeys []string for k := range oldMap { if _, exist := newMap[k]; !exist { differentKeys = append(differentKeys, k) } } return differentKeys }
identifier_body
elasticsearch_metadata.go
interface { Perform(*http.Request) (*http.Response, error) } // NewBgMetadataElasticSearchConnector : contructor for BgMetadataElasticSearchConnector func newBgMetadataElasticSearchConnector(elasticSearchClient ElasticSearchClient, registry prometheus.Registerer, bulkSize, maxRetry uint, indexName, IndexDateFmt stri...
random_line_split
elasticsearch_metadata.go
` { "_doc": { "properties": { "depth": { "type": "long" }, "name": { "type": "keyword", "ignore_above": 1024 }, "uuid": { "type": "keyword" }, "parent": { ...
} return es, err } // NewBgMetadataElasticSearchConnectorWithDefaults is the public contructor of BgMetadataElasticSearchConnector func NewBgMetadataElasticSearchConnectorWithDefaults(cfg *cfg.BgMetadataESConfig) *BgMetadataElasticSearchConnector { es, err := createElasticSearchClient(cfg.StorageServers, cfg.Usern...
{ cfg := elasticsearch.Config{ Addresses: servers, Username: username, Password: password, Transport: &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: allow_insecure_tls, }, }, } es, err := elasticsearch.NewClient(cfg) if err != nil { log.Fatalf("Error creating the Elastic...
identifier_body
elasticsearch_metadata.go
` { "_doc": { "properties": { "depth": { "type": "long" }, "name": { "type": "keyword", "ignore_above": 1024 }, "uuid": { "type": "keyword" }, "parent": { ...
(doc ElasticSearchDocument) error { esc.mux.Lock() defer esc.mux.Unlock() esc.bulkBuffer = append(esc.bulkBuffer, doc) if len(esc.bulkBuffer) == cap(esc.bulkBuffer) { esc.sendAndClearBuffer() } return nil } func (esc *BgMetadataElasticSearchConnector) sendAndClearBuffer() error { defer esc.clearBuffer() met...
addDocumentToBuff
identifier_name
elasticsearch_metadata.go
` { "_doc": { "properties": { "depth": { "type": "long" }, "name": { "type": "keyword", "ignore_above": 1024 }, "uuid": { "type": "keyword" }, "parent": { ...
return es, err } // NewBgMetadataElasticSearchConnectorWithDefaults is the public contructor of BgMetadataElasticSearchConnector func NewBgMetadataElasticSearchConnectorWithDefaults(cfg *cfg.BgMetadataESConfig) *BgMetadataElasticSearchConnector { es, err := createElasticSearchClient(cfg.StorageServers, cfg.Username...
{ log.Fatalf("Error getting ElasticSearch information response: %s", err) }
conditional_block
report_utils.py
y=best_objectives, title="Best objective found vs. # of iterations", ylabel=metric_name, model_transitions=model_transitions, optimization_direction=optimization_direction, plot_trial_points=True, ) def _get_objective_v_param_plot( search_space: SearchSpace, ...
optimization_direction: Optional[str] = None, ) -> Optional[go.Figure]: best_objectives = np.array([experiment.fetch_data().df["mean"]]) return optimization_trace_single_method_plotly(
random_line_split
report_utils.py
if max_chunks == 1: return {istr: istr for istr in input_str_list} # the upper range of this loop is `max_chunks + 2` because: # - `i` needs to take the value of `max_chunks`, hence one +1 # - the contents of the loop are run one more time to check if `all_unique`, # hence the...
if not ( isinstance(trial_properties_fields, list) and all(isinstance(field, str) for field in trial_properties_fields) ): raise ValueError( "trial_properties_fields must be List[str] or None. " f"Got {trial_properties_fields}" ) ...
conditional_block
report_utils.py
( "_get_objective_v_param_plot requires a search space with at least one " "RangeParameter. Returning None." ) return None def _get_suffix(input_str: str, delim: str = ".", n_chunks: int = 1) -> str: return delim.join(input_str.split(delim)[-n_chunks:]) def _get_shortest_unique_suffix_di...
# Accept Experiment and SimpleExperiment if isinstance(exp, MultiTypeExperiment): raise ValueError("Cannot transform MultiTypeExperiments to DataFrames.") key_components = ["trial_index", "arm_name"] # Get each trial-arm with parameters arms_df = pd.DataFrame() for trial_index, trial...
return not_none(not_none(df.drop(drop_col, axis=1)).sort_values(sort_by))
identifier_body
report_utils.py
( "_get_objective_v_param_plot requires a search space with at least one " "RangeParameter. Returning None." ) return None def _get_suffix(input_str: str, delim: str = ".", n_chunks: int = 1) -> str: return delim.join(input_str.split(delim)[-n_chunks:]) def _get_shortest_unique_suffix_di...
( df: pd.DataFrame, drop_col: str, sort_by: List[str] ) -> pd.DataFrame: return not_none(not_none(df.drop(drop_col, axis=1)).sort_values(sort_by)) # Accept Experiment and SimpleExperiment if isinstance(exp, MultiTypeExperiment): raise ValueError("Cannot transform MultiTypeExperiment...
prep_return
identifier_name
getlola.py
): pLon2 = pointList[0][0] pLat2 = pointList[0][1] else: # print(i+1) try: pLon2 = pointList[i + 1][0] pLat2 = pointList[i + 1][1] except IndexError: break ###转换数值类型 pLon1 = float(pLon1) ...
mid (day_id,org_name,grid
identifier_name
getlola.py
True except: conn.rollback() print("Exec sql failed: %s" % SqlStr) return False finally: cursor.close() # conn.close() # 判断坐标是否再坐标圈内 def is_pt_in_poly(aLon, aLat, pointList): ''''' :param aLon: double 经度 :param aLat: double 纬度 :param pointList: list [(lon, ...
judge_result = is_pt_in_poly(cellLo, cellLa, org_point) if judge_result: sql_insert_b_cell_mid = "insert into b_cell_mid (day_id,org_name,grid_id,city_id,org_level,cell_id) " \ "values ('%s','%s','%s','%s','%s','%s')" % ( ...
random_line_split
getlola.py
except: conn.rollback() print("Exec sql failed: %s" % SqlStr) return False finally: cursor.close() # conn.close() # 判断坐标是否再坐标圈内 def is_pt_in_poly(aLon, aLat, pointList): ''''' :param aLon: double 经度 :param aLat: double 纬度 :param pointList: list [(lon, lat)....
loat(pLat2) aLat = float(aLat) aLon = float(aLon) if ((aLat >= pLat1) and (aLat < pLat2)) or ((aLat >= pLat2) and (aLat < pLat1)): if (abs(pLat1 - pLat2) > 0): pLon = pLon1 - ((pLon1 - pLon2) * (pLat1 - aLat)) / (pLat1 - pLat2) if (pLon < aLon): ...
break ###转换数值类型 pLon1 = float(pLon1) pLat1 = float(pLat1) pLon2 = float(pLon2) pLat2 = f
conditional_block
getlola.py
" \ "and b.state='00A' " \ "and a.state='00A' " \ "and a.org_id in ( " \ "select org_id from s_orgnization start with org_id='%s' " \ "connect by pri...
对照中间表修改正式表中的所有数据 update小区region_id def updata_cell_region_all(): sqlSecCellIdFromMid = "select cell_id from B_CELL_MID" cellIdList = Oracle_Query(sqlSecCellIdFromMid) for cellIdTup in cellIdList: gridId = judge_cell_id_region(cellIdTup[0]) if gridId: print(cellIdTup[0]) ...
identifier_body
report_internal_faculty_cv.py
.context_processors import csrf from django.http import HttpResponse from django.shortcuts import render_to_response from django import forms from django.template import RequestContext from django.contrib.auth.decorators import login_required import copy # ========================================================...
c = RequestContext(request) c.update(csrf(request)) # if 'course_name' in request.GET and request.GET['course_name']: if request.method == 'POST': # form submitted form = InternalFacultyCVForm(request.POST) form.is_valid() instructor = form.cleaned_data['instruc...
random_line_split
report_internal_faculty_cv.py
.context_processors import csrf from django.http import HttpResponse from django.shortcuts import render_to_response from django import forms from django.template import RequestContext from django.contrib.auth.decorators import login_required import copy # ========================================================...
ts = [ ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('SPAN', (0, 0), (0, -1)) ] elements.append(make_table(data, widths=[6 * cm, 16 * cm, 4 * cm], style=ts)) ...
icon_string = str(counter) + '. <b>' + icon.organization + '</b>. ' + icon.description data.append([cat_header, Paragraph(icon_string, styleN), Paragraph(str(icon.date.year), styleN), ]) cat_header = '' counter += 1
conditional_block
report_internal_faculty_cv.py
.context_processors import csrf from django.http import HttpResponse from django.shortcuts import render_to_response from django import forms from django.template import RequestContext from django.contrib.auth.decorators import login_required import copy # ========================================================...
c = RequestContext(request) c.update(csrf(request)) # if 'course_name' in request.GET and request.GET['course_name']: if request.method == 'POST': # form submitted form = InternalFacultyCVForm(request.POST) form.is_valid() instructor = form.cleane...
if request.user.is_superuser: instructor = forms.ModelMultipleChoiceField(queryset=Instructor.objects.all()) else: instructor = forms.ModelMultipleChoiceField(queryset=Instructor.objects.filter(owner=request.user))
identifier_body
report_internal_faculty_cv.py
.context_processors import csrf from django.http import HttpResponse from django.shortcuts import render_to_response from django import forms from django.template import RequestContext from django.contrib.auth.decorators import login_required import copy # ========================================================...
(forms.Form): if request.user.is_superuser: instructor = forms.ModelMultipleChoiceField(queryset=Instructor.objects.all()) else: instructor = forms.ModelMultipleChoiceField(queryset=Instructor.objects.filter(owner=request.user)) c = RequestContext(request) ...
InternalFacultyCVForm
identifier_name
common_voices_eval.py
label, featureSize, labelSize).view(1, -1) if torch.isinf(loss).sum() > 0 or torch.isnan(loss).sum() > 0: loss = 0 return loss class IDModule(torch.nn.Module): def __init__(self): super(IDModule, self).__init__() def forward(self, feat...
'stereo audio.') parser_train.add_argument('--loss_reduction', type=str, default='mean', choices=['mean', 'sum'])
random_line_split
common_voices_eval.py
offsetEnd = self.seqOffset[idx+1] offsetPhoneStart = self.phoneOffsets[idx] offsetPhoneEnd = self.phoneOffsets[idx + 1] sizeSeq = int(offsetEnd - offsetStart) sizePhone = int(offsetPhoneEnd - offsetPhoneStart) outSeq = torch.zeros((self.inDim, self.maxSize)) out...
args.pathCheckpoint = data["pathCheckpoint"] args.no_pretraining = data["no_pretraining"] args.LSTM = data.get("LSTM", False) args.seqNorm = data.get("seqNorm", False) args.dropout = data.get("dropout", False) args.in_dim = data.get("in_dim", 1) args.loss_reduction = data.get("loss_reducti...
args.pathPhone = data["pathPhone"] args.pathVal = data["pathVal"]
conditional_block
common_voices_eval.py
] offsetEnd = self.seqOffset[idx+1] offsetPhoneStart = self.phoneOffsets[idx] offsetPhoneEnd = self.phoneOffsets[idx + 1] sizeSeq = int(offsetEnd - offsetStart) sizePhone = int(offsetPhoneEnd - offsetPhoneStart) outSeq = torch.zeros((self.inDim, self.maxSize)) o...
def getPrediction(self, cFeature, featureSize): B, S, H = cFeature.size() if self.seqNorm: for b in range(B): size = featureSize[b] m = cFeature[b, :size].mean(dim=0, keepdim=True) v = cFeature[b, :size].var(dim=0, keepdim=True) ...
super(CTCphone_criterion, self).__init__() self.seqNorm = seqNorm self.epsilon = 1e-8 self.dropout = torch.nn.Dropout2d( p=0.5, inplace=False) if dropout else None self.conv1 = torch.nn.LSTM(dimEncoder, dimEncoder, num_layers=1, batch_first=...
identifier_body
common_voices_eval.py
offsetEnd = self.seqOffset[idx+1] offsetPhoneStart = self.phoneOffsets[idx] offsetPhoneEnd = self.phoneOffsets[idx + 1] sizeSeq = int(offsetEnd - offsetStart) sizePhone = int(offsetPhoneEnd - offsetPhoneStart) outSeq = torch.zeros((self.inDim, self.maxSize)) out...
(self, feature, *args): B, C, S = feature.size() return feature.permute(0, 2, 1), None, None def cut_data(seq, sizeSeq): maxSeq = sizeSeq.max() return seq[:, :maxSeq] def prepare_data(data): seq, sizeSeq, phone, sizePhone = data seq = seq.cuda(non_blocking=True) phone = phone.cud...
forward
identifier_name
operational_test.go
} return &testDb{ db: db, blocks: blocks, dbName: dbname, dbNameVer: dbnamever, cleanUpFunc: cleanUp, }, nil } func TestOperational(t *testing.T) { testOperationalMode(t) } // testAddrIndexOperations ensures that all normal operations concerning // the optional address index funct...
{ // Ignore db remove errors since it means we didn't have an old one. dbnamever := dbname + ".ver" _ = os.RemoveAll(dbname) _ = os.RemoveAll(dbnamever) db, err := database.CreateDB("leveldb", dbname) if err != nil { return nil, err } testdatafile := filepath.Join("..", "/../blockchain/testdata", "blocks0to1...
identifier_body
operational_test.go
ktxLoc[0].TxStart), TxLen: uint32(blktxLoc[0].TxLen), }, } // Insert our test addr index into the DB. err = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex) if err != nil { t.Fatalf("UpdateAddrIndexForBlock: failed to index"+ " addrs for block #%d (%s) "+ "err %v", newestBlockIdx, n...
if blkid != height { t.Errorf("height does not match latest block height %v %v %v", blkid, height, err) } blkSha := block.Sha() if *newSha != *blkSha { t.Errorf("Newest block sha does not match freshly inserted one %v %v %v ", newSha, blkSha, err) } } // now that the db is populated, do some addit...
{ t.Errorf("failed to obtain latest sha %v %v", height, err) }
conditional_block
operational_test.go
ktxLoc[0].TxStart), TxLen: uint32(blktxLoc[0].TxLen), }, } // Insert our test addr index into the DB. err = db.UpdateAddrIndexForBlock(newestSha, newestBlockIdx, testIndex) if err != nil { t.Fatalf("UpdateAddrIndexForBlock: failed to index"+ " addrs for block #%d (%s) "+ "err %v", newestBlockIdx, n...
(db database.Db, t *testing.T, newestSha *chainhash.Hash, newestBlockIdx int64) { // Safe to ignore error, since height will be < 0 in "error" case. sha, height, _ := db.FetchAddrIndexTip() if newestBlockIdx != height { t.Fatalf("Height of address index tip failed to update, "+ "expected %v, got %v", newestBloc...
assertAddrIndexTipIsUpdated
identifier_name
operational_test.go
ExistsSha: unexpected error: %v", err) } _, err = testDb.db.FetchBlockBySha(sha) if err != nil { t.Errorf("failed to load block 99 from db %v", err) return } sha = testDb.blocks[119].Sha() if _, err := testDb.db.ExistsSha(sha); err != nil { t.Errorf("ExistsSha: unexpected error: %v", err) } _, err = test...
} if txSkipped != 1 {
random_line_split
kc_pattern_scanner.py
((df["high"] - df["close"])/(.001 + df["high"] - df["low"]) > 0.6) & \ ((df["high"] - df["open"])/(.001 + df["high"] - df["low"]) > 0.6)) & \ (abs(df["close"] - df["open"]) > 0.1* (df["high"] - df["low"])) return df def levels(ohlc_day): """ret...
return "Significance - {}, Pattern - {}".format(signi,pattern) ############################################################################################## tickers = ["BHEL", "CONCOR", "ASTRAL", "INDHOTEL", "DALBHARAT", "COFORGE", "ITI", "IPCALAB", "SUMICHEM", "DHANI", "DIXON", "SUNTV", ...
pattern = "engulfing_bullish"
conditional_block
kc_pattern_scanner.py
3=level-s3 lev_ser = pd.Series([l_p,l_r1,l_r2,l_r3,l_s1,l_s2,l_s3],index=["p","r1","r2","r3","s1","s2","s3"]) sup = lev_ser[lev_ser>0].idxmin() res = lev_ser[lev_ser<0].idxmax() return (eval('{}'.format(res)), eval('{}'.format(sup))) def candle_type(ohlc_df): """returns the candle type o...
"DLF",
random_line_split
kc_pattern_scanner.py
if (res - 1.5*avg_candle_size) < ohlc_df["close"][-1] < (res + 1.5*avg_candle_size): signi = "HIGH" if candle_type(ohlc_df) == 'doji' \ and ohlc_df["close"][-1] > ohlc_df["close"][-2] \ and ohlc_df["close"][-1] > ohlc_df["open"][-1]: pattern = "doji_bullish" ...
main
identifier_name
kc_pattern_scanner.py
((df["high"] - df["close"])/(.001 + df["high"] - df["low"]) > 0.6) & \ ((df["high"] - df["open"])/(.001 + df["high"] - df["low"]) > 0.6)) & \ (abs(df["close"] - df["open"]) > 0.1* (df["high"] - df["low"])) return df def levels(ohlc_day): """ret...
def res_sup(ohlc_df,ohlc_day): """calculates closest resistance and support levels for a given candle""" level = ((ohlc_df["close"][-1] + ohlc_df["open"][-1])/2 + (ohlc_df["high"][-1] + ohlc_df["low"][-1])/2)/2 p,r1,r2,r3,s1,s2,s3 = levels(ohlc_day) l_r1=level-r1 l_r2=level-r2 l_r3=...
"function to assess the trend by analyzing each candle" df = ohlc_df.copy() df["up"] = np.where(df["low"]>=df["low"].shift(1),1,0) df["dn"] = np.where(df["high"]<=df["high"].shift(1),1,0) if df["close"][-1] > df["open"][-1]: if df["up"][-1*n:].sum() >= 0.7*n: return "uptrend" ...
identifier_body
tex_mobject.py
objectFromSVGPathstring.pointwise_become_partial( self, mobject, 0, b ) self.set_stroke(width=added_width + mobject.get_stroke_width()) self.set_fill(opacity=opacity) class SingleStringTexMobject(SVGMobject): CONFIG = { "template_tex_file": TEMPLATE_TEX_FILE, "s...
(expression, template_tex_file): image_dir = os.path.join( TEX_IMAGE_DIR, tex_hash(expression, template_tex_file) ) if os.path.exists(image_dir): return get
tex_to_svg_file
identifier_name
tex_mobject.py
objectFromSVGPathstring.pointwise_become_partial( self, mobject, 0, b ) self.set_stroke(width=added_width + mobject.get_stroke_width()) self.set_fill(opacity=opacity) class SingleStringTexMobject(SVGMobject): CONFIG = { "template_tex_file": TEMPLATE_TEX_FILE, "s...
for t1, t2 in ("\\left", "\\right"), ("\\right", "\\left"): should_replace = reduce(op.and_, [ t1 in tex, t2 not in tex, len(tex) > len(t1) and tex[len(t1)] in "()[]<>|.\\" ]) if should_replace: tex = tex.replac...
tex = ""
conditional_block
tex_mobject.py
VMobjectFromSVGPathstring.pointwise_become_partial( self, mobject, 0, b ) self.set_stroke(width=added_width + mobject.get_stroke_width()) self.set_fill(opacity=opacity) class SingleStringTexMobject(SVGMobject): CONFIG = { "template_tex_file": TEMPLATE_TEX_FILE, ...
""" new_submobjects = [] curr_index = 0 for tex_string in self.tex_strings: sub_tex_mob = SingleStringTexMobject(tex_string, **self.CONFIG) num_submobs = len(sub_tex_mob.submobjects) new_index = curr_index + num_submobs if num_submobs == 0:...
of tex_strings)
random_line_split
tex_mobject.py
objectFromSVGPathstring.pointwise_become_partial( self, mobject, 0, b ) self.set_stroke(width=added_width + mobject.get_stroke_width()) self.set_fill(opacity=opacity) class SingleStringTexMobject(SVGMobject): CONFIG = { "template_tex_file": TEMPLATE_TEX_FILE, "s...
def index_of_part(self, part): split_self = self.split() if part not in split_self: raise Exception("Trying to get index of part not in TexMobject") return split_self.index(part) def index_of_part_by_tex(self, tex, **kwargs): part = self.get_part_by_tex(tex, **kwar...
for texs, color in texs_to_color_map.items(): try: # If the given key behaves like tex_strings texs + '' self.set_color_by_tex(texs, color, **kwargs) except TypeError: # If the given key is a tuple for tex in texs: ...
identifier_body
index.js
/updateState', payload: {...obj} }) } // mock columns let columns = [] let overViewcolumns = [ { dataIndex: "a", key: "a", title: "区域" }, { dataIndex: "b", key: "b", title: "事业部" }, { ...
d9a9e3750a34e91", "value" : "测试水厂0001", "name" : "测试水厂0001", "parentId" : "e6a34203250b471c969fba90fccc6c87" }, { "id" : "c3e5d28d0da94357ad3625af1e58f342", "value" : "水厂测试门户1", "name" : "水厂测试门户1", "parentId" : "e6a34203250b471c969fba90fccc6c87" }, { ...
"id" : "08ffc34f7b7444249
identifier_body
index.js
{ dataIndex: "c", key: "c", title: "起始时间" }, { dataIndex: "d", key: "d", title: "结束时间" }, { dataIndex: "e", key: "e", title: "情况说明" }, { dataInd...
行导出'); return; } param.isAll = true; }
conditional_block
index.js
State', payload: {...obj} }) } // mock columns let columns = [] let overViewcolumns = [ { dataIndex: "a", key: "a", title: "区域" }, { dataIndex: "b", key: "b", title: "事业部" }, { da...
ata.id], onSuccess: (ids) => { let page = currentPage !=1 && ids.length === (total - (currentPage -1) * pageSize) ? currentPage -1 : currentPage; dispatch({ type: 'onlineOperation/getList', payload: { selectedRowKeys: [], curren...
: [rowD
identifier_name
index.js
}, { dataIndex: "h", key: "h", title: "人工监测结果(mg/L)" }, { dataIndex: "i", key: "i", title: "备注" }, ] const optCol = [['操作', 'action', { renderButtons: ()=>{ let btns = []; if(...
</Select> <Select {...vtxGridParams.nameProps}>
random_line_split
data_farmer.rs
::get_simple_byte_values, }; use regex::Regex; pub type TimeOffset = f64; pub type Value = f64; #[derive(Debug, Default)] pub struct TimedData { pub rx_data: Value, pub tx_data: Value, pub cpu_data: Vec<Value>, pub mem_data: Value, pub swap_data: Value, } /// AppCollection represents the pooled d...
else { 0.0 }; // In addition copy over latest data for easy reference self.network_harvest = network.clone(); } fn eat_cpu(&mut self, cpu: &[cpu::CpuData], new_entry: &mut TimedData) { trace!("Eating CPU."); // Note this only pre-calculates the data points ...
{ (network.tx as f64).log2() }
conditional_block
data_farmer.rs
::get_simple_byte_values, }; use regex::Regex; pub type TimeOffset = f64; pub type Value = f64; #[derive(Debug, Default)] pub struct TimedData { pub rx_data: Value, pub tx_data: Value, pub cpu_data: Vec<Value>, pub mem_data: Value, pub swap_data: Value, } /// AppCollection represents the pooled d...
fn default() -> Self { DataCollection { current_instant: Instant::now(), frozen_instant: None, timed_data_vec: Vec::default(), network_harvest: network::NetworkHarvest::default(), memory_harvest: mem::MemHarvest::default(), swap_harvest...
} impl Default for DataCollection {
random_line_split
data_farmer.rs
::get_simple_byte_values, }; use regex::Regex; pub type TimeOffset = f64; pub type Value = f64; #[derive(Debug, Default)] pub struct
{ pub rx_data: Value, pub tx_data: Value, pub cpu_data: Vec<Value>, pub mem_data: Value, pub swap_data: Value, } /// AppCollection represents the pooled data stored within the main app /// thread. Basically stores a (occasionally cleaned) record of the data /// collected, and what is needed to co...
TimedData
identifier_name
data_farmer.rs
get_simple_byte_values, }; use regex::Regex; pub type TimeOffset = f64; pub type Value = f64; #[derive(Debug, Default)] pub struct TimedData { pub rx_data: Value, pub tx_data: Value, pub cpu_data: Vec<Value>, pub mem_data: Value, pub swap_data: Value, } /// AppCollection represents the pooled dat...
pub fn set_frozen_time(&mut self) { self.frozen_instant = Some(self.current_instant); } pub fn clean_data(&mut self, max_time_millis: u64) { trace!("Cleaning data."); let current_time = Instant::now(); let mut remove_index = 0; for entry in &self.timed_data_vec { ...
{ self.timed_data_vec = Vec::default(); self.network_harvest = network::NetworkHarvest::default(); self.memory_harvest = mem::MemHarvest::default(); self.swap_harvest = mem::MemHarvest::default(); self.cpu_harvest = cpu::CpuHarvest::default(); self.process_harvest = Vec::...
identifier_body
lib.rs
<X>(a: X, b: X) -> X where X: PrimInt + Integer + Signed, { let GcdData { gcd, .. } = extended_gcd__inline(a, b); gcd } /// Compute a least common multiple. pub fn lcm<X>(a: X, b: X) -> X where X: PrimInt + Integer + Signed, { let GcdData { lcm, .. } = extended_gcd__inline(a, b); lcm } /// Compute a modular mul...
gcd
identifier_name
lib.rs
: X) -> X where X: PrimInt + Integer + Signed, { let GcdData { gcd, .. } = extended_gcd__inline(a, b); gcd } /// Compute a least common multiple. pub fn lcm<X>(a: X, b: X) -> X where X: PrimInt + Integer + Signed, { let GcdData { lcm, .. } = extended_gcd__inline(a, b); lcm } /// Compute a modular multiplicative...
else { Some(upper - One::one()) }, Upto(max) => if min > max { None } else { Some(max) }, } } } #[test] fn test_inclusive_limit_from() { assert_eq!(Upto(4).inclusive_limit_from(3), Some(4)); assert_eq!(Upto(3).inclusive_limit_from(3), Some(3)); assert_eq!(Upto(2).inclusive_limit_from(3), None); assert_eq...
{ None }
conditional_block
lib.rs
: X) -> X where X: PrimInt + Integer + Signed,
/// Compute a least common multiple. pub fn lcm<X>(a: X, b: X) -> X where X: PrimInt + Integer + Signed, { let GcdData { lcm, .. } = extended_gcd__inline(a, b); lcm } /// Compute a modular multiplicative inverse, if it exists. /// /// This implementation uses the extended Gcd algorithm, pub fn inverse_mod<X>(a: X...
{ let GcdData { gcd, .. } = extended_gcd__inline(a, b); gcd }
identifier_body
lib.rs
a2.div_rem(&g); if a1rem != a2rem { None } else { let a3 = (a2div*c1*n1 + a1div*c2*n2 + a1rem).mod_floor(&n3); Some((a3, n3)) } } // used for conversions of literals (which will clearly never fail) fn lit<X>(x: i64) -> X where X: PrimInt { X::from(x).unwrap() } // slightly more verbose for use outside mathemat...
random_line_split
main.rs
fn print_current(last_secs: &mut u32, cur_secs: f32, total_secs: f32) { let secs = cur_secs.trunc() as u32; if *last_secs == secs { return; } *last_secs = secs; print!("\r"); print_time(secs); print!(" -> "); print_time((total_secs - cur_secs).trunc() as u32); stdout().flus...
{ let hours = secs / 3600; let minutes = (secs % 3600) / 60; let secs = secs % 60; if hours != 0 { print!("{hours}:{minutes:02}:{secs:02}"); } else { print!("{minutes:02}:{secs:02}"); } }
identifier_body
main.rs
+ MulNorm + 'static + std::fmt::Debug, S: FromSample<SD> + AudioSample + cpal::SizedSample { let Args { volume, repeat, channels: channel_map, mode, track, hpass, lpass, .. } = args; log::debug!("Repeat: {repeat}, volume: {volume}%"); let ampl_level = amplitude_level(args.volume); log::trace...
parse_stream_config
identifier_name
main.rs
frame fits into the sample buffer */ buf.resize(frame_sample_count * channels, S::silence()); render_audio(&mut bandlim, buf); }); /* send a rendered sample buffer to the consumer */ audio.producer.send_frame().unwrap(); if finished { log::info!("Fi...
ChannelMode::Channel(channel) }
random_line_split
component.py
{} on " "topic {}".format(rpc_id, rpc_method, self.target.topic)) rpc = self.RPC.query.one(rpc_id) return rpc def cast(self, ctxt, method, args): """Asynchronous Call""" rpc = self.RPC(action=self.RPC.CAST, ctxt=ctxt, method=method, args...
random_line_split
component.py
.'), ] CONF.register_opts(MESSAGING_SERVER_OPTS, group='messaging_server') # Some class/method descriptions taken from this Oslo Messaging # RPC API Tutorial/Demo: https://www.youtube.com/watch?v=Bf4gkeoBzvA RPCSVRNAME = "Music-RPC Server" class Target(object): """Returns a messaging target. A target enca...
def _flush_enqueued(self): """Flush all messages with an enqueued status. Use this only when the parent service is not running concurrently. """ msgs = self.RPC.query.all() for msg in msgs: if msg.enqueued: if 'plan_name' in list(msg.ctxt.keys(...
self._flush_enqueued()
conditional_block
component.py
.'), ] CONF.register_opts(MESSAGING_SERVER_OPTS, group='messaging_server') # Some class/method descriptions taken from this Oslo Messaging # RPC API Tutorial/Demo: https://www.youtube.com/watch?v=Bf4gkeoBzvA RPCSVRNAME = "Music-RPC Server" class Target(object): """Returns a messaging target. A target enca...
(self, topic): """Set the topic and topic class""" self._topic = topic # Because this is Music-specific, the server is # built-in to the API class, stored as the transport. # Thus, unlike oslo.messaging, there is no server # specified for a target. There also isn't an ...
__init__
identifier_name
component.py
out at {} seconds"). format(rpc_id, topic, self.conf.messaging_server.response_timeout)) elif not rpc.ok: LOG.error(_LE("Message {} on topic {} returned an error"). format(rpc_id, topic)) response = rpc.response ...
"""Run""" # The server listens for messages and calls the # appropriate methods. It also deletes messages once # processed. if self.conf.messaging_server.debug: LOG.debug("%s" % self.__class__.__name__) # Listen for messages within a thread executor = futuris...
identifier_body
mod.rs
world.get_resource::<RenderResources>().unwrap(); let vertex_shader = Shader::from_glsl(ShaderStage::Vertex, include_str!("pbr.vert")) .get_spirv_shader(None) .unwrap(); let fragment_shader = Shader::from_glsl(ShaderStage::Fragment, include_str!("pbr.frag")) .get_spi...
} commands.insert_resource(ExtractedMeshes { meshes: extracted_meshes, }); } #[derive(Default)] pub struct MeshMeta { transform_uniforms: DynamicUniformVec<Mat4>, } pub fn prepare_meshes( render_resources: Res<RenderResources>, mut mesh_meta: ResMut<MeshMeta>, mut extracted_meshe...
{ if let Some(gpu_data) = &mesh.gpu_data() { extracted_meshes.push(ExtractedMesh { transform: transform.compute_matrix(), vertex_buffer: gpu_data.vertex_buffer, index_info: gpu_data.index_buffer.map(|i| IndexInfo { ...
conditional_block
mod.rs
Float32x3, offset: 12, shader_location: 0, }, VertexAttribute { name: "Vertex_Normals".into(), format: VertexFormat::Float32x3, offset: 0, shader_location: 1, ...
{ Self { params: SystemState::new(world), } }
identifier_body
mod.rs
br.vert")) .get_spirv_shader(None) .unwrap(); let fragment_shader = Shader::from_glsl(ShaderStage::Fragment, include_str!("pbr.frag")) .get_spirv_shader(None) .unwrap(); let vertex_layout = vertex_shader.reflect_layout(&Default::default()).unwrap(); ...
fn run( &self,
random_line_split
mod.rs
include_str!("pbr.vert")) .get_spirv_shader(None) .unwrap(); let fragment_shader = Shader::from_glsl(ShaderStage::Fragment, include_str!("pbr.frag")) .get_spirv_shader(None) .unwrap(); let vertex_layout = vertex_shader.reflect_layout(&Default::default())...
run
identifier_name
kafka_scaler.go
(config *ScalerConfig) (Scaler, error) { metricType, err := GetMetricTargetType(config) if err != nil { return nil, fmt.Errorf("error getting scaler metric type: %w", err) } logger := InitializeLogger(config, "kafka_scaler") kafkaMetadata, err := parseKafkaMetadata(config, logger) if err != nil { return nil...
NewKafkaScaler
identifier_name
kafka_scaler.go
enableTLS = true case stringDisable: enableTLS = false default: return fmt.Errorf("error incorrect TLS value given, got %s", val) } } if enableTLS { certGiven := config.AuthParams["cert"] != "" keyGiven := config.AuthParams["key"] != "" if certGiven && !keyGiven { return errors.New("key must be ...
{ var topicsToDescribe = make([]string, 0) // when no topic is specified, query to cg group to fetch all subscribed topics if s.metadata.topic == "" { listCGOffsetResponse, err := s.admin.ListConsumerGroupOffsets(s.metadata.group, nil) if err != nil { return nil, fmt.Errorf("error listing cg offset: %w", err...
identifier_body
kafka_scaler.go
Bearer extension, must be of format key=value") } meta.oauthExtensions[splittedExtension[0]] = splittedExtension[1] } } } } else { return fmt.Errorf("err SASL mode %s given", mode) } } meta.enableTLS = false enableTLS := false if val, ok := config.TriggerMetadata["tls"]; ok { switc...
meta.scalerIndex = config.ScalerIndex return meta, nil } func getKafkaClients(metadata kafkaMetadata) (sarama.Client, sarama.ClusterAdmin, error) { config := sarama.NewConfig() config.Version = metadata.version if metadata.saslType != KafkaSASLTypeNone { config.Net.SASL.Enable = true config.Net.SASL.User = ...
{ val = strings.TrimSpace(val) version, err := sarama.ParseKafkaVersion(val) if err != nil { return meta, fmt.Errorf("error parsing kafka version: %w", err) } meta.version = version }
conditional_block
kafka_scaler.go
listing cg offset: %w", listCGOffsetResponse.Err) s.logger.Error(errMsg, "") } for topicName := range listCGOffsetResponse.Blocks { topicsToDescribe = append(topicsToDescribe, topicName) } } else { topicsToDescribe = []string{s.metadata.topic} } topicsMetadata, err := s.admin.DescribeTopics(topicsTo...
}
random_line_split
auto.go
_update() if play { glog.Warningln("WITH PLAY MODE") } else { p.Merge(true, store) } atomic.StoreInt32(&p.loaded, 2) return true } func (p *Stock) days_download(t time.Time) ([]int, error) { inds := []int{} tds, err := robot.Days_download(p.Id, t) if err != nil { return inds, err } for i, count := 0, ...
s.Split(line, []byte(",")) if len(infos) < 33 { glog.Warningln("sina hq api, res format changed") return false } p.Name = string(infos[0]) nul := []byte("") tick := RealtimeTick{} t, _ := time.Parse("2006-01-02", string(infos[30])) tick.FromString(t, infos[31], infos[3], nul, infos[8], infos[9], nul) tick....
identifier_body
auto.go
*Stocks) Chan(ch chan *Stock) { p.ch = ch } func (p *Stocks) res(stock *Stock) { if p.ch != nil { p.ch <- stock } } func (p *Stocks) update(s *Stock) { if s.Update(p.store, p.play > minPlay) { p.res(s) } } func (p *Stocks) Insert(id string) (int, *Stock, bool) { p.rwmutex.RLock() i, ok := p.stocks.Search...
(t time.Time) ([]int, error) { inds := []int
days_download
identifier_name
auto.go
*Stocks) Chan(ch chan *Stock) { p.ch = ch } func (p *Stocks) res(stock *Stock) { if p.ch != nil { p.ch <- stock } } func (p *Stocks) update(s *Stock) { if s.Update(p.store, p.play > minPlay) { p.res(s) } } func (p *Stocks) Insert(id string) (int, *Stock, bool) { p.rwmutex.RLock() i, ok := p.stocks.Search...
for _, line := range bytes.Split(body, []byte("\";")) { line = bytes.TrimSpace(line) info := bytes.Split(line, []byte("=\"")) if len(info) != 2 { continue } prefix := "var hq_str_" if !bytes.HasPrefix(info[0], []byte(prefix)) { continue } id := info[0][len(prefix):] if i...
return }
random_line_split
auto.go
) Insert(id string) (int, *Stock, bool) { p.rwmutex.RLock() i, ok := p.stocks.Search(id) if ok { s := p.stocks[i] p.rwmutex.RUnlock() if atomic.AddInt32(&s.count, 1) < 1 { atomic.StoreInt32(&s.count, 1) } return i, s, false } s := NewStock(id, p.min_hub_height) p.rwmutex.RUnlock() p.rwmutex.Lock()...
{ inds = append(inds, ind) }
conditional_block
mod.rs
//! os_queue.register(&mut stream, event::Id(0), TcpStream::INTERESTS, RegisterOption::EDGE)?; //! # Ok(()) //! # } //! ``` //! //! ### Timeout granularity //! //! The timeout provided to [`event::Source::blocking_poll`] will be rounded //! up to the system clock granularity (usually 1ms), and kernel scheduling //!...
/// e.g. read or write. /// /// To use this queue an [`Evented`] handle must first be registered using the /// [`register`] method, supplying an associated id, readiness interests and /// polling option. The [associated id] is used to associate a readiness event /// with an `Evented` handle. The readiness [interests] d...
/// /// This queue allows a program to monitor a large number of [`Evented`] /// handles, waiting until one or more become "ready" for some class of /// operations; e.g. [reading] or [writing]. An [`Evented`] type is considered /// ready if it is possible to immediately perform a corresponding operation;
random_line_split
mod.rs
interest for that type, e.g. [`TcpStream` /// interests] are readable and writable. /// /// `opt`: Specifies the registration option. Just like the interests and /// id, the option can be changed for an `Evented` handle at any time by /// calling [`reregister`]. /// /// [`poll`]: crate::pol...
{ &self.selector }
identifier_body
mod.rs
//! os_queue.register(&mut stream, event::Id(0), TcpStream::INTERESTS, RegisterOption::EDGE)?; //! # Ok(()) //! # } //! ``` //! //! ### Timeout granularity //! //! The timeout provided to [`event::Source::blocking_poll`] will be rounded //! up to the system clock granularity (usually 1ms), and kernel scheduling //!...
{ selector: sys::Selector, } impl OsQueue { /// Create a new OS backed readiness event queue. /// /// This function will make a syscall to the operating system to create the /// system selector. If this syscall fails it will return the error. /// /// # Examples /// /// ``` /// ...
OsQueue
identifier_name
data-enums.ts
auna', } export enum CharacterDetail { Age = 'age', Aliases = 'aliases', Background = 'background', Career = 'career', Faction = 'faction', Gender = 'gender', Interest = 'interest', Languages = 'languages', } export enum AptitudeType { Cognition = 'cog', Intuition = 'int', Reflexes = 'ref', Sa...
export enum ExplosiveType { Grenade = 'grenade', Missile = 'missile', Generic = 'generic', } export enum AreaEffectType { Uniform = 'uniform', Centered = 'centered', Cone = 'cone', } export enum CalledShot { BypassArmor = 'bypassArmor', Disarm = 'disarm', Knockdown = 'knockdown', Redirect = 'redi...
Standard = 'standard', }
random_line_split
data-enums.ts
return existing; }; export enum Fork { Alpha = 'alpha', Beta = 'beta', Gamma = 'gamma', } export enum ThreatInfo { Classification = 'classification', Niche = 'niche', Numbers = 'numbers', StressValue = 'stressValue', MinStressValue = 'minStressValue', ThreatLevel = 'threatLevel', } export enum T...
{ existing = Object.freeze(Object.values(o)); valuedEnums.set(o, existing); }
conditional_block
config.go
" configRootKubernetes = "kubernetes" configRootManifest = "manifest" configRootGo = "go" configRootGenerate = "generate" configRootResources = "resources" configRootAssemblies = "assemblies" configRootBinaries = "artifactory" // bootstrap.yml configRootAppInfo = "info.app" configRootServer =...
() string { return strconv.Itoa(p.Server.Port) } func (p Config) OutputConfigPath() string { return path.Join(configOutputRootPath, p.Fs.Root, p.Fs.Configs) } func (p Config) OutputResourcesPath() string { return path.Join(configOutputRootPath, p.Fs.Root, p.Fs.Resources) } func (p Config) OutputBinaryPath() strin...
Port
identifier_name
config.go
" configRootKubernetes = "kubernetes" configRootManifest = "manifest" configRootGo = "go" configRootGenerate = "generate" configRootResources = "resources" configRootAssemblies = "assemblies" configRootBinaries = "artifactory" // bootstrap.yml configRootAppInfo = "info.app" configRootServer =...
func (p Config) OutputRoot() string { return configOutputRootPath } func (p Config) TestPath() string { return configTestPath } func (p Config) AssemblyPath() string { return configAssemblyPath } func (p Config) InputCommandRoot() string { return path.Join("cmd", p.Executable.Cmd) } func (p Config) Port() str...
{ return fmt.Sprintf("%s-%s", p.Msx.Release, p.Build.Number) }
identifier_body
config.go
docker" configRootKubernetes = "kubernetes" configRootManifest = "manifest" configRootGo = "go" configRootGenerate = "generate" configRootResources = "resources" configRootAssemblies = "assemblies" configRootBinaries = "artifactory" // bootstrap.yml configRootAppInfo = "info.app" configRootSer...
_ = cfg.Load(ctx) } if err = cfg.Populate(&BuildConfig.Server, configRootServer); err != nil { return } if err = cfg.Populate(&BuildConfig.Docker, configRootDocker); err != nil { return } if err = cfg.Populate(&BuildConfig.Kubernetes, configRoot
if springAppName == "build" { defaultConfigs["spring.application.name"] = BuildConfig.App.Name
random_line_split
config.go
" configRootKubernetes = "kubernetes" configRootManifest = "manifest" configRootGo = "go" configRootGenerate = "generate" configRootResources = "resources" configRootAssemblies = "assemblies" configRootBinaries = "artifactory" // bootstrap.yml configRootAppInfo = "info.app" configRootServer =...
// Set the spring app name if it is not set springAppName, _ := cfg.StringOr("spring.application.name", "build") if springAppName == "build" { defaultConfigs["spring.application.name"] = BuildConfig.App.Name _ = cfg.Load(ctx) } if err = cfg.Populate(&BuildConfig.Server, configRootServer); err != nil { ret...
{ return }
conditional_block
scan.go
repo is empty", repo.Name) } // load up alternative config if possible, if not use manager's config if repo.Manager.Opts.RepoConfig
scanTimeStart := time.Now() // See https://github.com/zricethezav/gitleaks/issues/326 // Scan commit patches, all files at a commit, or a range of commits if repo.Manager.Opts.Commit != "" { return scanCommit(repo.Manager.Opts.Commit, repo, scanCommitPatches) } else if repo.Manager.Opts.FilesAtCommit != "" { ...
{ cfg, err := repo.loadRepoConfig() if err != nil { return err } repo.config = cfg }
conditional_block
scan.go
}() if repo.timeoutReached() { return nil } if parent == nil { // shouldn't reach this point but just in case return nil } start := time.Now() patch, err := parent.Patch(c) if err != nil { log.Errorf("could not generate Patch") } repo.Manager.RecordTime(manager.PatchTime(howLong(start)))...
scanFilesAtCommit
identifier_name
scan.go
scanTimeStart := time.Now() // See https://github.com/zricethezav/gitleaks/issues/326 // Scan commit patches, all files at a commit, or a range of commits if repo.Manager.Opts.Commit != "" { return scanCommit(repo.Manager.Opts.Commit, repo, scanCommitPatches) } else if repo.Manager.Opts.FilesAtCommit != "" { ...
{ if err := repo.setupTimeout(); err != nil { return err } if repo.cancel != nil { defer repo.cancel() } if repo.Repository == nil { return fmt.Errorf("%s repo is empty", repo.Name) } // load up alternative config if possible, if not use manager's config if repo.Manager.Opts.RepoConfig { cfg, err := r...
identifier_body
scan.go
s repo is empty", repo.Name) } // load up alternative config if possible, if not use manager's config if repo.Manager.Opts.RepoConfig { cfg, err := repo.loadRepoConfig() if err != nil { return err } repo.config = cfg } scanTimeStart := time.Now() // See https://github.com/zricethezav/gitleaks/issues...
wg.Done() }() scanPatch(patch, c, repo) }(c, patch) if c.Hash.String() == repo.Manager.Opts.CommitTo { return storer.ErrStop } return nil }) wg.Wait() repo.Manager.RecordTime(manager.ScanTime(howLong(scanTimeStart))) repo.Manager.IncrementCommits(cc) return nil } // scanEmpty scans an empty...
go func(c *object.Commit, patch *object.Patch) { defer func() { <-semaphore
random_line_split
main.go
}, }) // Initialize twitch notification listener diBuilder.Add(di.Def{ Name: static.DiTwitchNotifyListener, Build: func(ctn di.Container) (interface{}, error) { return listeners.NewListenerTwitchNotify(ctn), nil }, Close: func(obj interface{}) error { listener := obj.(*listeners.ListenerTwitchNotify)...
{ f, err := os.Create(profLoc) if err != nil { logrus.WithError(err).Fatal("failed starting profiler") } pprof.StartCPUProfile(f) logrus.WithField("location", profLoc).Warning("CPU profiling is active") defer pprof.StopCPUProfile() }
identifier_body
main.go
.com/zekroTJA/shinpuru/pkg/startuptime" "github.com/zekroTJA/shireikan" "github.com/zekroTJA/shinpuru/pkg/angularservice" ) var ( flagConfig = flag.String("c", "config.yml", "The location of the main config file") flagDocker = flag.Bool("docker", false, "wether shinpuru is running in a docker container or...
}) // Initialize auth refresh token handler diBuilder.Add(di.Def{ Name: static.DiAuthRefreshTokenHandler, Build: func(ctn di.Container) (interface{}, error) { return auth.NewDatabaseRefreshTokenHandler(ctn), nil }, }) // Initialize auth access token handler diBuilder.Add(di.Def{ Name: static.DiAuthAc...
random_line_split
main.go
.com/zekroTJA/shinpuru/pkg/startuptime" "github.com/zekroTJA/shireikan" "github.com/zekroTJA/shinpuru/pkg/angularservice" ) var ( flagConfig = flag.String("c", "config.yml", "The location of the main config file") flagDocker = flag.Bool("docker", false, "wether shinpuru is running in a docker container or...
() { // Parse command line flags flag.Parse() if !*flagQuiet { startupmsg.Output(os.Stdout) } // Initialize dependency injection builder diBuilder, _ := di.NewBuilder() // Setup config parser diBuilder.Add(di.Def{ Name: static.DiConfigParser, Build: func(ctn di.Container) (p interface{}, err error) { ...
main
identifier_name
main.go
/zekroTJA/shinpuru/pkg/startuptime" "github.com/zekroTJA/shireikan" "github.com/zekroTJA/shinpuru/pkg/angularservice" ) var ( flagConfig = flag.String("c", "config.yml", "The location of the main config file") flagDocker = flag.Bool("docker", false, "wether shinpuru is running in a docker container or not...
// Initialize dependency injection builder diBuilder, _ := di.NewBuilder() // Setup config parser diBuilder.Add(di.Def{ Name: static.DiConfigParser, Build: func(ctn di.Container) (p interface{}, err error) { ext := strings.ToLower(filepath.Ext(*flagConfig)) switch ext { case ".yml", ".yaml": p =...
{ startupmsg.Output(os.Stdout) }
conditional_block
server_http_response.go
copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NO...
(statusCode int, headers Header, body interface{}, bytes []byte) { contentTypePresent := false if headers != nil { for _, k := range headers.Keys() { v, ok := headers.Get(k) if ok { if k == "Content-Type" { contentTypePresent = true } res.responseWriter.Header().Set(k, v) } } } // Set...
SendResponse
identifier_name
server_http_response.go
copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NO...
return value, valueType, nil } // Flush will write the body to the response. Before flush is called // the body is pending. A pending body allows a response middleware to // write a different body. func (res *ServerHTTPResponse) flush(ctx context.Context) { if res.flushed { /* coverage ignore next line */ res....
{ return nil, -1, err }
conditional_block
server_http_response.go
flushed bool finished bool finishTime time.Time DownstreamFinishTime time.Duration ClientType string pendingBodyBytes []byte pendingBodyObj interface{} pendingStatusCode int contextLogger ContextLogger scope tally.Scope jsonWrapp...
{ return res.pendingBodyObj }
identifier_body
server_http_response.go
" "go.uber.org/zap/zapcore" ) // ServerHTTPResponse struct manages server http response type ServerHTTPResponse struct { Request *ServerHTTPRequest StatusCode int responseWriter http.ResponseWriter flushed bool finished bool finishTime time.Time D...
// which isn't sent back yet. func (res *ServerHTTPResponse) GetPendingResponse() ([]byte, int) { return res.pendingBodyBytes, res.pendingStatusCode }
random_line_split
push_service.go
ps.doSenderClose: close(ps.sentQueue) return case messages := <-mainSendingMessage: logdebug("Sending new message: %d to %s", messages.id, messages.DeviceToken) data, err := createBinaryNotification(messages, messages.id, messages.DeviceToken) if err != nil { messages.SetStatus(err, true) break...
//mark all as failed if finishMessage.unknownMessage { messageList.SetAllFailed(fmt.Errorf("Unknown error response from apple, all failed")) logdebug("All messages are marked as error :%p", ps) break } //mark all from front to the id as success if finishMessage.status == 0 { messageLis...
{ messageList.SetLastFailed(fmt.Errorf("Unknow error after last message sent")) logdebug("Going to remove last message from queue with error: %p", ps) break }
conditional_block
push_service.go
from the queue ps.lastError = fmt.Errorf("Unknow apple message (%s) socket will be closed", hex.EncodeToString(readb[:n])) ps.confirmedQueue <- &apnsReceiveMessage{unknownMessage: true} ps.doSenderClose <- true close(ps.confirmedQueue) break } } } func (ps *pushService) monitorMessages() { defer fu...
Config() (expiration uint32, priority uint8) } func statusToError(status uint8) error { e, ok := appleErrorMap[status]
random_line_split
push_service.go
if err != nil { ps.lastError = nil pushPool.releasedServices <- ps close(ps.sentQueue) return } logdebug("Message id: %d sent", messages.id) ps.sentQueue <- messages pushPool.reportQueue <- &notifReport{sent: 1} } } } func (ps *pushService) monitorReply() { defer func() { ps.waitClos...
SetSuccessOlder
identifier_name
push_service.go
to send the payload) - close socket // if status number unknown ???? (ok, let's retry to send the payload) - close socket status := readb[1] id := binary.BigEndian.Uint32(readb[2:]) ps.confirmedQueue <- &apnsReceiveMessage{status: status, id: id} logdebug("Received confirmation for id: %d with status...
{ var next *list.Element logdebug("Set message %d to status failed permanent: %t (%s)", id, permanentError, err) for e := amq.mList.Front(); e != nil; e = next { next = e.Next() message := e.Value.(*ApnsMessage) amq.mList.Remove(e) if message.id == id { message.SetStatus(err, permanentError) return...
identifier_body
view_test.go
); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.Compilers.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.Settings.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } } func (e *TestEnv) CreateUserRoles(login string, roles ...string) error { for _, role := range roles { ...
func NewTestUser(e *TestEnv) *TestUser { login := fmt.Sprintf("login-%d", e.Rand.Int31()) password := fmt.Sprintf("password-%d", e.Rand.Int63()) user, err := e.Client.Register(context.Background(), RegisterUserForm{ Login: login, Email: login + "@example.com", Password: password, FirstName: "F...
{ if err := u.env.CreateUserRoles(u.User.Login, names...); err != nil { u.env.tb.Fatal("Error:", err) } u.env.SyncStores() }
identifier_body
view_test.go
if err := e.Core.Sessions.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.Roles.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.RoleEdges.Sync(ctx); err != nil { e.tb.Fatal("Error:", err) } if err := e.Core.AccountRoles.Sync(ctx); err != nil { e.tb.Fatal("Error:...
{ e.tb.Fatal("Error:", err) }
conditional_block