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 |
|---|---|---|---|---|
read.go | "twitter:description" {
if _, exist := mapAttribute[metaName]; !exist {
mapAttribute[metaName] = metaContent
}
return
}
if metaProperty == "og:description" ||
metaProperty == "og:image" ||
metaProperty == "og:title" {
if _, exist := mapAttribute[metaProperty]; !exist {
mapAttribute[metaP... |
// Set final title
metadata.Title = r.getArticleTitle(doc)
if metadata.Title == "" {
if _, exist := mapAttribute["og:title"]; exist {
metadata.Title = mapAttribute["og:title"]
} else if _, exist := mapAttribute["twitter:title"]; exist {
metadata.Title = mapAttribute["twitter:title"]
}
}
return metad... | {
metadata.Excerpt = mapAttribute["twitter:description"]
} | conditional_block |
read.go | String(matchString) &&
!okMaybeItsACandidate.MatchString(matchString) &&
!s.Is("body") && !s.Is("a") {
s.Remove()
return
}
if unlikelyElements.MatchString(r.getTagName(s)) {
s.Remove()
return
}
// Remove DIV, SECTION, and HEADER nodes without any content(e.g. text, image, video, or iframe).
... | Style(s *g | identifier_name | |
read.go | ancestors = append(ancestors, &parent)
}
return ancestors
}
// Check if a given node has one of its ancestor tag name matching the provided one.
func (r *readability) hasAncestorTag(node *goquery.Selection, tag string) bool {
for parent := *node; len(parent.Nodes) > 0; parent = *parent.Parent() {
if parent.Node... | nd("h1,h2,h3").Each(func(_ int, s1 *goquery.Selection) {
if r.getClassWeight(s1) < 0 {
s1.Remove()
}
})
}
// Co | identifier_body | |
Model.py | def initialize(self):
self.build_CNN()
self.build_RNN()
self.build_CTC()
self.trained_batches = 0
self.learning_rate = tf.placeholder(tf.float32, shape=[])
self.update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
with tf.control_dependencies(self.update... | def __init__(self, char_list, restore=False):
self.decoder_selected = Constants.decoder_selected
self.path_model = Constants.path_model
self.batch_size = Constants.batch_size
self.char_list = char_list
self.learning_rate = Constants.learning_rate
self.text_length = Const... | identifier_body | |
Model.py | self.file_word_beam_search = Constants.file_word_beam_search
self.file_collection_words = Constants.file_collection_words
self.is_restore = restore
self.model_id = 0
self.is_train = tf.placeholder(tf.bool, name='is_train')
self.input_images = tf.placeholder(tf.float32, shape=(N... | dtype=rnn_input_3d.dtype)
rnn_combined = tf.concat([fw, bw], 2) # combine the fw & bw
rnn = tf.expand_dims(rnn_combined, 2) # adds dimensions of size 1 to the 2nd index
features_in = n_cell * 2 # no. of input
features_out = len... | cell_multi = tf.contrib.rnn.MultiRNNCell(cells, state_is_tuple=True)
((fw, bw), _) = tf.nn.bidirectional_dynamic_rnn(cell_fw=cell_multi,
cell_bw=cell_multi,
inputs=rnn_input_3d, | random_line_split |
Model.py | .file_word_beam_search = Constants.file_word_beam_search
self.file_collection_words = Constants.file_collection_words
self.is_restore = restore
self.model_id = 0
self.is_train = tf.placeholder(tf.bool, name='is_train')
self.input_images = tf.placeholder(tf.float32, shape=(None, ... | (self):
word_beam_search_module = tf.load_op_library(self.file_word_beam_search)
chars = str().join(self.char_list)
word_chars = open(self.file_word_char_list).read().splitlines()[0]
data_handler = DataHandler()
data_handler.prepare_collection_words()
collection_words ... | load_word_beam | identifier_name |
Model.py | .file_word_beam_search = Constants.file_word_beam_search
self.file_collection_words = Constants.file_collection_words
self.is_restore = restore
self.model_id = 0
self.is_train = tf.placeholder(tf.bool, name='is_train')
self.input_images = tf.placeholder(tf.float32, shape=(None, ... |
return (indices, values, shape)
def decode(self, ctc_output, batch_size):
"transform sparse tensor to labels"
encoded_label_list = [] # store batch elements labels
for i in range(batch_size):
encoded_label_list.append([])
blank = len(self.char_list) # last... | indices.append([batch_element, i])
values.append(label) | conditional_block |
process.py | .update_refpix_metadata(ifg_paths, refx, refy, transform, params)
log.debug("refpx, refpy: "+str(refx) + " " + str(refy))
ifg.close()
return int(refx), int(refy)
def _orb_fit_calc(multi_paths: List[MultiplePaths], params, preread_ifgs=None) -> None:
"""
MPI wrapper for orbital fit correction
... | """
Get RDIst class object
"""
ifg = Ifg(ifg_path)
ifg.open()
r_dist = vcm_module.RDist(ifg)()
ifg.close()
return r_dist | identifier_body | |
process.py | ))
refpixel.update_refpix_metadata(ifg_paths, refx, refy, transform, params)
log.debug("refpx, refpy: "+str(refx) + " " + str(refy))
ifg.close()
return int(refx), int(refy)
def _orb_fit_calc(multi_paths: List[MultiplePaths], params, preread_ifgs=None) -> None:
"""
MPI wrapper for orbital fit... | ifg.close() | random_line_split | |
process.py | eread_ifgs.pk')
if mpiops.rank == MASTER_PROCESS:
# add some extra information that's also useful later
gt, md, wkt = shared.get_geotiff_header_info(process_tifs[0])
epochlist = algorithm.get_epochs(ifgs_dict)[0]
log.info('Found {} unique epochs in the {} interferogram network'.for... | (tile, i, preread_ifgs):
"""
Convenient inner loop for mst tile saving
"""
mst_tile = mst.mst_multiprocessing(tile, dest_tifs, preread_ifgs, params)
# locally save the mst_mat
mst_file_process_n = join(params[cf.TMPDIR], 'mst_mat_{}.npy'.format(i))
np.save(file=ms... | _save_mst_tile | identifier_name |
process.py | eread_ifgs.pk')
if mpiops.rank == MASTER_PROCESS:
# add some extra information that's also useful later
gt, md, wkt = shared.get_geotiff_header_info(process_tifs[0])
epochlist = algorithm.get_epochs(ifgs_dict)[0]
log.info('Found {} unique epochs in the {} interferogram network'.for... |
rows, cols = params["rows"], params["cols"]
return process_ifgs(ifg_paths, params, rows, cols)
def process_ifgs(ifg_paths, params, rows | ifg_paths.append(ifg_path.sampled_path) | conditional_block |
corpora.py | component from its storage directory
"""
path = os.path.join(self.storagedir, which)
print("Loading from", path)
with open(path, "rb") as handle:
setattr(self, which, _pickle.load(handle))
def load_full(self):
"""
Load the entire corpus from its storage directory
"""
for filename in self.FILENAMES... | batch = all_sentences[i:min(i+self.HYBRID_LENGTH, len(all_sentences))]
hybrid_tokenized_document = []
hybrid_X = []
hybrid_labels = []
for sentence, label in batch:
for word in word_tokenize(sentence):
hybrid_tokenized_document.append(word)
hybrid_X.append(self.worddict.get(word, self.worddi... | conditional_block | |
corpora.py | .EMB_SIZE))
counter = 0
words = []
weights_tmp = []
with open(self.embeddingpath) as handle:
for i, line in enumerate(handle):
tmp = line.strip()
if len(tmp) > 0:
split = tmp.split(" ")
if split[0] in self.worddict and len(split[1:]) == 300:
words.append(split[0])
weights_t... | (self, dataset):
print("Word-tokenizing documents in", dataset)
self.tokenized_documents[dataset] = [word_tokenize(document) for document in self.raw_documents[dataset]]
def shuffle_dataset(self, dataset):
print("Shuffling dataset", dataset)
indices = list(range(len(self.X[dataset])))
np.random.seed(0)
n... | tokenize_documents | identifier_name |
corpora.py | self.EMB_SIZE))
counter = 0
words = []
weights_tmp = []
with open(self.embeddingpath) as handle:
for i, line in enumerate(handle):
tmp = line.strip()
if len(tmp) > 0:
split = tmp.split(" ")
if split[0] in self.worddict and len(split[1:]) == 300:
words.append(split[0])
weig... | for filename in self.FILENAMES:
with open(os.path.join(self.storagedir, filename), "wb") as handle:
_pickle.dump(getattr(self, filename), handle)
def load(self, which):
"""
Load a corpus component from its storage directory
"""
path = os.path.join(self.storagedir, which)
print("Loading from", path)... | Store corpus to its storage directory
"""
print("Storing to", self.storagedir)
| random_line_split |
corpora.py | self.EMB_SIZE))
counter = 0
words = []
weights_tmp = []
with open(self.embeddingpath) as handle:
for i, line in enumerate(handle):
tmp = line.strip()
if len(tmp) > 0:
split = tmp.split(" ")
if split[0] in self.worddict and len(split[1:]) == 300:
words.append(split[0])
weig... |
def get_generator(self, dataset, batchsize, shuffle = False):
"""
Returns a generator that will generate (X,Y) pairs for the given dataset.
dataset: one of 'train', 'dev', 'test', 'hybrid'
batchsize: batch size that the generator will be working on
shuffle: if true, the dataset is shuffled at the beginni... | """
Load selected corpus components only if they have not yet been loaded
"""
for which in selected:
self.load_if_necessary(which)
if "worddict" in selected and "classdict" in selected:
self.reverse_dicts() | identifier_body |
trainer.py | Denormalize
import cv2
import numpy as np
from utils.gradcam import *
class Trainer(nn.Module):
def __init__(self, config, model, train_loader, val_loader, **kwargs):
super().__init__()
self.config = config
self.model = model
self.train_loader = train_loader
self.val_loade... | grayscale_cam, label_idx = grad_cam(inputs, target_category)
label = self.cfg.obj_list[label_idx]
img_cam = show_cam_on_image(img_show, grayscale_cam, label)
cv2.imwrite(image_outname, img_cam)
def __str__(self) -> str:
title = '------------- Model Summary -... | if not os.path.exists('./samples'):
os.mkdir('./samples')
denom = Denormalize()
batch = next(iter(self.val_loader))
images = batch["imgs"]
#targets = batch["targets"]
self.model.eval()
config_name = self.cfg.model_name.split('_')[0]
grad_cam = GradC... | identifier_body |
trainer.py | Denormalize
import cv2
import numpy as np
from utils.gradcam import *
class Trainer(nn.Module):
def __init__(self, config, model, train_loader, val_loader, **kwargs):
super().__init__()
self.config = config
self.model = model
self.train_loader = train_loader
self.val_loade... |
if print_per_iter is not None:
self.print_per_iter = print_per_iter
else:
self.print_per_iter = int(len(self.train_loader) / 10)
self.epoch = start_epoch
# For one-cycle lr only
if self.scheduler is not None and self.step_per_epoch:
self.sc... | self.checkpoint = CheckPoint(save_per_epoch=int(num_epochs/10) + 1) | conditional_block |
trainer.py | Denormalize
import cv2
import numpy as np
from utils.gradcam import *
class Trainer(nn.Module):
def __init__(self, config, model, train_loader, val_loader, **kwargs):
super().__init__()
self.config = config
self.model = model
self.train_loader = train_loader
self.val_loade... | (self.num_epochs + i) / len(self.train_loader))
lrl = [x['lr'] for x in self.optimizer.param_groups]
lr = sum(lrl) / len(lrl)
log_dict = {'Learning rate/Iterations': lr}
self.logging(log_dict)
torch.cuda... | self.optimizer.zero_grad()
if self.scheduler is not None and not self.step_per_epoch:
# self.scheduler.step()
self.scheduler.step( | random_line_split |
trainer.py | Denormalize
import cv2
import numpy as np
from utils.gradcam import *
class Trainer(nn.Module):
def | (self, config, model, train_loader, val_loader, **kwargs):
super().__init__()
self.config = config
self.model = model
self.train_loader = train_loader
self.val_loader = val_loader
self.optimizer = model.optimizer
self.criterion = model.criterion
self.metri... | __init__ | identifier_name |
main.py | �于阈值的就不管了(去除掉),小于阈值的就可能是另一个目标框,留下来继续比较
inds = np.where(ovr <= thresh)[0] # 返回满足条件的order[1:]中的索引值
order = order[inds + 1] # +1得到order中的索引值
return keep
class FaceDetector:
def __init__(self, model_path):
self.strides = [8.0, 16.0, 32.0, 64.0]
self.min_boxes = [
[10.... | iow = image_h / 640, image_w / 640
# Scan through all the bounding boxes output from the network and keep only the
# ones with high confidence scores. Assign the box's class label as the class with the highest score.
classIds = []
confidences = []
boxes = []
for out in ou... | atioh, rat | identifier_name |
main.py | �于阈值的就不管了(去除掉),小于阈值的就可能是另一个目标框,留下来继续比较
inds = np.where(ovr <= thresh)[0] # 返回满足条件的order[1:]中的索引值
order = order[inds + 1] # +1得到order中的索引值
return keep
class FaceDetector:
def __init__(self, model_path):
self.strides = [8.0, 16.0, 32.0, 64.0]
self.min_boxes = [
[10.... | )
if len(indices):
indices = indices.flatten()
boxes = np.array(boxes)[indices]
confidences = np.array(confidences)[indices]
return boxes, confidences
def __call__(self, srcimg):
blob = cv2.dnn.blobFromImage(srcimg, 1 / 255.0, (640, 640), [0, 0, 0], swapRB=Tru... | t(center_x - width / 2)
top = int(center_y - height / 2)
classIds.append(classId)
confidences.append(float(confidence))
boxes.append([left, top, width, height])
# Perform non maximum suppression to eliminate redundant overlapping b... | conditional_block |
main.py | �于阈值的就不管了(去除掉),小于阈值的就可能是另一个目标框,留下来继续比较
inds = np.where(ovr <= thresh)[0] # 返回满足条件的order[1:]中的索引值
order = order[inds + 1] # +1得到order中的索引值
return keep
class FaceDetector:
def __init__(self, model_path):
self.strides = [8.0, 16.0, 32.0, 64.0]
self.min_boxes = [
[10.... |
ratioh, ratiow = image_h / 640, image_w / 640
# Scan through all the bounding boxes output from the network and keep only the
# ones with high confidence scores. Assign the box's class label as the class with the highest score.
classIds = []
confidences = []
boxes = []
... | [30, 61, 62, 45, 59, 119], [116, 90, 156, 198, 373, 326]]
self.nl = len(anchors) # number of detection layers
self.na = len(anchors[0]) // 2 # number of anchors
self.no = num_classes + 5 # number of outputs per anchor
self.grid = [np.zeros(1)] * self.nl # init grid
self.stri... | identifier_body |
main.py | 大于阈值的就不管了(去除掉),小于阈值的就可能是另一个目标框,留下来继续比较
inds = np.where(ovr <= thresh)[0] # 返回满足条件的order[1:]中的索引值
order = order[inds + 1] # +1得到order中的索引值
return keep
class FaceDetector:
def __init__(self, model_path):
self.strides = [8.0, 16.0, 32.0, 64.0]
self.min_boxes = [
[10... | return rect_boxes, confidences
class SmokeDetector:
def __init__(self, model_path, confThreshold=0.5, nmsThreshold=0.5, objThreshold=0.5):
self.classes = ['smoke']
self.colors = [np.random.randint(0, 255, size=3).tolist() for _ in range(len(self.classes))]
# num_classes = len(self.... | scores, boxes = self.face_detector.forward(["scores", "boxes"])
# print(scores)
image_h, image_w = img.shape[:2]
rect_boxes, confidences = self.postprocess(image_w, image_h, scores, boxes, 0.6)
| random_line_split |
director.ts | {
after: options.after || null,
before: options.before || null,
on: options.on || null,
};
return this;
};
Router.prototype.param = function (token, matcher) {
if (token[0] !== ':') {
token = `:${token}`;
}
const compiled = new RegExp(token, 'g');
this.params[token] = function (str) {
... | _metho | identifier_name | |
director.ts | e() {
if (this.mode === 'modern') {
this.history === true ? window.onpopstate() : window.onhashchange();
} else {
this.onHashChanged();
}
},
init(fn, history) {
const self = this;
this.history = history;
if (!Router.listeners) {
Router.listeners = [];
}
function ... | nst h = dloc.hash;
if (h != this.hash) {
this.hash = h;
this.onHashChanged();
}
},
fir | identifier_body | |
director.ts | //
// IE support, based on a concept by Erik Arvidson ...
//
const frame = document.createElement('iframe');
frame.id = 'state-frame';
frame.style.display = 'none';
document.body.appendChild(frame);
this.writeFrame('');
if ('onpropertychange' in document && 'attach... | // At least for now HTML5 history is available for 'modern' browsers only
if (this.history === true) {
// There is an old bug in Chrome that causes onpopstate to fire even
// upon initial page load. Since the handler is run manually in init(),
// this would cause Chrome to run it twise. Cu... | conditional_block | |
director.ts | 'once', 'after', 'before'];
this.scope = [];
this._methods = {};
this._insert = this.insert;
this.insert = this.insertEx;
this.historySupport =
(window.history != null ? window.history.pushState : null) != null;
this.configure();
this.mount(routes || {});
};
const Router = router;
Router.prototy... | this.params[token] = function (str) {
return str.replace(compiled, matcher.source || matcher);
};
return this;
};
Router.prototype.on = Router.prototype.route = function (method, path, route) {
const self = this;
if (!route && typeof path === 'function') {
route = path;
path = method;
method ... | random_line_split | |
junk.py |
# In[16]:
# put in init
def findFFTloc(baseline,imageShapeAlong1Axis,wavel_lambda,plateScale,lOverD=1.):
# returns the FFT pixel locations equivalent to a certain pixel distance on the science image
# baseline: distance in physical space in the pupil plane (in m)
# imageShapeAlong1Axis: length of ... | max2 = 1.635
min2 = 2.233
max3 = 2.679
min3 = 3.238
max4 = 3.699 | random_line_split | |
junk.py | plate scale (in asec/pix)
# lOverD: option if we are interested in the circular Airy rings (values 1.22, etc.)
line_diam_pixOnScience = lOverD*(wavel_lambda*asecInRad)/(baseline*plateScale) # distance in pixels on science detector
line_diam_freq = np.divide(1.,line_diam_pixOnScience) # the correspondi... |
# apply the masks
sciImg1 = np.copy(sciImg) # initialize arrays of same size as science image
sciImg2 = np.copy(sciImg)
sciImg3 = np.copy(sciImg)
sciImg4 = np.copy(sciImg)
# region 1
sciImg1.fill(np.nan) # initialize arrays of nans
mask_circHighFreq_L.data[mask_circHighFreq_L.data ... | line_M1diam_pixOnFFT = findFFTloc(8.25,np.shape(sciImg)[0],wavel_lambda,plateScale)
line_center2center_pixOnFFT = findFFTloc(14.4,np.shape(sciImg)[0],wavel_lambda,plateScale)
line_edge2edge_pixOnFFT = findFFTloc(22.65,np.shape(sciImg)[0],wavel_lambda,plateScale)
# define circles
circR... | identifier_body |
junk.py |
# plateScale: plate scale of the detector (asec/pixel)
# make division lines separating different parts of the PSF
line_M1diam_pixOnFFT = findFFTloc(8.25,np.shape(sciImg)[0],wavel_lambda,plateScale)
line_center2center_pixOnFFT = findFFTloc(14.4,np.shape(sciImg)[0],wavel_lambda,plateScale)
line... | filename_str = stem+'lm_180507_'+str("{:0>6d}".format(f))+'.fits'
if os.path.isfile(filename_str): # if FITS file exists in the first place
print('Working on frame '+str("{:0>6d}".format(f))+' ...')
image, header = fits.getdata(filename_str,0,header=True)
# test:... | conditional_block | |
junk.py | plate scale (in asec/pix)
# lOverD: option if we are interested in the circular Airy rings (values 1.22, etc.)
line_diam_pixOnScience = lOverD*(wavel_lambda*asecInRad)/(baseline*plateScale) # distance in pixels on science detector
line_diam_freq = np.divide(1.,line_diam_pixOnScience) # the correspondi... | (sciImg,wavel_lambda,plateScale):
# sciImg: this is actually the FFT image, not the science detector image
# wavel_lambda: wavelenth of the observation
# plateScale: plate scale of the detector (asec/pixel)
# make division lines separating different parts of the PSF
line_M1diam_pixOnFFT = findF... | fftMask | identifier_name |
dropdown.component.ts | boolean = false;
// 下拉菜单设置选项
protected _dropdownSettings: DropdownSettings = new DropdownSettings();
public _currentDropdownSettings: DropdownSettings = new DropdownSettings();
// 可选下拉
protected _dropdownOptions: Array<any> = [];
// 已选中下拉
protected _selectedOptions: Array<any> = [];
// 原型
protected _... | this.renderer.setElementClass(this.selectWarp.toggleSelectElement, 'hide', true);
this.renderer.setElementClass(this.selectWarp.toggleInput, 'se-input-current', false);
| identifier_body | |
dropdown.component.ts | .component";
import {DropdownSelectComponent} from "./dropdown-select.component";
import {DropdownOptionModel} from "../dropdown-element";
@Component({
selector: 'dropdown-search',
templateUrl: './../template/dropdown.component.html',
encapsulation: ViewEncapsulation.None
})
export class DropdownComponent imple... | }
if (data && !this.resetDropdown) {
for (let key in data) {
if (this.dropdownSettings.hasOwnProperty(key) && data.hasOwnProperty(key)) {
this.dropdownSettings[key] = data[key];
}
}
this.resetDropdown = false;
}
};
get dropdownSettings() {
return this._dr... | @ViewChild('toggleSelect') toggleSelect: ElementRef;
@Input('dropdownSettings') set dropdownSettings(data: DropdownSettings) {
if (data) {
this._currentDropdownSettings = data; | random_line_split |
dropdown.component.ts | .component";
import {DropdownSelectComponent} from "./dropdown-select.component";
import {DropdownOptionModel} from "../dropdown-element";
@Component({
selector: 'dropdown-search',
templateUrl: './../template/dropdown.component.html',
encapsulation: ViewEncapsulation.None
})
export class DropdownComponent imple... | this.getCalcHeight = height;
}
}
get optionModelArr() {
return this._optionModelArr;
}
@Output('optionModelArrChange') optionModelArrChange = new EventEmitter<any>();
@ViewChild('toggleInput') toggleInput: ElementRef;
@ViewChild('dropdownInput') dropdownInputComponent: DropdownInputComponen... | if (height) {
| identifier_name |
dropdown.component.ts | .component";
import {DropdownSelectComponent} from "./dropdown-select.component";
import {DropdownOptionModel} from "../dropdown-element";
@Component({
selector: 'dropdown-search',
templateUrl: './../template/dropdown.component.html',
encapsulation: ViewEncapsulation.None
})
export class DropdownComponent imple... | );
}
if (this.reset || this.optionInit) {
this.dropdownInputComponent.selectedOptions = this._selectedOptions;
}
if (this.reset || this.optionInit) {
this.dropdownSelectComponent.selectedOptions = this._selectedOptions;
}
if (this.reset) {
this.reset = false;
... | 'Not Found');
}
this._selectedOptions[j] = this.typeService.clone(selectedEle | conditional_block |
Detector.py | .centralwidget)
self.label_3.setGeometry(QtCore.QRect(630, 480, 221, 51))
font = QtGui.QFont()
font.setFamily("微软雅黑")
font.setPointSize(12)
self.label_3.setFont(font)
self.label_3.setStyleSheet("color: rgb(0, 0, 0);")
self.label_3.setObjectName("label_3")
... | ws1.write(0, 3, "裂纹在整个舌头中的占比 ")
self.wb.save('Data.xls')
def pb_1(self):
global c, r, s1, img, x0, x1, y0, y1
while self.flag:
c = 0
r = 0
s1 = 0
# self.textEdit_4.setText(self.file)
# self.textEdit_3.setText("{}".forma... | identifier_body | |
Detector.py | :, 1]
# 图片处理
def bi_demo(image, d, m, n): # 双边滤波
dst = cv2.bilateralFilter(image, d, m, n)
return dst
kernel = np.ones((6, 6), dtype=np.uint8)
erosion = cv2.erode(img2, kernel, 16)
img2 = cv2.dilate(img2, kernel, 25)
img2 = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, ke... | ): # 按住左键拖曳
cv2.rectangle(img2, point1, (x, y), (0, 255, 0), 1)
cv2.imshow('image', img2)
elif event == cv2.EVENT_LBUTTONUP: # 左键释放
point2 = (x, y)
cv2.rectangle(img2, point1, point2, (0, 0, 255), 1)
cv2.imshow('image', img2)
min_x = min(point1[0], point2[0])... | _LBUTTON | identifier_name |
Detector.py | getcontext().prec = 4
s = Decimal(count) / Decimal((img4.shape[0] * img4.shape[1] - all))
return count, s
count, s = area(img3, img2)
str = '要显示的字符串'
print("舌像裂纹面积为:{} 像素点, 占整个舌头像素的:{}".format(count, s))
result = lwdt(img3)
r = result
c = count
s1 = s
... | # self.lb.raise_()
mainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(mainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 958, 26))
self.menubar.setObjectName("menubar")
| random_line_split | |
Detector.py | 1]
# 图片处理
def bi_demo(image, d, m, n): # 双边滤波
dst = cv2.bilateralFilter(image, d, m, n)
return dst
kernel = np.ones((6, 6), dtype=np.uint8)
erosion = cv2.erode(img2, kernel, 16)
img2 = cv2.dilate(img2, kernel, 25)
img2 = cv2.morphologyEx(img2, cv2.MORPH_CLOSE, kerne... | ):
if (image0[y, x] == 0):
all = all + 1
img4 = img[:, :, 0]
for y in range(0, image.shape[0], 1):
for x in range(0, image.shape[1], 1):
if (image[y, x] == 255):
count = count + 1
getcontext().prec = 4
... | for x in range(0, image0.shape[1], 1 | conditional_block |
admin_panel.py | tgid"] in UsersDB.allAdminsId():
await message.answer(f'Пользователь {user["username"]} уже является админом!')
return
# Successful adding admin
UsersDB.update(user["tgid"], "role", Role.Admin.value)
await message.answer(f'@{user["username"]} Назначен Администратор... | tent_types=[ContentType.ANY])
async def stateBroadcastAll(message: Message, state: FSMContext):
q = str(message.text).replace('<', '').replace('>', '')
await state.update_data(broadcast_msg=q)
await message.answer(text="⭐Вот превью рассылки\n"
"———————————————\n"
... | нена",
reply_markup=nav.startMenu(message.from_user.id))
await state.finish()
@dp.message_handler(IsAdmin(), state=AdminPanel.Broadcast, con | identifier_body |
admin_panel.py | (chat_id=user["tgid"],
text=f'Вы назначены Администратором!'
f'Ваш бог: @{message.from_user.username}')
@dp.message_handler(IsAdmin(), commands=[CMDS["CHANGE_FEE"]])
async def cmdAddAdmin(message: Message, command):
if command and command.a... | thdraw_data")["card"], float(wd["amount"]))
try:
await cb.message.answer(text=MSG["AUTOPAY_INFO"].format(s["fields"]["account"],
s["sum"][" | conditional_block | |
admin_panel.py |
@dp.message_handler(IsAdmin(), commands=[CMDS["CHANGE_FEE"]])
async def cmdAddAdmin(message: Message, command):
if command and command.args:
nick = command.args.split()[0]
user = UsersDB.getUserByContraNick(nick)
# If username is not valid
if not user:
await ... | identifier_name | ||
admin_panel.py | tgid"] in UsersDB.allAdminsId():
await message.answer(f'Пользователь {user["username"]} уже является админом!')
return
# Successful adding admin
UsersDB.update(user["tgid"], "role", Role.Admin.value)
await message.answer(f'@{user["username"]} Назначен Администратор... | await message.answer(text="⭐Вот превью рассылки\n"
"———————————————\n"
f"{q}\n"
"———————————————\n",
reply_markup=nav.confirm_menu)
@dp.message_handler(IsAdmin(), Text(NAV["BACK"]))
async def... | random_line_split | |
dg_terraria.py | 2, W=Normal(0.05), nonlinearity=nn.lrelu)))
disc_layers.append(nn.weight_norm(ll.NINLayer(disc_layers[-1], num_units=192, W=Normal(0.05), nonlinearity=nn.lrelu)))
disc_layers.append(ll.GlobalPoolLayer(disc_layers[-1]))
disc_layers.append(nn.MinibatchLayer(disc_layers[-1], num_kernels=100))
# Number of units in the last... | random_line_split | ||
dg_terraria.py | = T.mean(T.neq(T.argmax(output_before_softmax_lab, axis=1), labels))
#Error.
output_before_softmax = ll.get_output(disc_layers[-1], x_lab, deterministic=True)
test_err = T.mean(T.neq(T.argmax(output_before_softmax, axis=1), labels))
print("Finished setting up cost functions.")
#Training set-up.
if tdg_train:
pri... | NNdiff = np.sum(
np.sum(np.sum(np.square(np.expand_dims(sample_x, axis=1) - np.expand_dims(trainx, axis=0)), axis=2),
axis=2), axis=2)
NN = trainx[np.argmin(NNdiff, axis=1)]
NN = np.transpose(NN[:100], (0, 2, 3, 1))
NN_tile = plotting.img_tile(NN, aspect_ratio=1.0,... | conditional_block | |
builtin_fn_misc.go | // ```elvish-transcript
// ~> var f = (constantly lorem ipsum)
// ~> $f
// ▶ lorem
// ▶ ipsum
// ```
//
// The above example is equivalent to simply `var f = { put lorem ipsum }`;
// it is most useful when the argument is **not** a literal value, e.g.
//
// ```elvish-transcript
// ~> var f = (constantly (uname))
// ~> ... | unique names for each source passed to eval.
var (
evalCount int
evalCountMutex sync.Mutex
)
func nextEvalCount() int {
evalCountMutex.Lock()
defer evalCountMutex.Unlock()
evalCount++
return evalCount
}
//elvdoc:fn use-mod
//
// ```elvish
// use-mod $use-spec
// ```
//
// Imports a module, and outputs the ... | k of eval")
errCb := opts.OnEnd.Call(newFm, []interface{}{newNs}, NoOpts)
if exc == nil {
return errCb
}
}
return exc
}
// Used to generate | conditional_block |
builtin_fn_misc.go | // ```elvish-transcript
// ~> var f = (constantly lorem ipsum)
// ~> $f
// ▶ lorem
// ▶ ipsum
// ```
//
// The above example is equivalent to simply `var f = { put lorem ipsum }`;
// it is most useful when the argument is **not** a literal value, e.g.
//
// ```elvish-transcript
// ~> var f = (constantly (uname))
// ~> ... | lOpts, code string) error {
src := parse.Source{Name: fmt.Sprintf("[eval %d]", nextEvalCount()), Code: code}
ns := opts.Ns
if ns == nil {
ns = CombineNs(fm.up, fm.local)
}
// The stacktrace already contains the line that calls "eval", so we pass
// nil as the second argument.
newNs, exc := fm.Eval(src, nil, ns... | *Frame, opts eva | identifier_name |
builtin_fn_misc.go |
// For rand and randint.
rand.Seed(time.Now().UTC().UnixNano())
}
//elvdoc:fn nop
//
// ```elvish
// nop &any-opt= $value...
// ```
//
// Accepts arbitrary arguments and options and does exactly nothing.
//
// Examples:
//
// ```elvish-transcript
// ~> nop
// ~> nop a b c
// ~> nop &k=v
// ```
//
// Etymology: Var... | {
addBuiltinFns(map[string]interface{}{
"nop": nop,
"kind-of": kindOf,
"constantly": constantly,
// Introspection
"call": call,
"resolve": resolve,
"eval": eval,
"use-mod": useMod,
"deprecate": deprecate,
// Time
"sleep": sleep,
"time": timeCmd,
"-ifaddrs": _ifaddrs,
}) | identifier_body | |
builtin_fn_misc.go | //
// ```elvish-transcript
// ~> var f = (constantly lorem ipsum)
// ~> $f
// ▶ lorem
// ▶ ipsum
// ```
//
// The above example is equivalent to simply `var f = { put lorem ipsum }`;
// it is most useful when the argument is **not** a literal value, e.g.
//
// ```elvish-transcript
// ~> var f = (constantly (uname))
// ... | // ~> var f = {|a &k1=v1 &k2=v2| put $a $k1 $k2 }
// ~> call $f [foo] [&k1=bar]
// ▶ foo
// ▶ bar
// ▶ v2
// ```
func call(fm *Frame, fn Callable, argsVal vals.List, optsVal vals.Map) error {
args := make([]interface{}, 0, argsVal.Len())
for it := argsVal.Iterator(); it.HasElem(); it.Next() {
args = append(args, i... | random_line_split | |
Executor.py | status """
def __init__(self, config=None, **kwargs):
"""
Args:
config (dict): dictionary of config settings. will be merged with
any other provided kwargs. valid keys are:
CCDDRONEPATH (str): path to top-level of CCDDrone installation
CC... | status['cmdoutput'] += line
except FileNotFoundError:
status['cmdoutput'] = ""
# info for the lastimg to update
status['lastimg'] = self.lastimgpath
try:
status['lastimg_timestamp'] = path.getmtime(self.lastimgpath)
except ... | if not line.endswith('\r'): | random_line_split |
Executor.py | status """
def __init__(self, config=None, **kwargs):
"""
Args:
config (dict): dictionary of config settings. will be merged with
any other provided kwargs. valid keys are:
CCDDRONEPATH (str): path to top-level of CCDDrone installation
CC... | (self, fitsfile, seconds=5):
""" Expose the CCD and read a new image to `fitsfile` """
# make sure the file has good name
if not fitsfile.endswith('.fits'):
fitsfile += '.fits'
tstamp = datetime.now().strftime('_%y%m%d-%H%M')
match = re.match(r'.*(_\d\d\d\d\d\d-\d\d\d... | Expose | identifier_name |
Executor.py | status """
def __init__(self, config=None, **kwargs):
"""
Args:
config (dict): dictionary of config settings. will be merged with
any other provided kwargs. valid keys are:
CCDDRONEPATH (str): path to top-level of CCDDrone installation
CC... |
# methods to run exectuables
def _run(self, args, cwd=None, env=None, logmode='wb'):
""" Run the commands in `args` in a subprocess """
args = tuple(str(arg) for arg in args)
if self.process and self.process.poll() is None:
raise RuntimeError("A process is already running"... | if kill:
self.process.kill()
else:
self.process.terminate()
with open(self.logfilename, 'a') as f:
print("!!!!!! process killed by user !!!!!!!", file=f) | conditional_block |
Executor.py | self.max_exposures = None
self.exposethread = None
self.lastfile=None
self.lastimgpath = getkey('LASTIMGPATH', 'static/lastimg.png')
self.datapath = getkey("DATAPATH", 'data')
self.ccddpath = getkey('CCDDRONEPATH')
CCDDConfigFile = getkey('CCDDCONFIGFILE','config/... | """ Run CCDD processes and keep track of status """
def __init__(self, config=None, **kwargs):
"""
Args:
config (dict): dictionary of config settings. will be merged with
any other provided kwargs. valid keys are:
CCDDRONEPATH (str): path to top-level... | identifier_body | |
UTM.py | return N
N_or_S = "N"
if "S" in row:
N_or_S = "S"
return N_or_S
@staticmethod
def zone2use(el_df):
"""
Create a common UTM Zone for this facility from the emission locations.
All emission sources input to Aermod must have UTM coordinates
f... |
else:
hemi = "N"
if hemi == "N":
epsg = 'epsg:326'+str(zonetxt)
else:
epsg = 'epsg:327'+str(zonetxt)
transformer = UTM.getTransformer('epsg:4326', epsg)
# Use the cached transformer to perform the transformation more quickly!
... | hemi = "S" | conditional_block |
UTM.py | _utmzu
else:
utmzone = min(min_utmzu, min_utmzl)
hemi = min(min_utmbu, min_utmbl)
if utmzone == 0:
emessage = "Error! UTM zone is 0"
Logger.logMessage(emessage)
raise Exception(emessage)
if hemi == "Z":
emessag... | getTransformer | identifier_name | |
UTM.py |
@staticmethod
def getBand(row):
# returns the hemisphere (N or S) portion of a zone string; if none return N
N_or_S = "N"
if "S" in row:
N_or_S = "S"
return N_or_S
@staticmethod
def zone2use(el_df):
"""
Create a common UTM Zone for th... | hemilist = ['N', 'S']
if any(elem in zonestr for elem in hemilist):
return zonestr[:-1]
else:
return zonestr | identifier_body | |
UTM.py | none return N
N_or_S = "N"
if "S" in row:
N_or_S = "S"
return N_or_S
@staticmethod
def zone2use(el_df):
"""
Create a common UTM Zone for this facility from the emission locations.
All emission sources input to Aermod must have UTM coordinates
... | else:
min_utmbl = "N"
if min_utmzu == 0:
utmzone = min_utmzl
else:
if min_utmzl == 0:
utmzone = min_utmzu
else:
utmzone = min(min_utmzu, min_utmzl)
hemi = min(min_utmbu, min_utmbl)
if utmzo... |
lat_df = el_df[["lat"]].loc[el_df["location_type"] == "L"]
if lat_df.shape[0] > 0 and lat_df["lat"].min() < 0:
min_utmbl = "S" | random_line_split |
trace.go | andb/api/event"
databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
apischema "github.com/apache/skywalking-banyandb/api/schema"
"git... | return
}
s.setShardNum(e)
s.log.Info().
Str("action", databasev1.Action_name[int32(e.Action)]).
Uint64("shardID", e.Shard.Id).
Msg("received a shard e")
return
}
func (s *shardInfo) setShardNum(eventVal *databasev1.ShardEvent) {
s.RWMutex.Lock()
defer s.RWMutex.Unlock()
idx := eventVal.Shard.Series.GetN... | func (s *shardInfo) Rev(message bus.Message) (resp bus.Message) {
e, ok := message.Data().(*databasev1.ShardEvent)
if !ok {
s.log.Warn().Msg("invalid e data type") | random_line_split |
trace.go | andb/api/event"
databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
apischema "github.com/apache/skywalking-banyandb/api/schema"
"git... | (seriesMeta string) []int {
s.RWMutex.RLock()
defer s.RWMutex.RUnlock()
return s.seriesEventsMap[seriesMeta]
}
func (s *Server) PreRun() error {
s.log = logger.GetLogger("liaison-grpc")
s.shardInfo.log = s.log
s.seriesInfo.log = s.log
err := s.repo.Subscribe(event.TopicShardEvent, s.shardInfo)
if err != nil {
... | FieldIndexCompositeSeriesID | identifier_name |
trace.go | b/api/event"
databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
apischema "github.com/apache/skywalking-banyandb/api/schema"
"github... |
func (s *shardInfo) shardNum(idx string) uint32 {
s.RWMutex.RLock()
defer s.RWMutex.RUnlock()
return s.shardEventsMap[idx]
}
type seriesInfo struct {
log *logger.Logger
seriesEventsMap map[string][]int
sync.RWMutex
}
func (s *seriesInfo) Rev(message bus.Message) (resp bus.Message) {
e, ok := mess... | {
s.RWMutex.Lock()
defer s.RWMutex.Unlock()
idx := eventVal.Shard.Series.GetName() + "-" + eventVal.Shard.Series.GetGroup()
if eventVal.Action == databasev1.Action_ACTION_PUT {
s.shardEventsMap[idx] = eventVal.Shard.Total
} else if eventVal.Action == databasev1.Action_ACTION_DELETE {
delete(s.shardEventsMap, i... | identifier_body |
trace.go | b/api/event"
databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
apischema "github.com/apache/skywalking-banyandb/api/schema"
"github... |
}
func (s *shardInfo) shardNum(idx string) uint32 {
s.RWMutex.RLock()
defer s.RWMutex.RUnlock()
return s.shardEventsMap[idx]
}
type seriesInfo struct {
log *logger.Logger
seriesEventsMap map[string][]int
sync.RWMutex
}
func (s *seriesInfo) Rev(message bus.Message) (resp bus.Message) {
e, ok := me... | {
delete(s.shardEventsMap, idx)
} | conditional_block |
raft.go | () {
// Your code here (2C).
// Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w)
// e.Encode(rf.xxx)
// e.Encode(rf.yyy)
// data := w.Bytes()
// rf.persister.SaveRaftState(data)
}
//
// restore previously persisted state.
//
func (rf *Raft) readPersist(data []byte) {
if data == nil || len(data)... | {
for i := 0; i < len(rf.peers); i++ {
wg.Add(1)
go func(index int, request AppendEntriesRequest, reply AppendEntriesResponse) {
ok := rf.sendAppendEntries(index, &request, &reply)
if ok {
rf.handleAppendEntriesResponse(request, reply)
}
wg.Done()
}(i, request, reply)
}
time.Sleep(t... | conditional_block | |
raft.go | ANDIDATE
FOLLOWER
)
// return currentTerm and whether this server
// believes it is the leader.
func (rf *Raft) GetState() (int, bool) {
var term int
var isleader bool
{
rf.mu.Lock()
term = int(rf.currentTerm)
if rf.leaderId == LEADER {
isleader = true
} else {
isleader = false
}
rf.mu.Unlock()... | // e.Encode(rf.xxx)
// e.Encode(rf.yyy)
// data := w.Bytes()
// rf.persister.SaveRaftState(data)
}
//
// restore previously persisted state.
//
func (rf *Raft) readPersist(data []byte) {
if data == nil || len(data) < 1 { // bootstrap without any state?
return
}
// Your code here (2C).
// Example:
// r := by... | // Example:
// w := new(bytes.Buffer)
// e := labgob.NewEncoder(w) | random_line_split |
raft.go | IDATE
FOLLOWER
)
// return currentTerm and whether this server
// believes it is the leader.
func (rf *Raft) GetState() (int, bool) {
var term int
var isleader bool
{
rf.mu.Lock()
term = int(rf.currentTerm)
if rf.leaderId == LEADER {
isleader = true
} else {
isleader = false
}
rf.mu.Unlock()
}... |
func (rf *Raft) handleAppendEntriesResponse(request AppendEntriesRequest, | {
ok := rf.peers[server].Call("Raft.AppendEntries", args, reply)
return ok
} | identifier_body |
raft.go | IDATE
FOLLOWER
)
// return currentTerm and whether this server
// believes it is the leader.
func (rf *Raft) GetState() (int, bool) {
var term int
var isleader bool
{
rf.mu.Lock()
term = int(rf.currentTerm)
if rf.leaderId == LEADER {
isleader = true
} else {
isleader = false
}
rf.mu.Unlock()
}... | (server int, args *RequestVoteArgs, reply *RequestVoteReply) bool {
ok := rf.peers[server].Call("Raft.RequestVote", args, reply)
return ok
}
func (rf *Raft) handleRequestVoteResponse(request RequestVoteArgs, reply RequestVoteReply) bool {
rf.updateTerm(reply.Term)
rf.mu.Lock()
if rf.currentTerm != request.Term {
... | sendRequestVote | identifier_name |
waxxedit.js | //h1:"h1",
//h2:"h2",
//h3:"h3", | //upload:"upload"
},
configuration:function(editor_id,textareaId,width,height,color){
wedit.configs.editor_id = editor_id || this.configs.editor_id;
wedit.configs.textareaId = textareaId || this.configs.textareaId;
wedit.configs.width = width || this.configs.width;
wedit.configs.height = height || this.co... | //h4:"h4", | random_line_split |
waxxedit.js | s.toolbarH,wedit.configs.toobarBorder,wedit.configs.toobarBgColor));
//创建UL标签
var ulObj = this.uMethods.createEle("ul","ul");
ulObj.className = wedit.configs.ulClassName;
//加载菜单栏按钮
this.toolMethods.loadToolBarMenu(ulObj);
wedit.toolbarObj.appendChild(ulObj);
//菜单栏样式调整
//加载菜单栏绑定事件
wedit.toolMethods.cre... | ele.className = wedit.tbarMenu.h1;
}else if(type | identifier_body | |
waxxedit.js | Class.setTooBgColor(wedit.toolbarObj,wedit.configs.toolbarW,wedit.configs.toolbarH,wedit.configs.toobarBorder,wedit.configs.toobarBgColor));
//创建UL标签
var ulObj = this.uMethods.createEle("ul","ul");
ulObj.className = wedit.configs.ulClassName;
//加载菜单栏按钮
this.toolMethods.loadToolBarMenu(ulObj);
wedit.toolbarO... | if(type == 'h1' | identifier_name | |
index.funcs.js | (num2Scroll, dir2Scroll) {
carousel.carouFredSel({
align : "center",
width : "100%",
onWindowResize : 'throttle',
items : Math.round(window.innerWidth/200),
scroll : window.num2Scroll,
direction : window.dir2Scroll,
swipe : {
onTouch : true
},
pr... | setCarousel | identifier_name | |
index.funcs.js | tmp = "'<li><time datetime=\"' + item.updated + '\">' + item.updated.substr(0,10) + '</time>: <a href=\"' + item.url + '\" target=\"_blank\">' + item.title + '</a></li>'";
limit = 5;
break;
case ('twitter'):
http = 'http://search.twitter.com/search.json?q=jahdakine&callback=?';
obj = 'dat... | {
//console.log(http);
//!!!cache? Would need to use local storage or DB or jquery-json.2.4.0
if(http !== '') {
$.ajax({
dataType: "jsonp",
jsonp: "callback",
url: http,
success: function(data) {
console.log("Data received via test: " + JSON.stringify(data));
if(id==="coderb... | identifier_body | |
index.funcs.js | window\" target=\"_blank\">' +item.commit.message+ '</a></li>'";
limit = 5;
break;
case ('youtube'):
http="https://gdata.youtube.com/feeds/api/users/jahdakine/uploads?v=2&alt=json";
obj = "data.feed.entry";
tmp = "'<li><time datetime=\"' + item.updated.$t + '\">' +item.updated.$t.substr(0,10) + ... | {
menu_graphics.trigger('click');
} | conditional_block | |
index.funcs.js | = false;
show = "content_frame.css('display','inline').removeClass('image-matrix')";
switch (id) {
case ('blogger'):
http = 'https://www.googleapis.com/blogger/v3/blogs/2575251403540723939/posts?key=AIzaSyC4Zhv-nd_98_9Vn8Ad3U6TjY99Pd2YzOQ';
obj = 'data.items';
tmp = "'<li><time datetime=\"' + item... | dataType: "jsonp",
jsonp: "callback", | random_line_split | |
backend.rs | the License.
//! Substrate blockchain trait
use log::warn;
use parking_lot::RwLock;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT, NumberFor, Saturating},
Justifications,
};
use std::collections::btree_set::BTreeSet;
use crate::header_metadata::HeaderMetadata;
use crate::error:... | (&self, hash: Block::Hash) -> Result<Block::Header> {
self.header(hash)?
.ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", hash)))
}
/// Convert an arbitrary block ID into a block number. Returns `UnknownBlock` error if block is
/// not found.
fn expect_block_number_from_id(&self, id: &BlockId<B... | expect_header | identifier_name |
backend.rs | License.
//! Substrate blockchain trait
use log::warn;
use parking_lot::RwLock;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT, NumberFor, Saturating},
Justifications,
};
use std::collections::btree_set::BTreeSet;
use crate::header_metadata::HeaderMetadata;
use crate::error::{Er... | ,
Ok(None) | Err(_) => {
missing_blocks.push(BlockId::<Block>::Number(parent_number));
break
},
}
route_head = meta.parent;
},
Err(_e) => {
missing_blocks.push(BlockId::<Block>::Hash(route_head));
break
},
}
}
}
if !missing_blocks.is_empt... | {
break
} | conditional_block |
backend.rs | }
/// Convert an arbitrary block ID into a block hash.
fn block_number_from_id(&self, id: &BlockId<Block>) -> Result<Option<NumberFor<Block>>> {
match *id {
BlockId::Hash(h) => self.number(h),
BlockId::Number(n) => Ok(Some(n)),
}
}
/// Get block header. Returns `UnknownBlock` error if block is not foun... | pub enum BlockStatus {
/// Already in the blockchain.
InChain,
/// Not in the queue or the blockchain. | random_line_split | |
webpack.config.js | WebpackManifestPlugin: ManifestPlugin,
} = require("webpack-manifest-plugin");
const postcssNormalize = require("postcss-normalize");
const paths = require("./paths");
const { StonksWatcherWidget } = require("../widget.config");
const isDevelopment = process.env.NODE_ENV === "development";
const appPackageJson = req... | ],
},
sourceMap: true,
},
},
].filter(Boolean);
if (preProcessor) {
loaders.push(
{
loader: require.resolve("resolve-url-loader"),
options: {
sourceMap: true,
root: paths.appSrc,
},
},
{
loader: require.res... | }),
postcssNormalize(), | random_line_split |
webpack.config.js | WebpackManifestPlugin: ManifestPlugin,
} = require("webpack-manifest-plugin");
const postcssNormalize = require("postcss-normalize");
const paths = require("./paths");
const { StonksWatcherWidget } = require("../widget.config");
const isDevelopment = process.env.NODE_ENV === "development";
const appPackageJson = req... |
return loaders;
};
module.exports = {
mode: isDevelopment ? "development" : "production",
bail: !isDevelopment,
devtool: isDevelopment ? "cheap-module-source-map" : "source-map",
devServer: {
contentBase: paths.appBuild,
port: 3002,
},
entry: paths.appIndexJs,
output: {
path: paths.appBuil... | {
loaders.push(
{
loader: require.resolve("resolve-url-loader"),
options: {
sourceMap: true,
root: paths.appSrc,
},
},
{
loader: require.resolve(preProcessor),
options: {
sourceMap: true,
},
}
);
} | conditional_block |
retrieval.py | chunk_bytes: int = CSV_CHUNK_BYTES) -> str:
"""Download file as stream checking filesize and retrying (if able)"""
for _ in range(reps):
# stream from source to avoid MemoryError for very large (>10Gb) files
fd, local_filename = tempfile.mkstemp(dir=tempdir)
with... |
if list(filter(lambda x: x['jobName'].startswith(
f'{source_name}-'), jobs)):
logger.info("Deltas: Ongoing batch jobs relating to source found. "
"Abandoning deltas generation.")
return True
return False
def generate_deltas(env: str, latest_... | logger.info("Deltas: Ongoing batch jobs relating to source found. "
"Abandoning deltas generation.")
return True | conditional_block |
retrieval.py | _id}{d.strftime(TIME_FILEPART_FORMAT)}content.csv"
logger.info(f"Deltas: Identified last good ingestion source at: {s3_bucket}/{s3_key}")
s3_client.download_file(s3_bucket, s3_key, last_ingested_file_name)
logger.info(f"Deltas: Retrieved last good ingestion source: {last_ingested_file_name}")
# confirm ... | e, env, upload_error, source_id, upload_id,
api_headers, cookies)
| random_line_split | |
retrieval.py | : Snapshot batch processes")
batch_client = boto3.client("batch")
jobs: List[Dict] = []
for jobStatus in IN_PROGRESS_STATUS:
r = batch_client.list_jobs(
jobQueue='ingestion-queue',
jobStatus=jobStatus)
jobs.extend(r['jobSummaryList'])
... | parse_datetime | identifier_name | |
retrieval.py | jobStatus in IN_PROGRESS_STATUS:
r = batch_client.list_jobs(
jobQueue='ingestion-queue',
jobStatus=jobStatus)
jobs.extend(r['jobSummaryList'])
logger.info(jobs)
# Be careful here - names are not always immediately obvious:
# e.g. 'ch_zuric... | """Isolate functionality to facilitate easier mocking"""
return dateutil.parser.parse(date_str) | identifier_body | |
wal.go |
closed int32
}
// NewReader constructs a new Reader for reading from this WAL starting at the
// given offset. The returned Reader is NOT safe for use from multiple
// goroutines. Name is just a label for the reader used during logging.
func (wal *WAL) NewReader(name string, offset Offset, bufferSource func() ... | {
return ts.UnixNano() / 1000
} | identifier_body | |
wal.go | .Close()
out, err := ioutil.TempFile("", "")
if err != nil {
return false, fmt.Errorf("Unable to open temp file to compress %v: %v", infile, err)
}
defer out.Close()
defer os.Remove(out.Name())
compressedOut := snappy.NewWriter(out)
_, err = io.Copy(compressedOut, bufio.NewReaderSize(in, defaultFileBuffer))
i... | {
if atomic.LoadInt32(&r.stopped) == 1 {
return 0, io.EOF
}
if atomic.LoadInt32(&r.closed) == 1 {
return 0, io.ErrUnexpectedEOF
}
n, err := r.reader.Read(headBuf[read:])
read += n
r.position += int64(n)
if err != nil && err.Error() == "EOF" && read < 4 {
if r.wal.hasMovedBeyond(r.fil... | conditional_block | |
wal.go | .writer.Flush()
syncErr := wal.file.Sync()
wal.mx.Unlock()
closeErr := wal.file.Close()
if flushErr != nil {
err = flushErr
}
if syncErr != nil {
err = syncErr
}
err = closeErr
})
return
}
func (wal *WAL) advance() error {
wal.fileSequence = newFileSequence()
wal.position = 0
err := wal.ope... | random_line_split | ||
wal.go | offset = NewOffset(fileSequence, position)
}
}()
var r io.Reader
r, err := os.OpenFile(filepath.Join(wal.dir, filename), os.O_RDONLY, 0600)
if err != nil {
return false, fmt.Errorf("Unable to open WAL file %v: %v", filename, err)
}
if strings.HasSuffix(filename, compressedSuffix) {
r = snappy.... | () {
defer close(wal.backlogFinished)
for bufs := range wal.backlog {
if err := wal.doWrite(bufs...); err != nil {
wal.log.Errorf("Error writing to WAL!: %v", err)
}
}
}
func (wal *WAL) doWrite(bufs ...[]byte) error {
wal.mx.Lock()
defer wal.mx.Unlock()
length := 0
for _, b := range bufs {
blen := len... | writeAsync | identifier_name |
dirutils.js | constructed as needed.
For example if a folder exists here:
/path/to/folder
... but the following sub-folders don't exists:
/path/to/folder/sub/one/two/three
... Then the "sub/one/two/three" tree will be constructed inside "/path/to/folder")
* @method makedir
* @private
* @param {string} dest="path/t... | removed.push(dir);
if( ! dryRun ){
fs.rmdirSync(dir);
}
}
}
return removed;
}
;
/**
* Recursively removes a folder and all of it's sub-folders as well.
*
* @method removedir
* @private
* @param {string} who - The path to the folder
* @param {boolean} dryRun - Prevents a... | {
var removed = [];
if( exists(who) ) {
var list = readdir(who, null, true);
var files = list.files;
for(var i=files.length; i--;){
var file = files[i];
removed.push(file);
if( ! dryRun ){
fs.unlinkSync(file);
}
}
var dirs = list.dirs.sort(); // should be... | identifier_body |
dirutils.js | constructed as needed.
For example if a folder exists here:
/path/to/folder
... but the following sub-folders don't exists:
/path/to/folder/sub/one/two/three
... Then the "sub/one/two/three" tree will be constructed inside "/path/to/folder")
* @method makedir
* @private
* @param {string} dest="path/t... | (who, dryRun) {
var removed = [];
if( exists(who) ) {
var list = readdir(who, null, true);
var files = list.files;
for(var i=files.length; i--;){
var file = files[i];
removed.push(file);
if( ! dryRun ){
fs.unlinkSync(file);
}
}
var dirs = list.dirs.sort()... | emptydir | identifier_name |
dirutils.js | constructed as needed.
For example if a folder exists here:
/path/to/folder
... but the following sub-folders don't exists:
/path/to/folder/sub/one/two/three
... Then the "sub/one/two/three" tree will be constructed inside "/path/to/folder")
* @method makedir
* @private
* @param {string} dest="path/t... |
} else {
store.files.push(file);
}
}
}
}
return store;
}
/**
* Copies the entire folder's heirarchy folder from one location to another. If the other location doesn't exists, it will be constructed.
*
* @method copydir
* @private
* @param {string}... | {
store.files.push(file);
} | conditional_block |
dirutils.js | constructed as needed.
For example if a folder exists here:
/path/to/folder
... but the following sub-folders don't exists:
/path/to/folder/sub/one/two/three
... Then the "sub/one/two/three" tree will be constructed inside "/path/to/folder")
* @method makedir
* @private
* @param {string} dest="path/t... | if( ! store ){
store = { dirs: [], files: [] };
}
var hasFilterFunction = typeof filter == 'function';
var files = fs.readdirSync(from);
var len = files.length;
for(var i=0; i<len; i++){
var file = path.join(from, files[i]);
var stats = false; // set this value otherwise a failing try will pickup... | function readdir(from, filter, recursive, store){ | random_line_split |
model_sql_test.go | (src interface{}) error {
if value, ok := src.(string); ok {
*p = password{
hashed: value,
}
}
return nil
}
// used in gopg
func (p *password) ScanValue(rd gopg.TypesReader, n int) error {
value, err := gopg.TypesScanString(rd, n)
if err == nil {
*p = password{
hashed: value,
}
}
return err
}
fun... | Scan | identifier_name | |
model_sql_test.go | used in gopg
func (p *password) ScanValue(rd gopg.TypesReader, n int) error {
value, err := gopg.TypesScanString(rd, n)
if err == nil {
*p = password{
hashed: value,
}
}
return err
}
func (p password) Value() (driver.Value, error) {
return p.hashed, nil
}
func (p password) MarshalJSON() ([]byte, error) {... | if _, err := rand.Read(randomBytes); err != nil {
t.Fatal(err)
}
tradeNo := hex.EncodeToString(randomBytes)
totalAmount, _ := decimal.NewFromString("12.34")
createInput := strings.NewReader(`{
"Status": "changed",
"TradeNumber": "` + tradeNo + `",
"TotalAmount": "` + totalAmount.String() + `",
"foobar_us... | {
t := test{_t}
o := db.NewModel(order{})
o.SetConnection(conn)
o.SetLogger(logger.StandardLogger)
// drop table
err := o.NewSQLWithValues(o.DropSchema()).Execute()
if err != nil {
t.Fatal(err)
}
// create table
err = o.NewSQLWithValues(o.Schema()).Execute()
if err != nil {
t.Fatal(err)
}
randomByt... | identifier_body |
model_sql_test.go | used in gopg
func (p *password) ScanValue(rd gopg.TypesReader, n int) error {
value, err := gopg.TypesScanString(rd, n)
if err == nil {
*p = password{
hashed: value,
}
}
return err
}
func (p password) Value() (driver.Value, error) {
return p.hashed, nil
}
func (p password) MarshalJSON() ([]byte, error) {... |
// create table
err = o.NewSQLWithValues(o.Schema()).Execute()
if err != nil {
t.Fatal(err)
}
randomBytes := make([]byte, 10)
if _, err := rand.Read(randomBytes); err != nil {
t.Fatal(err)
}
tradeNo := hex.EncodeToString(randomBytes)
totalAmount, _ := decimal.NewFromString("12.34")
createInput := strin... | {
t.Fatal(err)
} | conditional_block |
model_sql_test.go | t.Fatal(err)
}
t.Int("second order id", id, 2)
var statuses []string
model.Select("status").MustQuery(&statuses)
t.Int("statuses length", len(statuses), 2)
t.String("status 0", statuses[0], "new")
t.String("status 1", statuses[1], "new2")
var ids []int
model.Select("id").MustQuery(&ids)
t.Int("ids length", ... | t.Logf("%s test passed", name)
} else {
t.Errorf("%s test failed, got %d", name, got)
}
} | random_line_split | |
land_ocean_ratio.py |
and latitude values.
Parameters
----------
georeferenced_array : 2D Array
DESCRIPTION.
loc0 : float or integer
The first extent value of the georeferenced array.
loc1 : float or integer
The second extent value of the georeferenced array.
Returns
-------
int... | MultiProcessCrop | identifier_name | |
land_ocean_ratio.py | 0, 0, right_x, bottom_y),
gdal.GCP(0, -60, 0, left_x, bottom_y)]
ds.SetProjection(sr.ExportToWkt())
wkt = ds.GetProjection()
ds.SetGCPs(gcps, wkt)
os.chdir(r'/home/huw/Dropbox/Sophie/SeaLevelChange/georeferenced')
gdal.Warp(f"{tif_image}.tif", ds, dstSRS='EPSG:4326', format='gtiff')
... |
elif type(box_perimeter_fill_value) == int:
land_percentage = round((land_pixels/image_pixels)*100, 4)
ocean_percentage = round((ocean_pixels/image_pixels)*100, 4)
# land_percentage = round((land_pixels/image_pixels)*100, 4)
# ocean_percentage = round((ocean_pixels/image_pixels)*100, 4)
land_ocean_... | land_percentage = round((land_pixels/non_nan_pixels)*100, 4)
ocean_percentage = round((ocean_pixels/non_nan_pixels)*100, 4) | conditional_block |
land_ocean_ratio.py | 0, 0, right_x, bottom_y),
gdal.GCP(0, -60, 0, left_x, bottom_y)]
ds.SetProjection(sr.ExportToWkt())
wkt = ds.GetProjection()
ds.SetGCPs(gcps, wkt)
os.chdir(r'/home/huw/Dropbox/Sophie/SeaLevelChange/georeferenced')
gdal.Warp(f"{tif_image}.tif", ds, dstSRS='EPSG:4326', format='gtiff')
... |
land_ocean_ratio = round(land_percentage/ocean_percentage, 10)
print(f'{box_perimeter_fill_value}', land_ocean_ratio)
map_projection = ccrs.PlateCarree()
fig, axes = plt.subplots(n | ocean_percentage = round((ocean_pixels/image_pixels)*100, 4)
# land_percentage = round((land_pixels/image_pixels)*100, 4)
# ocean_percentage = round((ocean_pixels/image_pixels)*100, 4)
| random_line_split |
land_ocean_ratio.py | 60, 0, right_x, bottom_y),
gdal.GCP(0, -60, 0, left_x, bottom_y)]
ds.SetProjection(sr.ExportToWkt())
wkt = ds.GetProjection()
ds.SetGCPs(gcps, wkt)
os.chdir(r'/home/huw/Dropbox/Sophie/SeaLevelChange/georeferenced')
gdal.Warp(f"{tif_image}.tif", ds, dstSRS='EPSG:4326', format='gtiff')
... | return converted_array
os.chdir(r'/home/huw/Dropbox/Sophie/SeaLevelChange/georeferenced')
georeferenced_images = os.listdir()
georeferenced_images.sort()
test = raster_to_array(georeferenced_images[0])
test_extent = map_extent(georeferenced_images[0])
x0, x1 = test_extent[0], test_extent[1]
y0, y1 = test_exten... | """
Convert a raster tiff image to a numpy array. Input Requires the
address to the tiff image.
Parameters
----------
input_raster : string
Directory to the raster which should be in tiff format.
Returns
-------
converted_array : numpy array
A numpy array of the input r... | identifier_body |
mod.rs | ));
Ok(storage)
}
/// Sets up an instance of `Storage`, with git turned on.
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::C... |
/// Testing only, | {
let metadata = try!(fs::metadata(path));
let accessed = try!(metadata.accessed());
Ok(try!(accessed.elapsed()))
} | identifier_body |
mod.rs | fn projects_to_csv(projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects... | random_line_split | ||
mod.rs | ));
Ok(storage)
}
/// Sets up an instance of `Storage`, with git turned on.
pub fn setup_luigi_with_git() -> Result<Storage<Project>> {
trace!("setup_luigi()");
let working = try!(::CONFIG.get_str("dirs/working").ok_or("Faulty config: dirs/working does not contain a value"));
let archive = try!(::C... | (projects:&[Project]) -> Result<String>{
let mut string = String::new();
let splitter = ";";
try!(writeln!(&mut string, "{}", [ "Rnum", "Bezeichnung", "Datum", "Rechnungsdatum", "Betreuer", "Verantwortlich", "Bezahlt am", "Betrag", "Canceled"].join(splitter)));
for project in projects{
try!(writ... | projects_to_csv | identifier_name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.