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
ExportGltf.ts
const pbrMetallicRoughness: GltfMaterialPbrMetallicRoughness = { baseColorTexture: { index: GltfGlobals.gltf.textures.length - 1 }, baseColorFactor: [1, 1, 1, 1], metallicFactor: 0, roughnessFactor: 1, }; const material: GltfMaterial = ({ pbrMetallicRoughness, doubleSided: true }); resu...
{ let result = GltfGlobals.textureToMaterialMap.get(textureId); if (result !== undefined) return result; // glTF-Validator complains if textures/images are defined but empty - wait for texture to define. if (GltfGlobals.gltf.textures === undefined) { GltfGlobals.gltf.textures = []; GltfGlobals.g...
identifier_body
ExportGltf.ts
.data, () => { }); // async is fine const texture: GltfTexture = { source: GltfGlobals.gltf.images!.length, sampler: 0 }; GltfGlobals.gltf.textures.push(texture); GltfGlobals.gltf.images!.push({ uri: textureName }); const pbrMetallicRoughness: GltfMaterialPbrMetallicRoughness = { baseColorTexture: ...
findOrAddMaterialIndexForColor(color); const primitive: GltfMeshPrimitive = { mode: MeshPrimitiveMode.GlTriangles, material, indices: GltfGlobals.gltf.accessors.length, attributes: { // eslint-disable-next-line @typescript-eslint/naming-convention POSITION: GltfGlobals.gltf.ac...
function addMesh(mesh: ExportGraphicsMesh, color: number, textureId?: Id64String) { const material = textureId !== undefined ? findOrAddMaterialIndexForTexture(textureId) :
random_line_split
v2.py
from PyQt4.QtGui import * from PyQt4.QtCore import * import txt2csv as t2csv import glob, os, re from measurements import perform_filter OWNER = 'rn' try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def...
# # WARNING! All changes made in this file will be lost! import os, sys from PyQt4 import QtCore, QtGui
random_line_split
v2.py
return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, te...
(self, profileDialog): profileDialog.setWindowTitle(_translate("profileDialog", "Dialog", None)) self.profilebtn1.setText(_translate("profileDialog", "profile", None)) self.label.setText(_translate("profileDialog", "Host Name", None)) self.statusLabel.setText(_translate("profileDialog", ...
retranslateUi
identifier_name
v2.py
return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, te...
self.choice_icmp.setChecked(True) self.choice_tcp = QtGui.QRadioButton(profileDialog) self.choice_tcp.setGeometry(QtCore.QRect(330, 100, 198, 27)) self.choice_tcp.setObjectName(_fromUtf8("choice_tcp")) self.label = QtGui.QLabel(profileDialog) self.label.setGeometry(QtCo...
profileDialog.setObjectName(_fromUtf8("profileDialog")) profileDialog.resize(492, 428) profileDialog.setContextMenuPolicy(QtCore.Qt.DefaultContextMenu) profileDialog.setAutoFillBackground(True) self.buttonBox = QtGui.QDialogButtonBox(profileDialog) self.buttonBox.setGeometry(QtCo...
identifier_body
v2.py
return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) except AttributeError: def _translate(context, text, disambig): return QtGui.QApplication.translate(context, te...
elif txt == 4 or txt == 99: return "99;99" def msgbtn(self): self.pushButton_2.setEnabled(True) txt_index = self.cmbUsage.currentIndex() txt = self.assign_details(txt_index) host = self.hostText.toPlainText() usage = txt.split(';')[0] task_cycle ...
return "70;20"
conditional_block
forminput.js
(function() { $.ajax({ type: "GET", url: "http://localhost:3000/", success: function(data) { //select what should be shown if (data != false) { if (show == true) { graphShow(data) } else { chartSh...
function dragended(d) { if (!d3.event.active) simulation.alphaTarget(0); d.fx = null; d.fy = null; } var mouseover_node = function(z) { var neighbors = {}; neighbors[z.index] = true; link.filter(function(d) { if (d.source == z) { ...
{ d.fx = d3.event.x; d.fy = d3.event.y; }
identifier_body
forminput.js
setInterval(function() { $.ajax({ type: "GET", url: "http://localhost:3000/", success: function(data) { //select what should be shown if (data != false) { if (show == true) { graphShow(data) } el...
() { var g = d3.selectAll(".container"); g.attr("transform", d3.event.transform); } function ticked() { link.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy);...
zoomed
identifier_name
forminput.js
setInterval(function() { $.ajax({ type: "GET", url: "http://localhost:3000/", success: function(data) { //select what should be shown if (data != false) { if (show == true) { graphShow(data) } el...
else if (d == "cd") { return "cardinal digit" } else return d }); function zoomed() { var g = d3.selectAll(".container"); g.attr("transform", d3.event.transform); } function ticked() { link.attr("d", function(d) { var dx = d.tar...
{ return "preposition/subordinating conjunction" }
conditional_block
forminput.js
("y", 0) .attr("dy", ".35em") .attr("stroke", "black") .style("text-anchor", "start") .text(function(d) { if (d == "nn") { return "noun, singular" } else if (d == "nns") { return "noun, plural" } else if (d == "vbg") { ...
random_line_split
supervisor_processor.go
runnable has died. type processorRequestDied struct { dn string err error } type processorRequestWaitSettled struct { waiter chan struct{} } // processor is the main processing loop. func (s *supervisor) processor(ctx context.Context) { s.ilogger.Info("supervisor processor started") // Waiters waiting for the...
// Simple case: the context was canceled and the returned error is the context error. if err := ctx.Err(); err != nil && perr == err { // Mark the node as canceled successfully. n.state = nodeStateCanceled return } // Otherwise, the Runnable should not have died or quit. Handle accordingly. err := r.err ...
{ if inner := errors.Unwrap(perr); inner != nil { perr = inner continue } break }
conditional_block
supervisor_processor.go
runnable has died. type processorRequestDied struct { dn string err error } type processorRequestWaitSettled struct { waiter chan struct{} } // processor is the main processing loop. func (s *supervisor) processor(ctx context.Context) { s.ilogger.Info("supervisor processor started") // Waiters waiting for the...
() { s.mu.Lock() defer s.mu.Unlock() // Gather all context cancel functions. var cancels []func() queue := []*node{s.root} for { if len(queue) == 0 { break } cur := queue[0] queue = queue[1:] cancels = append(cancels, cur.ctxC) for _, c := range cur.children { queue = append(queue, c) } } ...
processKill
identifier_name
supervisor_processor.go
runnable has died. type processorRequestDied struct { dn string err error } type processorRequestWaitSettled struct { waiter chan struct{} } // processor is the main processing loop. func (s *supervisor) processor(ctx context.Context) { s.ilogger.Info("supervisor processor started") // Waiters waiting for the...
n := s.nodeByDN(r.dn) ctx := n.ctx // Simple case: it was marked as Done and quit with no error. if n.state == nodeStateDone && r.err == nil { // Do nothing. This was supposed to happen. Keep the process as DONE. return } // Find innermost error to check if it's a context canceled error. perr := r.err for...
// Okay, so a Runnable has quit. What now?
random_line_split
supervisor_processor.go
runnable has died. type processorRequestDied struct { dn string err error } type processorRequestWaitSettled struct { waiter chan struct{} } // processor is the main processing loop. func (s *supervisor) processor(ctx context.Context)
for { select { case <-ctx.Done(): s.ilogger.Infof("supervisor processor exiting: %v", ctx.Err()) s.processKill() s.ilogger.Info("supervisor exited") return case <-gc.C: if !clean { s.processGC() } clean = true cleanCycles += 1 // This threshold is somewhat arbitrary. It's a balanc...
{ s.ilogger.Info("supervisor processor started") // Waiters waiting for the GC to be settled. var waiters []chan struct{} // The GC will run every millisecond if needed. Any time the processor requests a change in the supervision tree // (ie a death or a new runnable) it will mark the state as dirty and run the ...
identifier_body
ipc.rs
EventLoopHandle::spawn(move |handle| Self::with_event_loop(&path, &handle).map_err(Into::into)) } /// Create new IPC transport within existing Event Loop. /// /// IPC is only available on Unix. On other systems, this always returns an error. #[cfg(unix)] pub fn with_event_loop<P>(path: P, hand...
<T>(&self, requests: T) -> Self::Batch where T: IntoIterator<Item = (RequestId, rpc::Call)>, { let mut it = requests.into_iter(); let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None)); let requests = first.into_iter().chain(it.map(|x| x.1)).collect();...
send_batch
identifier_name
ipc.rs
EventLoopHandle::spawn(move |handle| Self::with_event_loop(&path, &handle).map_err(Into::into)) } /// Create new IPC transport within existing Event Loop. /// /// IPC is only available on Unix. On other systems, this always returns an error. #[cfg(unix)] pub fn with_event_loop<P>(path: P, hand...
else { log::warn!("Got unsupported response (id: {:?})", id); } } Message::
{ if let Some(request) = self.pending.lock().remove(&(num as usize)) { log::trace!("Responding to (id: {:?}) with {:?}", num, outputs); if let Err(err) = request.send(helpers::to_results_from_outputs(outputs)) { log::warn!("...
conditional_block
ipc.rs
EventLoopHandle::spawn(move |handle| Self::with_event_loop(&path, &handle).map_err(Into::into)) } /// Create new IPC transport within existing Event Loop. /// /// IPC is only available on Unix. On other systems, this always returns an error. #[cfg(unix)] pub fn with_event_loop<P>(path: P, hand...
fn unsubscribe(&self, id: &SubscriptionId) { self.subscriptions.lock().remove(id); } } enum WriteState { WaitingForRequest, Writing { buffer: Vec<u8>, current_pos: usize }, } /// Writing part of the IPC transport /// Awaits new requests using `mpsc::UnboundedReceiver` and writes them to the ...
{ let (tx, rx) = mpsc::unbounded(); if self.subscriptions.lock().insert(id.clone(), tx).is_some() { log::warn!("Replacing already-registered subscription with id {:?}", id) } Box::new(rx.map_err(|()| Error::Transport("No data available".into()))) }
identifier_body
ipc.rs
EventLoopHandle::spawn(move |handle| Self::with_event_loop(&path, &handle).map_err(Into::into)) } /// Create new IPC transport within existing Event Loop. /// /// IPC is only available on Unix. On other systems, this always returns an error. #[cfg(unix)] pub fn with_event_loop<P>(path: ...
let requests = first.into_iter().chain(it.map(|x| x.1)).collect(); self.send_request(id, rpc::Request::Batch(requests), Ok) } } impl DuplexTransport for Ipc { type NotificationStream = Box<dyn Stream<Item = rpc::Value, Error = Error> + Send + 'static>; fn subscribe(&self, id: &Subscription...
where T: IntoIterator<Item = (RequestId, rpc::Call)>, { let mut it = requests.into_iter(); let (id, first) = it.next().map(|x| (x.0, Some(x.1))).unwrap_or_else(|| (0, None));
random_line_split
map.js
ATELLITE_MAP: case BMAP_HYBRID_MAP: cL = ['<span style="' + cN + '">&copy; 2013 Baidu - Data &copy; ']; cL.push('<a target="_blank" href="http://www.navinfo.com/" style="' + cN + '">NavInfo</a> &amp; '); for (var cK in cR) { if (cR[cK] == cP) { cO = true; ...
{ return }
conditional_block
map.js
K)
aY(cK); cK.addEventListener("maptypechange", function () { aY(cK) }); cK.addControl(cL); var T = new b0(); T._opts = { printable: true }; cK.addControl(T); cK.addEventListener("resize", function () { if (this.getSize().width >= 220 && cK.getSize().h...
{ if (cK.temp.copyadded) { return } cK.temp.copyadded = true; var cM = new aG(81, 2); if (az()) { if (cK.highResolutionEnabled()) { cM.width = 148; fontSize = "21px" } else { cM.width = 72; cM.height = 0 } ...
identifier_body
map.js
K) { if (cK.temp.copyadded) { return } cK.temp.copyadded = true; var cM = new aG(81, 2); if (az()) { if (cK.highResolutionEnabled()) { cM.width = 148; fontSize = "21px" } else { cM.width = 72; cM.height = 0 ...
(T) { this.defaultAnchor = BMAP_ANCHOR_BOTTOM_LEFT; this.defaultOffset = new aG(1, 0); this.IMG_URL = cb.imgPath + (az() ? "copyright_logo_s.png" : "copyright_logo.png") } b0.prototype = new co(); b0.prototype.initialize = function (cK) { this._map = cK; var cL = Z("div"); cL.style.heig...
b0
identifier_name
map.js
(this.getSize().width >= 220 && cK.getSize().height >= 100) { T.show(); cL.setOffset(cM) } else { T.hide(); cL.setOffset(new aG(4, 2)) } }); if (cK.getSize().width >= 220 && cK.getSize().height >= 100) { T.show() } else { ...
var T = Math.round(this.width / 2);
random_line_split
GroupINN.py
classmethod def update_parser_argument(cls, parser: argparse.ArgumentParser): args, _ = parser.parse_known_args() parser.set_defaults(selected_model="gcn_classification_net") print("===> Selected model: GroupINN") group = parser.add_argument_group(title="GroupINN arguments") ...
# Define accuracy metric eval_metric_ops = { "metrics/accuracy": tf.metrics.accuracy( labels=labels, predictions=predictions["classes"]), "confusion_matrix/TP": tf.metrics.true_positives( labels=labels, predictions=predictions["classes"]), ...
tf.summary.scalar(loss_scalar.name, loss_scalar, family="loss")
conditional_block
GroupINN.py
: cross_entropy = 1.0 neg_penalty_reduce = 0.1 neg_penalty_gnn = 0.2 ortho_penalty_p = 0.2 ortho_penalty_n = 0.2 variance_penalty_p = 0.3 variance_penalty_n = 0.5 l2_penalty = 2e-3 @classmethod def update_parser_argument(cls, parser: argparse.Argu...
loss_weights
identifier_name
GroupINN.py
classmethod def update_parser_argument(cls, parser: argparse.ArgumentParser): args, _ = parser.parse_known_args() parser.set_defaults(selected_model="gcn_classification_net") print("===> Selected model: GroupINN") group = parser.add_argument_group(title="GroupINN arguments") ...
def model_fn(self, features, labels, mode:tf.estimator.ModeKeys, params): """ features: batch_features from input_fn labels: batch_labels from input_fn mode: An instance of tf.estimator.ModeKeys params: Additional configuration """ self.runtime_init(...
self.losses = [] self.is_training = (mode==tf.estimator.ModeKeys.TRAIN)
identifier_body
GroupINN.py
_model="gcn_classification_net") print("===> Selected model: GroupINN") group = parser.add_argument_group(title="GroupINN arguments") group.add_argument("--dropout_rate", default=0, type=float, help="(default: %(default)s)") group.add_argument("--c", default=0.85, type=float, help="(def...
labels=labels, predictions=predictions["classes"]), "confusion_matrix/FP": tf.metrics.false_positives( labels=labels, predictions=predictions["classes"]), "confusion_matrix/FN": tf.metrics.false_negatives( labels=labels, predictions=predictions["cl...
random_line_split
plot_TL_results.py
estimated / fitted poorly """ ret_list = [] for b in B: D = (A-b).reshape((2,2)) det = np.linalg.det(D) ret = 1 if det < 0 or D[0,0] < 0: ret = 0 ret_list.append(ret) return ret_list ## compare each number of secondary initpts ## to baseline with wilc...
(b_times, r_times, N = None, alpha = 0.1, method = mannwhitneyu): """ do wilxocon test to see if b_times - r_times median is less than 0 H0: it is """ if N is None: N = min([len(b_times), len(r_times)])*5 b = np.random.choice(b_times, size = N, replace = True) r = np.random.choice(r_...
indicator_loss
identifier_name
plot_TL_results.py
estimated / fitted poorly """ ret_list = [] for b in B: D = (A-b).reshape((2,2)) det = np.linalg.det(D) ret = 1 if det < 0 or D[0,0] < 0: ret = 0 ret_list.append(ret) return ret_list ## compare each number of secondary initpts ## to baseline with wilc...
convergence_time = exp['totaltime_to_gmp_convergence'][5] convergence_times.append([secondary_initpts, convergence_time]) # plot convergence_iterations = np.array(convergence_iterations, dtype = float) axs[0, i].scatter(convergence_iterations[:,0...
experiment = experiment_folders[i].copy() baseline = baseline_folders[i].copy() explist = baseline for exp in experiment: explist.append(exp) convergence_iterations = [] convergence_times = [] for exp in explist: if len(exp['initpts'])>1: ...
conditional_block
plot_TL_results.py
## compare each number of secondary initpts ## to baseline with wilcoxon 2 sample signed rank test to see ## when TL is faster than the baseline, also collect the lowest, ## highest, median and mean expected improvement and their secondary initpts def indicator_loss(b_times, r_times, N = None, alpha = 0.1, method ...
""" Return true, if A>=B where >= is loewner order (matrix comparison) if A>=B, A spans over B used to detect poor fits of coregionalization if [coregionalization matrix] > [measured covariance]is broken, covariance matrix is overestimated / fitted poorly """ ret_list = [] for b in...
identifier_body
plot_TL_results.py
overestimated / fitted poorly """ ret_list = [] for b in B: D = (A-b).reshape((2,2)) det = np.linalg.det(D) ret = 1 if det < 0 or D[0,0] < 0: ret = 0 ret_list.append(ret) return ret_list ## compare each number of secondary initpts ## to baseline with...
polyreg=make_pipeline(PolynomialFeatures(degree),LinearRegression()) polyreg.fit(x_train,y_train) x = np.unique(convergence_iterations[:,0]).reshape(-1,1) axs[0,i].set_xticks(x[::2]) y = polyreg.predict(x) axs[1, i].plot(x,y, color = 'red', label = 'trend', linewidth = 3...
cputime_max = max(clean_rows[:,1]) x_train = clean_rows[:,0].reshape(-1,1) y_train = clean_rows[:,1].reshape(-1,1) degree=1
random_line_split
mod.rs
meta_data_add_string(meta, c_key.as_ptr(), c_value.as_ptr()); } } MetaValue::SignedInt(i) => unsafe { meta_data_add_signed_int(meta, c_key.as_ptr(), *i); }, MetaValue::UnsignedInt(u) => unsafe { meta_data...
random_line_split
mod.rs
user", "system" metrics. pub plugin_instance: Option<&'a str>, /// This is the string found in types.db, determines how many values are expected and how they /// should be interpreted pub type_: &'a str, /// The type instance is used to separate values of identical type which nonetheless belong to...
/// The interval in which new values are to be expected. This is typically handled at a global /// or plugin level. Use at your own discretion. pub fn interval(mut self, interval: Duration) -> ValueListBuilder<'a> { self.list.interval = Some(interval); self } /// Add a metadata en...
{ self.list.time = Some(dt); self }
identifier_body
mod.rs
<'a> { /// Name of the metric. If values has a length of 1, this is often just "value" pub name: &'a str, /// The value reported pub value: Value, /// Minimum value seen in an interval pub min: f64, /// Maximum value seen in an interval pub max: f64, } /// Contains values and metadat...
ValueReport
identifier_name
input.ts
Down(e) }, { target: window, eventName: "mouseup", action: (e: MouseEvent) => onPotentialDoubleClick(e) }, { target: window, eventName: "wheel", action: (e: WheelEvent) => onWheelScroll(e), options: { passive: false } }, { target: window, eventName: "modifyinputfield", action: (e: CustomEvent) => onModifyInputFie...
} function onContextMenu(e: MouseEvent): void { if (!targetIsTextField(e.target || undefined) && e.target !== textToolInteractiveInputElement) { e.preventDefault(); } } // Receives a custom event dispatched when the user begins interactively editing with the text tool. //
{ e.preventDefault(); const modifiers = makeKeyboardModifiersBitfield(e); editor.instance.onWheelScroll(e.clientX, e.clientY, e.buttons, e.deltaX, e.deltaY, e.deltaZ, modifiers); }
conditional_block
input.ts
Down(e) }, { target: window, eventName: "mouseup", action: (e: MouseEvent) => onPotentialDoubleClick(e) }, { target: window, eventName: "wheel", action: (e: WheelEvent) => onWheelScroll(e), options: { passive: false } }, { target: window, eventName: "modifyinputfield", action: (e: CustomEvent) => onModifyInputFie...
// Pointer events // While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events and these are handled in the backend function onPointerMove(e: PointerEvent): void { if (!e.buttons) viewportPointerInteractionOngoing = false; // Don't red...
{ const key = await getLocalizedScanCode(e); if (await shouldRedirectKeyboardEventToBackend(e)) { e.preventDefault(); const modifiers = makeKeyboardModifiersBitfield(e); editor.instance.onKeyUp(key, modifiers, e.repeat); } }
identifier_body
input.ts
entry into HTML elements if (targetIsTextField(e.target || undefined) && key !== "Escape" && !(accelKey && ["Enter", "NumpadEnter"].includes(key))) return false; // Don't redirect paste if (key === "KeyV" && accelKey) return false; // Don't redirect a fullscreen request if (key === "F11" && e.type === "key...
item.getAsString((text) => { if (text.startsWith("graphite/layer: ")) {
random_line_split
input.ts
Down(e) }, { target: window, eventName: "mouseup", action: (e: MouseEvent) => onPotentialDoubleClick(e) }, { target: window, eventName: "wheel", action: (e: WheelEvent) => onWheelScroll(e), options: { passive: false } }, { target: window, eventName: "modifyinputfield", action: (e: CustomEvent) => onModifyInputFie...
(e: PointerEvent): void { if (!e.buttons) viewportPointerInteractionOngoing = false; // Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas // TODO: A better approach is to pass along a boolean to the backend's...
onPointerMove
identifier_name
main.rs
match get_args_as_strings() { Ok(e) => e, Err(e) => { println!("\n{}", e); print_help(); return; } }; if args.len() < 4 { print_help(); return; }; let mut parse_result: generator::GeneratorInput = match parse(args) { ...
{ Ok(ofpath) }
conditional_block
main.rs
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF ...
{ pub input_file: String, pub output_file: String, pub output_dir: String, pub lang: Lang,
GeneratorInput
identifier_name
main.rs
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF ...
_ => "", }; } fn get_args_as_strings() -> Result<Vec<String>, &'static str> { let mut ret: Vec<String> = Vec::new(); let args = env::args_os(); for cmd in args { ret.push(match cmd.into_string() { Ok(c) => c, _ => return Err("Invalid unicode character found"), ...
match parse_result.generate() { Err(e) => panic!("Generator error: {}", e),
random_line_split
production_example.py
import os import numpy as np import pandas as pd import matplotlib.pyplot as plt # required only for graphs from autots import AutoTS, load_live_daily, create_regressor fred_key = None # https://fred.stlouisfed.org/docs/api/api_key.html gsa_key = None forecast_name = "example" graph = True # whether to plot graphs...
patch_sklearn() except Exception as e: print(repr(e)) import json import datetime
random_line_split
production_example.py
in x]] df = df[[x for x in df.columns if "stock_splits" not in x]] # scale 'wiki_all' to millions to prevent too much skew of MAE if 'wiki_all' in df.columns: df['wiki_all_millions'] = df['wiki_all'] / 1000000 df = df.drop(columns=['wiki_all']) # manual NaN cleaning where real values are easily approximated, ...
plt.subplots_adjust(bottom=0.5) model.plot_horizontal_transformers() plt.show() model.plot_horizontal_model_count() plt.show() model.plot_horizontal() plt.show() # plt.savefig("horizontal.png", dpi=300, bbox_inches="tight") ...
conditional_block
ip6.go
} bytes[0] = (ip6.Version << 4) | (ip6.TrafficClass >> 4) bytes[1] = (ip6.TrafficClass << 4) | uint8(ip6.FlowLabel>>16) binary.BigEndian.PutUint16(bytes[2:], uint16(ip6.FlowLabel)) if opts.FixLengths { ip6.Length = uint16(len(payload)) } binary.BigEndian.PutUint16(bytes[4:], ip6.Length) bytes[6] = byte(ip6.Ne...
if err != nil { return err
random_line_split
ip6.go
ip6.Version << 4) | (ip6.TrafficClass >> 4) bytes[1] = (ip6.TrafficClass << 4) | uint8(ip6.FlowLabel>>16) binary.BigEndian.PutUint16(bytes[2:], uint16(ip6.FlowLabel)) if opts.FixLengths { ip6.Length = uint16(len(payload)) } binary.BigEndian.PutUint16(bytes[4:], ip6.Length) bytes[6] = byte(ip6.NextHeader) bytes...
} if ip6.Length == 0 { return fmt.Errorf("IPv6 length 0, but next header is %v, not HopByHop", ip6.NextHeader) } else { pEnd := int(ip6.Length) if pEnd > len(ip6.Payload) { df.SetTruncated() pEnd = len(ip6.Payload) } ip6.Payload = ip6.Payload[:pEnd] } return nil } func (i *IPv6) CanDecode() gopac...
{ for _, o := range ip6.hbh.Options { if o.OptionType == IPv6HopByHopOptionJumbogram { if len(o.OptionData) != 4 { return fmt.Errorf("Invalid jumbo packet option length") } payloadLength := binary.BigEndian.Uint32(o.OptionData) pEnd := int(payloadLength) if pEnd > len(ip6.Payload) ...
conditional_block
ip6.go
ip6.Version << 4) | (ip6.TrafficClass >> 4) bytes[1] = (ip6.TrafficClass << 4) | uint8(ip6.FlowLabel>>16) binary.BigEndian.PutUint16(bytes[2:], uint16(ip6.FlowLabel)) if opts.FixLengths { ip6.Length = uint16(len(payload)) } binary.BigEndian.PutUint16(bytes[4:], ip6.Length) bytes[6] = byte(ip6.NextHeader) bytes...
func decodeIPv6HopByHop(data []byte, p gopacket.PacketBuilder) error { i := &IPv6HopByHop{} err := i.DecodeFromBytes(data, p) p.AddLayer(i) if err != nil { return err } return p.NextDecoder(i.NextHeader) } type ipv6HeaderTLVOption struct { OptionType, OptionLength uint8 ActualLength int Option...
{ i.ipv6ExtensionBase = decodeIPv6ExtensionBase(data) i.Options = i.opts[:0] var opt *IPv6HopByHopOption for d := i.Contents[2:]; len(d) > 0; d = d[opt.ActualLength:] { i.Options = append(i.Options, IPv6HopByHopOption(decodeIPv6HeaderTLVOption(d))) opt = &i.Options[len(i.Options)-1] } return nil }
identifier_body
ip6.go
(b gopacket.SerializeBuffer, opts gopacket.SerializeOptions) error { payload := b.Bytes() if ip6.HopByHop != nil { return fmt.Errorf("unable to serialize hopbyhop for now") } bytes, err := b.PrependBytes(40) if err != nil { return err } bytes[0] = (ip6.Version << 4) | (ip6.TrafficClass >> 4) bytes[1] = (ip6...
SerializeTo
identifier_name
pod.go
od.Name = opts.Name } // Override default container name if applicable if opts.ContainerName != "" { pod.Spec.Containers[0].Name = opts.ContainerName } // Add Annotations and Labels, if specified if opts.Annotations != nil { pod.ObjectMeta.Annotations = opts.Annotations } if pod.ObjectMeta.Labels == nil {...
WaitForPodCompletion
identifier_name
pod.go
[]metav1.OwnerReference EnvironmentVariables []v1.EnvVar Lifecycle *v1.Lifecycle } func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1.Pod, error) { // If Namespace is not specified, use the controller Namespace. cns, err := GetControllerNamespace() if err != nil {...
// DeletePod deletes the specified pod func DeletePod(ctx context.Context, cli kubernetes.Interface, pod *v1.Pod) error { if err := cli.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{}); err != nil { log.WithError(err).Print("DeletePod failed") } return nil } func StreamPodLogs(ctx cont...
{ pod, err := GetPodObjectFromPodOptions(cli, opts) if err != nil { return nil, errors.Wrapf(err, "Failed to get pod from podOptions. Namespace: %s, NameFmt: %s", opts.Namespace, opts.GenerateName) } pod, err = cli.CoreV1().Pods(pod.Namespace).Create(ctx, pod, metav1.CreateOptions{}) if err != nil { return ni...
identifier_body
pod.go
if ns == "" { ns = cns } // If a ServiceAccount is not specified and we are in the controller's // namespace, use the same service account as the controller. sa := opts.ServiceAccountName if sa == "" && ns == cns { sa, err = GetControllerServiceAccount(cli) if err != nil { return nil, errors.Wrap(err, ...
{ node, err := cli.CoreV1().Nodes().Get(context.TODO(), n[0], metav1.GetOptions{}) if err != nil { return errors.Wrapf(err, "%s %s", errAccessingNode, n[0]) } if !IsNodeReady(node) || !IsNodeSchedulable(node) { return errors.Errorf("Node %s is currently not ready/schedulable", n[0]) } }
conditional_block
pod.go
[]metav1.OwnerReference EnvironmentVariables []v1.EnvVar Lifecycle *v1.Lifecycle } func GetPodObjectFromPodOptions(cli kubernetes.Interface, opts *PodOptions) (*v1.Pod, error) { // If Namespace is not specified, use the controller Namespace. cns, err := GetControllerNamespace() if err...
attachLog = false return false, errors.Errorf("Pod stuck in pending state, reason: %s", p.Status.Reason) } } // check if pvc and pv are up and ready to mount if err := getVolStatus(timeoutCtx, p, cli, namespace); err != nil { attachLog = false return false, err } return p.Status.Phase != v1...
if p.Status.Phase == v1.PodPending { if p.Status.Reason == "OutOfmemory" || p.Status.Reason == "OutOfcpu" {
random_line_split
js_PassengerEdit.js
2,'0')+" "+date.getHours().toString().padLeft(2,'0')); } else if(fg==2)//yyyy-MM-dd HH:mm { d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0')+" "+date.getHours().toString().padLeft(2,'0')+":"+date.getMinutes().toString().padLeft(2,'...
var carrNo=[]; jQuery("#tab_carry tr").each(function (index,tr) { var carrCode=jQuery(tr).find("select[id*='ddlCarryCode_']").val(); var AirNo=jQuery.trim(jQuery(tr).find("input[id*='txtAirNo_']").val()); if(carrCode!=""&&AirNo=="") { msg="航空公司卡号不能为空!"; return fals...
n false; } //验证航空公司卡号 暂时不验证 var val_CpyandNo=""; var msg="";
conditional_block
js_PassengerEdit.js
d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0')); } else if(fg==1)//yyyy-MM-dd HH { d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0')+" "+date.getHours().toStrin...
-MM-dd
identifier_name
js_PassengerEdit.js
(2,'0')+" "+date.getHours().toString().padLeft(2,'0')); } else if(fg==2)//yyyy-MM-dd HH:mm { d1=(date.getFullYear()+"-"+(date.getMonth()+1).toString().padLeft(2,'0')+"-"+date.getDate().toString().padLeft(2,'0')+" "+date.getHours().toString().padLeft(2,'0')+":"+date.getMinutes().toString().padLeft(2,...
} for(var key in arr[i]) { if(arr[i][key]=="0") { index=key.replace("_",""); istrue=true; break; } } } return index; } function ddlSetText(ddlObj,flag,num) { var ddlVal=jQuery.trim(jQuery(ddlObj).val()).split('-...
if(istrue) { break;
random_line_split
js_PassengerEdit.js
); } } //最多可以添加航空公司和卡号数 var maxCarryNum=20; var carryArr=[]; //添加一行 function addGroup(evt,name) { if(evt!=null) { var target=evt.srcElement?evt.srcElement:evt.target; jQuery(target).attr("disabled",true); } var num=0; //模板 var trHtml=jQuery("<div></div>").append(jQuery("#tab_"+na...
tDate").hide(); } } else if(pasType.indexOf('婴儿')!= -1) { jQuery("#txtCardNum").hide(); jQuery("#txtDate").show(); } } //加载。。。 jQuery(function () { //初始化航空公司和卡号数 initArr(carryArr,maxCarryNum); var IsEdit=jQuery("#Hid_IsEdit").val(); //单击旅客类型事件 jQuery("input[type='rad...
identifier_body
translator.ts
includes(property)) target.cachable = false // eslint-disable-next-line @typescript-eslint/no-unsafe-return return target[property] } } type TranslatorHeader = { translatorID: string translatorType: number label: string description: string creator: string target: string minVersion: string max...
(field: string): string { field = field.trim() if (field.startsWith('bibtex.')) return this.BetterBibTeX ? field.replace(/^bibtex\./, '') : '' if (field.startsWith('biblatex.')) return this.BetterBibLaTeX ? field.replace(/^biblatex\./, '') : '' return field } public init(mode: TranslatorMode) { ...
typefield
identifier_name
translator.ts
includes(property)) target.cachable = false // eslint-disable-next-line @typescript-eslint/no-unsafe-return return target[property] } } type TranslatorHeader = { translatorID: string translatorType: number label: string description: string creator: string target: string minVersion: string max...
// children: undefined // childCollections: undefined // primary: undefined // fields: undefined // type: undefined // level: undefined } } for (collection of Object.values(this.collections)) { if (collection.parent && !this.collec...
{ let collection: any while (collection = Zotero.nextCollection()) { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment const children = collection.children || collection.descendents || [] // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment co...
conditional_block
translator.ts
includes(property)) target.cachable = false // eslint-disable-next-line @typescript-eslint/no-unsafe-return return target[property] } } type TranslatorHeader = { translatorID: string translatorType: number label: string description: string creator: string target: string minVersion: string max...
for (const key in this.options) { if (typeof this.options[key] === 'boolean') { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment this.options[key] = !!Zotero.getOption(key) } else { // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment ...
caseSensitive: this.platform !== 'mac' && this.platform !== 'win', sep: this.platform === 'win' ? '\\' : '/', }
random_line_split
translator.ts
} type TranslatorHeader = { translatorID: string translatorType: number label: string description: string creator: string target: string minVersion: string maxVersion: string priority: number inRepository: boolean lastUpdated: string browserSupport: string displayOptions: { exportNotes:...
{ // collections: jabref 4 stores collection info inside the reference, and collection info depends on which part of your library you're exporting if (['collections'].includes(property)) target.cachable = false // eslint-disable-next-line @typescript-eslint/no-unsafe-return return target[property] }
identifier_body
dposhandler.go
// only candidate node is able to participant to this process. return; } pm.lock.Lock() defer pm.lock.Unlock() log.Info("Preparing for next big period..."); // pull the newest delegators from voting contract. a, b, err0 := VotingAccessor.Refresh() if err0 != nil { log.Error(err0.Error()) return; } Deleg...
NextGigPeriodInstance.confirmedBestNode[nodeId] = &GigPeriodTable{ response.Round,
random_line_split
dposhandler.go
, ";") ids := make([]string, len(delegatorIds)) peerinfo := make([]*discover.Node, len(delegatorIds)) for i,delegatorId := range delegatorIds { // call delegatorInfo(string) 0x6162630000000000000000000000000000000000000000000000000000000000 data1, err0 := d.dappabi.Pack("delegatorInfo", delegatorId) if err0 !=...
{ if !TestMode { gap := int64(NextGigPeriodInstance.activeTime) - time.Now().Unix() if gap > 2 || gap < -2 { log.Warn(fmt.Sprintf("Scheduling of the new electing round is improper! current gap: %v seconds", gap)) //restart the scheduler NextElectionInfo = nil; go pm.syncDelegatedNodeSafely(); ...
conditional_block
dposhandler.go
an inbound message is received from a remote // peer. The remote connection is torn down upon returning any error. func (pm *DPoSProtocolManager) handleMsg(msg *p2p.Msg, p *peer) error { pm.lock.Lock() defer pm.lock.Unlock() // Handle the message depending on its contents switch { case msg.Code == SYNC_BIGPERIOD_...
{ if DelegatorsTable == nil { return false; } for i :=0; i < len(DelegatorsTable); i++ { if DelegatorsTable[i] == nodeId { return true; } } return false; }
identifier_body
dposhandler.go
legatedNodes, NextGigPeriodInstance.delegatedNodesSign, currNodeIdHash}); if err != nil { log.Debug("Error occurred while sending SyncBigPeriodRequest: " + err.Error()) } } } } // handleMsg is invoked whenever an inbound message is received from a remote // peer. The remote connection is torn do...
isDelegatedNode2
identifier_name
staging.py
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 permissions and # limitations under the License. """Code to provide a hook for staging. Some App Engine runtimes require an additional ...
msg = ('The component [{component}] is required for staging this ' 'application.').format(component=self.component) update_manager.UpdateManager.EnsureInstalledAndRestart([self.component], msg=msg) def Run(self, staging_area, descriptor, ...
return
conditional_block
staging.py
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 permissions and # limitations under the License. """Code to provide a hook for staging. Some App Engine runtimes require an additional ...
(self): super(NoSdkRootError, self).__init__( 'No SDK root could be found. Please check your installation.') class StagingCommandFailedError(exceptions.Error): def __init__(self, args, return_code, output_message): super(StagingCommandFailedError, self).__init__( 'Staging command [{0}] fail...
__init__
identifier_name
staging.py
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 permissions and # limitations under the License. """Code to provide a hook for staging. Some App Engine runtimes require an additional ...
def Stage(self, descriptor, app_dir, runtime, environment): """Stage the given deployable or do nothing if N/A. Args: descriptor: str, path to the unstaged <service>.yaml or appengine-web.xml app_dir: str, path to the unstaged app directory runtime: str, the name of the runtime for the ap...
self.registry = registry self.staging_area = staging_area
identifier_body
staging.py
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 permissions and # limitations under the License. """Code to provide a hook for staging. Some App Engine runtimes require an additional ...
- On success, the STDOUT and STDERR of the staging command are logged at the INFO level. On failure, a StagingCommandFailedError is raised containing the STDOUT and STDERR of the staging command (which are surfaced to the user as an ERROR message). """ import cStringIO import os import tempfile from googleclouds...
- A staging command is an executable (binary or script) that takes two positional parameters: the path of the `<service>.yaml` in the directory containing the unstaged application code, and the path of an empty directory in which to stage the application code.
random_line_split
rozetka_webscrapper.py
#sellers #parse vars_list parsed_comment_vars_list = [] if comment_vars_list: comment_vars_lists = comment_vars_list.find_all(class_="comment__vars-item") if comment_vars_lists: for item in comment_vars_lists: res = {} label = item.find(class_="c...
(url): driver = Driver.get() driver.get(url) html = driver.page_source parsed_category = Category() parsed_category.url = url soup = BeautifulSoup(html, 'html.parser') title = soup.find("h1", class_="portal__heading") if title: parsed_category.name = decode_str(title.get_text...
parse_category
identifier_name
rozetka_webscrapper.py
") #sellers #parse vars_list parsed_comment_vars_list = [] if comment_vars_list: comment_vars_lists = comment_vars_list.find_all(class_="comment__vars-item") if comment_vars_lists: for item in comment_vars_lists: res = {} label = item.find(class_=...
#parse essentials comment_text = comment.find(class_="comment__text") if comment_text: parsed_comment.text = decode_str(comment_text.get_text()) comment_essentials_list = comment.find_all(class_="comment__essentials-item") #has label and optional <dd> with text parsed_essentials_list = [] ...
if fill == "url(#1)": stars_count += 1 parsed_comment.rating = stars_count
random_line_split
rozetka_webscrapper.py
def parse_comment(comment): parsed_comment = Comment() comment_author = comment.find(class_="comment__author") if comment_author: comment_date = comment.find(class_="comment__date") if comment_date: parsed_comment.date = decode_str(comment_date.get_text()) comment_dat...
return unicodestr
identifier_body
rozetka_webscrapper.py
") #sellers #parse vars_list parsed_comment_vars_list = [] if comment_vars_list: comment_vars_lists = comment_vars_list.find_all(class_="comment__vars-item") if comment_vars_lists: for item in comment_vars_lists: res = {} label = item.find(class_=...
return parsed_comments def parse_item_page_for_description(url): page = requests.get(url) soup = BeautifulSoup(page.text, 'html.parser') description = soup.find(class_="product-about__description-content") return decode_str(description.get_text()) if description else "" #runtime generated def pa...
comments_list = comments.find_all("li", class_="product-comments__list-item") comments_count = 0 if comments_list: for comment in comments_list: parsed_comments.append(parse_comment(comment)) comments_count += 1 if comments_count >= settings.CO...
conditional_block
value.rs
use serde::de::{Deserialize, Deserializer, Error as DeError, Visitor, SeqVisitor, MapVisitor}; use serde::de::impls::VecVisitor; use serde_json; use error::Error; /// The type which represents the key for maps used throughout the Ardite /// codebase. /// /// Functions similarly to an object key in JavaScript. pub typ...
//! the driver to these types. use linear_map::LinearMap; use serde::ser::{Serialize, Serializer};
random_line_split
value.rs
Error> where D: Deserializer { struct ValueVisitor; impl Visitor for ValueVisitor { type Value = Value; #[inline] fn visit_bool<E>(&mut self, value: bool) -> Result<Value, E> { Ok(Value::Boolean(value)) } #[inline] fn visit_u64<E>(&mut self, value: u64) -> Result<Value, E> { Ok(Value::I64(va...
{ assert_eq!(&value!().to_json().unwrap(), "null"); assert_eq!(&value!(true).to_json().unwrap(), "true"); assert_eq!(&value!(false).to_json().unwrap(), "false"); assert_eq!(&value!(7).to_json().unwrap(), "7"); assert_eq!(&value!(6.667).to_json().unwrap(), "6.667"); assert_eq!(&value!("Hello,\n\"...
identifier_body
value.rs
section /// 5). /// /// [1]: http://ecma-international.org/publications/files/ECMA-ST/ECMA-404.pdf #[derive(PartialEq, Clone, Debug)] pub enum Value { /// The abscense of any value. Null, /// True or false. Boolean(bool), /// An integer numeric value. I64(i64), /// A floating point numeric value. F64(f...
() { assert_eq!(value!().get(point![]).cloned(), Some(value!())); assert_eq!(value!().get(point!["hello"]).cloned(), None); assert_eq!(value!().get(point!["a", "b", "c", "d", "e"]).cloned(), None); assert_eq!(value!(true).get(point![]).cloned(), Some(value!(true))); assert_eq!(value!(true).get(point...
test_get_primitive
identifier_name
balloon.rs
PartiallyBalloonedPage { fn new() -> Self { let page_size = get_page_size(); let len = ((page_size >> VIRTIO_BALLOON_PFN_SHIFT) + 63) / 64; // Initial each padding bit as 1 in bitmap. let mut bitmap = vec![0_u64; len as usize]; let pad_num = len * 64 - (page_size >> VIRTIO_B...
(&mut self, addr: u64) { let addr_offset = (addr % self.page_size) >> VIRTIO_BALLOON_PFN_SHIFT; self.bitmap[(addr_offset / 64) as usize] |= 1 << (addr_offset % 64); } fn reset(&mut self) { let len = ((self.page_size >> VIRTIO_BALLOON_PFN_SHIFT) + 63) / 64; self.addr = 0; ...
set_bit
identifier_name
balloon.rs
lyBalloonedPage { fn new() -> Self { let page_size = get_page_size(); let len = ((page_size >> VIRTIO_BALLOON_PFN_SHIFT) + 63) / 64; // Initial each padding bit as 1 in bitmap. let mut bitmap = vec![0_u64; len as usize]; let pad_num = len * 64 - (page_size >> VIRTIO_BALLOON_P...
1 => { let page_size = get_page_size() as usize; let rbase = align_page_size_down((pfn as u64) << VIRTIO_BALLOON_PFN_SHIFT); Self::advise_memory_range( desc_chain.memory(), ...
{ Self::release_memory_range_4k(&mut self.pbp, desc_chain.memory(), pfn)?; }
conditional_block
balloon.rs
).map_err(|e| { EpollHelperError::HandleEvent(anyhow!( "Failed to signal used inflate queue: {:?}", e )) })?; } DEFLATE_QUEUE_EVENT => { self.deflate_queue_evt.read().map_err(|...
fn resume(&mut self) -> result::Result<(), MigratableError> {
random_line_split
authenticate-helper.ts
|| null; const now = getNow(); const deviceName = getUA(req.headers['user-agent']); if (!token) { if (!!req.cookies.refreshToken) { const ignoredOperationList = ['getProducts', 'getCategories', 'getNewspapers']; if (ignoredOperationList.includes(req.body.operationName)) { // console.log(`...
let customer = await db.collection('customer').aggregate([ { '$match': condition }, { '$project': projection }, { '$lookup': { from: 'store', localField: 'store_id', foreignField: '_id', as: 'store' } }, { '$lookup': { from: 'zip_code', ...
{ projection = { 'password': 0 } }
conditional_block
authenticate-helper.ts
.authorization || null; const now = getNow(); const deviceName = getUA(req.headers['user-agent']); if (!token) { if (!!req.cookies.refreshToken) { const ignoredOperationList = ['getProducts', 'getCategories', 'getNewspapers']; if (ignoredOperationList.includes(req.body.operationName)) { //...
//login token = token.replace('Basic ', ''); let query = Buffer.from(token, 'base64').toString('binary').split(':'); let customer = await findAndProcessCustomer({ '$or': [ { 'email': query[0], }, { 'username': query[0], }, ...
if (token.startsWith('Basic')) { if (!config.REFRESH_TOKEN_EXPIRE_LIMIT || !config.JWT_EXPIRE_LIMIT) { throw new AuthenticationError(MSG_SYSTEM_ERROR); }
random_line_split
disk_location.go
.IdxDirectory + "/" + volumeName) return false } // parse out collection, volume id vid, collection, err := volumeIdFromFileName(basename) if err != nil { glog.Warningf("get volume id failed, %s, err : %s", volumeName, err) return false } // avoid loading one volume more than once l.volumesLock.RLock() ...
logLevel := glog.Level(4) if l.isDiskSpaceLow { logLevel = glog.Level(0) }
random_line_split
disk_location.go
func NewDiskLocation(dir string, maxVolumeCount int32, minFreeSpace util.MinFreeSpace, idxDir string, diskType types.DiskType) *DiskLocation { dir = util.ResolvePath(dir) if idxDir == "" { idxDir = dir } else { idxDir = util.ResolvePath(idxDir) } dirUuid, err := GenerateDirUuid(dir) if err != nil { glog.F...
{ glog.V(1).Infof("Getting uuid of volume directory:%s", dir) dirUuidString = "" fileName := dir + "/vol_dir.uuid" if !util.FileExists(fileName) { dirUuid, _ := uuid.NewRandom() dirUuidString = dirUuid.String() writeErr := util.WriteFile(fileName, []byte(dirUuidString), 0644) if writeErr != nil { return ...
identifier_body
disk_location.go
UuidString), 0644) if writeErr != nil { return "", fmt.Errorf("failed to write uuid to %s : %v", fileName, writeErr) } } else { uuidData, readErr := os.ReadFile(fileName) if readErr != nil { return "", fmt.Errorf("failed to read uuid from %s : %v", fileName, readErr) } dirUuidString = string(uuidData...
} l.concurrentLoadingVolumes(needleMapKind, workerNum, ldbTimeout) glog.V(0).Infof("Store started on dir: %s with %d volumes max %d", l.Directory, len(l.volumes), l.MaxVolumeCount) l.loadAllEcShards() glog.V(0).Infof("Store started on dir: %s with %d ec shards", l.Directory, len(l.ecVolumes)) } func (l *DiskLo...
{ workerNum = 10 }
conditional_block
disk_location.go
, vol, err } func isValidVolume(basename string) bool { return strings.HasSuffix(basename, ".idx") || strings.HasSuffix(basename, ".vif") } func getValidVolumeName(basename string) string { if isValidVolume(basename) { return basename[:len(basename)-4] } return "" } func (l *DiskLocation) loadExistingVolume(di...
UnUsedSpace
identifier_name
utility.rs
let Bar(field) = Bar("hello"); // more common syntax /// # } /// ``` /// /// This function helps field access in context where you are declaring either /// a tuple struct or a struct with named fields. If you don't have a field name, /// it means you need to access the struct through an index. pub(crate) fn ident_or_i...
; (ty, bounds) }) .unzip(); let (ignored_types, ignored_trait_bounds): (Vec<_>, Vec<_>) = ignored_fields .map(|field| { let ty = field.data.ty.clone(); let custom_bounds = ignored_bounds(field).map(|bounds| quote!(+ #bounds))...
{ quote!(#bevy_reflect_path::Reflect #custom_bounds) }
conditional_block
utility.rs
std::iter::empty(), |_| None, |_| None, ) } /// Create [`WhereClauseOptions`] for a struct or enum type. /// /// Compared to [`WhereClauseOptions::new`], this version allows you to specify /// custom trait bounds for each field. pub fn new_with_bounds...
} /// Creates a [constant] [`StringExpr`] by interpreting a [string slice][str] as a [`struct@LitStr`]. ///
random_line_split
utility.rs
.map(|field| { let ty = field.data.ty.clone(); let custom_bounds = active_bounds(field).map(|bounds| quote!(+ #bounds)); let bounds = if is_from_reflect { quote!(#bevy_reflect_path::FromReflect #custom_bounds) } else { ...
{ match self { Self::Const(tokens) | Self::Borrowed(tokens) => tokens, Self::Owned(owned) => quote! { &#owned }, } }
identifier_body
utility.rs
let Bar(field) = Bar("hello"); // more common syntax /// # } /// ``` /// /// This function helps field access in context where you are declaring either /// a tuple struct or a struct with named fields. If you don't have a field name, /// it means you need to access the struct through an index. pub(crate) fn ident_or_i...
( where_clause: Option<&WhereClause>, where_clause_options: &WhereClauseOptions, ) -> proc_macro2::TokenStream { let parameter_types = &where_clause_options.parameter_types; let active_types = &where_clause_options.active_types; let ignored_types = &where_clause_options.ignored_types; let parame...
extend_where_clause
identifier_name
views_ajax.py
account locking...'.format(strUsername)) result = {'status': 3, 'msg': '登录失败超过5次,该账号已被锁定5分钟!', 'data': ''} return HttpResponse(json.dumps(result), content_type='application/json') if user and user.is_active: request.session['login_username'] = strUsername result ...
elif dictSHA1 != {} and sqlID not in dictSHA1: pctResult = {"status":4, "msg":"该行SQL不是由pt-OSC执行的", "data":""} else: pctResult = {"status":-2, "msg":"整个工单不由pt-OSC执行", "data":""} return HttpResponse(json.dumps(pctResult), content_type='application/json')
random_line_split
views_ajax.py
result = {'msg': 'l
#Oracle SQL简单审核 @csrf_exempt def orasimplecheck(request): if request.is_ajax(): sqlContent = request.POST.get('sql_content') clusterName = request.POST.get('cluster_name') else: sqlContent = request.POST['sql_content'] clusterName = request.POST['cluster_name'] ...
dap authorization failed'} return HttpResponse(json.dumps(result), content_type='application/json') if strUsername in login_failure_counter and login_failure_counter[strUsername]["cnt"] >= lockCntThreshold and ( datetime.datetime.now() - login_failure_counter[strUsername][ "...
identifier_body
views_ajax.py
result = {'msg': 'ldap authorization failed'} return HttpResponse(json.dumps(result), content_type='application/json') if strUsername in login_failure_counter and login_failure_counter[strUsername]["cnt"] >= lockCntThreshold and ( datetime.datetime.now() - login_failure_counter[strUser...
sqlContent = request.POST['sql_content'] clusterName = request.POST['cluster_name'] finalResult = {'status':'ok', 'msg':'检测通过', 'data':[]} #服务器端参数验证 if sqlContent is None or clusterName is None: finalResult['status'] = 'error' finalResult['msg'] = '页面提交参数可能为空' ...
nse(json.dumps(result), content_type='application/json') #Oracle SQL简单审核 @csrf_exempt def orasimplecheck(request): if request.is_ajax(): sqlContent = request.POST.get('sql_content') clusterName = request.POST.get('cluster_name') else:
conditional_block
views_ajax.py
ReCheckResult[rownum][10] if sqlSHA1 != '': dictSHA1[id] = sqlSHA1 if dictSHA1 != {}: # 如果找到有sqlSHA1值,说明是通过pt-OSC操作的,将其放入缓存。 # 因为使用OSC执行的SQL占较少数,所以不设置缓存过期时间 sqlSHA1_cache[workflowId] = dictSHA1 return dictSHA1 @csrf_exempt def getOscPercent(request): """获取该SQL的p...
n/json')
identifier_name
consts.go
// Default redundancy parameters. var ( // syncCheckInterval is how often the repair heap checks the consensus code // to see if the renter is synced. This is created because the contractor // may not update the synced channel until a block is received under some // conditions. syncCheckInterval = build.Select(b...
{ return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy) }
identifier_body
consts.go
(siaPath modules.SiaPath, health, redundancy float64) string { return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy) } // Default redundancy parameters. var ( // syncCheckInterval is how often the repair heap checks the consensus code // to see if the rente...
AlertCauseSiafileLowRedundancy
identifier_name
consts.go
// syncCheckInterval is how often the repair heap checks the consensus code // to see if the renter is synced. This is created because the contractor // may not update the synced channel until a block is received under some // conditions. syncCheckInterval = build.Select(build.Var{ Dev: time.Second * 3, S...
return fmt.Sprintf("Siafile '%v' has a health of %v and redundancy of %v", siaPath.String(), health, redundancy) } // Default redundancy parameters. var (
random_line_split
MADDPGAgent.py
AMMA = 0.99 # discount factor # TAU = 1e-3 # for soft update of target parameters ACTOR_LR = 1e-3 # Actor network learning rate CRITIC_LR = 1e-4 # Actor network learning rate UPDATE_EVERY = 20 # how often to update the network (time step) # UPDATE_TIMES = 5 # how many times to update in one go d...
epsilon = max((1500 - self.n_step) / 1500, .01) self.actor_local.eval() with torch.no_grad(): actions = self.actor_local(state) self.actor_local.train() if training: # return np.clip(actions.cpu().data.numpy()+np.random.uniform(-1,1,(2,2))*epsilon,-1,1)...
state = torch.from_numpy(state).float().detach().to(device) # print(state.shape,"act") self.n_step += 1
random_line_split
MADDPGAgent.py
AMMA = 0.99 # discount factor # TAU = 1e-3 # for soft update of target parameters ACTOR_LR = 1e-3 # Actor network learning rate CRITIC_LR = 1e-4 # Actor network learning rate UPDATE_EVERY = 20 # how often to update the network (time step) # UPDATE_TIMES = 5 # how many times to update in one go d...
else: return actions.cpu().data.numpy() def learn(self, experiences, gamma): """Update value parameters using given batch of experience tuples. Params ====== experiences (Tuple[torch.Variable]): tuple of (s, a, r, s', done) tuples gamma (float)...
return np.clip(actions.cpu().data.numpy(), -1, 1) # epsilon greedy policy
conditional_block
MADDPGAgent.py
AMMA = 0.99 # discount factor # TAU = 1e-3 # for soft update of target parameters ACTOR_LR = 1e-3 # Actor network learning rate CRITIC_LR = 1e-4 # Actor network learning rate UPDATE_EVERY = 20 # how often to update the network (time step) # UPDATE_TIMES = 5 # how many times to update in one go d...
def add(self, states, all_state, action, all_actions, reward, next_state, all_next_state, done): """Add a new experience to memory.""" e = self.experience(states, all_state, action, all_actions, reward, next_state, all_next_state, done) self.memory.append(e) def sample(self): """Ra...
itialize a ReplayBuffer object. Params ====== action_size (int): dimension of each action buffer_size (int): maximum size of buffer batch_size (int): size of each training batch seed (int): random seed """ self.action_size = action_size ...
identifier_body
MADDPGAgent.py
AMMA = 0.99 # discount factor # TAU = 1e-3 # for soft update of target parameters ACTOR_LR = 1e-3 # Actor network learning rate CRITIC_LR = 1e-4 # Actor network learning rate UPDATE_EVERY = 20 # how often to update the network (time step) # UPDATE_TIMES = 5 # how many times to update in one go d...
(self, state, training=True): """Returns continous actions values for all action for given state as per current policy. Params ====== state (array_like): current state """ state = torch.from_numpy(state).float().detach().to(device) # print(state.shape,"act")...
act
identifier_name
server.go
"fmt" "math/rand" "net" "net/http" "regexp" "sort" "strings" "time" "github.com/casbin/casbin/v2" "github.com/cesanta/glog" "github.com/docker/distribution/registry/auth/token" "github.com/cesanta/docker_auth/auth_server/api" "github.com/cesanta/docker_auth/auth_server/authn" "github.com/cesanta/docker_...
random_line_split
server.go
} if c.LDAPAuth != nil { la, err := authn.NewLDAPAuth(c.LDAPAuth) if err != nil { return nil, err } as.authenticators = append(as.authenticators, la) } if c.MongoAuth != nil { ma, err := authn.NewMongoAuth(c.MongoAuth) if err != nil { return nil, err } as.authenticators = append(as.authenticato...
{ ares := []authzResult{} for _, scope := range ar.Scopes { ai := &api.AuthRequestInfo{ Account: ar.Account, Type: scope.Type, Name: scope.Name, Service: ar.Service, IP: ar.RemoteIP, Actions: scope.Actions, Labels: ar.Labels, } actions, err := as.authorizeScope(ai) if err != n...
identifier_body
server.go
Auth) if err != nil { return nil, err } as.authenticators = append(as.authenticators, gha) as.gha = gha } if c.OIDCAuth != nil { oidc, err := authn.NewOIDCAuth(c.OIDCAuth) if err != nil { return nil, err } as.authenticators = append(as.authenticators, oidc) as.oidc = oidc } if c.GitlabAuth !...
return result, labels, nil } // Deny by default. glog.Warningf("%s did not match any authn rule", ar) return false, nil, nil } func (as *AuthServer) authorizeScope(ai *api.AuthRequestInfo) ([]string, error) { for i, a := range as.authorizers { result, err := a.Authorize(ai) glog.V(2).Infof("Authz %s %s -> ...
{ if err == api.NoMatch { continue } else if err == api.WrongPass { glog.Warningf("Failed authentication with %s: %s", err, ar.Account) return false, nil, nil } err = fmt.Errorf("authn #%d returned error: %s", i+1, err) glog.Errorf("%s: %s", ar, err) return false, nil, err }
conditional_block