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
useless_chaining.rs
// Copyright 2018 Chao Lin & William Sergeant (Sorbonne University) // 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...
}
// test33 = &test32
random_line_split
tokenizer.rs
|p?l|res|f)|S(?:e(?:ns?|pt?|c)|(?:up|g)?t|ask|r)|s(?:e(?:ns?|pt?|c)|(?:up|g)?t|r)|a(?:ttys?|ssn|dm|pr|rc|ug|ve|l)|P(?:enna?|-a.s|de?|lz?|rof|a)|D(?:e(?:[cfl]|p?t)|ist|ak|r)|I(?:[as]|n[cd]|da?|.e|ll)|F(?:e[bd]|w?y|ig|la|t)|O(?:k(?:la)?|[cn]t|re)|d(?:e(?:p?t|c)|ist|r)|E(?:xpy?|.g|sp|tc|qs?)|R(?:e(?:ps?|sp|v)|d)|T(?:e(?:n...
if left_window.len() >= window_size { left_window.pop_front(); } } //TODO: Handle dot-dot-dot "..." else { // Not a special case, break the sentence // Reset the left window left_w...
{ // Regular word case. // Check for abbreviations: // Longest abbreviation is 6 characters, but MathFormula is 11, so take window // of window_size chars to the left (allow for a space before dot) let lw_string: String = left_window.clone().into_ite...
conditional_block
tokenizer.rs
|p?l|res|f)|S(?:e(?:ns?|pt?|c)|(?:up|g)?t|ask|r)|s(?:e(?:ns?|pt?|c)|(?:up|g)?t|r)|a(?:ttys?|ssn|dm|pr|rc|ug|ve|l)|P(?:enna?|-a.s|de?|lz?|rof|a)|D(?:e(?:[cfl]|p?t)|ist|ak|r)|I(?:[as]|n[cd]|da?|.e|ll)|F(?:e[bd]|w?y|ig|la|t)|O(?:k(?:la)?|[cn]t|re)|d(?:e(?:p?t|c)|ist|r)|E(?:xpy?|.g|sp|tc|qs?)|R(?:e(?:ps?|sp|v)|d)|T(?:e(?:n...
let space_char = text_iterator.next().unwrap(); end += space_char.len_utf8(); } if text_iterator.peek() == None { break; } // Uppercase next? if wordlike_with_upper_next(&text_iterator) { // Ok, uppercase, but is it a stop...
{ let text = &dnm.plaintext; let mut sentences: Vec<DNMRange<'a>> = Vec::new(); let mut text_iterator = text.chars().peekable(); let mut start = 0; let mut end = 0; let window_size = 12; // size of max string + 1 let mut left_window: VecDeque<char> = VecDeque::with_capacity(window_size); ...
identifier_body
tokenizer.rs
|p?l|res|f)|S(?:e(?:ns?|pt?|c)|(?:up|g)?t|ask|r)|s(?:e(?:ns?|pt?|c)|(?:up|g)?t|r)|a(?:ttys?|ssn|dm|pr|rc|ug|ve|l)|P(?:enna?|-a.s|de?|lz?|rof|a)|D(?:e(?:[cfl]|p?t)|ist|ak|r)|I(?:[as]|n[cd]|da?|.e|ll)|F(?:e[bd]|w?y|ig|la|t)|O(?:k(?:la)?|[cn]t|re)|d(?:e(?:p?t|c)|ist|r)|E(?:xpy?|.g|sp|tc|qs?)|R(?:e(?:ps?|sp|v)|d)|T(?:e(?:n...
} } upper_found } impl Tokenizer { /// gets the sentences from a dnm pub fn sentences<'a>(&self, dnm: &'a DNM) -> Vec<DNMRange<'a>> { let text = &dnm.plaintext; let mut sentences: Vec<DNMRange<'a>> = Vec::new(); let mut text_iterator = text.chars().peekable(); let mut start = 0; let mut...
} } else { break;
random_line_split
tokenizer.rs
univ|Yuk|oct|tce|vs)\s?$").unwrap(), } } } fn wordlike_with_upper_next(peekable: &Peekable<Chars>) -> bool { let new_iterator = peekable.clone(); let mut upper_found = false; for c in new_iterator { if c.is_alphabetic() { if c.is_uppercase() { upper_found = true; break; } ...
_bounded<'
identifier_name
app_chooser.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::{from_glib_none}; use ffi; use cast::GTK_APP_CHOOSER; pub trait App...
} } fn get_content_info(&self) -> Option<String> { unsafe { from_glib_none( ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget()))) } } fn refresh(&self) -> () { unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self...
random_line_split
app_chooser.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::{from_glib_none}; use ffi; use cast::GTK_APP_CHOOSER; pub trait App...
fn refresh(&self) -> () { unsafe { ffi::gtk_app_chooser_refresh(GTK_APP_CHOOSER(self.unwrap_widget())) } } }
{ unsafe { from_glib_none( ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget()))) } }
identifier_body
app_chooser.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::{from_glib_none}; use ffi; use cast::GTK_APP_CHOOSER; pub trait App...
(&self) -> Option<::AppInfo> { let tmp_pointer = unsafe { ffi::gtk_app_chooser_get_app_info(GTK_APP_CHOOSER(self.unwrap_widget())) }; if tmp_pointer.is_null() { None } else { Some(::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget)) } } fn get...
get_app_info
identifier_name
app_chooser.rs
// Copyright 2013-2015, The Rust-GNOME Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> use glib::translate::{from_glib_none}; use ffi; use cast::GTK_APP_CHOOSER; pub trait App...
else { Some(::FFIWidget::wrap_widget(tmp_pointer as *mut ffi::C_GtkWidget)) } } fn get_content_info(&self) -> Option<String> { unsafe { from_glib_none( ffi::gtk_app_chooser_get_content_type(GTK_APP_CHOOSER(self.unwrap_widget()))) } } fn ...
{ None }
conditional_block
Throbber.ts
/** * Throbber.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ import $ from 'tinymce/core/api/dom/DomQuery'; import Control from './Control'; import Delay from 'tiny...
() { if (state) { $(elm).append( '<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>' ); if (callback) { callback(); } } } self.hide(); state = true; if (time) { timer = De...
render
identifier_name
Throbber.ts
/** * Throbber.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ import $ from 'tinymce/core/api/dom/DomQuery'; import Control from './Control'; import Delay from 'tiny...
self.hide(); state = true; if (time) { timer = Delay.setTimeout(render, time); } else { render(); } return self; }; /** * Hides the throbber. * * @method hide * @return {tinymce.ui.Throbber} Current throbber instance. */ self.hide = function () { const ...
{ if (state) { $(elm).append( '<div class="' + classPrefix + 'throbber' + (inline ? ' ' + classPrefix + 'throbber-inline' : '') + '"></div>' ); if (callback) { callback(); } } }
identifier_body
Throbber.ts
/** * Throbber.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ import $ from 'tinymce/core/api/dom/DomQuery'; import Control from './Control'; import Delay from 'tiny...
}
random_line_split
Throbber.ts
/** * Throbber.js * * Released under LGPL License. * Copyright (c) 1999-2017 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ import $ from 'tinymce/core/api/dom/DomQuery'; import Control from './Control'; import Delay from 'tiny...
state = false; return self; }; }
{ child.parentNode.removeChild(child); }
conditional_block
Badge.tsx
import React, {forwardRef} from 'react' import cn from 'classnames' import {Text} from '../Typography/Text' import type {HTMLAttributes, PropsWithRef} from 'react' import type {OmuiColors} from '@/styles/colorType' export type BadgeVariantProp = 'gray' | 'primary' | 'tertiary' | 'quaternary' | 'danger' | 'success' exp...
} const badges: Badges = Object.assign( {}, ...(Object.keys(VARIANT_COLORS) as Array<BadgeVariantProp>).map(variant => { const color = VARIANT_COLORS[variant] return { [variant]: { outline: [ 'py-px border', `border-${color}-500 text-${color}-600 dark:border-${color}-200 d...
[O in BadgeTypeProp]: string | string[] }
random_line_split
size_constraint.rs
use std::cmp::min; /// Single-dimensional constraint on a view size. /// /// This describes a possible behaviour for a [`ResizedView`]. /// /// [`ResizedView`]: crate::views::ResizedView #[derive(Debug, Clone, Copy)] pub enum SizeConstraint { /// No constraint imposed, the child view's response is used. Free, ...
(self, (result, available): (usize, usize)) -> usize { match self { SizeConstraint::AtLeast(value) if result < value => value, SizeConstraint::AtMost(value) if result > value => value, SizeConstraint::Fixed(value) => value, SizeConstraint::Full if available > resu...
result
identifier_name
size_constraint.rs
use std::cmp::min; /// Single-dimensional constraint on a view size. /// /// This describes a possible behaviour for a [`ResizedView`]. /// /// [`ResizedView`]: crate::views::ResizedView #[derive(Debug, Clone, Copy)] pub enum SizeConstraint { /// No constraint imposed, the child view's response is used. Free, ...
} /// Returns the size the child view should actually use. /// /// When it said it wanted `result`. pub fn result(self, (result, available): (usize, usize)) -> usize { match self { SizeConstraint::AtLeast(value) if result < value => value, SizeConstraint::AtMost(valu...
random_line_split
size_constraint.rs
use std::cmp::min; /// Single-dimensional constraint on a view size. /// /// This describes a possible behaviour for a [`ResizedView`]. /// /// [`ResizedView`]: crate::views::ResizedView #[derive(Debug, Clone, Copy)] pub enum SizeConstraint { /// No constraint imposed, the child view's response is used. Free, ...
} } /// Returns the size the child view should actually use. /// /// When it said it wanted `result`. pub fn result(self, (result, available): (usize, usize)) -> usize { match self { SizeConstraint::AtLeast(value) if result < value => value, SizeConstraint::...
{ min(value, available) }
conditional_block
moodle-mod_quiz-repaginate.js
YUI.add('moodle-mod_quiz-repaginate', function (Y, NAME) { // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, o...
// // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Repaginate functionality for a popup in quiz editing page. * * @package mod_quiz * @copyright 2014 The Open University * @license http://www.gnu.org/copyleft/gpl.ht...
// Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details.
random_line_split
tag_pattern.py
# -*- coding: utf-8 -*- ''' tag_treetagger.py This module is a wrapper to TreeTagger. ''' import os import sys import string import six import sklearn from itertools import chain from bakfu.core.routes import register from bakfu.process.base import BaseProcessor __errors__ = [] try: import pattern.fr except...
(self, *args, **kwargs): super(PatternTagger, self).__init__(*args, **kwargs) self.tagger = None def run(self, caller, *args, **kwargs): ''' ''' super(PatternTagger, self).run(caller, *args, **kwargs) data_source = caller.get_chain('data_source') self.calle...
__init__
identifier_name
tag_pattern.py
# -*- coding: utf-8 -*- ''' tag_treetagger.py This module is a wrapper to TreeTagger. ''' import os import sys import string import six import sklearn from itertools import chain from bakfu.core.routes import register from bakfu.process.base import BaseProcessor __errors__ = [] try: import pattern.fr except...
[lemmas.extend(a.lemma) for a in tagger(sentence,tokenize = True, tags = True, chunks = True, relations = True, lemmata = True, light = False)] return lemmas @register('tagging.pattern', __errors__) class PatternTagger(BaseProcessor): ''' Pre-processes data with pattern. :Example: .. doctest:...
random_line_split
tag_pattern.py
# -*- coding: utf-8 -*- ''' tag_treetagger.py This module is a wrapper to TreeTagger. ''' import os import sys import string import six import sklearn from itertools import chain from bakfu.core.routes import register from bakfu.process.base import BaseProcessor __errors__ = [] try: import pattern.fr except...
def run(self, caller, *args, **kwargs): ''' ''' super(PatternTagger, self).run(caller, *args, **kwargs) data_source = caller.get_chain('data_source') self.caller=caller lang = caller.get('lang') if lang == 'fr': self.tagger = pattern.fr.parsetr...
super(PatternTagger, self).__init__(*args, **kwargs) self.tagger = None
identifier_body
tag_pattern.py
# -*- coding: utf-8 -*- ''' tag_treetagger.py This module is a wrapper to TreeTagger. ''' import os import sys import string import six import sklearn from itertools import chain from bakfu.core.routes import register from bakfu.process.base import BaseProcessor __errors__ = [] try: import pattern.fr except...
def tag(tagger, sentence): ''' ''' lemmas = [] [lemmas.extend(a.lemma) for a in tagger(sentence,tokenize = True, tags = True, chunks = True, relations = True, lemmata = True, light = False)] return lemmas @register('tagging.pattern', __errors__) class PatternTagger(BaseProcessor): ''' ...
__errors__.append(e)
conditional_block
fast_power.js
'use strict'; var multiplicationOperator = function (a, b) { return a * b; }; /** * Raise value to a positive integer power by repeated squaring. * * @param {*} base * @param {number} power * @param {function} [mul] - Multiplication function, * standard multiplication operator by default. * @param {*} id...
if (!power) { if (identity === undefined) { throw new Error('The power is zero, but identity value not set.'); } else { return identity; } } // Iterative form of the algorithm avoids checking the same thing twice. var result; var multiplyBy = function (value) { result = (resul...
random_line_split
fast_power.js
'use strict'; var multiplicationOperator = function (a, b) { return a * b; }; /** * Raise value to a positive integer power by repeated squaring. * * @param {*} base * @param {number} power * @param {function} [mul] - Multiplication function, * standard multiplication operator by default. * @param {*} id...
if (power < 0 || Math.floor(power) != power) { throw new Error('Power must be a positive integer or zero.'); } // If the power is zero, identity value must be given (or set by default). if (!power) { if (identity === undefined) { throw new Error('The power is zero, but identity value not set.');...
{ mul = multiplicationOperator; identity = 1; }
conditional_block
app.js
/** * @module main application controller * @description Runs socket.io and static http server, listens for client connections and directs user/room instances. * * @author cemckinley <cemckinley@gmail.com> * @copyright Copyright (c) 2013 Author, contributors * @license GPL v3 */ var fs = require('f...
function _onClientConnect(socket){ var client = new SessionHandler(socket); } function _onClientAuth(userData, clientSocket){ var user = new User(clientSocket, userData); clientSocket.emit('message', userData.name + 'successful user auth'); } /** PUBLIC API **/ return { init: init }; }()); nodeM...
{ res.writeHead(200); res.end(); }
identifier_body
app.js
/** * @module main application controller * @description Runs socket.io and static http server, listens for client connections and directs user/room instances. * * @author cemckinley <cemckinley@gmail.com> * @copyright Copyright (c) 2013 Author, contributors * @license GPL v3 */ var fs = require('f...
(userData, clientSocket){ var user = new User(clientSocket, userData); clientSocket.emit('message', userData.name + 'successful user auth'); } /** PUBLIC API **/ return { init: init }; }()); nodeMud.init();
_onClientAuth
identifier_name
app.js
/** * @module main application controller * @description Runs socket.io and static http server, listens for client connections and directs user/room instances. * * @author cemckinley <cemckinley@gmail.com> * @copyright Copyright (c) 2013 Author, contributors * @license GPL v3 */ var fs = require('fs...
/** PUBLIC API **/ return { init: init }; }()); nodeMud.init();
random_line_split
glicko2.py
class Player: self.rating = 1500 # Actual rating self.rd = 350 # Rating deviation self.sigma = 0.06 # Volatility self.mu = None self.phi = None class Glicko2: self.tau = 1.0 # Should be between 0.3 and 1.2, use higher numbers for more predicatable games def step2(self, player): player.mu = (player....
(phi): return 1/math.sqrt(1 + 3*phi*phi/9.86960440109) # 9.869... is Pi squared def E(mu, mu_j, phi_j): return 1/(1 + math.exp(-1 * g(phi_j) * (mu - mu_j))) def step3(self, player, opponents): v = 0 for opponent in opponents: e_j = E(player.mu, opponent.mu, opponent.phi) v += g(opponent.phi)**2 * e_j ...
g
identifier_name
glicko2.py
class Player: self.rating = 1500 # Actual rating self.rd = 350 # Rating deviation self.sigma = 0.06 # Volatility self.mu = None self.phi = None class Glicko2: self.tau = 1.0 # Should be between 0.3 and 1.2, use higher numbers for more predicatable games def step2(self, player): player.mu = (player....
return v # Outcomes is an associative array from opponent id to outcome def step4(self, player, opponents, outcomes): d = 0 for (opponent in opponents): e_j = E(player.mu, opponent.mu, opponent.phi) d += g(opponent.phi)*(outcomes[opponent.id] - e_j) d = v*d
e_j = E(player.mu, opponent.mu, opponent.phi) v += g(opponent.phi)**2 * e_j * (1 - e_j)
conditional_block
glicko2.py
class Player: self.rating = 1500 # Actual rating self.rd = 350 # Rating deviation self.sigma = 0.06 # Volatility self.mu = None self.phi = None class Glicko2: self.tau = 1.0 # Should be between 0.3 and 1.2, use higher numbers for more predicatable games def step2(self, player): player.mu = (player....
e_j = E(player.mu, opponent.mu, opponent.phi) d += g(opponent.phi)*(outcomes[opponent.id] - e_j) d = v*d
def step4(self, player, opponents, outcomes): d = 0 for (opponent in opponents):
random_line_split
glicko2.py
class Player: self.rating = 1500 # Actual rating self.rd = 350 # Rating deviation self.sigma = 0.06 # Volatility self.mu = None self.phi = None class Glicko2: self.tau = 1.0 # Should be between 0.3 and 1.2, use higher numbers for more predicatable games def step2(self, player): player.mu = (player....
# Outcomes is an associative array from opponent id to outcome def step4(self, player, opponents, outcomes): d = 0 for (opponent in opponents): e_j = E(player.mu, opponent.mu, opponent.phi) d += g(opponent.phi)*(outcomes[opponent.id] - e_j) d = v*d
v = 0 for opponent in opponents: e_j = E(player.mu, opponent.mu, opponent.phi) v += g(opponent.phi)**2 * e_j * (1 - e_j) return v
identifier_body
connection_core.js
onStart:['startEvent', 'start'], onComplete:['completeEvent', 'complete'], onSuccess:['successEvent', 'success'], onFailure:['failureEvent', 'failure'], onUpload:['uploadEvent', 'upload'], onAbort:['abortEvent', 'abort'] }, /** * @description Member to add an ActiveX id to the existing xml_progid arr...
// Fire global custom event -- startEvent this.startEvent.fire(o, args); if(o.startEvent){ // Fire transaction custom event -- startEvent o.startEvent.fire(o, args); } return o; } }, /** * @description This method creates and subscribes custom events, * specific to each transactio...
{ this.resetFormState(); }
conditional_block
connection_core.js
onStart:['startEvent', 'start'], onComplete:['completeEvent', 'complete'], onSuccess:['successEvent', 'success'], onFailure:['failureEvent', 'failure'], onUpload:['uploadEvent', 'upload'], onAbort:['abortEvent', 'abort'] }, /** * @description Member to add an ActiveX id to the existing xml_progid arr...
/**
o[this._customEvents[prop][0]].subscribe(callback.customevents[prop]); } } },
random_line_split
ReportConfigController.js
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by...
var allIsDeletable = true; for (var i = 0; i < arrSelections.length; i++) { var selectedRecord = arrSelections[i]; var deletable = selectedRecord.data.deletable; if (!deletable) { allIsDeletable = false; } } this.getView().actionDeleteGridRow.setDisabled(!all...
{ // more than one selection this.getView().actionEditGridRow.setDisabled(true); this.getView().actionExecuteGridRow.setDisabled(true); this.getView().actionDownloadGridRow.setDisabled(true); }
conditional_block
ReportConfigController.js
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by...
var recordData = this.getView().getSingleSelectedRecordData(fromTree); if (recordData ) { var leaf = this.getView().selectedIsLeaf(fromTree); if (leaf) { var node = this.getRecordID(recordData, { fromTree : fromTree }); attachmentURI = "reportConfig!download.action?nod...
/** * Downloads a report zip */ downloadReport : function(fromTree) {
random_line_split
dohtml.py
#!/usr/bin/python # Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # # Typical usage: # dohtml -r docs/* # - put all files and directories in docs into /usr/share/doc/${PF}/html # dohtml foo.html # - put foo.html into /usr/share/doc/${PF}/html # # # Detailed ...
(lines): cmd = "source '%s/isolated-functions.sh' ; " % \ os.environ["PORTAGE_BIN_PATH"] for line in lines: cmd += "eqawarn \"%s\" ; " % line os.spawnlp(os.P_WAIT, "bash", "bash", "-c", cmd) skipped_directories = [] skipped_files = [] warn_on_skipped_files = os.environ.get("PORTAGE_DOHTML_WARN_ON_SKIPPED_FILES"...
eqawarn
identifier_name
dohtml.py
#!/usr/bin/python # Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # # Typical usage: # dohtml -r docs/* # - put all files and directories in docs into /usr/share/doc/${PF}/html # dohtml foo.html # - put foo.html into /usr/share/doc/${PF}/html # # # Detailed ...
if "_E_DOCDESTTREE_" in os.environ: self.DOCDESTTREE = os.environ["_E_DOCDESTTREE_"] if self.DOCDESTTREE: self.DOCDESTTREE = normalize_path(self.DOCDESTTREE) self.allowed_exts = ['css', 'gif', 'htm', 'html', 'jpeg', 'jpg', 'js', 'png'] if os.environ.get("EAPI", "0") in ("4-python", "5-progress"): s...
self.ED = normalize_path(self.ED)
conditional_block
dohtml.py
#!/usr/bin/python # Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # # Typical usage: # dohtml -r docs/* # - put all files and directories in docs into /usr/share/doc/${PF}/html # dohtml foo.html # - put foo.html into /usr/share/doc/${PF}/html # # # Detailed ...
def eqawarn(lines): cmd = "source '%s/isolated-functions.sh' ; " % \ os.environ["PORTAGE_BIN_PATH"] for line in lines: cmd += "eqawarn \"%s\" ; " % line os.spawnlp(os.P_WAIT, "bash", "bash", "-c", cmd) skipped_directories = [] skipped_files = [] warn_on_skipped_files = os.environ.get("PORTAGE_DOHTML_WARN_ON_S...
shutil.copy(src, dst) os.chmod(dst, 0o644)
identifier_body
dohtml.py
#!/usr/bin/python # Copyright 1999-2013 Gentoo Foundation # Distributed under the terms of the GNU General Public License v2 # # Typical usage: # dohtml -r docs/* # - put all files and directories in docs into /usr/share/doc/${PF}/html # dohtml foo.html # - put foo.html into /usr/share/doc/${PF}/html # # # Detailed ...
self.doc_prefix = "" def print_help(): opts = OptionsClass() print("dohtml [-a .foo,.bar] [-A .foo,.bar] [-f foo,bar] [-x foo,bar]") print(" [-r] [-V] <file> [file ...]") print() print(" -a Set the list of allowed to those that are specified.") print(" Default:", ",".join(opts.allowed_exts)) pri...
self.allowed_files = [] self.disallowed_dirs = ['CVS'] self.recurse = False self.verbose = False
random_line_split
test.py
from planarprocess import * from gds_helpers import * from itertools import cycle xmin, xmax = -5, 5 layers = gds_cross_section('mypmos.gds', [(0,xmin), (0, xmax)], 'gdsmap.map') ['P-Active-Well', 'Active-Cut', 'N-Well', 'Metal-2', 'Metal-1', 'P-Select', 'N-Select', 'Transistor-Poly', 'Via1'] wafer = Wafer(1., 5., 0...
base_hatches = r'\/' # r'/\|-+xoO.*' hatches = cycle(list(base_hatches) + [h1+h2 for h1 in base_hatches for h2 in base_hatches]) colors = cycle('krgbcmy') plot_geometryref(wafer.air, hatch='.', fill=False, linewidth=0, color=(.9,.9,.9), zorder=-100) zorder = -99 for solid in wafer.solids: ...
custom_style[solid].update(dict(hatch=None, fill=True))
conditional_block
test.py
from planarprocess import * from gds_helpers import * from itertools import cycle xmin, xmax = -5, 5 layers = gds_cross_section('mypmos.gds', [(0,xmin), (0, xmax)], 'gdsmap.map') ['P-Active-Well', 'Active-Cut', 'N-Well', 'Metal-2', 'Metal-1', 'P-Select', 'N-Select', 'Transistor-Poly', 'Via1']
wafer.implant(.7, nw, outdiffusion=5., label='N-Well') # Field and gate oxides de = layers['P-Active-Well'] # TODO: channel stop under field oxide fox = wafer.grow(.5, wafer.blank_mask().difference(de), y_offset=-.2, outdiffusion=.1) gox = wafer.grow(.05, de, outdiffusion=.05, base=wafer.wells, label=...
wafer = Wafer(1., 5., 0, xmax - xmin) # N-Well nw = layers['N-Well']
random_line_split
models.py
import urllib, urllib2 import json from django.contrib.gis.db import models from django.contrib.gis import geos class Country(models.Model): name = models.CharField(max_length=30, unique=True) short_name = models.CharField(max_length=10, unique=True) objects = models.GeoManager() def __unicode____(...
return geos.Point([latlong[key] for key in ['lat', 'lng']]) def parse_address_type(addr_component): addr_types = addr_comp['types'] if 'locality' in addr_types: return 'city' if 'administrative_area_level_1' in addr_types: return 'state' if 'country' i...
if d['status'] == 'ZERO_RESULTS': return False def latlong_to_point(latlong):
random_line_split
models.py
import urllib, urllib2 import json from django.contrib.gis.db import models from django.contrib.gis import geos class Country(models.Model): name = models.CharField(max_length=30, unique=True) short_name = models.CharField(max_length=10, unique=True) objects = models.GeoManager() def __unicode____(...
if addr_type not in return_data: return_data[addr_type] = {} if 'name' not in return_data[addr_type]: return_data[addr_type]['name'] = addr_comp['long_name'] if addr_type != 'city' and 'short_name' not in return_data[addr_type]: return...
continue
conditional_block
models.py
import urllib, urllib2 import json from django.contrib.gis.db import models from django.contrib.gis import geos class Country(models.Model): name = models.CharField(max_length=30, unique=True) short_name = models.CharField(max_length=10, unique=True) objects = models.GeoManager() def __unicode____(...
def __unicode__(self): return self.name def get_geocode(address, **kwargs): address = urllib.quote_plus(address) show_debug = kwargs.get('show_debug', False) LOG = kwargs.get('log_fn') if LOG is None: def LOG(*args): if not show_debug: return ...
if self.value is None: default_value = GEOCODING_CONF_DEFAULTS.get(self.name) if default_value is not None: self.value = default_value super(GeoCodingConf, self).save(*args, **kwargs)
identifier_body
models.py
import urllib, urllib2 import json from django.contrib.gis.db import models from django.contrib.gis import geos class Country(models.Model): name = models.CharField(max_length=30, unique=True) short_name = models.CharField(max_length=10, unique=True) objects = models.GeoManager() def
(self): return self.short_name class State(models.Model): name = models.CharField(max_length=30) short_name = models.CharField(max_length=2) country = models.ForeignKey(Country, related_name='states') objects = models.GeoManager() def __unicode__(self): return self.short_nam...
__unicode____
identifier_name
noticeSound.ts
import window from 'global/window'; import memory from '@/browser/utilities/memory'; const getContext: () => AudioContext | null = memory(() => { const AudioContext = window.AudioContext || window.webkitAudioContext; if (!AudioContext) return null; return new AudioContext(); }); const getGainNode: () => GainNod...
oscillator.stop(); }, 100); }
random_line_split
noticeSound.ts
import window from 'global/window'; import memory from '@/browser/utilities/memory'; const getContext: () => AudioContext | null = memory(() => { const AudioContext = window.AudioContext || window.webkitAudioContext; if (!AudioContext) return null; return new AudioContext(); }); const getGainNode: () => GainNod...
(gain: number = 0.25): void { const gainNode = getGainNode(); if (!gainNode) return; gainNode.gain.value = gain; const context = getContext(); if (!context) return; const oscillator = context.createOscillator(); oscillator.type = 'sine'; oscillator.frequency.value = 523.251; oscillator.connect(gain...
playNoticeSound
identifier_name
noticeSound.ts
import window from 'global/window'; import memory from '@/browser/utilities/memory'; const getContext: () => AudioContext | null = memory(() => { const AudioContext = window.AudioContext || window.webkitAudioContext; if (!AudioContext) return null; return new AudioContext(); }); const getGainNode: () => GainNod...
{ const gainNode = getGainNode(); if (!gainNode) return; gainNode.gain.value = gain; const context = getContext(); if (!context) return; const oscillator = context.createOscillator(); oscillator.type = 'sine'; oscillator.frequency.value = 523.251; oscillator.connect(gainNode); oscillator.start();...
identifier_body
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate futures; extern crate hyper; extern crate tokio_core; extern crate tokio_process; extern crate tokio_io; mod manage; mod subprocesses; mod util; use std::net::SocketAddr; use std::thread; use manage::Admin; use subprocesses::Subprocesses; use util...
() { let subprocesses = Subprocesses::new(); let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap(); let admin = Admin::new(addr); let admin_thread = thread::Builder::new() .name("admin".into()) .spawn(move || admin.run().expect("could not run admin")) .expect("could not spawn a...
main
identifier_name
main.rs
#[macro_use] extern crate log; extern crate env_logger; extern crate futures; extern crate hyper; extern crate tokio_core; extern crate tokio_process; extern crate tokio_io; mod manage; mod subprocesses; mod util; use std::net::SocketAddr; use std::thread; use manage::Admin; use subprocesses::Subprocesses; use util...
{ let subprocesses = Subprocesses::new(); let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap(); let admin = Admin::new(addr); let admin_thread = thread::Builder::new() .name("admin".into()) .spawn(move || admin.run().expect("could not run admin")) .expect("could not spawn admi...
identifier_body
main.rs
#[macro_use] extern crate log; extern crate env_logger;
extern crate tokio_io; mod manage; mod subprocesses; mod util; use std::net::SocketAddr; use std::thread; use manage::Admin; use subprocesses::Subprocesses; use util::Runner; fn main() { let subprocesses = Subprocesses::new(); let addr: SocketAddr = "0.0.0.0:9989".parse().unwrap(); let admin = Admin::n...
extern crate futures; extern crate hyper; extern crate tokio_core; extern crate tokio_process;
random_line_split
async-fn-size.rs
// run-pass // aux-build:arc_wake.rs // edition:2018 extern crate arc_wake; use std::pin::Pin; use std::future::Future; use std::sync::{ Arc, atomic::{self, AtomicUsize}, }; use std::task::{Context, Poll}; use arc_wake::ArcWake; struct Counter { wakes: AtomicUsize, } impl ArcWake for Counter { fn wa...
async fn await3_level1() -> u8 { base().await + base().await + base().await } async fn await3_level2() -> u8 { await3_level1().await + await3_level1().await + await3_level1().await } async fn await3_level3() -> u8 { await3_level2().await + await3_level2().await + await3_level2().await } async fn await3...
{ base().await + base().await }
identifier_body
async-fn-size.rs
// run-pass // aux-build:arc_wake.rs // edition:2018 extern crate arc_wake; use std::pin::Pin; use std::future::Future; use std::sync::{ Arc, atomic::{self, AtomicUsize}, }; use std::task::{Context, Poll}; use arc_wake::ArcWake; struct Counter { wakes: AtomicUsize, } impl ArcWake for Counter { fn wa...
() -> u8 { await3_level4().await + await3_level4().await + await3_level4().await } fn main() { assert_eq!(2, std::mem::size_of_val(&base())); assert_eq!(3, std::mem::size_of_val(&await1_level1())); assert_eq!(4, std::mem::size_of_val(&await2_level1())); assert_eq!(5, std::mem::size_of_val(&await3_l...
await3_level5
identifier_name
async-fn-size.rs
// run-pass // aux-build:arc_wake.rs // edition:2018 extern crate arc_wake; use std::pin::Pin; use std::future::Future; use std::sync::{ Arc, atomic::{self, AtomicUsize}, }; use std::task::{Context, Poll}; use arc_wake::ArcWake; struct Counter { wakes: AtomicUsize, } impl ArcWake for Counter { fn wa...
async fn await3_level2() -> u8 { await3_level1().await + await3_level1().await + await3_level1().await } async fn await3_level3() -> u8 { await3_level2().await + await3_level2().await + await3_level2().await } async fn await3_level4() -> u8 { await3_level3().await + await3_level3().await + await3_level3(...
random_line_split
0020_auto_20190512_1744.py
# Generated by Django 2.0.10 on 2019-05-12 17:44 from django.db import migrations, models import django.db.models.deletion class
(migrations.Migration): dependencies = [ ('userprofile', '0020_auto_20190507_0150'), ('news', '0019_auto_20190512_1608'), ] operations = [ migrations.AddField( model_name='article', name='author', field=models.ForeignKey(blank=True, null=True, on...
Migration
identifier_name
0020_auto_20190512_1744.py
# Generated by Django 2.0.10 on 2019-05-12 17:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('userprofile', '0020_auto_20190507_0150'), ('news', '0019_auto_20190512_1608'), ] operations = [ migrations.AddField( model_name='article', name='author', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.dele...
identifier_body
0020_auto_20190512_1744.py
# Generated by Django 2.0.10 on 2019-05-12 17:44 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('userprofile', '0020_auto_20190507_0150'),
operations = [ migrations.AddField( model_name='article', name='author', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='userprofile.Profile'), ), migrations.AddField( model_name='event', ...
('news', '0019_auto_20190512_1608'), ]
random_line_split
editor.py
import wx import os.path class
( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents() sizer = wx.BoxSizer() ...
MainWindow
identifier_name
editor.py
import wx import os.path class MainWindow( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents...
menuBar.Append( editMenu, '&Edit' ) menuBar.Append( aboutMenu, '&About' ) self.SetMenuBar( menuBar ) # Add the menuBar to the Frame def SetTitle( self ): super( MainWindow, self ).SetTitle( 'ATE %s'%self.filename ) # helper methods def defaultFileDialogOptions( self ): ...
menuBar.Append( fileMenu, '&File' ) # Add the fileMenu to the MenuBar
random_line_split
editor.py
import wx import os.path class MainWindow( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents...
def OnExit( self, event ): self.Close() def OnSave( self, event ): if os.path.exists( self.filename ): self.OnSaveFile( event ) else: self.OnSaveAs( event ) def OnOpen( self, event ): if self.askUserForFilename( style = wx.OPEN, **self.defaultFileD...
dialog = wx.MessageDialog( self, 'A sample editor\n' 'in wxPython', 'About Sample Editor', wx.OK ) dialog.ShowModal() dialog.Destroy()
identifier_body
editor.py
import wx import os.path class MainWindow( wx.Frame ): def __init__( self, filename = '*.txt' ): super( MainWindow, self ).__init__( None, size = ( 800,640 ) ) self.filename = filename self.dirname = '.' self.panel = wx.Panel( self, -1 ) self.CreateInteriorWindowComponents...
app = wx.App() frame = MainWindow() frame.Show() app.MainLoop()
dataObj = wx.TextDataObject() success = wx.TheClipboard.GetData( dataObj ) wx.TheClipboard.Flush() wx.TheClipboard.Close() if not success: return text = dataObj.GetText() if text: self.multiText.WriteText( text )
conditional_block
remove_button.js
/** * Tom Select v2.0.0-rc.5 * Licensed under the Apache License, Version 2.0 (the "License"); */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== '...
return document.querySelector(query); }; /** * Converts a scalar to its best string representation * for hash keys and HTML attribute values. * * Transformations: * 'str' -> 'str' * null -> '' * undefined -> '' * true -> '1' * false -> '0' * 0 -> '0' * 1...
let div = document.createElement('div'); div.innerHTML = query.trim(); // Never return a text node of whitespace as the result return div.firstChild; }
conditional_block
remove_button.js
/** * Tom Select v2.0.0-rc.5 * Licensed under the Apache License, Version 2.0 (the "License"); */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== '...
erOptions) { const options = Object.assign({ label: '&times;', title: 'Remove', className: 'remove', append: true }, userOptions); //options.className = 'remove-single'; var self = this; // override the render method to add remove button to each item if (!options.append) { return;...
in (us
identifier_name
remove_button.js
/** * Tom Select v2.0.0-rc.5 * Licensed under the Apache License, Version 2.0 (the "License"); */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== '...
rendered.appendChild(close_button); addEvent(close_button, 'mousedown', evt => { preventDefault(evt, true); }); addEvent(close_button, 'click', evt => { // propagating will trigger the dropdown to show for single mode preventDefault(evt, true); if (self.is...
const options = Object.assign({ label: '&times;', title: 'Remove', className: 'remove', append: true }, userOptions); //options.className = 'remove-single'; var self = this; // override the render method to add remove button to each item if (!options.append) { return; } var h...
identifier_body
remove_button.js
/** * Tom Select v2.0.0-rc.5 * Licensed under the Apache License, Version 2.0 (the "License"); */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== '...
* https://stackoverflow.com/questions/494143/creating-a-new-dom-element-from-an-html-string-using-built-in-dom-methods-or-pro/35385518#35385518 * * param query should be {} */ const getDom = query => { if (query.jquery) { return query[0]; } if (query instanceof HTMLElement) { return query;...
}; new RegExp(Object.keys(latin_convert).join('|'), 'g'); /** * Return a dom element from either a dom query string, jQuery object, a dom element or html string
random_line_split
filters.py
import django_filters from dal import autocomplete from .models import SkosConcept, SkosConceptScheme django_filters.filters.LOOKUP_TYPES = [ ('', '---------'), ('exact', 'Is equal to'), ('iexact', 'Is equal to (case insensitive)'), ('not_exact', 'Is not equal to'), ('lt', 'Lesser than/before'), ...
(django_filters.FilterSet): pref_label = django_filters.ModelMultipleChoiceFilter( widget=autocomplete.Select2Multiple(url='vocabs-ac:skosconcept-autocomplete'), queryset=SkosConcept.objects.all(), lookup_expr='icontains', label='PrefLabel', help_text=False, ) schem...
SkosConceptFilter
identifier_name
filters.py
import django_filters from dal import autocomplete from .models import SkosConcept, SkosConceptScheme django_filters.filters.LOOKUP_TYPES = [ ('', '---------'), ('exact', 'Is equal to'), ('iexact', 'Is equal to (case insensitive)'), ('not_exact', 'Is not equal to'), ('lt', 'Lesser than/before'), ...
pref_label = django_filters.ModelMultipleChoiceFilter( widget=autocomplete.Select2Multiple(url='vocabs-ac:skosconcept-autocomplete'), queryset=SkosConcept.objects.all(), lookup_expr='icontains', label='PrefLabel', help_text=False, ) scheme = django_filters.ModelMultipleC...
identifier_body
filters.py
import django_filters from dal import autocomplete from .models import SkosConcept, SkosConceptScheme django_filters.filters.LOOKUP_TYPES = [ ('', '---------'), ('exact', 'Is equal to'), ('iexact', 'Is equal to (case insensitive)'), ('not_exact', 'Is not equal to'), ('lt', 'Lesser than/before'), ...
label='in SkosConceptScheme', help_text=False, ) class Meta: model = SkosConcept fields = '__all__'
queryset=SkosConceptScheme.objects.all(), lookup_expr='icontains',
random_line_split
shapeCircle.py
''' Created on 13.06.2016 @author: mkennert ''' from kivy.properties import NumericProperty, ObjectProperty from kivy.uix.gridlayout import GridLayout from crossSectionView.circleView import CSCircleView from shapes.ashape import AShape import numpy as np class ShapeCircle(GridLayout, AShape): ...
# diameter of the circle d = NumericProperty(0.25) ''' constructor ''' def __init__(self, **kwargs): super(ShapeCircle, self).__init__(**kwargs) self.view = CSCircleView() self.view.csShape, self.view.d = self, self.d self.view.create_graph() ...
# information-view of the cross-section information = ObjectProperty()
random_line_split
shapeCircle.py
''' Created on 13.06.2016 @author: mkennert ''' from kivy.properties import NumericProperty, ObjectProperty from kivy.uix.gridlayout import GridLayout from crossSectionView.circleView import CSCircleView from shapes.ashape import AShape import numpy as np class ShapeCircle(GridLayout, AShape): ...
x1 = -np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2. x2 = np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2. return x2 - x1
identifier_body
shapeCircle.py
''' Created on 13.06.2016 @author: mkennert ''' from kivy.properties import NumericProperty, ObjectProperty from kivy.uix.gridlayout import GridLayout from crossSectionView.circleView import CSCircleView from shapes.ashape import AShape import numpy as np class ShapeCircle(GridLayout, AShape): ...
(self, y): x1 = -np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2. x2 = np.sqrt(np.abs((self.d / 2.)**2 - (y - self.d / 2.)** 2)) + self.d / 2. return x2 - x1
get_width
identifier_name
utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as path from 'path'; import * as webpack from 'webpack'; export interface EmittedFiles { id?: string; ...
files.findIndex(f => f.file === file && (!name || name === f.name)) === index); }
random_line_split
utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as path from 'path'; import * as webpack from 'webpack'; export interface EmittedFiles { id?: string; ...
// dedupe return files.filter(({ file, name }, index) => files.findIndex(f => f.file === file && (!name || name === f.name)) === index); }
{ const files: EmittedFiles[] = []; // adds all chunks to the list of emitted files such as lazy loaded modules for (const chunk of compilation.chunks as webpack.compilation.Chunk[]) { for (const file of chunk.files as string[]) { files.push({ id: chunk.id.toString(), name: chunk.name, ...
identifier_body
utils.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import * as path from 'path'; import * as webpack from 'webpack'; export interface EmittedFiles { id?: string; ...
(compilation: webpack.compilation.Compilation): EmittedFiles[] { const files: EmittedFiles[] = []; // adds all chunks to the list of emitted files such as lazy loaded modules for (const chunk of compilation.chunks as webpack.compilation.Chunk[]) { for (const file of chunk.files as string[]) { files.pus...
getEmittedFiles
identifier_name
matrix_market.rs
use std::fs; use std::path::Path; use crate::sparse::CsMatrix;
struct MatrixMarketParser; // FIXME: return an Error instead of an Option. /// Parses a Matrix Market file at the given path, and returns the corresponding sparse matrix. pub fn cs_matrix_from_matrix_market<N: RealField, P: AsRef<Path>>(path: P) -> Option<CsMatrix<N>> { let file = fs::read_to_string(path).ok()?; ...
use crate::RealField; use pest::Parser; #[derive(Parser)] #[grammar = "io/matrix_market.pest"]
random_line_split
matrix_market.rs
use std::fs; use std::path::Path; use crate::sparse::CsMatrix; use crate::RealField; use pest::Parser; #[derive(Parser)] #[grammar = "io/matrix_market.pest"] struct MatrixMarketParser; // FIXME: return an Error instead of an Option. /// Parses a Matrix Market file at the given path, and returns the corresponding spa...
// FIXME: return an Error instead of an Option. /// Parses a Matrix Market file described by the given string, and returns the corresponding sparse matrix. pub fn cs_matrix_from_matrix_market_str<N: RealField>(data: &str) -> Option<CsMatrix<N>> { let file = MatrixMarketParser::parse(Rule::Document, data) ...
{ let file = fs::read_to_string(path).ok()?; cs_matrix_from_matrix_market_str(&file) }
identifier_body
matrix_market.rs
use std::fs; use std::path::Path; use crate::sparse::CsMatrix; use crate::RealField; use pest::Parser; #[derive(Parser)] #[grammar = "io/matrix_market.pest"] struct MatrixMarketParser; // FIXME: return an Error instead of an Option. /// Parses a Matrix Market file at the given path, and returns the corresponding spa...
<N: RealField, P: AsRef<Path>>(path: P) -> Option<CsMatrix<N>> { let file = fs::read_to_string(path).ok()?; cs_matrix_from_matrix_market_str(&file) } // FIXME: return an Error instead of an Option. /// Parses a Matrix Market file described by the given string, and returns the corresponding sparse matrix. pub f...
cs_matrix_from_matrix_market
identifier_name
matrix_market.rs
use std::fs; use std::path::Path; use crate::sparse::CsMatrix; use crate::RealField; use pest::Parser; #[derive(Parser)] #[grammar = "io/matrix_market.pest"] struct MatrixMarketParser; // FIXME: return an Error instead of an Option. /// Parses a Matrix Market file at the given path, and returns the corresponding spa...
_ => return None, // FIXME: return an Err instead. } } Some(CsMatrix::from_triplet( shape.0, shape.1, &rows, &cols, &data, )) }
{ let mut inner = line.into_inner(); // NOTE: indices are 1-based. rows.push(inner.next()?.as_str().parse::<usize>().ok()? - 1); cols.push(inner.next()?.as_str().parse::<usize>().ok()? - 1); data.push(crate::convert(inner.next()?.as_str().p...
conditional_block
stock.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe, random, erpnext from frappe.desk import query_report from erpnext.stock.stock_ledger import NegativeStockError from erpn...
make_delivery_note() make_stock_reconciliation() submit_draft_stock_entries() make_sales_return_records() make_purchase_return_records() def make_purchase_receipt(): if random.random() < 0.6: from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt report = "Purchase Order Items...
make_purchase_receipt()
random_line_split
stock.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe, random, erpnext from frappe.desk import query_report from erpnext.stock.stock_ledger import NegativeStockError from erpn...
def make_purchase_receipt(): if random.random() < 0.6: from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt report = "Purchase Order Items To Be Received" po_list =list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="'Total'"]))[:random.randint(1, 10)] for po...
frappe.set_user(frappe.db.get_global('demo_manufacturing_user')) make_purchase_receipt() make_delivery_note() make_stock_reconciliation() submit_draft_stock_entries() make_sales_return_records() make_purchase_return_records()
identifier_body
stock.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe, random, erpnext from frappe.desk import query_report from erpnext.stock.stock_ledger import NegativeStockError from erpn...
(): if random.random() < 0.6: from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt report = "Purchase Order Items To Be Received" po_list =list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="'Total'"]))[:random.randint(1, 10)] for po in po_list: pr = frappe...
make_purchase_receipt
identifier_name
stock.py
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors # License: GNU General Public License v3. See license.txt from __future__ import print_function, unicode_literals import frappe, random, erpnext from frappe.desk import query_report from erpnext.stock.stock_ledger import NegativeStockError from erpn...
def make_delivery_note(): # make purchase requests # make delivery notes (if possible) if random.random() < 0.6: from erpnext.selling.doctype.sales_order.sales_order import make_delivery_note report = "Ordered Items To Be Delivered" for so in list(set([r[0] for r in query_report.run(report)["result"] if ...
from erpnext.buying.doctype.purchase_order.purchase_order import make_purchase_receipt report = "Purchase Order Items To Be Received" po_list =list(set([r[0] for r in query_report.run(report)["result"] if r[0]!="'Total'"]))[:random.randint(1, 10)] for po in po_list: pr = frappe.get_doc(make_purchase_receipt(po...
conditional_block
defaults.py
__author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = 'Copyright (c) 2013 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('FIT_METHOD_CROP_SMART', 'FIT_METHOD_CROP_CENTER', 'FIT_METHOD_CROP_SCALE', 'FIT_METHOD_FIT_WIDTH', 'FIT_METHOD_FIT_HEIGHT', 'DEFAULT_FIT_METHOD', 'FI...
FIT_METHODS_CHOICES_WITH_EMPTY_OPTION = [('', '---------')] + list(FIT_METHODS_CHOICES) IMAGES_UPLOAD_DIR = 'dash-image-plugin-images'
(FIT_METHOD_CROP_CENTER, _("Crop center")), (FIT_METHOD_CROP_SCALE, _("Crop scale")), (FIT_METHOD_FIT_WIDTH, _("Fit width")), (FIT_METHOD_FIT_HEIGHT, _("Fit height")), )
random_line_split
config.py
# -*- coding: utf-8 -*- # Config file handling module # Copyright (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru> # This file is part of VKBuddy. # VKBuddy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either...
elif item in self.bare.config: return self.bare.config[item]['default'] else: raise KeyError(item)
if item in self.bare.config: return self.bare.config[item]['type'](self.__config[item]) else: return self.__config[item]
conditional_block
config.py
# -*- coding: utf-8 -*- # Config file handling module # Copyright (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru> # This file is part of VKBuddy. # VKBuddy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either...
def add_parameter(self, name, required=False, description='', default=None, typ=str): if required: self.required_list.append(name) self.config[name] = { 'description': description, 'default': default, 'type': typ } cla...
self.config = {} self.required_list = []
identifier_body
config.py
# -*- coding: utf-8 -*- # Config file handling module # Copyright (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru> # This file is part of VKBuddy. # VKBuddy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either...
(self, filename, bare): cfile = open(filename, 'r') self.__config = yaml.load(cfile) cfile.close() self.bare = bare if not self.__config: self.__config = {} for param in bare.required_list: if not param in self.__config: raise Incor...
__init__
identifier_name
config.py
# -*- coding: utf-8 -*-
# Config file handling module # Copyright (C) 2014 Yury Gavrilov <yuriy@igavrilov.ru> # This file is part of VKBuddy. # VKBuddy is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Licens...
random_line_split
main.py
""" instantly/main.py Defines the basic terminal interface for interacting with Instantly. Copyright (C) 2013 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without rest...
(): instantly = Instantly() if not len(sys.argv) > 1: print("Instantly allows you to expand simple templates, that take in a set number of arguments") print("Usage: instantly [template name] to expand a template") print(" type instantly help for full instructions.") print("...
main
identifier_name
main.py
""" instantly/main.py Defines the basic terminal interface for interacting with Instantly. Copyright (C) 2013 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without rest...
print("instantly find [template name]") print("\t Find pre-made templates to automate a task online") print("instantly download [template name]") print("\t Add a template shared online to your local template repository") print("instantly install [template directory]") pri...
instantly = Instantly() if not len(sys.argv) > 1: print("Instantly allows you to expand simple templates, that take in a set number of arguments") print("Usage: instantly [template name] to expand a template") print(" type instantly help for full instructions.") print("") ...
identifier_body
main.py
""" instantly/main.py Defines the basic terminal interface for interacting with Instantly. Copyright (C) 2013 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without rest...
else: sys.exit(1) elif command == "version": print("instantly v. {0}".format(__version__)) sys.exit(0) elif command == "location": template = instantly.installed_template(template_name) if not template: print("Sorry template does not exist...
print("Successfully removed %s from local templates" % template_name) sys.exit(0)
conditional_block
main.py
""" instantly/main.py Defines the basic terminal interface for interacting with Instantly. Copyright (C) 2013 Timothy Edmund Crosley Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without rest...
main()
random_line_split
qualifier.rs
use regex::Regex; lazy_static! { pub static ref REGEX: Regex = Regex::new("^[a-z0-9]+:([a-z0-9]+):(.*)$").unwrap(); } pub fn qualify(entity: &str, prefix: &str, method: &str) -> String { format!("{}:{}:{}", prefix, method, entity) } pub fn to_unqualified(entity: &str) -> String { match REGEX.captures(ent...
} } pub fn is_fully_qualified(entity: &str) -> bool { REGEX.is_match(&entity) } macro_rules! qualifiable_type (($newtype:ident) => ( #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct $newtype(pub String); impl $newtype { #[allow(dead_code)] pub fn ...
{ caps.get(1).map(|m| m.as_str().to_string()) }
conditional_block
qualifier.rs
use regex::Regex; lazy_static! { pub static ref REGEX: Regex = Regex::new("^[a-z0-9]+:([a-z0-9]+):(.*)$").unwrap(); } pub fn qualify(entity: &str, prefix: &str, method: &str) -> String { format!("{}:{}:{}", prefix, method, entity) } pub fn to_unqualified(entity: &str) -> String { match REGEX.captures(ent...
} pub fn is_fully_qualified(entity: &str) -> bool { REGEX.is_match(&entity) } macro_rules! qualifiable_type (($newtype:ident) => ( #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct $newtype(pub String); impl $newtype { #[allow(dead_code)] pub fn get_met...
}
random_line_split
qualifier.rs
use regex::Regex; lazy_static! { pub static ref REGEX: Regex = Regex::new("^[a-z0-9]+:([a-z0-9]+):(.*)$").unwrap(); } pub fn qualify(entity: &str, prefix: &str, method: &str) -> String { format!("{}:{}:{}", prefix, method, entity) } pub fn to_unqualified(entity: &str) -> String { match REGEX.captures(ent...
macro_rules! qualifiable_type (($newtype:ident) => ( #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct $newtype(pub String); impl $newtype { #[allow(dead_code)] pub fn get_method(&self) -> Option<String> { qualifier::method(&self.0) } ...
{ REGEX.is_match(&entity) }
identifier_body
qualifier.rs
use regex::Regex; lazy_static! { pub static ref REGEX: Regex = Regex::new("^[a-z0-9]+:([a-z0-9]+):(.*)$").unwrap(); } pub fn qualify(entity: &str, prefix: &str, method: &str) -> String { format!("{}:{}:{}", prefix, method, entity) } pub fn to_unqualified(entity: &str) -> String { match REGEX.captures(ent...
(entity: &str) -> bool { REGEX.is_match(&entity) } macro_rules! qualifiable_type (($newtype:ident) => ( #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Hash)] pub struct $newtype(pub String); impl $newtype { #[allow(dead_code)] pub fn get_method(&self) -> Option<String>...
is_fully_qualified
identifier_name
modulebase.py
from syhelpers.log import print_error, print_table_terminal class ModuleBase: """ Base class for all modules (handler, transport, platform, ...) Allows functions for options """ def __init__(self): """ Initialize Module, should be overwritten and options should be added ""...
elif 'Options' in values and values['Options']: # and if so, set the value to upper case value = value.upper() # finally set the value self.options[name.upper()]['Value'] = value return True else: # no option of that n...
print_error(str(name.upper())+" must be one of "+(", ".join(values['Options']))) return True # ok, strange, but True only means we found it, even if setting failed
conditional_block
modulebase.py
from syhelpers.log import print_error, print_table_terminal class ModuleBase: """ Base class for all modules (handler, transport, platform, ...) Allows functions for options """ def __init__(self): """ Initialize Module, should be overwritten and options should be added ""...
""" print information of options for this module :return: None """ headers = ["Name", "Value", "Required", "Description"] data = [] for name in self.options.keys(): value = str(self.options[name]["Value"]) if self.options[name]["Value"] else "" ...
identifier_body
modulebase.py
from syhelpers.log import print_error, print_table_terminal class ModuleBase: """ Base class for all modules (handler, transport, platform, ...) Allows functions for options """ def __init__(self): """ Initialize Module, should be overwritten and options should be added ""...
for option, values in self.options.items(): # make sure all options are set if values['Required'] and not(values['Value']) or (values['Value'] == ''): print_error(str(option)+" must be set") valid = False # make sure all options with listed alt...
# check for each option
random_line_split
modulebase.py
from syhelpers.log import print_error, print_table_terminal class ModuleBase: """ Base class for all modules (handler, transport, platform, ...) Allows functions for options """ def __init__(self): """ Initialize Module, should be overwritten and options should be added ""...
(self, name, value): """ Sets option <name> to value <value> if possible. Can be overwritten and expanded by modules. """ # name and value must be set and must be string if not name or not isinstance(name, str): print_error("Option name not understood...
setoption
identifier_name
ellipsebase.ts
import { GeometryNode } from './geometrynode' import { getAttribute, svgNodeIsVisible } from '../utils/node' import { Context } from '../context/context' import { Path } from '../utils/path' import { SvgNode } from './svgnode' import { Matrix } from 'jspdf' export abstract class EllipseBase extends GeometryNode { ab...
const x = parseFloat(getAttribute(this.element, context.styleSheets, 'cx') || '0'), y = parseFloat(getAttribute(this.element, context.styleSheets, 'cy') || '0') const lx = (4 / 3) * (Math.SQRT2 - 1) * rx, ly = (4 / 3) * (Math.SQRT2 - 1) * ry return new Path() .moveTo(x + rx, y) .c...
{ return null }
conditional_block