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 |
|---|---|---|---|---|
classifier.d15b2d9b.js | zcr_mean", "zcr_std", "zcr_var", "harm_mean", "harm_std", "harm_var", "perc_mean", "perc_std", "perc_var", "frame_mean", "frame_std", "frame_var"];
this.featuresToIgnore = [];
}
ShapeData.prototype.makeDatasetForTensors = function (data) {
var dataInputs = [];
var dataOutputs = [];
... | (result) {
result.done ? resolve(result.value) : new P(function (resolve) {
resolve(result.value);
}).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = this && this.__generator || funct... | step | identifier_name |
classifier.d15b2d9b.js | catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : new P(function (resolve) {
resolve(result.value);
}).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _argu... | {
var features = [];
for (var _i = 0, data_1 = data; _i < data_1.length; _i++) {
var singleSong = data_1[_i];
for (var _a = 0, _b = data[singleSong]; _a < _b.length; _a++) {
var singleFeature = _b[_a];
console.log(data[singleSong][singleFeature]);
... | identifier_body | |
wfq.go | new(heapItem)
}
func getHeapItem() *heapItem {
return hi_pool.Get().(*heapItem)
}
func putHeapItem(hi *heapItem) {
hi.fi = nil
hi.value = nil
hi_pool.Put(hi)
}
/*****************************************************************************
*
*********************************************************************... |
func getOverflowHeapItem() *overflowHeapItem {
return ohi_pool.Get().(*overflowHeapItem)
}
func putOverflowHeapItem(ohi *overflowHeapItem) {
ohi.hi = nil
ohi_pool.Put(ohi)
}
/*****************************************************************************
*
********************************************************... | {
return new(overflowHeapItem)
} | identifier_body |
wfq.go | new(heapItem)
}
func getHeapItem() *heapItem {
return hi_pool.Get().(*heapItem)
}
func putHeapItem(hi *heapItem) {
hi.fi = nil
hi.value = nil
hi_pool.Put(hi)
}
/*****************************************************************************
*
*********************************************************************... | (o *overflowHeapItem) bool {
if i.hi.weight > o.hi.weight {
return true
} else if i.hi.weight == o.hi.weight && i.arrord < o.arrord {
return true
}
return false
}
var ohi_pool sync.Pool
func newOverflowHeapItem() interface{} {
return new(overflowHeapItem)
}
func getOverflowHeapItem() *overflowHeapItem {
re... | less | identifier_name |
wfq.go | []*heapItem
func (h *itemHeap) Len() int {
return len(*h)
}
func (h *itemHeap) Less(i, j int) bool {
return (*h)[i].vft < (*h)[j].vft
}
func (h *itemHeap) Swap(i, j int) {
(*h)[i], (*h)[j] = (*h)[j], (*h)[i]
}
func (h *itemHeap) Push(x interface{}) {
item := x.(*heapItem)
*h = append(*h, item)
}
func (h *ite... | {
return false
} | conditional_block | |
wfq.go | return new(heapItem)
}
func getHeapItem() *heapItem {
return hi_pool.Get().(*heapItem)
}
func putHeapItem(hi *heapItem) {
hi.fi = nil
hi.value = nil
hi_pool.Put(hi)
}
/*****************************************************************************
*
**************************************************************... | // Queue will panic if the size of the item is greater then maxFlowSize (set in NewQueue).
// Queue is safe for concurrent use.
//
func (q *Queue) Queue(item interface{}) bool {
hi := getHeapItem()
hi.value = item
hi.key = q.helper.Key(item)
hi.size = q.helper.Size(item)
hi.weight = q.helper.Weight(item)
if hi.s... | }
// Place on item on the queue. Queue will not return (i.e. block) until the item can be placed on the queue
// or the queue was closed. If Queue returns true, then DeQueue will eventually return the item.
// If Queue returns false, then the item was not placed on the queue because the queue has been closed. | random_line_split |
mod.rs | max_amp: f32
}
impl UI<'static> {
pub fn create () -> Self {
let font_path = find_font();
if let Err(e) = font_path {
use std::io::Write;
let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap();
file.write_all(b"Could not find the font path!").unwrap();
}
le... |
if sample > | {
self.min_amp = sample
} | conditional_block |
mod.rs | ;
// Font size relative to UI overlay (always three lines high)
self.base_font_size = (overlay_height / 3.0 * 0.95).floor();
if self.base_font_size > 14.0 {
self.base_font_size = 14.0; // Don't overdo it
}
// Colors
let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32];
// Overlay ... | {
// ...
} | identifier_body | |
mod.rs | max_amp: f32
}
impl UI<'static> {
pub fn create () -> Self {
let font_path = find_font();
if let Err(e) = font_path {
use std::io::Write;
let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap();
file.write_all(b"Could not find the font path!").unwrap();
}
le... |
// Font size relative to UI overlay (always three lines high)
self.base_font_size = (overlay_height / 3.0 * 0.95).floor();
if self.base_font_size > 14.0 {
self.base_font_size = 14.0; // Don't overdo it
}
// Colors
let bg_color = [0.0, 0.0, 0.0, self.ui_opacity as f32];
// Overlay ar... | let overlay_top = self.height as f64 * 0.8;
let overlay_height = self.height as f64 * 0.2; | random_line_split |
mod.rs | max_amp: f32
}
impl UI<'static> {
pub fn create () -> Self {
let font_path = find_font();
if let Err(e) = font_path {
use std::io::Write;
let mut file = std::fs::File::create("/Users/hendrik/Desktop/log.txt").unwrap();
file.write_all(b"Could not find the font path!").unwrap();
}
le... | (&mut self, begin_point: [f64; 2], text: String, gl: &mut GlGraphics, context: Context) -> [f64; 4] {
// Draws a text button with the UIs style
let padding = 5.0;
let real_width = self.ui_font.width(self.base_font_size as u32, text.as_str()).unwrap() + 2.0 * padding;
let real_height = self.base_font_si... | draw_text_button | identifier_name |
mod.rs | )
});
let rebacking = HashMap::from_iter(rebacking_pairs);
Distribution(rebacking)
}
pub fn value_of_information(&self, study: &Study) -> f64 {
let mut entropy = 0.;
let mut probability_of_the_property = 0.;
let mut probability_of_the_negation = 0.;
... | let distribution = complexity_prior(standard_basic_hypotheses());
bencher.iter(|| {
distribution.entropy()
});
}
#[be | identifier_body | |
mod.rs | = 1.0/(hypotheses.len() as f64);
for hypothesis in hypotheses.into_iter() {
backing.insert(hypothesis, probability_each);
}
Distribution(backing)
}
fn backing(&self) -> &HashMap<H, f64> {
&self.0
}
fn mut_backing(&mut self) -> &mut HashMap<H, f64> {
... | // that I ran into when I was first sketching out the number game, as
// accounted in the README: if the true meaning of the complexity
// penalty is that the hypothesis "A" gets to sum over the unspecified
// details borne by the more complicated hypotheses "A ∧ B" and "A ∧
// C... | // ⎳ i=1 1/2^i = 1
//
// So ... I want to give conjunctions and disjunctions a lower prior
// probability, but I'm running into the same philosophical difficulty | random_line_split |
mod.rs | 1.0/(hypotheses.len() as f64);
for hypothesis in hypotheses.into_iter() {
backing.insert(hypothesis, probability_each);
}
Distribution(backing)
}
fn backing(&self) -> &HashMap<H, f64> {
&self.0
}
fn mut_backing(&mut self) -> &mut HashMap<H, f64> {
&... | (&self, desired_bits: f64, sample_cap: usize)
-> Study {
let mut study = Study::sample();
let mut value = self.value_of_information(&study);
let mut top_study = study.clone();
let mut top_value = value;
let mut samples = 1;
loop {
i... | burning_question | identifier_name |
mod.rs | 1.0/(hypotheses.len() as f64);
for hypothesis in hypotheses.into_iter() {
backing.insert(hypothesis, probability_each);
}
Distribution(backing)
}
fn backing(&self) -> &HashMap<H, f64> {
&self.0
}
fn mut_backing(&mut self) -> &mut HashMap<H, f64> {
&... |
study = Study::sample();
value = self.value_of_information(&study);
samples += 1;
}
top_study
}
pub fn inspect(&self, n: usize) {
let mut backing = self.backing().iter().collect::<Vec<_>>();
backing.sort_by(|a, b| b.1.partial_cmp(a.1).unwrap_... | {
break;
} | conditional_block |
ppno.py | ')])
tmp = []
for line in sections['PIPES']:
ide,series = myht.line_to_tuple(line)
ix = et.ENgetlinkindex(ide)
l = et.ENgetlinkvalue(ix,et.EN_LENGTH)
tmp.append((ix,ide,l,series))
self.pipes = np.array(tmp,dt)
print('%i pipe/s to si... | return deficits
def save_file(self,fn):
'''Save inp file updating d and roughness'''
# UPDATE AND SAVE MODEL
et.ENsaveinpfile(fn)
def get_cost(self):
'''Return the network cost. Sum of length x price for each pipe'''
acumulate = 0.0
... | elif mode == 'PD':
| random_line_split |
ppno.py | # CHECK PRESSURES IN NODES
for index,node in np.ndenumerate(self.nodes):
ix = int(node['ix'])
cp = et.ENgetnodevalue(ix,et.EN_PRESSURE)
rp = node['pressure']
nodaldeficit = rp - cp
if nodaldeficit > 0:
... | int the solution in a readable format'''
# PRINT SOLUTION
cost = 0
print('*** SOLUTION ***')
print('-'*80)
m = '{:>16} {:>16} {:>8} {:>9} {:>6} {:>6} {:>10}'.format( \
'Epanet Pipe ID', 'series name', 'diameter',\
... | identifier_body | |
ppno.py | ')])
tmp = []
for line in sections['PIPES']:
ide,series = myht.line_to_tuple(line)
ix = et.ENgetlinkindex(ide)
l = et.ENgetlinkvalue(ix,et.EN_LENGTH)
tmp.append((ix,ide,l,series))
self.pipes = np.array(tmp,dt)
print('%i pipe/s to si... |
if status:
solution = self.get_x().copy()
if self.algorithm in [A_DE, A_DA]:
# DIFFEERENTIAL EVOLUTION / DUAL ANNEALING ALGORITHM
# SET BOUNDS
tmp = list(zip(self.lbound,self.ubound))
self.boun... | elf.get_x()
if x[index] < self.ubound[index]:
x[index] += 1
self.set_x(x)
break
| conditional_block |
ppno.py | 6')])
tmp = []
for line in sections['PIPES']:
ide,series = myht.line_to_tuple(line)
ix = et.ENgetlinkindex(ide)
l = et.ENgetlinkvalue(ix,et.EN_LENGTH)
tmp.append((ix,ide,l,series))
self.pipes = np.array(tmp,dt)
print('%i pipe/s to s... | ):
'''Return x
'''
return self._x
def _update(self):
'''Update pipe diameter and roughness in the epanet model
'''
for index,pipe in np.ndenumerate(self.pipes):
ix = pipe['ix']
series = self.catalog[pipe['series']]
... | (self | identifier_name |
Scanner3D.py | corners clockwise of a rectangle so that the top-left corner
is the first one.
"""
center = np.sum(corners, axis=0) / 4
sorted_corners = sorted(
corners,
key=lambda p: math.atan2(p[0][0] - center[0][0], p[0][1] - center[0][1]),
reverse=True,
... | (
self,
original_image: np.ndarray,
image: np.ndarray,
extreme_points: ExtremePoints,
) -> Tuple[
Optional[np.ndarray],
Optional[np.ndarray],
Optional[np.ndarray],
Optional[np.ndarray],
]:
"""
Given the interesting regio... | get_laser_points | identifier_name |
Scanner3D.py | else good_contours[2],
)
cv.drawContours(mask, [self.contour1], 0, 255, -1)
cv.drawContours(mask, [self.contour2], 0, 255, -1)
return mask
def sort_corners(self, corners: np.ndarray):
"""
Sort the 4 corners clockwise of a rectangle so that th... | """
Given a thresholded image of the scene (ideally, the first frame),
return the masks for the two known rectangles: one on the wall and one on the desk.
"""
contours = cv.findContours(thresh, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)[0]
mask = np.zeros(thresh.shape, np.uint8)
... | identifier_body | |
Scanner3D.py | a tight bounding box of the area
between the two rectangles.
"""
ymin_wall = int(np.min(wall_corners[:, :, 1]))
ymax_wall = int(np.max(wall_corners[:, :, 1]))
ymin_desk = int(np.min(desk_corners[:, :, 1]))
ymax_desk = int(np.max(desk_corners[:, :, 1]))
xmi... | urn
| conditional_block | |
Scanner3D.py | corners clockwise of a rectangle so that the top-left corner
is the first one.
"""
center = np.sum(corners, axis=0) / 4
sorted_corners = sorted(
corners,
key=lambda p: math.atan2(p[0][0] - center[0][0], p[0][1] - center[0][1]),
reverse=True,
... | laser_wall = self.offset_points(
points=laser_wall, offset=Point(xmin, ymin_wall)
)
laser_obj = self.remove_obj_outliers(laser_obj)
if laser_obj is not None:
laser_obj = self.offset_point... | points=laser_desk, offset=Point(xmin, ymin_desk)
)
| random_line_split |
blackjack (1).py | =-1
else:
self.hand = new_sums[-1]
self.possible_sums = new_sums
def is_blackjack(self):
"""Is current cards the Blackjack?"""
if self.hand == 21 and len(list(self)) ==2:
print '%s = Blackjack'%self
return True
def __lt__... | dealer.deal_self()
print dealer | conditional_block | |
blackjack (1).py | append it.
Then, find all possible sums and the current hand.
The current hand is defined as max. of possible sums
The current hand should be -1 if burst"""
self.append(card)
values=[]
values.append(card.value())
if values[0] < 2:
values.append(value... | (self):
self.players = []
self.dealer = None
def join(self, player):
self.players.append(player)
def leave(self, player):
self.players.remove(player)
def dealer_join(self, dealer):
self.dealer = dealer
def dealer_leave(self, dealer):
self.dealer = None
... | __init__ | identifier_name |
blackjack (1).py | append it.
Then, find all possible sums and the current hand.
The current hand is defined as max. of possible sums
The current hand should be -1 if burst"""
self.append(card)
values=[]
values.append(card.value())
if values[0] < 2:
values.append(value... |
def join(self, game):
"""join a Blackjack game"""
self.game = game
self.game.dealer_join(self)
return self.game
def leave(self):
"""Leave the Blackjack game"""
self.game.dealer_leave(self)
return self.game
def showdown(self):
"""Face up dealer... | """Get a card from the deck"""
return self.deck.pop() | identifier_body |
blackjack (1).py | append it.
Then, find all possible sums and the current hand.
The current hand is defined as max. of possible sums
The current hand should be -1 if burst"""
self.append(card)
values=[]
values.append(card.value())
if values[0] < 2:
values.append(value... | player.restart()
self.dealer.restart()
return True
def repeat(self):
while self.start():
pass
if __name__ == '__main__':
print "==Testing BJCards"
def test_cards(card_list):
cards = BJCards()
for c in card_list:
... | random_line_split | |
classes.component.ts | isdisableBtn = false;
classForm: FormGroup;
classReferences: Array<DropDownModel> = [];
tableSettings: {};
rows: Array<any>;
columns: any[];
pageCnt: number;
lastSelectediId = '';
selectedIdsList: Array<string> = [];
totalRowsCount: number;
rowBasedAction: Array<any> = [];
closeForm: boolean;
... | {
this.classForm.controls[key].setValue(this.commonService.trimSpaces(this.classForm.controls[key].value)); // modify value here)
} | identifier_body | |
classes.component.ts | import { CustomDialogComponent } from 'app/shared/custom-dialog/custom-dialog.component';
import { AppSettings } from 'app/app.constants';
import { ClassResultViewModel, ClassResultView, ValidationMessageView } from '../models/class-result-view-model';
import { FormGroup, FormControl, Validators } from '@angular/forms'... | if (res.statusCode === HttpStatus.OK) {
this.openSnackBar(res.messages.ResultMessage);
this.myClassForm.resetForm();
if (!onContinue){
this.closeForm = true;
this.getAllFilteredClasses();
}
}
else {
... | this.isdisableBtn = true;
this.classesConfigService.createClass(form)
.subscribe((res: ValidationMessageView) => { | random_line_split |
classes.component.ts | { CustomDialogComponent } from 'app/shared/custom-dialog/custom-dialog.component';
import { AppSettings } from 'app/app.constants';
import { ClassResultViewModel, ClassResultView, ValidationMessageView } from '../models/class-result-view-model';
import { FormGroup, FormControl, Validators } from '@angular/forms';
impo... |
}, error => {
// this.isdisableBtn = false;
this.errorResponse(error);
});
this.isdisableBtn = false;
}
else if (this.classForm.valid) {
this.isdisableBtn = true;
this.classesConfigService.updateClass(form).subscribe((res: ValidationMessageView) => {
... | {
this.openSnackBar(res.messages.ResultMessage, true);
this.closeForm = false;
} | conditional_block |
classes.component.ts | import { CustomDialogComponent } from 'app/shared/custom-dialog/custom-dialog.component';
import { AppSettings } from 'app/app.constants';
import { ClassResultViewModel, ClassResultView, ValidationMessageView } from '../models/class-result-view-model';
import { FormGroup, FormControl, Validators } from '@angular/forms'... | (form: ClassResultViewModel, onContinue = false): void {
this.isFormSubmitted = true;
if (this.classForm.invalid) {
return;
}
if (!form.id && this.classForm.status === AppSettings.VALID) {
this.isdisableBtn = true;
this.classesConfigService.createClass(form)
.subscribe((res: V... | createOrUpdateClass | identifier_name |
lib.rs | mut first = true;
for &v in list {
if !first {
write!(f, ", ")?;
}
first = false;
write!(f, "{}", self.register.name(v).unwrap_or("{Unnamed}"))?;
}
Ok(())
};
sep_by_comma(&*self.sour... | {
bcnf.push(rel);
} | conditional_block | |
lib.rs | ,
register,
}
}
}
pub struct DepWithNames<'a> {
arrow: &'a str,
source: &'a Attrs,
target: &'a Attrs,
register: &'a NameRegister,
}
impl Display for DepWithNames<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let sep_by_comma = |list: &[u32], f: &mut Format... | (&self, f: &mut Formatter) -> fmt::Result {
<Self as fmt::Debug>::fmt(self, f)
}
}
pub fn categorize(sub: &Attrs, rel: &Attrs, FDs: &[FD]) -> Category {
let closure = closure_of(sub, FDs);
if !closure.is_superset(&rel) {
return Category::Nonkey;
}
let has_subkey = sub
.iter... | fmt | identifier_name |
lib.rs | ,
register,
}
}
}
pub struct DepWithNames<'a> {
arrow: &'a str,
source: &'a Attrs,
target: &'a Attrs,
register: &'a NameRegister,
}
impl Display for DepWithNames<'_> {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
let sep_by_comma = |list: &[u32], f: &mut Format... |
while let Some((rel, FDs)) = candidates.pop() {
// every 2-attribute relation is in BCNF
if rel.len() <= 2 {
bcnf.push(rel);
continue;
}
if let Some(fd) = violation(&rel, &FDs) {
let rel_0 | pub fn bcnf_decomposition(rel: &Attrs, FDs: &[FD]) -> Vec<Attrs> {
let rel: Attrs = rel.clone();
let mut candidates: Vec<(Attrs, Vec<FD>)> = vec![(rel, FDs.to_vec())];
let mut bcnf: Vec<Attrs> = vec![]; | random_line_split |
lib.rs |
pub fn with_names<'a>(&'a self, register: &'a NameRegister) -> DepWithNames<'a> {
DepWithNames {
arrow: "->",
source: &self.source,
target: &self.target,
register,
}
}
}
pub struct DepWithNames<'a> {
arrow: &'a str,
source: &'a Attrs,
... | {
self.target
.iter()
.map(move |&v| FD::new(self.source.clone(), attrs(&[v])))
} | identifier_body | |
main.py | 0.01
beta = 1.
margin = 0.5
s = 32
batch_size = 256
class_num = 1595
train_dataset = 'FS'
eval_dataset = "LFW"
args = get_args()
### Get image and label from tfrecord
image, label, iterator = {}, {}, {}
if train_dataset == 'YTF':
image['train'], label['train'], iter... |
elif eval_dataset == 'LFW':
image['gallery'], label['gallery'], iterator['gallery'] = load_lfw_data(batch_size, 'gallery')
image['test'], label['test'], iterator['test'] = load_lfw_data(batch_size, 'probe')
### Backbone network (Arcface)
embedding_tensor = tf.placeholder(name='img_inputs... | image['gallery'], label['gallery'], iterator['gallery'] = load_ytf_data(batch_size, 'train', eval=True)
image['test'], label['test'], iterator['test'] = load_ytf_data(batch_size, 'test') | conditional_block |
main.py | 0.01
beta = 1.
margin = 0.5
s = 32
batch_size = 256
class_num = 1595
train_dataset = 'FS'
eval_dataset = "LFW"
args = get_args()
### Get image and label from tfrecord
image, label, iterator = {}, {}, {}
if train_dataset == 'YTF':
image['train'], label['train'], iter... | embedding_tensor = tf.placeholder(name='img_inputs', shape=[None, 512], dtype=tf.float32)
labels = tf.placeholder(name='label', shape=[None, ], dtype=tf.int32)
### Global step & learning rate
global_step = tf.Variable(0, trainable=False)
starter_learning_rate = 0.003
learning_rate = tf.train.ex... | random_line_split | |
sentiment_clustering_speech_classification_v0.py | collections import OrderedDict
from sklearn.model_selection import KFold
# classifier information
from keras.layers import Dropout, Dense
from keras.models import Sequential
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifi... | ():
parser = argparse.ArgumentParser(description="")
# Add options
parser.add_argument("-v", "--verbosity", action="count", default=0,
help="increase output verbosity")
# Add arguments
parser.add_argument("input_file", help="The input file to be projected")
# parser.add_argument("speech_feats_file", h... | main | identifier_name |
sentiment_clustering_speech_classification_v0.py | collections import OrderedDict
from sklearn.model_selection import KFold
# classifier information
from keras.layers import Dropout, Dense
from keras.models import Sequential
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClassifi... | sample_dist_std=np.std(df.groupby(labels).size())
sample_dist_avrg=np.median(df.groupby(labels).size())
# The silhouette_score gives the average value for all the samples.
# This gives a perspective into the density and separation of the formed
# clusters
silhouette_avg = silhouette_score(X, cluster_label... | hyper_parm_turning=OrderedDict()
for n_clusters in range_n_clusters:
# Initialize the clusterer with n_clusters value and a random generator
# seed of 10 for reproducibility.
# clusterer = MiniBatchKMeans(n_clusters=n_clusters,init='k-means++', random_state=10)
from sklearn.mixture import GaussianMixture
... | identifier_body |
sentiment_clustering_speech_classification_v0.py | from collections import OrderedDict
from sklearn.model_selection import KFold
# classifier information
from keras.layers import Dropout, Dense
from keras.models import Sequential
from sklearn.metrics import roc_curve, auc
from sklearn.preprocessing import label_binarize
from sklearn.multiclass import OneVsRestClas... |
print("For n_clusters =", n_clusters,
"The average silhouette_score is :", silhouette_avg)
return df,hyper_parm_turning
def main():
parser = argparse.ArgumentParser(description="")
# Add options
parser.add_argument("-v", "--verbosity", action="count", default=0,
hel... | hyper_parm_turning['sample_dist_avrg'].append(sample_dist_avrg) | conditional_block |
sentiment_clustering_speech_classification_v0.py | from sklearn.multiclass import OneVsRestClassifier
from scipy import interp
from sklearn.metrics import roc_auc_score
import argparse
import matplotlib.cm as cm
import codecs
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.decomposition import NMF
# nltk.corpus.conll2002.fileids()
from tqdm i... |
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import label_binarize | random_line_split | |
menus.ts | ://*/*";
const URL_PATTERN_FILE = "file://*/*";
const URL_PATTERNS_REMOTE = [URL_PATTERN_HTTP, URL_PATTERN_HTTPS];
const URL_PATTERNS_ALL = [...URL_PATTERNS_REMOTE, URL_PATTERN_FILE];
type MenuId = string | number;
let menuIdCast: MenuId;
let menuIdCastMedia: MenuId;
let menuIdWhitelist: MenuId;
let menuIdWhitelistR... | (pageUrl?: string) {
/**
* If page URL doesn't exist, we're not on a page and have nothing
* to whitelist, so disable the menu and return.
*/
if (!pageUrl) {
browser.menus.update(menuIdWhitelist, {
enabled: false
});
browser.menus.refresh();
return;
... | updateWhitelistMenu | identifier_name |
menus.ts | ://*/*";
const URL_PATTERN_FILE = "file://*/*";
const URL_PATTERNS_REMOTE = [URL_PATTERN_HTTP, URL_PATTERN_HTTPS];
const URL_PATTERNS_ALL = [...URL_PATTERNS_REMOTE, URL_PATTERN_FILE];
type MenuId = string | number;
let menuIdCast: MenuId;
let menuIdCastMedia: MenuId;
let menuIdWhitelist: MenuId;
let menuIdWhitelistR... |
});
}
/** Handle updating menus when shown. */
async function onMenuShown(info: browser.menus._OnShownInfo) {
const menuIds = info.menuIds as unknown as number[];
// Only rebuild menus if whitelist menu present
if (menuIds.includes(menuIdWhitelist as number)) {
updateWhitelistMenu(info.pageUr... | {
browser.menus.update(menuIdCastMedia, {
targetUrlPatterns: newOpts.localMediaEnabled
? URL_PATTERNS_ALL
: URL_PATTERNS_REMOTE
});
} | conditional_block |
menus.ts | ://*/*";
const URL_PATTERN_FILE = "file://*/*";
const URL_PATTERNS_REMOTE = [URL_PATTERN_HTTP, URL_PATTERN_HTTPS];
const URL_PATTERNS_ALL = [...URL_PATTERNS_REMOTE, URL_PATTERN_FILE];
type MenuId = string | number;
let menuIdCast: MenuId;
let menuIdCastMedia: MenuId;
let menuIdWhitelist: MenuId;
let menuIdWhitelistR... |
/** Handle menu click events */
async function onMenuClicked(
info: browser.menus.OnClickData,
tab?: browser.tabs.Tab
) {
// Handle whitelist menus
if (info.parentMenuItemId === menuIdWhitelist) {
const pattern = whitelistChildMenuPatterns.get(info.menuItemId);
if (!pattern) {
... | {
const menuIds = info.menuIds as unknown as number[];
// Only rebuild menus if whitelist menu present
if (menuIds.includes(menuIdWhitelist as number)) {
updateWhitelistMenu(info.pageUrl);
return;
}
} | identifier_body |
menus.ts | https://*/*";
const URL_PATTERN_FILE = "file://*/*";
const URL_PATTERNS_REMOTE = [URL_PATTERN_HTTP, URL_PATTERN_HTTPS];
const URL_PATTERNS_ALL = [...URL_PATTERNS_REMOTE, URL_PATTERN_FILE];
type MenuId = string | number;
let menuIdCast: MenuId;
let menuIdCastMedia: MenuId;
let menuIdWhitelist: MenuId;
let menuIdWhite... | const pattern = whitelistChildMenuPatterns.get(info.menuItemId);
if (!pattern) {
throw logger.error(
`Whitelist pattern not found for menu item ID ${info.menuItemId}.`
);
}
const whitelist = await options.get("siteWhitelist");
if (!whiteli... | if (info.parentMenuItemId === menuIdWhitelist) { | random_line_split |
wordcount.py | big'
'JJR': wordnet.ADJ, # adjective, comparative 'bigger'
'JJS': wordnet.ADJ, # adjective, superlative 'biggest'
'LS': DEFAULT_TAG, # list marker 1)
'MD': wordnet.VERB, # modal could, will
'NN': wordnet.NOUN, # noun, singular 'desk'
'NNS': wordnet.NOUN, # noun pl... |
print('Total number of words after filtering: {:d}'.format(len(lemmatized_records)))
return lemmatized_records
# End of lemmatize_words()
def filter_stopwords(tagged_records):
"""Filters stopwords, punctuation, and contractions from the tagged records. This is done after tagging to make
sure ... | try:
lemmatized_record = list(map(lambda word: lemmatizer.lemmatize(word[0], POS_TRANSLATOR[word[1]]), record))
except Exception as err:
print(record)
raise err
lemmatized_records.append(lemmatized_record) | conditional_block |
wordcount.py | big'
'JJR': wordnet.ADJ, # adjective, comparative 'bigger'
'JJS': wordnet.ADJ, # adjective, superlative 'biggest'
'LS': DEFAULT_TAG, # list marker 1)
'MD': wordnet.VERB, # modal could, will
'NN': wordnet.NOUN, # noun, singular 'desk'
'NNS': wordnet.NOUN, # noun pl... | (records):
"""Tokenizes the records into word lists. Filters out any stopwords in the list.
Params:
- records (list<dict>): The non-empty records from the JSON file
Returns:
- tokenized_records (list<list<str>>): The tokenized text content of the records
"""
contents = map(lambda ... | tokenize_records | identifier_name |
wordcount.py | big'
'JJR': wordnet.ADJ, # adjective, comparative 'bigger'
'JJS': wordnet.ADJ, # adjective, superlative 'biggest'
'LS': DEFAULT_TAG, # list marker 1)
'MD': wordnet.VERB, # modal could, will
'NN': wordnet.NOUN, # noun, singular 'desk'
'NNS': wordnet.NOUN, # noun pl... |
Returns:
- lemmatized_records (list<str>)): The lemmatized words from all the records
"""
print('Length of tagged_records: {:d}'.format(len(records)))
print('Total number of words: {:d}'.format(sum([len(record) for record in records])))
tagged_records = map(lambda record: pos_tag(record),... |
Params:
- records (list<list<str>>): The word-tokenized records
| random_line_split |
wordcount.py | big'
'JJR': wordnet.ADJ, # adjective, comparative 'bigger'
'JJS': wordnet.ADJ, # adjective, superlative 'biggest'
'LS': DEFAULT_TAG, # list marker 1)
'MD': wordnet.VERB, # modal could, will
'NN': wordnet.NOUN, # noun, singular 'desk'
'NNS': wordnet.NOUN, # noun pl... | print("=====The {:d} Most Frequent Words=====".format(num_words))
print(frequent_words)
return frequent_words
# End of extract_frequent_words()
def extract_collocations(records, num_collocations, collocation_window, compare_collocations = False):
"""Extracts the most common collocations presen... | """Stems the words in the given records, and then counts the words using NLTK FreqDist.
Stemming is done using the English Snowball stemmer as per the recommendation from
http://www.nltk.org/howto/stem.html
NB: There is also a Lancaster stemmer available, but it is apparently very aggressive and can... | identifier_body |
client.ts | params. Useful for example, to ease up debugging and DevTools
* navigation you might want to use the operation name in the URL's search params (`/graphql?MyQuery`).
*/
url: string | ((request: RequestParams) => Promise<string> | string);
/**
* Indicates whether the user agent should send cookies from the ... | if (disposed) return;
disposed = true;
// we copy the listeners so that onDispose unlistens dont "pull the rug under our feet"
for (const listener of [...listeners]) {
listener();
}
},
};
})();
return {
subscribe(request, sink) {
if (client.dispo... | e() {
| identifier_name |
client.ts | params. Useful for example, to ease up debugging and DevTools
* navigation you might want to use the operation name in the URL's search params (`/graphql?MyQuery`).
*/
url: string | ((request: RequestParams) => Promise<string> | string);
/**
* Indicates whether the user agent should send cookies from the ... | };
})();
return {
subscribe(request, sink) {
if (client.disposed) throw new Error('Client has been disposed');
const control = new AbortControllerImpl();
const unlisten = client.onDispose(() => {
unlisten();
control.abort();
});
(async () => {
let retryin... | if (disposed) return;
disposed = true;
// we copy the listeners so that onDispose unlistens dont "pull the rug under our feet"
for (const listener of [...listeners]) {
listener();
}
},
| identifier_body |
client.ts | params. Useful for example, to ease up debugging and DevTools
* navigation you might want to use the operation name in the URL's search params (`/graphql?MyQuery`).
*/
url: string | ((request: RequestParams) => Promise<string> | string);
/**
* Indicates whether the user agent should send cookies from the ... | try {
const url =
typeof options.url === 'function'
? await options.url(request)
: options.url;
if (control.signal.aborted) return;
const headers =
typeof options.headers === 'function'
? await options... | const should = await shouldRetry(retryingErr, retries);
// requst might've been canceled while waiting for retry
if (control.signal.aborted) return;
if (!should) throw retryingErr;
retries++;
}
| conditional_block |
client.ts | referrer information when making same-origin-referrer requests.
* - `origin`: Sends only the ASCII serialization of the request’s referrerURL when making both same-origin-referrer requests and cross-origin-referrer requests.
* - `strict-origin`: Sends the ASCII serialization of the origin of the referrerURL ... | random_line_split | ||
test_language.py | triton result
z_tri = torch.empty_like(z_ref)
kernel[(1, )](z_tri, x, SIZE=SIZE, num_warps=4)
# compare
triton.testing.assert_allclose(z_ref, z_tri)
def _test_binary(dtype_x, dtype_y, expr, device='cuda'):
SIZE = 128
# define the kernel / launch-grid
@triton.jit
def kernel(Z, X, Y, **... | x_tri = torch.abs(x_tri) | conditional_block | |
test_language.py | (template, to_replace):
kernel = copy.deepcopy(template)
for key, value in to_replace.items():
kernel.src = kernel.src.replace(key, value)
return kernel
# generic test functions
def _test_unary(dtype_x, expr, torch_expr=None, device='cuda'):
SIZE = 128
# define the kernel / launch-grid
... | patch_kernel | identifier_name | |
test_language.py | .jit
def kernel(Z, X, **meta):
off = tl.arange(0, meta['SIZE'])
x = tl.load(X + off)
z = GENERATE_TEST_HERE
tl.store(Z + off, z)
kernel = patch_kernel(kernel, {'GENERATE_TEST_HERE': expr})
# inputs
x = triton.testing.random(SIZE, dtype=cvt[dtype_x], device=device)
if... |
kernel = patch_kernel(kernel, {'GENERATE_TEST_HERE': expr})
# inputs
x = triton.testing.random(SIZE, dtype=cvt[dtype_x], device=device)
y = triton.testing.random(SIZE, dtype=cvt[dtype_y], device=device)
# reference result
z_ref = eval(expr)
# triton result
z_tri = torch.empty(SIZE, dtyp... | y = tl.load(Y + off)
z = GENERATE_TEST_HERE
tl.store(Z + off, z) | random_line_split |
test_language.py | iton.jit
def kernel(Z, X, **meta):
off = tl.arange(0, meta['SIZE'])
x = tl.load(X + off)
z = GENERATE_TEST_HERE
tl.store(Z + off, z)
kernel = patch_kernel(kernel, {'GENERATE_TEST_HERE': expr})
# inputs
x = triton.testing.random(SIZE, dtype=cvt[dtype_x], device=device)
... | x = torch.tensor([1.3], device=device, dtype=torch.float32)
y = torch.tensor([1.9], device=device, dtype=torch.float32)
a_tri = torch.tensor([0], device=device, dtype=torch.float32)
b_tri = torch.tensor([0], device=device, dtype=torch.float32)
c_tri = torch.tensor([0], device=device, dtype=torch.flo... | device = 'cuda'
@triton.jit
def with_fn(X, Y, A, B, C):
x = tl.load(X)
y = tl.load(Y)
a, b, c = fn(x, y)
tl.store(A, a)
tl.store(B, b)
tl.store(C, c)
@triton.jit
def without_fn(X, Y, A, B, C):
x = tl.load(X)
y = tl.load(Y)
a, b, c... | identifier_body |
variant.go |
if m.Stderr == nil {
m.Stderr = os.Stderr
}
if m.Getenv == nil {
m.Getenv = os.Getenv
}
if m.Getwd == nil {
m.Getwd = os.Getwd
}
cmdNameFromEnv := m.Getenv("VARIANT_NAME")
if cmdNameFromEnv != "" {
m.Command = cmdNameFromEnv
}
return m
}
type Config struct {
Parameters func([]string) (map[stri... | {
m.Stdout = os.Stdout
} | conditional_block | |
variant.go | }
return f(args, ii)
}
}
if hasVarArgs {
cli.Args = cobra.MinimumNArgs(minArgs)
} else {
cli.Args = cobra.RangeArgs(minArgs, maxArgs)
}
params := func(args []string) (map[string]interface{}, error) {
m := map[string]interface{}{}
for name, f := range lazyParamValues {
v, err := f(args)
if... | r.variantCmd = r.createVariantRootCommand()
} | random_line_split | |
variant.go | interface{}{}
for i := range names {
curName := strings.Join(names[:i+1], " ")
if curCfg, ok := cfgs[curName]; ok {
curOpts := curCfg.Options()
for n := range curOpts {
optGetters[n] = curOpts[n]
}
}
}
cfg := cfgs[cmdName]
params, err := cfg.Parameters(args)
if err != nil {
return nil, nil... | {
return e.Message
} | identifier_body | |
variant.go | (setup Setup) *Runner {
r, err := Load(setup)
if err != nil {
panic(err)
}
return r
}
func New() Main {
return Init(Main{})
}
type Env struct {
Args []string
Getenv func(name string) string
Getwd func() (string, error)
}
func GetPathAndArgsFromEnv(env Env) (string, string, []string) {
osArgs := env.Ar... | MustLoad | identifier_name | |
image_build.py |
def _get_user_name():
"""
Get the current user.
"""
return pwd.getpwuid(os.getuid())[0]
def _user_belongs_to(group_name):
"""
Check that the current user belongs to the ``group_name`` group.
"""
user_name = _get_user_name()
groups = _get_user_groups(user_name)
return group_n... | """
Get a list of groups for the user ``user_name``.
"""
groups = [g.gr_name for g in grp.getgrall() if user_name in g.gr_mem]
gid = pwd.getpwnam(user_name).pw_gid
groups.append(grp.getgrgid(gid).gr_name)
return groups | identifier_body | |
image_build.py | """
if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):
_raise_group_error('kvm')
def _check_virtualbox():
"""
Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must
*not* be running together with S2E.
"""
# Adapted from... | ():
"""
Check if VMWare is running. VMware conflicts with S2E's requirement for KVM, so VMWare must
*not* be running together with S2E.
"""
for proc in psutil.process_iter():
try:
if proc.name() == 'vmware-vmx':
raise CommandError('S2E uses KVM to build images. VM... | _check_vmware | identifier_name |
image_build.py | """
if not _user_belongs_to('libvirtd') and not _user_belongs_to('kvm'):
_raise_group_error('kvm')
def _check_virtualbox():
"""
Check if VirtualBox is running. VirtualBox conflicts with S2E's requirement for KVM, so VirtualBox must
*not* be running together with S2E.
"""
# Adapted from... | missing_keys = []
for image_name in image_names:
image = image_descriptors[image_name]
if 'product_key' in image:
if not image['product_key']:
missing_keys.append(image_name)
ios = image_descriptors[image_name].get('os', {})
if 'product_key' in ios:... | random_line_split | |
image_build.py | ', 'vmlinu*')):
with open(f, 'rb'):
pass
except IOError:
raise CommandError('Make sure that the kernels in /boot are readable. '
'This is required for guestfish. Please run the '
'following command:\n\n'
... | rule_names = _get_archive_rules(self.image_path(), image_names) | conditional_block | |
ChangeSwimlanesJira.user.js | /https:\/\/trackspace.lhsystems.com\/secure\/RapidBoard.jspa\?rapidView=2839.*/
// The CSS file, use file:/// for local CSS files.
// @resource customCSS https://github.com/tepesware/TepesColors/raw/master/ChangeJiraSwim.css
// @grant GM_getResourceText
// @grant GM_addStyle
// ==/UserScript==
var ... |
function addIssueAdditionalInfo(issue, ussueID, data, parrsedSubtasks) {
var temp = $(issue).children("div.ghx-heading");
var html = "<span class='issueInfo ";
html = html.concat(ussueID);
html = html.concat("'>");
var subtaskHtml = addSubtaskRectangles(ussueID, data.field... | {
//debugger
var temp = $(issue).children("div.ghx-heading");
var html = "<div class=\"testexec-status-block\">";
var statuses = stat.statuses;
for (var i = 0; i < statuses.length; i++) {
if (statuses[i].statusCount > 0) {
html = html.concat("<span sty... | identifier_body |
ChangeSwimlanesJira.user.js | (function (mutations) {
mutations.forEach(function (mutation) {
var message = mutation.type;
//debugger;
if (mutation.addedNodes.length > 0) {
updateTheBoard();
}
});
});
var targetNode = docu... | random_line_split | ||
ChangeSwimlanesJira.user.js | /https:\/\/trackspace.lhsystems.com\/secure\/RapidBoard.jspa\?rapidView=2839.*/
// The CSS file, use file:/// for local CSS files.
// @resource customCSS https://github.com/tepesware/TepesColors/raw/master/ChangeJiraSwim.css
// @grant GM_getResourceText
// @grant GM_addStyle
// ==/UserScript==... | () {
getAllData();
var swimlanes = document.getElementsByClassName("ghx-info");
if (swimlanes.length > 0) {
for (var i = 0; i < swimlanes.length; i++) {
if (swimlanes[i].getElementsByTagName("span")[0].textContent == "To Do") {
$(document.getEl... | updateTheBoard | identifier_name |
ChangeSwimlanesJira.user.js | /https:\/\/trackspace.lhsystems.com\/secure\/RapidBoard.jspa\?rapidView=2839.*/
// The CSS file, use file:/// for local CSS files.
// @resource customCSS https://github.com/tepesware/TepesColors/raw/master/ChangeJiraSwim.css
// @grant GM_getResourceText
// @grant GM_addStyle
// ==/UserScript==... | html = html.concat("<img src='" + avatarUrl + "'></img>");
}
// if(j ===1 ){
| {
if (parrseedSubtasks[i].status === order[j]) {
html = html.concat(" <span class='" + orderClass[j] + "'>" + parrseedSubtasks[i].name);
var avatarUrl = parrseedSubtasks[i].avatarForSubtask;
var size = "";
if (order[j] ===... | conditional_block |
avi.go | // 'LIST' listSize listType listData
// listSize includes size of listType(FOURCC), listdata(io.Reader)
// actual size is fileSize + 8
type List struct {
Size uint32
Type FOURCC
JunkSize uint32 // JUNK is only in
lists []*List
chunks []*Chunk
imagechunks []*ImageChunk
imageNum int
}
// ck... | (u uint32) *FOURCC {
return &FOURCC{byte(u >> 0), byte(u >> 8), byte(u >> 16), byte(u >> 24)}
}
func (fcc *FOURCC) String() string {
return string([]byte{fcc[0], fcc[1], fcc[2], fcc[3]})
}
func equal(a, b FOURCC) bool {
if a[0] != b[0] || a[1] != b[1] || a[2] != b[2] || a[3] != b[3] {
return false
}
return true... | encodeU32 | identifier_name |
avi.go | // 'LIST' listSize listType listData
// listSize includes size of listType(FOURCC), listdata(io.Reader)
// actual size is fileSize + 8
type List struct {
Size uint32
Type FOURCC | lists []*List
chunks []*Chunk
imagechunks []*ImageChunk
imageNum int
}
// ckID ckSize ckData
// ckSize includes size of ckData.
// actual size is ckSize + 8
// The data is always padded to nearest WORD boundary.
type Chunk struct {
ID FOURCC
Size uint32
Data map[string]uint32
}
type ImageChunk ... | JunkSize uint32 // JUNK is only in
| random_line_split |
avi.go | 'LIST' listSize listType listData
// listSize includes size of listType(FOURCC), listdata(io.Reader)
// actual size is fileSize + 8
type List struct {
Size uint32
Type FOURCC
JunkSize uint32 // JUNK is only in
lists []*List
chunks []*Chunk
imagechunks []*ImageChunk
imageNum int
}
// ckID... |
avi.r = bytes.NewReader(data)
buf := make([]byte, size)
if n, err := io.ReadFull(avi.r, buf); err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
err = errShortData
}
fmt.Println(n, " out of ", size)
return nil, err
}
return buf, nil
}
// NewReader returns the RIFF stream's form type, such... | {
return nil, err
} | conditional_block |
avi.go | 6
if err := avi.ChunkReader(&l); err != nil {
return nil, err
}
// Read strf 8 + 1064
if err := avi.ChunkReader(&l); err != nil {
return nil, err
}
// Read indx 8 + 40
if err := avi.ChunkReader(&l); err != nil {
return nil, err
}
case fccodml:
// Read dmlr 8 + 4
if err := avi.ChunkReade... | {
buf, err := avi.readData(size)
if err != nil {
return nil, err
}
m := make(map[string]uint32)
m["wLongsPerEntry"] = decodeU32(buf[:2])
m["bIndexSubType"] = decodeU32(buf[2:3])
m["bIndexType"] = decodeU32(buf[3:4])
m["nEntriesInUse"] = decodeU32(buf[4:8])
m["dwChunkId"] = decodeU32(buf[8:12])
m["dwReserv... | identifier_body | |
parser.py | sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
elif p[2] in ("=", "<>", "<", "<=", ">", ">="):
p[0] = ast.ComparisonPredicateNode(p[1], p[3], p[2])
else:
not_ = False
op = p[2]
if op == 'NOT':
not_ = True
op = p[3]
if op == "BETWEEN":
p[0] ... | p[0] = p[1] | conditional_block |
parser.py | sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS IS",... | :
def __init__(self, geometry_factory=values.Geometry, bbox_factory=values.BBox,
time_factory=values.Time, duration_factory=values.Duration):
self.lexer = CQLLexer(
# lextab='ecql.lextab',
# outputdir="ecql"
geometry_factory,
bbox_factory,
... | CQLParser | identifier_name |
parser.py | /or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS I... | | BBOX LPAREN expression COMMA number COMMA number COMMA number COMMA number COMMA QUOTED RPAREN
"""
op = p[1]
lhs = p[3]
rhs = p[5]
if op == "RELATE":
p[0] = ast.SpatialPredicateNode(lhs, rhs, op, pattern=p[7])
elif op in ("DWIT... | | EQUALS LPAREN expression COMMA expression RPAREN
| RELATE LPAREN expression COMMA expression COMMA QUOTED RPAREN
| DWITHIN LPAREN expression COMMA expression COMMA number COMMA UNITS RPAREN
| BEYOND... | random_line_split |
parser.py | sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies of this Software or works derived from this Software.
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
def p_condition(self, p):
""" condition : predicate
| condition AND condition
| condition OR condition
| NOT condition
| LPAREN condition RPAREN
| LBRACKET condition RBRACKET
"""
... | """ condition_or_empty : condition
| empty
"""
p[0] = p[1] | identifier_body |
driver.go | DriverFactory struct{}
func (factory *ipfsDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
return FromParameters(parameters), nil
}
type driver struct {
root string
shell *shell.Shell
roothash string
rootlock sync.Mutex
publish chan<- string
}
func (d *dri... | fi.Size = int64(output.Size)
}
return storagedriver.FileInfoInternal{FileInfoFields: fi}, nil
}
// List returns a list of the objects that are direct descendants of the given
// path.
func (d *driver) List(ctx context.Context, path string) ([]string, error) {
defer debugTime()()
output, err := d.shell.FileList... | {
defer debugTime()()
d.rootlock.Lock()
defer d.rootlock.Unlock()
output, err := d.shell.FileList(d.fullPath(path))
if err != nil {
if strings.HasPrefix(err.Error(), "no link named") {
return nil, storagedriver.PathNotFoundError{Path: path}
}
return nil, err
}
fi := storagedriver.FileInfoFields{
Pat... | identifier_body |
driver.go | DriverFactory struct{}
func (factory *ipfsDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
return FromParameters(parameters), nil
}
type driver struct {
root string
shell *shell.Shell
roothash string
rootlock sync.Mutex
publish chan<- string
}
func (d *dri... | () string {
return driverName
}
// GetContent retrieves the content stored at "path" as a []byte.
func (d *driver) GetContent(ctx context.Context, path string) ([]byte, error) {
defer debugTime()()
reader, err := d.shell.Cat(d.fullPath(path))
if err != nil {
if strings.HasPrefix(err.Error(), "no link named") {
... | Name | identifier_name |
driver.go | fsDriverFactory struct{}
func (factory *ipfsDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
return FromParameters(parameters), nil
}
type driver struct {
root string
shell *shell.Shell
roothash string
rootlock sync.Mutex
publish chan<- string
}
func (d *d... | if err != nil {
log.Error("failed to get new empty dir: ", err)
return nil
}
hash = h
}
d := &driver{
shell: shell,
root: root,
roothash: hash,
}
d.publish = d.runPublisher(info.ID)
return &Driver{
baseEmbed: baseEmbed{
Base: base.Base{
StorageDriver: d,
},
},
}
}
// Imp... | log.Error("failed to resolve docker-registry dir: ", err)
return nil
}
h, err := shell.NewObject("unixfs-dir") | random_line_split |
driver.go | DriverFactory struct{}
func (factory *ipfsDriverFactory) Create(parameters map[string]interface{}) (storagedriver.StorageDriver, error) {
return FromParameters(parameters), nil
}
type driver struct {
root string
shell *shell.Shell
roothash string
rootlock sync.Mutex
publish chan<- string
}
func (d *dri... | case <-short:
k := topub
topub = ""
long = nil
short = nil
err := d.publishChild(ipnskey, "docker-registry", k)
if err != nil {
log.Error("failed to publish: ", err)
}
}
}
}()
return out
}
func (d *driver) publishChild(ipnskey, dirname, hash string) error {
val, err := d.s... | {
select {
case k := <-out:
if topub == "" {
long = time.After(time.Second * 5)
short = time.After(time.Second * 1)
} else {
short = time.After(time.Second * 1)
}
topub = k
case <-long:
k := topub
topub = ""
long = nil
short = nil
err := d.publishChild(ipnske... | conditional_block |
tracker.py | async def ensure_connection_id(self, peer_id, tracker_ip, tracker_port):
# peer_id is just to ensure cache coherency
return (await self.connect(tracker_ip, tracker_port)).connection_id
async def announce(self, info_hash, peer_id, port, tracker_ip, tracker_port, stopped=False):
connection_i... | req = decode(AnnounceRequest, data)
if req.connection_id not in self.known_conns:
resp = encode(ErrorResponse(3, req.transaction_id, b'Connection ID missmatch.\x00'))
else:
compact_address = encode_peer(addr[0], req.port)
if req.event != 3:
... | conditional_block | |
tracker.py | AnnounceResponse):
return structs[AnnounceResponse].pack(*obj[:-1]) + b''.join([encode(peer) for peer in obj.peers])
return structs[type(obj)].pack(*obj)
def make_peer_id(random_part: Optional[str] = None) -> bytes:
# see https://wiki.theory.org/BitTorrentSpecification#peer_id and https://www.bittorr... | peers = [
(str(ipaddress.ip_address(peer.address)), peer.port)
for announcement in announcements for peer in announcement.peers if peer.port > 1024 # no privileged or 0
]
return get_kademlia_peers_from_hosts(peers) | identifier_body | |
tracker.py | action", "transaction_id", "items"])
ScrapeResponseItem = namedtuple("ScrapeResponseItem", ["seeders", "completed", "leechers"])
ErrorResponse = namedtuple("ErrorResponse", ["action", "transaction_id", "message"])
structs = {
ConnectRequest: struct.Struct(">QII"),
ConnectResponse: struct.Struct(">IIQ"),
Ann... | info_hash for (info_hash, (next_announcement, _)) in self.results.get(tracker_ip, {}).items()
if time.time() < next_announcement
}
results = await asyncio.gather(
*[self._probe_server(info_hash, tracker_ip, server[1], stopped=stopped)
for info_hash in in... |
async def _announce_many(self, server, info_hashes, stopped=False):
tracker_ip = await resolve_host(*server, 'udp')
still_good_info_hashes = { | random_line_split |
tracker.py | (data, offset))
def encode(obj):
if isinstance(obj, ScrapeRequest):
return structs[ScrapeRequest].pack(*obj[:-1]) + b''.join(obj.infohashes)
elif isinstance(obj, ErrorResponse):
return structs[ErrorResponse].pack(*obj[:-1]) + obj.message
elif isinstance(obj, AnnounceResponse):
retu... | announcement_to_kademlia_peers | identifier_name | |
endpoints_calculator.go | {
nodeLister listers.NodeLister
zoneGetter types.ZoneGetter
subsetSizeLimit int
svcId string
logger klog.Logger
networkInfo *network.NetworkInfo
}
func NewLocalL4ILBEndpointsCalculator(nodeLister listers.NodeLister, zoneGetter types.ZoneGetter, svcId string, logger klog.Logger, ... | (_ []types.EndpointsData, currentMap map[string]types.NetworkEndpointSet) (map[string]types.NetworkEndpointSet, types.EndpointPodMap, error) {
// this should be the same as CalculateEndpoints for L4 ec
subsetMap, _, _, err := l.CalculateEndpoints(nil, currentMap)
return subsetMap, nil, err
}
func (l *ClusterL4ILBEn... | CalculateEndpointsDegradedMode | identifier_name |
endpoints_calculator.go | should be the same as CalculateEndpoints for L4 ec
subsetMap, _, _, err := l.CalculateEndpoints(nil, currentMap)
return subsetMap, nil, err
}
func (l *LocalL4ILBEndpointsCalculator) ValidateEndpoints(endpointData []types.EndpointsData, endpointPodMap types.EndpointPodMap, dupCount int) error {
// this should be a ... | if countFromEndpointData == 0 {
l.logger.Info("Detected endpoint count from endpointData going to zero", "endpointData", endpointData)
return fmt.Errorf("%w: Detect endpoint count goes to zero", types.ErrEPSEndpointCountZero) | random_line_split | |
endpoints_calculator.go | {
nodeLister listers.NodeLister
zoneGetter types.ZoneGetter
subsetSizeLimit int
svcId string
logger klog.Logger
networkInfo *network.NetworkInfo
}
func NewLocalL4ILBEndpointsCalculator(nodeLister listers.NodeLister, zoneGetter types.ZoneGetter, svcId string, logger klog.Logger, ... |
func (l *LocalL4ILBEndpointsCalculator) ValidateEndpoints(endpointData []types.EndpointsData, endpointPodMap types.EndpointPodMap, dupCount int) error {
// this should be a no-op for now
return nil
}
// ClusterL4ILBEndpointGetter implements the NetworkEndpointsCalculator interface.
// It exposes methods to calcula... | {
// this should be the same as CalculateEndpoints for L4 ec
subsetMap, _, _, err := l.CalculateEndpoints(nil, currentMap)
return subsetMap, nil, err
} | identifier_body |
endpoints_calculator.go | {
nodeLister listers.NodeLister
zoneGetter types.ZoneGetter
subsetSizeLimit int
svcId string
logger klog.Logger
networkInfo *network.NetworkInfo
}
func NewLocalL4ILBEndpointsCalculator(nodeLister listers.NodeLister, zoneGetter types.ZoneGetter, svcId string, logger klog.Logger, ... | if ok := candidateNodeCheck(node); !ok {
l.logger.Info("Dropping Node from subset since it is not a valid LB candidate", "nodeName", node.Name)
continue
}
if !l.networkInfo.IsNodeConnected(node) {
l.logger.Info("Node not connected to service network", "nodeName", node.Name, "network", l.networkInfo... | {
if addr.NodeName == nil {
l.logger.V(2).Info("Address inside Endpoints does not have an associated node. Skipping", "address", addr.Addresses, "endpoints", klog.KRef(ed.Meta.Namespace, ed.Meta.Name))
continue
}
if addr.TargetRef == nil {
l.logger.V(2).Info("Address inside Endpoints does not have ... | conditional_block |
api.go | submissionTime, err := a.storage.Submissions(r.Context()).LastSubmissionTime(identifier)
if err != nil {
// TODO: look at error handling
log.Println(err)
return
}
_, ok := radio.CalculateCooldown(
time.Duration(a.Conf().UserUploadDelay),
submissionTime,
)
response := userCooldownResponse{
Cooldown: ... | random_line_split | ||
api.go | return r
}
func (a *API) getSong(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(410), 410)
}
func (a *API) getMetadata(w http.ResponseWriter, r *http.Request) {
http.Error(w, http.StatusText(410), 410)
}
func (a *API) getUserCooldown(w http.ResponseWriter, r *http.Request) {
identifier ... | {
r := chi.NewRouter()
r.Use(chiware.SetHeader("Content-Type", "application/json"))
r.Method("GET", "/", a.status)
r.Get("/ping", func(w http.ResponseWriter, _ *http.Request) {
w.Write([]byte(`{"ping":true}`))
})
r.Get("/user-cooldown", a.getUserCooldown)
r.Get("/news", a.getNews)
r.Get("/search/{query}", a.... | identifier_body | |
api.go | cannot upload another song just yet. You can upload %s",
submissionTime.
Add(time.Duration(a.Conf().UserUploadDelay)).
Format(timeagoFormat),
)
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
// TODO: look at error handling
log.Println(err)
return
}
}
type userCooldownResponse stru... | (w http.ResponseWriter, r *http.Request) {
status, err := a.manager.Status(r.Context())
if err != nil {
return
}
response := canRequestResponse{}
// send our response when we return
defer func() {
// but not if an error occured
if err != nil {
// TODO: handle error
http.Error(w, http.StatusText(501)... | getCanRequest | identifier_name |
api.go | upload another song just yet. You can upload %s",
submissionTime.
Add(time.Duration(a.Conf().UserUploadDelay)).
Format(timeagoFormat),
)
}
err = json.NewEncoder(w).Encode(response)
if err != nil {
// TODO: look at error handling
log.Println(err)
return
}
}
type userCooldownResponse struct {
/... |
response.Main.Requests = true
return
}
type canRequestResponse struct {
Main struct {
Requests bool `json:"requests"`
}
}
func (a *API) getDJImage(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
w.Header().Del("Content-Type")
w.Header().Set("Content-Type", "image/png")
user, ok := ctx.Value... | {
return
} | conditional_block |
assets.responsive.js | () {
//Set responsive indicator in body
var indicator = document.createElement('div');
indicator.id = 'screen-indicator';
$('body').prepend(indicator);
//add browser compatibility
if ($('meta[http-equiv]').length === 0) {
$('title').before('<meta http... | var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout... | },
debounce: function(func, wait, immediate) {
var timeout;
return function() {
| random_line_split |
assets.responsive.js | () {
//Set responsive indicator in body
var indicator = document.createElement('div');
indicator.id = 'screen-indicator';
$('body').prepend(indicator);
//add browser compatibility
if ($('meta[http-equiv]').length === 0) {
$('title').before('<meta http... |
// Make the links expand collapse if the parent menu contains more than 1 link
if ($(jPMmenu).find('> li ul > li').length > 1) {
$('#jPanelMenu-menu > li > a')
.wrapInner('<span>')
.attr('href', 'javascript:void(... | {
// Remove jquery ui stuff
$('#jPanelMenu-menu li').removeClass('ui-menu-item');
$('#jPanelMenu-menu li a').removeAttr('id aria-haspopup').removeClass('ui-corner-all');
$('#jPanelMenu-menu .submenu-separator-container, #jPanelMenu-menu... | conditional_block |
table_1.py | ").reset_index()
# This flattens the column levels
df.columns = ['_'.join(col) for col in df.columns.values if col]
df.rename(columns={"location_id_":"location_id"}, inplace=True)
return df
def get_max_pop_year(group):
"""Takes a dataframe (or GroupBy object) with 'mean' and 'year_id' columns,
... | worksheet (Worksheet object): | random_line_split | |
table_1.py | (df):
"""Melts GBD data with 'mean', 'lower', and 'upper' columns to a single
'quantile' column; converts to xarray dataarray; and adds a scenario
dimension.
Args:
df (pandas dataframe):
Dataframe with 'year_id', 'location_id', 'mean', 'lower', and
'upper' columns.
... | melt_to_xarray | identifier_name | |
table_1.py | _mean_ui(df, df_type="pop"):
"""Takes a dataframe with 'mean', 'lower', and 'upper' columns,
and returns a dataframe with a 'value' column that has the mean, lower,
and upper all together. If df_type == "pop", values are converted to
millions.
Args:
df (pandas dataframe):
Datafr... |
# Get 2017 GBD pops
pop_2017 = get_population(gbd_round_id=gbd_round_id, age_group_id=22,
sex_id=3, location_id=location_ids,
status="best", year_id=p_end, with_ui=True)[[
"year_id", "location_id", "population", "lower", "upper"
]].rename(colu... | """Pulls year 2017 GBD round 5 populations, converts it an xarray dataarray,
pulls forecast population, and concatenates the dataarrays. The new array is
then converted to a pandas dataframe. Peak population and peak population
year are pulled for each location in the dataframe. All required data are
th... | identifier_body |
table_1.py | 2017)
# Get future TFR
tfr_fut = open_xr(f"{gbd_round_id}/future/tfr/"
f"{tfr_version}/tfr_combined.nc").data
tfr_fut_sel = tfr_fut.sel(location_id=location_ids, scenario=SCENARIOS,
year_id=YEARS.forecast_years)
# Concat and make quantil... | loc_name = INDENT_MAP[row["level"]] + row[col]
worksheet.merge_range(row_range, loc_name, loc_fmt_obj) | conditional_block | |
response.rs | erialize, Debug)]
pub struct JSONResponse {
pub error: Option<String>,
pub payload: Option<serde_json::Value>,
}
impl JSONResponse {
fn error(reason: Option<String>) -> Self {
JSONResponse {
error: reason,
payload: None,
}
}
fn payload<T: Serialize>(value: T... | new | identifier_name | |
response.rs | _decode;
use mime_types;
use csv;
use chrono::naive::date::NaiveDate;
use chrono::Datelike;
use serde::ser::Serialize;
use serde_json;
// local imports
use route::{Route, HumanError, APIError};
use database::Database;
// statics
lazy_static! {
static ref MIME_TYPES: mime_types::Types = mime_types::Types::ne... | }
}
fn process_multipart<R: Read>(headers: Headers, http_reader: R) -> Option<Multipart<R>> {
let boundary = headers.get::<ContentType>().and_then(|ct| {
use hyper::mime::{Mime, TopLevel, SubLevel, Attr, Value};
let ContentType(ref mime) = *ct;
let params = match *mime {
... | }
}
| random_line_split |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.