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
EditorServices.ts
import * as bootstrap from 'htmlrapier.bootstrap/src/main'; import { Fetcher } from 'htmlrapier/src/fetcher'; import { WindowFetch } from 'htmlrapier/src/windowfetch'; import { WithCredentialsFetcher } from 'editymceditface.client/EditorCore/WithCredentialsFetcher'; import * as urlInjector from 'editymceditface.client...
: controller.InjectedControllerBuilder { if (!mainBuilder) { mainBuilder = new controller.InjectedControllerBuilder(); let config = pageConfig.read<Config>(); if (!config) { config = {}; } if (!config.editSettings) { config.editSettings = { ...
eateBaseBuilder()
identifier_name
EditorServices.ts
import * as bootstrap from 'htmlrapier.bootstrap/src/main'; import { Fetcher } from 'htmlrapier/src/fetcher';
import { WithCredentialsFetcher } from 'editymceditface.client/EditorCore/WithCredentialsFetcher'; import * as urlInjector from 'editymceditface.client/EditorCore/BaseUrlInjector'; import * as controller from 'htmlrapier/src/controller'; import * as client from 'editymceditface.client/EditorCore/EdityHypermediaClient';...
import { WindowFetch } from 'htmlrapier/src/windowfetch';
random_line_split
EditorServices.ts
import * as bootstrap from 'htmlrapier.bootstrap/src/main'; import { Fetcher } from 'htmlrapier/src/fetcher'; import { WindowFetch } from 'htmlrapier/src/windowfetch'; import { WithCredentialsFetcher } from 'editymceditface.client/EditorCore/WithCredentialsFetcher'; import * as urlInjector from 'editymceditface.client...
}
if (!mainBuilder) { mainBuilder = new controller.InjectedControllerBuilder(); let config = pageConfig.read<Config>(); if (!config) { config = {}; } if (!config.editSettings) { config.editSettings = { baseUrl: '/' }; ...
identifier_body
EditorServices.ts
import * as bootstrap from 'htmlrapier.bootstrap/src/main'; import { Fetcher } from 'htmlrapier/src/fetcher'; import { WindowFetch } from 'htmlrapier/src/windowfetch'; import { WithCredentialsFetcher } from 'editymceditface.client/EditorCore/WithCredentialsFetcher'; import * as urlInjector from 'editymceditface.client...
if (!config.editSettings) { config.editSettings = { baseUrl: '/' }; } const services = mainBuilder.Services; services.addShared(Fetcher, s => new WithCredentialsFetcher(new WindowFetch())); services.addShared(urlInjector.IBaseUrlInjector, s...
config = {}; }
conditional_block
mod.rs
/* * Copyright 2013 Hayden Smith * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
impl Send for Parser {} impl Emitter for Parser { fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
} } // TODO This is probably not a good idea
random_line_split
mod.rs
/* * Copyright 2013 Hayden Smith * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
emit
identifier_name
mod.rs
/* * Copyright 2013 Hayden Smith * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed t...
} // TODO This is probably not a good idea impl Send for Parser {} impl Emitter for Parser { fn emit(&mut self, cmsp: Option<(&CodeMap, Span)>, msg: &str, code: Option<&str>, lvl: Level) { } fn custom_emit(&mut self, cm: &CodeMap, sp: RenderSpan, msg: &str, lvl: Level) { } }
{ // TODO use diagnostic emitter? let parse_session = new_parse_sess_special_handler(mk_span_handler(mk_handler(box *self), CodeMap::new())); let cfg: ast::CrateConfig = Vec::new(); let mut c = parse_crate_from_source_str(String::from_str(name), String::from_str(source), cfg.clone(), &parse_session); //...
identifier_body
icmp.rs
use network::common::*; use network::icmp::*;
use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop(){ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::...
random_line_split
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop()
response.header.checksum.data = Checksum::compile( Checksum::sum(header_ptr as usize, size_of::<ICMPHeader>()) + Checksum::sum(response.data.as_ptr() as usize, response.data.len()) ); ...
{ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::new(); match ip.read_to_end(&mut bytes) { Option::Some(_) => { if let Option::Some(message) = ICMP::from_bytes(bytes) { if message....
identifier_body
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn reply_loop(){ loop{ let mut ip = URL::from_str("ip:///1").open(...
} } }, Option::None => sys_yield() } } } }
{ if message.header._type == 0x08 { let mut response = ICMP { header: message.header, data: message.data }; response.header._type = 0x00; ...
conditional_block
icmp.rs
use network::common::*; use network::icmp::*; use programs::common::*; pub struct ICMPScheme; impl SessionItem for ICMPScheme { fn scheme(&self) -> String { return "icmp".to_string(); } } impl ICMPScheme { pub fn
(){ loop{ let mut ip = URL::from_str("ip:///1").open(); let mut bytes: Vec<u8> = Vec::new(); match ip.read_to_end(&mut bytes) { Option::Some(_) => { if let Option::Some(message) = ICMP::from_bytes(bytes) { if messag...
reply_loop
identifier_name
swizzle.rs
use crate::base::allocator::Allocator; use crate::base::{DefaultAllocator, DimName, Scalar}; use crate::geometry::{Point, Point2, Point3}; use typenum::{self, Cmp, Greater}; macro_rules! impl_swizzle { ($( where $BaseDim: ident: $( $name: ident() -> $Result: ident[$($i: expr),+] ),+ ;)* ) => { $( ...
D::Value: Cmp<typenum::$BaseDim, Output=Greater> { $( /// Builds a new point from components of `self`. #[inline] pub fn $name(&self) -> $Result<N> { $Result::new($(self[$i].inlined_clone()),*...
DefaultAllocator: Allocator<N, D>,
random_line_split
gulpfile.js
'use strict' let ugly = require('gulp-uglify') ,gulp = require('gulp') ,watch = require('gulp-watch') ,plumber = require('gulp-plumber') ,newer = require('gulp-newer') ,stylus = require('gulp-stylus') ,jade = require('gulp-jade') ,concat = require('gulp-concat') ,rename = require('gulp-rename') ,runSequence = require(...
process.exit(code) }) runner.on('error', function (err) { cb(err) }) }) gulp.task('watch', function () { runSequence('server') watch([cssFolder + '/*.styl', cssFolder + '/parts/*.styl'], function() { runSequence('stylus') }) watch(jsFolder, function() { runSequence('ugly') }) watch([ views + '...
) runner.on('exit', function (code) {
random_line_split
nonbinary.py
# -*- coding: utf-8 -*- # Copyright 2014-2015 Michael Helmling # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation """This module contains classes and helper functions for non-binary cod...
def makeNonBinary(code, q): matrix = code.parityCheckMatrix.copy() for i in range(matrix.shape[0]): nonzeros = np.flatnonzero(matrix[i]) for j in range(nonzeros.size): matrix[i, nonzeros[j]] = 1 + (j % (q-1)) return NonbinaryLinearBlockCode("{}_F{}".format(code.name, q), matr...
ret = np.zeros(vector.size//(q-1), np.int) for i in np.flatnonzero(vector): ret[i//q] = 1 + i % q return ret
identifier_body
nonbinary.py
# -*- coding: utf-8 -*- # Copyright 2014-2015 Michael Helmling # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation """This module contains classes and helper functions for non-binary cod...
(self, name=None, parityCheckMatrix=None, q=None): if parityCheckMatrix is not None: if utils.isStr(parityCheckMatrix): self.filename = os.path.expanduser(parityCheckMatrix) self._parityCheckMatrix = matrices.getNonbinaryMatrix(self.filename) if name i...
__init__
identifier_name
nonbinary.py
# -*- coding: utf-8 -*- # Copyright 2014-2015 Michael Helmling # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation """This module contains classes and helper functions for non-binary cod...
elif not isinstance(parityCheckMatrix, np.ndarray): self._parityCheckMatrix = matrices.getNonbinaryMatrix(parityCheckMatrix) else: self._parityCheckMatrix = parityCheckMatrix if q is None: q = int(np.max(self.parityCheckMatrix) + 1...
self.filename = os.path.expanduser(parityCheckMatrix) self._parityCheckMatrix = matrices.getNonbinaryMatrix(self.filename) if name is None: name = os.path.basename(self.filename)
conditional_block
nonbinary.py
# -*- coding: utf-8 -*- # Copyright 2014-2015 Michael Helmling # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 3 as # published by the Free Software Foundation """This module contains classes and helper functions for non-binary cod...
H = [[1,1,1, 1,1]] code = NonbinaryLinearBlockCode(parityCheckMatrix=H, q=2, name='NBtestCode') codewords = [flanaganEmbedding(cw, code.q) for cw in code.allCodewords()] from lpdec.polytopes import convexHull print(codewords) print(len(codewords)) print(code.generatorMatrix) A,b = conve...
return NonbinaryLinearBlockCode("{}_F{}".format(code.name, q), matrix, q) if __name__ == '__main__':
random_line_split
accounts_settings.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt import frappe from frappe import _ from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.model....
def validate_stale_days(self): if not self.allow_stale and cint(self.stale_days) <= 0: frappe.msgprint( _("Stale Days should start from 1."), title='Error', indicator='red', raise_exception=1) def enable_payment_schedule_in_print(self): show_in_print = cint(self.show_payment_schedule_in_print) for...
frappe.db.set_default("add_taxes_from_item_tax_template", self.get("add_taxes_from_item_tax_template", 0)) self.validate_stale_days() self.enable_payment_schedule_in_print() self.toggle_discount_accounting_fields()
identifier_body
accounts_settings.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt import frappe from frappe import _ from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.model....
for doctype in ["Sales Invoice", "Purchase Invoice"]: make_property_setter(doctype, "additional_discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False) if enable_discount_accounting: make_property_setter(doctype, "additional_discount_account", "mandatory_d...
make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False) if enable_discount_accounting: make_property_setter(doctype, "discount_account", "mandatory_depends_on", "eval: doc.discount_amount", "Code", validate_fields_for_doctype=False)...
conditional_block
accounts_settings.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt import frappe from frappe import _ from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.model....
(self): enable_discount_accounting = cint(self.enable_discount_accounting) for doctype in ["Sales Invoice Item", "Purchase Invoice Item"]: make_property_setter(doctype, "discount_account", "hidden", not(enable_discount_accounting), "Check", validate_fields_for_doctype=False) if enable_discount_accounting: ...
toggle_discount_accounting_fields
identifier_name
accounts_settings.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt # For license information, please see license.txt import frappe from frappe import _ from frappe.custom.doctype.property_setter.property_setter import make_property_setter from frappe.model....
_("Stale Days should start from 1."), title='Error', indicator='red', raise_exception=1) def enable_payment_schedule_in_print(self): show_in_print = cint(self.show_payment_schedule_in_print) for doctype in ("Sales Order", "Sales Invoice", "Purchase Order", "Purchase Invoice"): make_property_setter(doct...
if not self.allow_stale and cint(self.stale_days) <= 0: frappe.msgprint(
random_line_split
addon-controls.stories.tsx
import React from 'react'; import Button from '../components/TsButton'; export default { title: 'Addons/Controls', component: Button, argTypes: { children: { control: 'text', name: 'Children', mapping: { basic: 'BASIC' } }, type: { control: 'text', name: 'Type' }, json: { control: 'object', name: 'JS...
export const ImageFileControl = (args) => <img src={args.imageUrls[0]} alt="Your Example Story" />; ImageFileControl.args = { imageUrls: ['http://place-hold.it/350x150'], }; export const CustomControls = Template.bind({}); CustomControls.args = { children: 'hmmm', type: 'action', json: DEFAULT_NESTED_OBJECT, }...
};
random_line_split
qt5.py
st=Utils.listdir('/usr/local/Trolltech/') except OSError: pass else: if lst: lst.sort() lst.reverse() qtdir='/usr/local/Trolltech/%s/'%lst[0] qtbin=os.path.join(qtdir,'bin') paths.append(qtbin) cand=None prev_ver=['5','0','0'] for qmk in('qmake-qt5','qmake5','qmake'): try: qmake=se...
opt.add_option('--want-rpath',action='store_true',default=False,dest='want_rpath',help='enable the rpath for qt libraries') opt.add_option('--header-ext',type='string',default='',help='header extension for moc files',dest='qt_header_ext')
random_line_split
qt5.py
else: delattr(self,'cache_sig') include_nodes=[node.parent]+self.generator.includes_nodes moctasks=[] mocfiles=set([]) for d in bld.raw_deps.get(self.uid(),[]): if not d.endswith('.moc'): continue if d in mocfiles: continue mocfiles.add(d) h_node=None base2=d[:-4] for x in include...
(Task.Task): run_str='${QT_LUPDATE} ${SRC} -ts ${TGT}' color='BLUE' Task.update_outputs(trans_update) class XMLHandler(ContentHandler): def __init__(self): self.buf=[] self.files=[] def startElement(self,name,attrs): if name=='file': self.buf=[] def endElement(self,name): if name=='file': self.files....
trans_update
identifier_name
qt5.py
else: delattr(self,'cache_sig') include_nodes=[node.parent]+self.generator.includes_nodes moctasks=[] mocfiles=set([]) for d in bld.raw_deps.get(self.uid(),[]): if not d.endswith('.moc'): continue if d in mocfiles: continue mocfiles.add(d) h_node=None base2=d[:-4] for x in include...
if lst: lst.sort() lst.reverse() qtdir='/usr/local/Trolltech/%s/'%lst[0] qtbin=os.path.join(qtdir,'bin') paths.append(qtbin) cand=None prev_ver=['5','0','0'] for qmk in('qmake-qt5','qmake5','qmake'): try: qmake=self.find_program(qmk,path_list=paths) except self.errors.ConfigurationError...
env=self.env opt=Options.options qtdir=getattr(opt,'qtdir','') qtbin=getattr(opt,'qtbin','') paths=[] if qtdir: qtbin=os.path.join(qtdir,'bin') if not qtdir: qtdir=os.environ.get('QT5_ROOT','') qtbin=os.environ.get('QT5_BIN',None)or os.path.join(qtdir,'bin') if qtbin: paths=[qtbin] if not qtdir: paths...
identifier_body
qt5.py
else: delattr(self,'cache_sig') include_nodes=[node.parent]+self.generator.includes_nodes moctasks=[] mocfiles=set([]) for d in bld.raw_deps.get(self.uid(),[]): if not d.endswith('.moc'): continue if d in mocfiles: continue mocfiles.add(d) h_node=None base2=d[:-4] for x in include...
def endElement(self,name): if name=='file': self.files.append(str(''.join(self.buf))) def characters(self,cars): self.buf.append(cars) @extension(*EXT_RCC) def create_rcc_task(self,node): rcnode=node.change_ext('_rc.cpp') self.create_task('rcc',node,rcnode) cpptask=self.create_task('cxx',rcnode,rcnode.chan...
self.buf=[]
conditional_block
mod.rs
/* Copyright (C) 2017-2018 Open Information Security Foundation * * You can copy, redistribute or modify this Program under the terms of * the GNU General Public License version 2 as published by the Free * Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY...
pub mod ikev2; pub mod state; pub mod log;
// written by Pierre Chifflier <chifflier@wzdftpd.net> extern crate ipsec_parser;
random_line_split
pipil.py
with IPC for opening/saving image files nopil_port = 4859 import string from multiprocessing import Process import imp import os import tempfile import subprocess from time import sleep import atexit import socket # Remove our temporary files when the module is unloaded temp_files = [] def cleanup_temp(): for file...
w1, h1 = self.size w2,
return Image(self) def __ne__(self, other):
random_line_split
pipil.py
IPC for opening/saving image files nopil_port = 4859 import string from multiprocessing import Process import imp import os import tempfile import subprocess from time import sleep import atexit import socket # Remove our temporary files when the module is unloaded temp_files = [] def cleanup_temp(): for filename ...
: def __init__(self, color): if type(color) is type(0): self.color = Color.int_to_rgb(color) else: self.color = color def as_int(self): return Color.rgb_to_int(self.color) def as_rgb(self): return self.color @staticmethod def int_to_rgb(rgb_int): r = (rgb_int >> 16) & 255 ...
Color
identifier_name
pipil.py
IPC for opening/saving image files nopil_port = 4859 import string from multiprocessing import Process import imp import os import tempfile import subprocess from time import sleep import atexit import socket # Remove our temporary files when the module is unloaded temp_files = [] def cleanup_temp(): for filename ...
def _open(self, filename): if _has_PIL and use_PIL: _opener = _pil_open else: _opener = _nopil_open self.data, self.size = _opener(filename) def _create(self, size, color = (0, 0, 0)): size = tuple(int(x) for x in size) w, h = self.size = size self.data = [color] * w * h d...
self._create(*args)
conditional_block
pipil.py
)) for line in lines for pixel in line.split()] return (data, (w, h)) def _bytes_to_int(bs): return sum(ord(bs[i]) << (8 * (len(bs) - i - 1)) for i in xrange(len(bs))) def _bytes_to_rgb(bs): return tuple(ord(bs[i]) for i in xrange(1, 4)) def _nopil_open_socket(filename): # Listen on a local IPv4-style socket...
fill, (w, h) = self.Tkphoto import Tkinter self.root = Tkinter.Tk() self.root.title("Info 103 Image Viewer") self.root.configure(width=w, height=h) # Convert our image to a PhotoImage used by Tkinter photo = Tkinter.PhotoImage(width=w, height=h) photo.put(fill) label = Tkinter.Label(s...
identifier_body
libvnc_session.py
import logging import os from twisted.internet import defer, endpoints from universe import error, utils from universe.twisty import reactor from universe.vncdriver import screen, vnc_client PYGAME_INSTALLED = None def load_pygame(): global PYGAME_INSTALLED, pygame if PYGAME_INSTALLED is not None: re...
logger.info("Using libvncdriver's %s encoding" % encoding) self.driver = libvncdriver.VNCSession( remotes=remotes, error_buffer=error_buffer, encoding=encoding, compress_level=compress_level, fine_quality_level=fine_quality_level, ...
raise error.Error(''' *=================================================* || libvncdriver is not installed || || Try installing with "pip install libvncdriver" || || or use the go or python driver by setting || || UNIVERSE_VNCDRIVER=go || || UNIVERSE_VNCDRIVER=py...
conditional_block
libvnc_session.py
import logging import os from twisted.internet import defer, endpoints from universe import error, utils from universe.twisty import reactor from universe.vncdriver import screen, vnc_client PYGAME_INSTALLED = None def load_pygame(): global PYGAME_INSTALLED, pygame if PYGAME_INSTALLED is not None: re...
def render(self): self._guard(self._render) def _guard(self, fn): try: return fn() except (KeyboardInterrupt, SystemExit): self.close() def _render(self): self.before_render() if not PYGAME_INSTALLED: return # For some r...
return self.driver.step(action)
identifier_body
libvnc_session.py
import logging import os from twisted.internet import defer, endpoints from universe import error, utils from universe.twisty import reactor from universe.vncdriver import screen, vnc_client PYGAME_INSTALLED = None def load_pygame(): global PYGAME_INSTALLED, pygame if PYGAME_INSTALLED is not None: re...
self.screen = None self.render_called_once = False if PYGAME_INSTALLED: pygame.init() def flip(self): return self._guard(self.driver.flip) def step(self, action): return self.driver.step(action) def render(self): self._guard(self._render) d...
)
random_line_split
libvnc_session.py
import logging import os from twisted.internet import defer, endpoints from universe import error, utils from universe.twisty import reactor from universe.vncdriver import screen, vnc_client PYGAME_INSTALLED = None def load_pygame(): global PYGAME_INSTALLED, pygame if PYGAME_INSTALLED is not None: re...
(self, action): return self.driver.step(action) def render(self): self._guard(self._render) def _guard(self, fn): try: return fn() except (KeyboardInterrupt, SystemExit): self.close() def _render(self): self.before_render() if not PY...
step
identifier_name
index.d.ts
// Type definitions for tail 1.2 // Project: https://github.com/lucagrulla/node-tail // Definitions by: Mike Linkovich <https://github.com/spacejack> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 declare namespace Tail { interface TailOptions { separator?: st...
} interface TailConstructor { /** Creates a new Tail object that starts watching the specified file immediately. */ new(filename: string, options?: TailOptions): Tail; } interface Static { Tail: TailConstructor; } } declare const Tail: Tail.Static; export = Tail;
random_line_split
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
} sorted } fn main() { let a = vec![1, 5, 7]; let b = vec![-2, 3, 4]; let v = vec![a, b]; dbg!(merge(v)); }
{ heap.push(it) }
conditional_block
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
impl<'a> Ord for Item<'a> { fn cmp(&self, other: &Self) -> Ordering { self.get_item().cmp(&other.get_item()) } } impl<'a> Item<'a> { fn new(arr: &'a Vec<i32>, idx: usize) -> Self { Self { arr, idx } } fn get_item(&self) -> i32 { self.arr[self.idx] } } fn merge(arrays:...
self.get_item().partial_cmp(&other.get_item()) } }
random_line_split
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool
} impl<'a> PartialOrd for Item<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { self.get_item().partial_cmp(&other.get_item()) } } impl<'a> Ord for Item<'a> { fn cmp(&self, other: &Self) -> Ordering { self.get_item().cmp(&other.get_item()) } } impl<'a> Item<'a> { f...
{ self.get_item() == other.get_item() }
identifier_body
kmerge.rs
use std::cmp::Ordering; use std::cmp::Reverse; use std::collections::BinaryHeap; #[derive(Debug, Eq)] struct Item<'a> { arr: &'a Vec<i32>, idx: usize, } impl<'a> PartialEq for Item<'a> { fn eq(&self, other: &Self) -> bool { self.get_item() == other.get_item() } } impl<'a> PartialOrd for Item<...
(arrays: Vec<Vec<i32>>) -> Vec<i32> { let mut sorted = vec![]; let mut heap = BinaryHeap::with_capacity(arrays.len()); // From each vector we build an item which // stores the array and the current index. for arr in &arrays { let item = Item::new(arr, 0); println!("item={:?}", item...
merge
identifier_name
label.stories.js
import React from 'react'; import { IconInfoBadgedSmallFilled, IconMarkerSmallOutline } from '@teamleader/ui-icons'; import { Icon, Input, Label, TextSmall, Tooltip } from '../../index'; import { addStoryInGroup, LOW_LEVEL_BLOCKS } from '../../../.storybook/utils'; const TooltippedIcon = Tooltip(Icon); export default...
} connectedRight={ <TooltippedIcon tooltip={<TextSmall>This is the label tooltip text</TextSmall>} tooltipSize="small"> <IconInfoBadgedSmallFilled /> </TooltippedIcon> } > Input label <Input id="input1" placeholder="I am the placeholder" /> </Label> ); DefaultStory.args = { ...
connectedLeft={ <Icon> <IconMarkerSmallOutline /> </Icon>
random_line_split
http_client.py
# - Fall back to urllib2 with a warning if needed try: import urllib2 except ImportError: pass try: import pycurl except ImportError: pycurl = None try: import requests except ImportError: requests = None else: try: # Require version 0.8.8, but don't want to depend on distutils ...
# - Requests is the preferred HTTP library # - Google App Engine has urlfetch # - Use Pycurl if it's there (at least it verifies SSL certs)
random_line_split
http_client.py
except ImportError: pass try: import pycurl except ImportError: pycurl = None try: import requests except ImportError: requests = None else: try: # Require version 0.8.8, but don't want to depend on distutils version = requests.__version__ major, minor, patch = [int(i)...
else: err += " with no error message" msg = textwrap.fill(msg) + "\n\n(Network error: %s)" % (err,) raise error.APIConnectionError(msg) class UrlFetchClient(HTTPClient): name = 'urlfetch' def request(self, method, url, headers, post_data=None): try: ...
err += " with error message %s" % (str(e),)
conditional_block
http_client.py
version__ major, minor, patch = [int(i) for i in version.split('.')] except Exception: # Probably some new-fangled version, so it should support verify pass else: if (major, minor, patch) < (0, 8, 8): sys.stderr.write( 'Warning: the Stripe library requ...
if sys.version_info >= (3, 0): name = 'urllib.request' else: name = 'urllib2' def request(self, method, url, headers, post_data=None): if sys.version_info >= (3, 0) and isinstance(post_data, basestring): post_data = post_data.encode('utf-8') req = urllib2.Request(ur...
identifier_body
http_client.py
2 except ImportError: pass try: import pycurl except ImportError: pycurl = None try: import requests except ImportError: requests = None else: try: # Require version 0.8.8, but don't want to depend on distutils version = requests.__version__ major, minor, patch = [int(i...
(self, e): if e[0] in [pycurl.E_COULDNT_CONNECT, pycurl.E_COULDNT_RESOLVE_HOST, pycurl.E_OPERATION_TIMEOUTED]: msg = ("Could not connect to Stripe. Please check your " "internet connection and try again. If this problem " ...
_handle_request_error
identifier_name
ui-grid.language.fa.js
/*! * ui-grid - v4.6.1 - 2018-07-04 * Copyright (c) 2018 ; License: MIT */ /** * Translated by: R. Salarmehr * M. Hosseynzade * Using Vajje.com online dictionary. */ (function () { angular.module('ui.grid').config(['$provide', function ($provide) { $provide.decorator('i18nSe...
column: { hide: 'پنهان\u200cکردن ستون' }, aggregation: { count: 'تعداد: ', sum: 'مجموع: ', avg: 'میانگین: ', min: 'کمترین: ', max: 'بیشترین: ' }, pinning: { pinLeft: 'پین کردن سمت چپ', pinRight: 'پین ...
ascending: 'ترتیب صعودی', descending: 'ترتیب نزولی', remove: 'حذف مرتب کردن' },
random_line_split
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
} } impl fmt::Display for ConsoleMetricSink { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "console metric backend".fmt(f) } } impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); ...
/// Create a new console `MetricSink` pub fn new() -> ConsoleMetricSink { ConsoleMetricSink { formatter: GraphiteMetricFormatter::new() }
random_line_split
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
(&self, f: &mut fmt::Formatter) -> fmt::Result { "console metric backend".fmt(f) } } impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); let counters = metrics.counters(); let timers = metr...
fmt
identifier_name
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
} impl MetricSink for ConsoleMetricSink { fn accept(&mut self, metrics: &AggregatedMetrics) -> MetricResult<()> { let now = time::get_time(); let counters = metrics.counters(); let timers = metrics.timers(); let gauges = metrics.gauges(); debug!("Flushing {} counters to ...
{ "console metric backend".fmt(f) }
identifier_body
console.rs
// Legato - Statsd Server in Rust // // Copyright 2016 TSH Labs // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or d...
Ok(()) } }
{ print!("{}", self.formatter.fmt_gauges(metrics.gauges(), &now)); }
conditional_block
tree.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
/// Whether this element and the `other` element have the same local name and namespace. fn is_same_type(&self, other: &Self) -> bool; fn attr_matches( &self, ns: &NamespaceConstraint<&<Self::Impl as SelectorImpl>::NamespaceUrl>, local_name: &<Self::Impl as SelectorImpl>::LocalName...
fn has_namespace(&self, ns: &<Self::Impl as SelectorImpl>::BorrowedNamespaceUrl) -> bool;
random_line_split
tree.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
(NonNull<()>); unsafe impl Send for OpaqueElement {} impl OpaqueElement { /// Creates a new OpaqueElement from an arbitrarily-typed pointer. pub fn new<T>(ptr: &T) -> Self { unsafe { OpaqueElement(NonNull::new_unchecked( ptr as *const T as *const () as *mut (), ...
OpaqueElement
identifier_name
tree.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Traits that nodes must implement. Breaks the otherwise-cyclic dependency //! between layout and style. use c...
fn has_id( &self, id: &<Self::Impl as SelectorImpl>::Identifier, case_sensitivity: CaseSensitivity, ) -> bool; fn has_class( &self, name: &<Self::Impl as SelectorImpl>::ClassName, case_sensitivity: CaseSensitivity, ) -> bool; fn is_part(&self, name...
{ None }
identifier_body
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
token, tweetust::DefaultHttpHandler::with_https_connector().unwrap(), ); // Information of the authenticated user: let user = rest .account() .verify_credentials() .execute() .unwrap() .object; let bot = stream .for_each(move |json| { ...
random_line_split
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
} Ok(()) }) .map_err(|e| println!("error: {}", e)); rt::run(bot); }
{ println!( "On {}, @{} tweeted: {:?}", tweet.created_at, tweet.user.screen_name, tweet.text ); let response = format!("@{} {}", tweet.user.screen_name, tweet.text); rest.statuses() ...
conditional_block
echo_bot.rs
extern crate serde; extern crate serde_json as json; extern crate tweetust; extern crate twitter_stream; use std::fs::File; use std::path::PathBuf; use serde::de; use serde::Deserialize; use twitter_stream::rt::{self, Future, Stream}; use twitter_stream::{Error, Token, TwitterStreamBuilder}; #[derive(Deserialize)] #...
{ Tweet(Tweet), Other(de::IgnoredAny), } #[derive(Deserialize)] struct Tweet { created_at: String, entities: Entities, id: i64, text: String, user: User, } #[derive(Deserialize)] struct Entities { user_mentions: Vec<UserMention>, } #[derive(Deserialize)] struct UserMention { id: ...
StreamMessage
identifier_name
task5.py
from __future__ import division from __future__ import print_function import os import sys import functools # Update path root = os.path.join(os.getcwd().split('proj1')[0], 'proj1') if root not in sys.path: sys.path.append(root) import numpy as np import pandas as pd import multiprocessing from pdb import set_tra...
def plot_runtime_vs_avg(x, y, y_1): line2(x, y, x, y_1, label_1="Actual Runtimes", label_2="Expected value of $\rho$", x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$") def task_5(): rho_list = np.arange(0.05, 1, 0.1) C = 1e5 elapsed = [] ...
line(x, y, x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$")
identifier_body
task5.py
from __future__ import division from __future__ import print_function import os import sys import functools # Update path root = os.path.join(os.getcwd().split('proj1')[0], 'proj1') if root not in sys.path: sys.path.append(root) import numpy as np import pandas as pd import multiprocessing from pdb import set_tra...
(x=None, y=None): line(x, y, x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$") def plot_runtime_vs_avg(x, y, y_1): line2(x, y, x, y_1, label_1="Actual Runtimes", label_2="Expected value of $\rho$", x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\...
plot_runtime
identifier_name
task5.py
from __future__ import division from __future__ import print_function import os import sys import functools # Update path root = os.path.join(os.getcwd().split('proj1')[0], 'proj1') if root not in sys.path: sys.path.append(root) import numpy as np import pandas as pd import multiprocessing from pdb import set_tra...
def plot_runtime_vs_avg(x, y, y_1): line2(x, y, x, y_1, label_1="Actual Runtimes", label_2="Expected value of $\rho$", x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$") def task_5(): rho_list = np.arange(0.05, 1, 0.1) C = 1e5 elapsed = [] ...
line(x, y, x_label=r"$\rho$", y_label=r"Run Times", the_title=r"$\mathrm{Run\ Times\ in\ }\mu\mathrm{s\ vs.\ }\rho$")
random_line_split
task5.py
from __future__ import division from __future__ import print_function import os import sys import functools # Update path root = os.path.join(os.getcwd().split('proj1')[0], 'proj1') if root not in sys.path: sys.path.append(root) import numpy as np import pandas as pd import multiprocessing from pdb import set_tra...
task_5() task5_plot() compare_plot()
conditional_block
BattlePvP.ts
import { sample } from 'lodash'; import { Event } from './Event'; import { Player } from '../../../../shared/models/entity'; import { AdventureLogEventType, ICombat, EventMessageType } from '../../../../shared/interfaces'; export class BattlePvP extends Event { public static readonly WEIGHT = 3; public
(player: Player) { const checkPlayers = this.playerManager.allPlayers.filter( x => (player.$party ? x.$party : !x.$party) && (player.$party ? x.$party.name !== player.$party.name : true) && x !== player ); if(checkPlayers.length < 1) { this.emitMessage([player], 'You almost fou...
operateOn
identifier_name
BattlePvP.ts
import { sample } from 'lodash'; import { Event } from './Event'; import { Player } from '../../../../shared/models/entity'; import { AdventureLogEventType, ICombat, EventMessageType } from '../../../../shared/interfaces'; export class BattlePvP extends Event { public static readonly WEIGHT = 3; public operateOn...
const chosenTarget = sample(checkPlayers); const allPlayers = []; allPlayers.push(...(player.$party ? player.$party.members : [player.name])); allPlayers.push(...(chosenTarget.$party ? chosenTarget.$party.members : [chosenTarget.name])); if(!player.$$game.combatHelper.canDoCombat(player) || !pla...
{ this.emitMessage([player], 'You almost found a sparring partner!', AdventureLogEventType.Party); return; }
conditional_block
BattlePvP.ts
import { sample } from 'lodash'; import { Event } from './Event'; import { Player } from '../../../../shared/models/entity'; import { AdventureLogEventType, ICombat, EventMessageType } from '../../../../shared/interfaces'; export class BattlePvP extends Event { public static readonly WEIGHT = 3; public operateOn(...
const chosenTarget = sample(checkPlayers); const allPlayers = []; allPlayers.push(...(player.$party ? player.$party.members : [player.name])); allPlayers.push(...(chosenTarget.$party ? chosenTarget.$party.members : [chosenTarget.name])); if(!player.$$game.combatHelper.canDoCombat(player) || !play...
}
random_line_split
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
while let Some(msg) = stream.try_next().await? { let api_cache_state = Arc::clone(&api_cache_state); let user_state = Arc::clone(&user_state); match msg { iml_postgres::AsyncMessage::Notification(n) => { if n.channel() == "table_update" { let...
// Keep the client alive within the spawned future so the LISTEN/NOTIFY stream is not dropped let _keep_alive = &client;
random_line_split
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
Ok(()) } iml_postgres::AsyncMessage::Notice(err) => { tracing::error!("Error from postgres {}", err); Err(error::ImlWarpDriveError::from(err)) } _ => unreachable!(), }?; } Ok(()) }
{ // Keep the client alive within the spawned future so the LISTEN/NOTIFY stream is not dropped let _keep_alive = &client; while let Some(msg) = stream.try_next().await? { let api_cache_state = Arc::clone(&api_cache_state); let user_state = Arc::clone(&user_state); match msg { ...
identifier_body
listen.rs
// Copyright (c) 2020 DDN. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. use crate::{cache, db_record, error, users, DbRecord}; use futures::{Stream, TryStreamExt}; use iml_wire_types::{ db::TableName, warp_drive::{Message, RecordCh...
(s: &str) -> serde_json::error::Result<(MessageType, DbRecord)> { let (msg_type, table_name, x): (MessageType, TableName, serde_json::Value) = serde_json::from_str(&s)?; let r = db_record::DbRecord::try_from((table_name, x))?; Ok((msg_type, r)) } async fn handle_record_change( record_change: ...
into_db_record
identifier_name
NodeHotUpdateChunkTemplate.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var HotUpdateChunkTemplate = require("../HotUpdateChunkTemplate"); function NodeHotUpdateChunkTemplate(outputOptions) { HotUpdateChunkTemplate.call(this, outputOptions); } module.exports = NodeHotUpdateChunkTemplate; ...
};
random_line_split
NodeHotUpdateChunkTemplate.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var HotUpdateChunkTemplate = require("../HotUpdateChunkTemplate"); function NodeHotUpdateChunkTemplate(outputOptions)
module.exports = NodeHotUpdateChunkTemplate; NodeHotUpdateChunkTemplate.prototype = Object.create(HotUpdateChunkTemplate.prototype); NodeHotUpdateChunkTemplate.prototype.renderHeader = function(id, modules, hash) { var buf = HotUpdateChunkTemplate.prototype.renderHeader.call(this, id, modules, hash); buf.unshift( ...
{ HotUpdateChunkTemplate.call(this, outputOptions); }
identifier_body
NodeHotUpdateChunkTemplate.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var HotUpdateChunkTemplate = require("../HotUpdateChunkTemplate"); function
(outputOptions) { HotUpdateChunkTemplate.call(this, outputOptions); } module.exports = NodeHotUpdateChunkTemplate; NodeHotUpdateChunkTemplate.prototype = Object.create(HotUpdateChunkTemplate.prototype); NodeHotUpdateChunkTemplate.prototype.renderHeader = function(id, modules, hash) { var buf = HotUpdateChunkTemplate...
NodeHotUpdateChunkTemplate
identifier_name
index.d.ts
// Type definitions for webpack-plugin-serve 0.10 // Project: https://github.com/shellscape/webpack-plugin-serve // Definitions by: Matheus Gonçalves da Silva <https://github.com/PlayMa256> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="node" /> impo...
{ constructor(opts?: WebpackPluginServeOptions); attach(): { apply(compiler: Compiler): void; }; hook(compiler: Compiler): void; apply(compiler: Compiler): void; }
ebpackPluginServe
identifier_name
index.d.ts
// Type definitions for webpack-plugin-serve 0.10 // Project: https://github.com/shellscape/webpack-plugin-serve // Definitions by: Matheus Gonçalves da Silva <https://github.com/PlayMa256> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="node" /> impo...
hook(compiler: Compiler): void; apply(compiler: Compiler): void; }
apply(compiler: Compiler): void; };
random_line_split
earlyforce.py
from rpython.jit.codewriter.effectinfo import EffectInfo from rpython.jit.metainterp.optimizeopt.optimizer import Optimization from rpython.jit.metainterp.resoperation import rop def is_raw_free(op, opnum): if not op.is_real_call(): return False einfo = op.getdescr().get_extra_info() return einfo....
if (opnum != rop.SETFIELD_GC and opnum != rop.SETARRAYITEM_GC and opnum != rop.SETARRAYITEM_RAW and opnum != rop.QUASIIMMUT_FIELD and opnum != rop.SAME_AS_I and opnum != rop.SAME_AS_R and opnum != rop.SAME_AS_F and not is_raw_fr...
class OptEarlyForce(Optimization): def propagate_forward(self, op): opnum = op.getopnum()
random_line_split
earlyforce.py
from rpython.jit.codewriter.effectinfo import EffectInfo from rpython.jit.metainterp.optimizeopt.optimizer import Optimization from rpython.jit.metainterp.resoperation import rop def is_raw_free(op, opnum): if not op.is_real_call():
einfo = op.getdescr().get_extra_info() return einfo.oopspecindex == EffectInfo.OS_RAW_FREE class OptEarlyForce(Optimization): def propagate_forward(self, op): opnum = op.getopnum() if (opnum != rop.SETFIELD_GC and opnum != rop.SETARRAYITEM_GC and opnum != rop.SETA...
return False
conditional_block
earlyforce.py
from rpython.jit.codewriter.effectinfo import EffectInfo from rpython.jit.metainterp.optimizeopt.optimizer import Optimization from rpython.jit.metainterp.resoperation import rop def is_raw_free(op, opnum): if not op.is_real_call(): return False einfo = op.getdescr().get_extra_info() return einfo...
self.optimizer.optearlyforce = self
identifier_body
earlyforce.py
from rpython.jit.codewriter.effectinfo import EffectInfo from rpython.jit.metainterp.optimizeopt.optimizer import Optimization from rpython.jit.metainterp.resoperation import rop def is_raw_free(op, opnum): if not op.is_real_call(): return False einfo = op.getdescr().get_extra_info() return einfo...
(self, op): opnum = op.getopnum() if (opnum != rop.SETFIELD_GC and opnum != rop.SETARRAYITEM_GC and opnum != rop.SETARRAYITEM_RAW and opnum != rop.QUASIIMMUT_FIELD and opnum != rop.SAME_AS_I and opnum != rop.SAME_AS_R and opnum != ...
propagate_forward
identifier_name
apptemplateloader.py
# -*- coding: utf-8 -*- # adaped from https://www.djangosnippets.org/snippets/1376/ from os.path import abspath, dirname, isdir, join from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loaders.filesystem import Load...
def load_template_from_app(self, template_name, template_dirs=None): """ Template loader that only serves templates from specific app's template directory. Works for template_names in format app_label:some/template/name.html """ if ":" not in template_name: rais...
return template_name, template_dir
random_line_split
apptemplateloader.py
# -*- coding: utf-8 -*- # adaped from https://www.djangosnippets.org/snippets/1376/ from os.path import abspath, dirname, isdir, join from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loaders.filesystem import Load...
(self, template_name, template_dirs=None): return self.load_template_from_app(template_name)
load_template_source
identifier_name
apptemplateloader.py
# -*- coding: utf-8 -*- # adaped from https://www.djangosnippets.org/snippets/1376/ from os.path import abspath, dirname, isdir, join from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loaders.filesystem import Load...
def load_template_source(self, template_name, template_dirs=None): return self.load_template_from_app(template_name)
""" Template loader that only serves templates from specific app's template directory. Works for template_names in format app_label:some/template/name.html """ if ":" not in template_name: raise TemplateDoesNotExist() template_name, template_dir = self._get_templat...
identifier_body
apptemplateloader.py
# -*- coding: utf-8 -*- # adaped from https://www.djangosnippets.org/snippets/1376/ from os.path import abspath, dirname, isdir, join from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loaders.filesystem import Load...
return super().load_template_source(template_name, template_dirs=[template_dir]) def load_template_source(self, template_name, template_dirs=None): return self.load_template_from_app(template_name)
raise TemplateDoesNotExist()
conditional_block
file_tags.py
# -*- coding: utf-8 -*- import logging import posixpath from collections import defaultdict from seaserv import seafile_api from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email from seahub.utils.timeutils import timestamp_to_isoformat_timestr from seahub.file_tags.models import FileTag...
return files_tags_in_dir def get_tagged_files(repo, repo_tag_id): # get tagged files tagged_file_objs = FileTags.objects.filter( repo_tag__id=repo_tag_id).select_related('repo_tag', 'file_uuid') tagged_files = defaultdict(list) for tagged_file_obj in tagged_file_objs: file_tag_...
file_tag_dict = dict() file_tag_dict['file_tag_id'] = file_tag.pk file_tag_dict['repo_tag_id'] = file_tag.repo_tag.pk file_tag_dict['tag_name'] = file_tag.repo_tag.name file_tag_dict['tag_color'] = file_tag.repo_tag.color files_tags_in_dir[file_tag.file_uuid.filename].append(file...
conditional_block
file_tags.py
# -*- coding: utf-8 -*- import logging import posixpath from collections import defaultdict from seaserv import seafile_api from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email from seahub.utils.timeutils import timestamp_to_isoformat_timestr from seahub.file_tags.models import FileTag...
tagged_file["file_tag_id"] = file_tag_id tagged_file["parent_path"] = parent_path tagged_file["filename"] = filename tagged_file["size"] = file_obj.size tagged_file["mtime"] = file_obj.mtime tagged_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime) ...
random_line_split
file_tags.py
# -*- coding: utf-8 -*- import logging import posixpath from collections import defaultdict from seaserv import seafile_api from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email from seahub.utils.timeutils import timestamp_to_isoformat_timestr from seahub.file_tags.models import FileTag...
(repo_id, path): # Get QuerySet from file_tags, repo_tags and file_uuid_map files_tags = FileTags.objects.get_dir_file_tags(repo_id, path).select_related('repo_tag', 'file_uuid') files_tags_in_dir = defaultdict(list) for file_tag in files_tags: file_tag_dict = dict() file_tag_dict['fil...
get_files_tags_in_dir
identifier_name
file_tags.py
# -*- coding: utf-8 -*- import logging import posixpath from collections import defaultdict from seaserv import seafile_api from seahub.base.templatetags.seahub_tags import email2nickname, email2contact_email from seahub.utils.timeutils import timestamp_to_isoformat_timestr from seahub.file_tags.models import FileTag...
tagged_file["file_tag_id"] = file_tag_id tagged_file["parent_path"] = parent_path tagged_file["filename"] = filename tagged_file["size"] = file_obj.size tagged_file["mtime"] = file_obj.mtime tagged_file["last_modified"] = timestamp_to_isoformat_timestr(file_obj.mtime) ...
tagged_file_objs = FileTags.objects.filter( repo_tag__id=repo_tag_id).select_related('repo_tag', 'file_uuid') tagged_files = defaultdict(list) for tagged_file_obj in tagged_file_objs: file_tag_id = tagged_file_obj.pk parent_path = tagged_file_obj.file_uuid.parent_path filename =...
identifier_body
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
common::problem!("31626", solve);
{ compute(10000).to_string() }
identifier_body
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
() -> String { compute(10000).to_string() } common::problem!("31626", solve);
solve
identifier_name
p021.rs
//! [Problem 21](https://projecteuler.net/problem=21) solver. #![warn( bad_style, unused, unused_extern_crates, unused_import_braces, unused_qualifications, unused_results )] use prime::{Factorize, PrimeSet}; fn compute(limit: u64) -> u64 { let ps = PrimeSet::new(); let sum_of_div = ...
.enumerate() .map(|(n, div)| (n as u64, div)) .filter(|&(n, div)| div < n) .filter(|&(n, div)| sum_of_div[div as usize] == n) .map(|(a, b)| a + b) .sum() } fn solve() -> String { compute(10000).to_string() } common::problem!("31626", solve);
.collect::<Vec<_>>(); sum_of_div .iter() .cloned()
random_line_split
Grid.ts
class Grid { //声明构造 private startPnode: Pnode;//开始节点 private endPnode: Pnode;//目标节点 private nodes: Pnode[][];//节点数组 private numCols: number;//格子列数 private numRows: number;//格子行数 private gridX: number;//格子像素宽 private gridY: number;//格子像素高 constructor(numCols: number, numRows: numbe...
} } }//构造网格 //其他函数 getGridX(): number { return this.gridX; }//获得格子宽 getGridY(): number { return this.gridY; }//获得格子高 getPnode(x: number, y: number): Pnode { return this.nodes[x][y]; }//获得网格中某个格子 getEndPnode(): Pnode { return this...
random_line_split
Grid.ts
class Grid { //声明构造 private startPnode: Pnode;//开始节点 private endPnode: Pnode;//目标节点 private nodes: Pnode[][];//节点数组 private numCols: number;//格子列数 private numRows: number;//格子行数 private gridX: number;//格子像素宽 private gridY: number;//格子像素高 constructor(numCols: number, numRows: numbe...
e { return this.nodes[x][y]; }//获得网格中某个格子 getEndPnode(): Pnode { return this.endPnode; }//获得终点 getStartPnode(): Pnode { return this.startPnode; }//获得起点 getNumCols(): number { return this.numCols; }//获得网格列数 getNumRows(): number { return this....
r): Pnod
identifier_name
Grid.ts
class Grid { //声明构造 private startPnode: Pnode;//开始节点 private endPnode: Pnode;//目标节点 private nodes: Pnode[][];//节点数组 private numCols: number;//格子列数 private numRows: number;//格子行数 private gridX: number;//格子像素宽 private gridY: number;//格子像素高 constructor(numCols: number, numRows: numbe...
rn this.gridX; }//获得格子宽 getGridY(): number { return this.gridY; }//获得格子高 getPnode(x: number, y: number): Pnode { return this.nodes[x][y]; }//获得网格中某个格子 getEndPnode(): Pnode { return this.endPnode; }//获得终点 getStartPnode(): Pnode { return this.startPno...
} }//构造网格 //其他函数 getGridX(): number { retu
conditional_block
Grid.ts
class Grid { //声明构造 private startPnode: Pnode;//开始节点 private endPnode: Pnode;//目标节点 private nodes: Pnode[][];//节点数组 private numCols: number;//格子列数 private numRows: number;//格子行数 private gridX: number;//格子像素宽 private gridY: number;//格子像素高 constructor(numCols: number, numRows: numbe...
tartPnode; }//获得起点 getNumCols(): number { return this.numCols; }//获得网格列数 getNumRows(): number { return this.numRows; }//获得网格行数 setEndPnode(x: number, y: number): void { this.endPnode = this.nodes[x][y]; }//设置终点 setStartPnode(x: number, y: number): void { ...
ndPnode; }//获得终点 getStartPnode(): Pnode { return this.s
identifier_body
fsdev_disks.py
options fstype = splt[4] fsopts = splt[5] # Check for something other than a r/w mount if fsopts[:3] != '(rw': mstat = -1 break
# Does the caller only want to allow 'standard' mount points? if std_mounts_only and mstat < 0: continue # Was this partition mounted at all? if not mountpt: # Ask the client where we should mount this partition mountpt = fd_mgr.check_mount_point(par...
# The drive is mounted at the 'normal' mount point mstat = 1
random_line_split
fsdev_disks.py
if not mountpt: # Ask the client where we should mount this partition mountpt = fd_mgr.check_mount_point(partname, None) if not mountpt: # Client doesn't know where to mount partition - ignore it continue # Looks like we have a valid disk dri...
prepare_fsdev
identifier_name
fsdev_disks.py
fstype = splt[4] fsopts = splt[5] # Check for something other than a r/w mount if fsopts[:3] != '(rw': mstat = -1 break # The drive is mounted at the 'normal' mount point mstat = 1 ...
except: raise Exception("Could not create a filesystem on '%s'" % dev_path) # Make sure the volume is unmounted if disk["mounted"]: try: fs.unmount(mnt_path) except Exception, info: raise Exception("umount failed: exception = %...
""" Prepare all the drives in 'disk_list' for testing. For each disk this means unmounting any mount points that use the disk, running mkfs with 'fs_type' as the file system type and 'fs_makeopt' as the 'mkfs' options, and finally remounting the freshly formatted drive using the flags in 'fs_mnt_opt'. ...
identifier_body
fsdev_disks.py
# Record the new file system type and options in the disk list disk["mounted"] = True disk["fs_type"] = fs_type disk["fs_mkfs"] = fs_makeopt disk["fs_opts"] = fs_mnt_opt # Try to wipe the file system slate clean utils.drop_caches() # XXX(gps): Remove this code once ref...
slash = tuner.find("/") if slash < 0: break tuner = tuner[slash+1:]
conditional_block
api.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { ReplaySubject, Subject } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { Logger } from 'app/shared/logger.service'; import { DOC_CONTENT_URL_PREFIX } from 'app/d...
return this._sections.pipe(tap(sections => { sections.forEach(section => { section.deprecated = !!section.items && section.items.every(item => item.stability === 'deprecated'); }); })); } constructor(private http: HttpClient, private logger: Logger) { } ngOnDestroy() { ...
{ this.firstTime = false; this.fetchSections(); // TODO: get URL for fetchSections by configuration? // makes sectionsSubject hot; subscribe ensures stays alive (always refCount > 0); this._sections.subscribe(sections => this.logger.log(`ApiService got API ${sections.length} section(s)`)); ...
conditional_block
api.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { ReplaySubject, Subject } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { Logger } from 'app/shared/logger.service'; import { DOC_CONTENT_URL_PREFIX } from 'app/d...
implements OnDestroy { private apiBase = DOC_CONTENT_URL_PREFIX + 'api/'; private apiListJsonDefault = 'api-list.json'; private firstTime = true; private onDestroy = new Subject(); private sectionsSubject = new ReplaySubject<ApiSection[]>(1); private _sections = this.sectionsSubject.pipe(takeUntil(this.on...
ApiService
identifier_name
api.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { ReplaySubject, Subject } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { Logger } from 'app/shared/logger.service'; import { DOC_CONTENT_URL_PREFIX } from 'app/d...
this.firstTime = false; this.fetchSections(); // TODO: get URL for fetchSections by configuration? // makes sectionsSubject hot; subscribe ensures stays alive (always refCount > 0); this._sections.subscribe(sections => this.logger.log(`ApiService got API ${sections.length} section(s)`)); } ...
if (this.firstTime) {
random_line_split
api.service.ts
import { Injectable, OnDestroy } from '@angular/core'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { ReplaySubject, Subject } from 'rxjs'; import { takeUntil, tap } from 'rxjs/operators'; import { Logger } from 'app/shared/logger.service'; import { DOC_CONTENT_URL_PREFIX } from 'app/d...
}
{ // TODO: get URL by configuration? const url = this.apiBase + (src || this.apiListJsonDefault); this.http.get<ApiSection[]>(url) .pipe( takeUntil(this.onDestroy), tap(() => this.logger.log(`Got API sections from ${url}`)), ) .subscribe( sections => this.sectionsSu...
identifier_body
golem-scripts.js
day, id, suffix) { var suffix = ""; if (graph == 'ACDA' || graph == 'ACDV') { suffix = " Seconds"; } else if (graph == 'Buy' || graph == 'Sell') { suffix = " EUR Cent"; } else if (graph == 'ARSV' || graph == 'GpPercent') { suffix = "%;" } else { suffix = " Minutes"; } var yserie = []; $.each(jdata...
options_disabled.push({ label : name, value : name }); }); console.log(options_active) console.log(options_disabled) $.each(json["toplot"], function(index, benchmark) { benchmarkPlot(benchmark['measures'], $('#sampleTabs>.active') .text(), 'graph'); }); $("#benchmarks").mu...
{ var servlet = "/benchmark"; var call = "?list=true&country=" + country + "&customer=" + customer; var options_active = []; var options_disabled = []; initBenchmarkMenus(); console.log(call); $.getJSON(servlet + call, function(json) { setTimeout(function() { $.each(json["active_opt"], function(index, n...
identifier_body
golem-scripts.js
day, id, suffix) { var suffix = ""; if (graph == 'ACDA' || graph == 'ACDV') { suffix = " Seconds"; } else if (graph == 'Buy' || graph == 'Sell') { suffix = " EUR Cent"; } else if (graph == 'ARSV' || graph == 'GpPercent') { suffix = "%;" } else { suffix = " Minutes"; } var yserie = []; $.each(jdata...
(id, button) { $.ajax({ url : "/user?admin=false&id=" + id, type : 'POST', success : function() { $(button).parent().parent().parent().remove(); setTimeout(function() { location.reload(); }, 0001); } }); }; function upgrade(id, button) { $.ajax({ url : "/user?up=true&id=" + id, type : 'POST'...
makeUser
identifier_name