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
contact-detail.ts
import {inject} from 'aurelia-framework'; import {EventAggregator} from 'aurelia-event-aggregator'; import {WebAPI} from './web-api'; import {areEqual} from './utility'; import {ContactUpdated,ContactViewed} from './messages'; interface Contact { firstName: string; lastName: string; email: string; } ...
get canSave() { return this.contact.firstName && this.contact.lastName && !this.api.isRequesting; } save() { this.api.saveContact(this.contact).then(contact => { this.contact = <Contact>contact; this.routeConfig.navModel.setTitle(this.contact.firstName); this.originalContact...
{ this.routeConfig = routeConfig; return this.api.getContactDetails(params.id).then(contact => { this.contact = <Contact>contact; this.routeConfig.navModel.setTitle(this.contact.firstName); this.originalContact = JSON.parse(JSON.stringify(this.contact)); this.ea.publish(new Conta...
identifier_body
contact-detail.ts
import {inject} from 'aurelia-framework'; import {EventAggregator} from 'aurelia-event-aggregator'; import {WebAPI} from './web-api'; import {areEqual} from './utility'; import {ContactUpdated,ContactViewed} from './messages'; interface Contact { firstName: string; lastName: string; email: string; } ...
this.ea.publish(new ContactViewed(this.contact)); } return result; } return true; } }
if (!areEqual(this.originalContact, this.contact)) { let result = confirm('You have unsaved changes. Are you sure you wish to leave?'); if (!result) {
random_line_split
contact-detail.ts
import {inject} from 'aurelia-framework'; import {EventAggregator} from 'aurelia-event-aggregator'; import {WebAPI} from './web-api'; import {areEqual} from './utility'; import {ContactUpdated,ContactViewed} from './messages'; interface Contact { firstName: string; lastName: string; email: string; } ...
return result; } return true; } }
{ this.ea.publish(new ContactViewed(this.contact)); }
conditional_block
contact-detail.ts
import {inject} from 'aurelia-framework'; import {EventAggregator} from 'aurelia-event-aggregator'; import {WebAPI} from './web-api'; import {areEqual} from './utility'; import {ContactUpdated,ContactViewed} from './messages'; interface Contact { firstName: string; lastName: string; email: string; } ...
(params, routeConfig) { this.routeConfig = routeConfig; return this.api.getContactDetails(params.id).then(contact => { this.contact = <Contact>contact; this.routeConfig.navModel.setTitle(this.contact.firstName); this.originalContact = JSON.parse(JSON.stringify(this.contact)); thi...
activate
identifier_name
test.py
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """...
"""Asserts text1 and text2 have the same lines, ignoring differences in line endings between platforms """ testcase.assertEqual(text1.splitlines(), text2.splitlines(), msg)
def assert_samelines(testcase, text1, text2, msg=None):
random_line_split
test.py
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """...
else: import boto # assuming boto=2.2.2 bucket = boto.connect_s3().get_bucket(bucket, validate=False) key = bucket.get_key(path) content = key.get_contents_as_string() bucket.delete_key(path) return (content, key) if with_key else content def get_gcs_content_and...
import botocore.session session = botocore.session.get_session() client = session.create_client('s3') key = client.get_object(Bucket=bucket, Key=path) content = key['Body'].read() client.delete_object(Bucket=bucket, Key=path)
conditional_block
test.py
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """...
def get_pythonpath(): """Return a PYTHONPATH suitable to use in processes so that they find this installation of Scrapy""" scrapy_path = import_module('scrapy').__path__[0] return os.path.dirname(scrapy_path) + os.pathsep + os.environ.get('PYTHONPATH', '') def get_testenv(): """Return a OS enviro...
"""Return an unconfigured Crawler object. If settings_dict is given, it will be used to populate the crawler settings with a project level priority. """ from scrapy.crawler import CrawlerRunner from scrapy.spiders import Spider runner = CrawlerRunner(settings_dict) return runner.create_craw...
identifier_body
test.py
""" This module contains some assorted functions used in tests """ from __future__ import absolute_import import os from importlib import import_module from twisted.trial.unittest import SkipTest from scrapy.exceptions import NotConfigured from scrapy.utils.boto import is_botocore def assert_aws_environ(): """...
(): """Return a OS environment dict suitable to fork processes that need to import this installation of Scrapy, instead of a system installed one. """ env = os.environ.copy() env['PYTHONPATH'] = get_pythonpath() return env def assert_samelines(testcase, text1, text2, msg=None): """Asserts t...
get_testenv
identifier_name
styler.service.ts
: 'anonymous', anchor: [0.5, 1], }), }); constructor( public hsQueryVectorService: HsQueryVectorService, public hsUtilsService: HsUtilsService, private hsLayerUtilsService: HsLayerUtilsService, private hsEventBusService: HsEventBusService, private hsLogService: HsLogService, publi...
/** * Style clustered layer features using cluster style or individual feature style. * @param layer - Any vector layer */ async styleClusteredLayer( layer: VectorLayer<VectorSource<Geometry>> ): Promise<void> { await this.fill(layer); //Check if layer already has SLD style for clusters ...
{ if (!layer) { return; } let src: VectorSource<Geometry>; if (isClustered) { src = (layer.getSource() as Cluster).getSource(); } else { src = layer.getSource(); } return src; }
identifier_body
styler.service.ts
: 'anonymous', anchor: [0.5, 1], }), }); constructor( public hsQueryVectorService: HsQueryVectorService, public hsUtilsService: HsUtilsService, private hsLayerUtilsService: HsLayerUtilsService, private hsEventBusService: HsEventBusService, private hsLogService: HsLogService, publi...
} /** * Convert SLD to OL style object */ async sldToOlStyle(sld: string): Promise<StyleLike> { try { const sldObject = await this.sldToJson(sld); return await this.geoStylerStyleToOlStyle(sldObject); } catch (ex) { this.hsLogService.error(ex); } } /** * Convert QML t...
{ for (const rule of this.styleObject.rules) { if (rule.symbolizers) { for (const symbol of rule.symbolizers.filter( (symb) => symb.kind == 'Fill' ) as FillSymbolizer[]) { symbol.opacity = symbol.fillOpacity; } } } }
conditional_block
styler.service.ts
<VectorSource<Geometry>> ): Promise<void> { await this.fill(layer); //Check if layer already has SLD style for clusters if ( !this.styleObject.rules.find((r) => { try { /* For clusters SLD styles created by Hslayers have 'AND' rule where the first condition ch...
decodeToUnicode
identifier_name
styler.service.ts
: 'anonymous', anchor: [0.5, 1], }), }); constructor( public hsQueryVectorService: HsQueryVectorService, public hsUtilsService: HsUtilsService, private hsLayerUtilsService: HsLayerUtilsService, private hsEventBusService: HsEventBusService, private hsLogService: HsLogService, publi...
typeof style == 'object' && !this.hsUtilsService.instOf(style, Style) ) { //Backwards compatibility with style encoded in custom JSON object return parseStyle(style); } else { return {style}; } } /** * Prepare current layers style for editing by converting * SLD attr...
} else if (
random_line_split
configuration.test.ts
import * as assert from 'assert'; import * as srcConfiguration from '../../src/configuration/configuration'; import * as testConfiguration from '../testConfiguration'; import { cleanUpWorkspace, setupWorkspace } from './../testUtils'; import { Mode } from '../../src/mode/mode'; import { newTest } from '../testSimplifie...
endMode: Mode.Visual, }); });
end: ['|'],
random_line_split
math.py
## def
(x): return np.exp(x - np.logaddexp.reduce(x)) def expnormalize(x): b = x.max() y = np.exp(x - b) return y / y.sum() def categorical(params): return np.where(np.random.multinomial(1, params) == 1)[0] def bernoulli(param, size=1): return np.random.binomial(1, param, size=size) ### Power law d...
lognormalize
identifier_name
math.py
## def lognormalize(x): return np.exp(x - np.logaddexp.reduce(x)) def expnormalize(x): b = x.max() y = np.exp(x - b) return y / y.sum() def categorical(params): return np.where(np.random.multinomial(1, params) == 1)[0] def bernoulli(param, size=1): return np.random.binomial(1, param, size=si...
return d, dc def random_degree(Y, params=None): _X = [] _Y = [] N = Y[0].shape[0] nb_uniq_degree = [] dc_list = [] for y in Y: ba_c = adj_to_degree(y) d, dc = degree_hist(ba_c) nb_uniq_degree.append(len(dc)) dc_list.append(dc) dc_mat = ma.array(np.empty(...
random_line_split
math.py
## def lognormalize(x): return np.exp(x - np.logaddexp.reduce(x)) def expnormalize(x): b = x.max() y = np.exp(x - b) return y / y.sum() def categorical(params): return np.where(np.random.multinomial(1, params) == 1)[0] def bernoulli(param, size=1): return np.random.binomial(1, param, size=si...
num = np.sum(np.asarray(w) * kernel(np.asarray(a))) denom = np.sum(np.asarray(w)) return out(num / denom) ########################## ### Matrix/Image Operation ########################## from scipy import ndimage def draw_square(mat, value, topleft, l, L, w=0): tl = topleft # Vertical draw ...
raise NotImplementedError('Mean Unknwow: %s' % mean)
conditional_block
math.py
## def lognormalize(x): return np.exp(x - np.logaddexp.reduce(x)) def expnormalize(x): b = x.max() y = np.exp(x - b) return y / y.sum() def categorical(params):
def bernoulli(param, size=1): return np.random.binomial(1, param, size=size) ### Power law distribution generator def random_powerlaw(alpha, x_min, size=1): ### Discrete alpha = float(alpha) u = np.random.random(size) x = (x_min-0.5)*(1-u)**(-1/(alpha-1))+0.5 return np.floor(x) ### A stick b...
return np.where(np.random.multinomial(1, params) == 1)[0]
identifier_body
getJudgeInfo.ts
import { DEFAULT_RENDER_KEY, TreeRootIdArray, ITreeData, ITreeRenderKey, ITreeRootInfoMap, } from './common'; // getJudgeInfo export interface IJudgeInfoParams { expandAll?: boolean; checkable?: boolean; loadMore?: (data: ITreeData) => Promise<any>; tree: ITreeData[]; renderKey?: ITreeRenderKey; } ...
JudgeInfoParams): IJudgeInfoReturn { const expandNode: TreeRootIdArray = []; const rootInfoMap: ITreeRootInfoMap = {}; const { children, id } = renderKey; function collector({ nodeTree, parentId, }: { nodeTree: ITreeData[]; parentId?: string | number; }) { nodeTree.forEach(item => { ...
ER_KEY, }: I
identifier_name
getJudgeInfo.ts
import { DEFAULT_RENDER_KEY, TreeRootIdArray, ITreeData, ITreeRenderKey, ITreeRootInfoMap, } from './common'; // getJudgeInfo export interface IJudgeInfoParams { expandAll?: boolean; checkable?: boolean; loadMore?: (data: ITreeData) => Promise<any>; tree: ITreeData[]; renderKey?: ITreeRenderKey; } ...
ntId: nodeId, }); } // 收集当前节点能够影响的所有节点(self + children) if (parentId !== undefined && rootInfoMap[parentId]) { rootInfoMap[parentId].rootIncludeIds = rootInfoMap[ parentId ].rootIncludeIds.concat(rootInfoMap[nodeId].rootIncludeIds); } }); } collector({...
nodeTree: item[children], pare
conditional_block
getJudgeInfo.ts
import { DEFAULT_RENDER_KEY, TreeRootIdArray, ITreeData, ITreeRenderKey, ITreeRootInfoMap, } from './common'; // getJudgeInfo export interface IJudgeInfoParams { expandAll?: boolean; checkable?: boolean; loadMore?: (data: ITreeData) => Promise<any>; tree: ITreeData[]; renderKey?: ITreeRenderKey; } ...
son: (item[children] || []).map((t: ITreeData) => t[id]), rootIncludeIds: [nodeId], }; // 是否为父节点 const isParentNode = !!( !item.isLeaf && (loadMore || (item[children] && item[children].length > 0)) ); rootInfoMap[nodeId].isParent = isParentNode; // 收...
InfoMap = {}; const { children, id } = renderKey; function collector({ nodeTree, parentId, }: { nodeTree: ITreeData[]; parentId?: string | number; }) { nodeTree.forEach(item => { const nodeId = item[id]; // 初始化 rootInfoMap[nodeId] = { id: nodeId, parentId,...
identifier_body
getJudgeInfo.ts
import { DEFAULT_RENDER_KEY, TreeRootIdArray, ITreeData, ITreeRenderKey, ITreeRootInfoMap, } from './common'; // getJudgeInfo export interface IJudgeInfoParams { expandAll?: boolean; checkable?: boolean; loadMore?: (data: ITreeData) => Promise<any>; tree: ITreeData[]; renderKey?: ITreeRenderKey; } ...
// 收集当前节点能够影响的所有节点(self + children) if (parentId !== undefined && rootInfoMap[parentId]) { rootInfoMap[parentId].rootIncludeIds = rootInfoMap[ parentId ].rootIncludeIds.concat(rootInfoMap[nodeId].rootIncludeIds); } }); } collector({ nodeTree: tree, parentId:...
}
random_line_split
index.tsx
import React, { memo } from 'react'; import Axios from 'axios'; import { useDispatch, useSelector } from 'react-redux'; import { pdfjs, Document, Page } from 'react-pdf'; import CircularProgress from '@material-ui/core/CircularProgress'; import { Button } from '@pluto_network/pluto-design-elements'; import ActionTicket...
(prev, next) => prev.paper.id === next.paper.id ); export default PDFViewer;
); },
random_line_split
index.tsx
import React, { memo } from 'react'; import Axios from 'axios'; import { useDispatch, useSelector } from 'react-redux'; import { pdfjs, Document, Page } from 'react-pdf'; import CircularProgress from '@material-ui/core/CircularProgress'; import { Button } from '@pluto_network/pluto-design-elements'; import ActionTicket...
const PDFViewer: React.FC<PDFViewerProps> = memo( props => { useStyles(styles); const { paper } = props; const dispatch = useDispatch(); const PDFViewerState = useSelector<AppState, PDFViewerState>(state => state.PDFViewerState); const isLoggedIn = useSelector<AppState, boolean>(state => state....
{ return `${DIRECT_PDF_PATH_PREFIX + path}`; }
identifier_body
index.tsx
import React, { memo } from 'react'; import Axios from 'axios'; import { useDispatch, useSelector } from 'react-redux'; import { pdfjs, Document, Page } from 'react-pdf'; import CircularProgress from '@material-ui/core/CircularProgress'; import { Button } from '@pluto_network/pluto-design-elements'; import ActionTicket...
(path: string) { return `${DIRECT_PDF_PATH_PREFIX + path}`; } const PDFViewer: React.FC<PDFViewerProps> = memo( props => { useStyles(styles); const { paper } = props; const dispatch = useDispatch(); const PDFViewerState = useSelector<AppState, PDFViewerState>(state => state.PDFViewerState); co...
getDirectPDFPath
identifier_name
__init__.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # 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 the Free Software Foundation; either version 2 # of the License...
def init_regex_checker(self, regex_edit, regex_error): """ regex_edit : a widget supporting text() and textChanged() methods, ie QLineEdit regex_error : a widget supporting setStyleSheet() and setText() methods, ie. QLabel """ def check(): try: ...
log = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.info, QtWidgets.QMessageBox.Ok, self) dialog.exec_()
identifier_body
__init__.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # 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 the Free Software Foundation; either version 2 # of the License...
self.load() # Restore the config values incase the user doesn't save after restoring defaults for key in old_options: config.setting[key] = old_options[key] def display_error(self, error): dialog = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Warning, error.title, error.inf...
_options[option.name] = config.setting[option.name] config.setting[option.name] = option.default
conditional_block
__init__.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # 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 the Free Software Foundation; either version 2 # of the License...
try: re.compile(regex_edit.text()) except re.error as e: raise OptionsCheckError(_("Regex Error"), string_(e)) def live_checker(text): regex_error.setStyleSheet("") regex_error.setText("") try: check() ...
ck():
identifier_name
__init__.py
# -*- coding: utf-8 -*- # # Picard, the next-generation MusicBrainz tagger # Copyright (C) 2006 Lukáš Lalinský # # 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 the Free Software Foundation; either version 2 # of the License...
def __init__(self, title, info): self.title = title self.info = info class OptionsPage(QtWidgets.QWidget): PARENT = None SORT_ORDER = 1000 ACTIVE = True STYLESHEET_ERROR = "QWidget { background-color: #f55; color: white; font-weight:bold }" STYLESHEET = "QLabel { qproperty-wo...
class OptionsCheckError(Exception):
random_line_split
importborme.py
from django.core.management.base import BaseCommand from django.utils import timezone import logging import time from borme.models import Config from borme.parser.importer import import_borme_download # from borme.parser.postgres import psql_update_documents import borme.parser.importer from libreborme.utils import ...
'--local-only', action='store_true', default=False, help='Do not download any file') parser.add_argument( '--no-missing', action='store_true', default=False, help='Abort if local file ...
parser.add_argument(
random_line_split
importborme.py
from django.core.management.base import BaseCommand from django.utils import timezone import logging import time from borme.models import Config from borme.parser.importer import import_borme_download # from borme.parser.postgres import psql_update_documents import borme.parser.importer from libreborme.utils import ...
if verbosity == 0: borme.parser.importer.logger.setLevel(logging.ERROR) elif verbosity == 1: # default borme.parser.importer.logger.setLevel(logging.INFO) elif verbosity == 2: borme.parser.importer.logger.setLevel(logging.INFO) elif verbosity > 2: ...
identifier_body
importborme.py
from django.core.management.base import BaseCommand from django.utils import timezone import logging import time from borme.models import Config from borme.parser.importer import import_borme_download # from borme.parser.postgres import psql_update_documents import borme.parser.importer from libreborme.utils import ...
elif verbosity == 1: # default borme.parser.importer.logger.setLevel(logging.INFO) elif verbosity == 2: borme.parser.importer.logger.setLevel(logging.INFO) elif verbosity > 2: borme.parser.importer.logger.setLevel(logging.DEBUG) logging.getLogger...
borme.parser.importer.logger.setLevel(logging.ERROR)
conditional_block
importborme.py
from django.core.management.base import BaseCommand from django.utils import timezone import logging import time from borme.models import Config from borme.parser.importer import import_borme_download # from borme.parser.postgres import psql_update_documents import borme.parser.importer from libreborme.utils import ...
(BaseCommand): # args = '<ISO formatted date (ex. 2015-01-01 or --init)> [--local]' help = 'Import BORMEs from date' def add_arguments(self, parser): parser.add_argument( '-f', '--from', nargs=1, required=True, help='ISO formatted date (ex. 2015-01-01...
Command
identifier_name
viewport-ruler.d.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 { Optional } from '@angular/core'; import { ScrollDispatcher } from './scroll-dispatcher'; /** * Simple utili...
top: number; left: number; }; /** Caches the latest client rectangle of the document element. */ _cacheViewportGeometry(): void; } /** @docs-private */ export declare function VIEWPORT_RULER_PROVIDER_FACTORY(parentRuler: ViewportRuler, scrollDispatcher: ScrollDispatcher): ViewportRuler; /** ...
* @param documentRect */ getViewportScrollPosition(documentRect?: ClientRect | undefined): {
random_line_split
viewport-ruler.d.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 { Optional } from '@angular/core'; import { ScrollDispatcher } from './scroll-dispatcher'; /** * Simple utili...
{ /** Cached document client rectangle. */ private _documentRect?; constructor(scrollDispatcher: ScrollDispatcher); /** Gets a ClientRect for the viewport's bounds. */ getViewportRect(documentRect?: ClientRect | undefined): ClientRect; /** * Gets the (top, left) scroll position of the view...
ViewportRuler
identifier_name
index.js
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(co...
console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.action === 'deletePad'){ var pad = new Pad(packet.padId) pad.remove(functio...
callback(false); return false; }
random_line_split
index.js
var eejs = require('ep_etherpad-lite/node/eejs') /* * Handle incoming delete requests from clients */ exports.handleMessage = function(hook_name, context, callback){ var Pad = require('ep_etherpad-lite/node/db/Pad.js').Pad // Firstly ignore any request that aren't about chat var isDeleteRequest = false; if(co...
} } if(!isDeleteRequest){ callback(false); return false; } console.log('DELETION REQUEST!') var packet = context.message.data; /*** What's available in a packet? * action -- The action IE chatPosition * padId -- The padId of the pad both authors are on ***/ if(packet.actio...
{ if(context.message.data){ if(context.message.data.type){ if(context.message.data.type === 'ep_push2delete'){ isDeleteRequest = true; } } } }
conditional_block
version_sync_test.js
'use strict';
/* ======== A Handy Little Nodeunit Reference ======== https://github.com/caolan/nodeunit Test methods: test.expect(numAssertions) test.done() Test assertions: test.ok(value, [message]) test.equal(actual, expected, [message]) test.notEqual(actual, expected, [message]) test.deepEqual(act...
var grunt = require('grunt');
random_line_split
pythontex.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Run PythonTeX */ import { exec, ExecOutput } from "../generic/client"; import { parse_path } from "../frame-tree/util"; import { ProcessedLatexLog, Error } from "./latex-lo...
/ * example of what we're after: the line number on the first line is correct (in the tex file) This is PythonTeX 0.16 ---- Messages for py:default:default ---- * PythonTeX stderr - error on line 19: File "<outputdir>/py_default_default.py", line 65 print(pytex.formatter(34*131*)) ...
const { base, directory } = parse_path(path); const args = ["--jobs", "2"]; if (force) { // forced build implies to run all snippets args.push("--rerun=always"); } status(`pythontex ${args.join(" ")}`); const aggregate = time && !force ? { value: time } : undefined; return exec({ timeout: 360, ...
identifier_body
pythontex.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Run PythonTeX */ import { exec, ExecOutput } from "../generic/client"; import { parse_path } from "../frame-tree/util"; import { ProcessedLatexLog, Error } from "./latex-lo...
project_id: string, path: string, time: number, force: boolean, status: Function, output_directory: string | undefined ): Promise<ExecOutput> { const { base, directory } = parse_path(path); const args = ["--jobs", "2"]; if (force) { // forced build implies to run all snippets args.push("--rerun...
hontex(
identifier_name
pythontex.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Run PythonTeX */ import { exec, ExecOutput } from "../generic/client"; import { parse_path } from "../frame-tree/util"; import { ProcessedLatexLog, Error } from "./latex-lo...
// collecting message until the end if (err != undefined) { if (line.startsWith("-----")) { break; } err.content += `${line}\n`; } } return pll; }
const hit = line.match(/line (\d+):/); let line_no: number | null = null; if (hit !== null && hit.length >= 2) { line_no = parseInt(hit[1]); } err = { line: line_no, file, level: "error", message: line, content: "", raw: "", }; ...
conditional_block
pythontex.ts
/* * This file is part of CoCalc: Copyright © 2020 Sagemath, Inc. * License: AGPLv3 s.t. "Commons Clause" – see LICENSE.md for details */ /* Run PythonTeX */ import { exec, ExecOutput } from "../generic/client"; import { parse_path } from "../frame-tree/util"; import { ProcessedLatexLog, Error } from "./latex-lo...
} status(`pythontex ${args.join(" ")}`); const aggregate = time && !force ? { value: time } : undefined; return exec({ timeout: 360, bash: true, // timeout is enforced by ulimit command: "pythontex3", args: args.concat(base), env: { MPLBACKEND: "Agg" }, // for python plots -- https://github....
// forced build implies to run all snippets args.push("--rerun=always");
random_line_split
config.rs
#![allow(dead_code)] extern crate clap; use helper::Log; use self::clap::{Arg, App};
pub const APP_VERSION: &'static str = "1.0.34"; pub const MAX_API_VERSION: u32 = 1000; pub struct NodeConfig { pub value: u64, pub token: String, pub api_version: u32, pub network: NetworkingConfig, pub parent_address: String } pub struct NetworkingConfig { pub tcp_server_host: String, pu...
use std::process; use std::error::Error;
random_line_split
config.rs
#![allow(dead_code)] extern crate clap; use helper::Log; use self::clap::{Arg, App}; use std::process; use std::error::Error; pub const APP_VERSION: &'static str = "1.0.34"; pub const MAX_API_VERSION: u32 = 1000; pub struct NodeConfig { pub value: u64, pub token: String, pub api_version: u32, pub n...
{ pub tcp_server_host: String, pub concurrency: usize } pub fn parse_args() -> NodeConfig { let matches = App::new("TreeScale Node Service") .version(APP_VERSION) .author("TreeScale Inc. <hello@treescale.com>") .about("TreeScale technology endpoi...
NetworkingConfig
identifier_name
coherence.rs
_def_id={})", impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx.tcx)); let param_env = &ty::empty_parameter_environment(infcx.tcx); let selcx = &mut SelectionContext::intercrate(infcx, param_env); infcx.probe(|_| { overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selc...
/// 1. All type parameters in `Self` must be "covered" by some local type constructor. /// 2. Some local type must appear in `Self`. pub fn orphan_check<'tcx>(tcx: &ty::ctxt<'tcx>, impl_def_id: ast::DefId) -> Result<(), OrphanCheckErr<'tcx>> { debug!("orphan_check...
/// Checks the coherence orphan rules. `impl_def_id` should be the /// def-id of a trait impl. To pass, either the trait must be local, or else /// two conditions must be satisfied: ///
random_line_split
coherence.rs
_def_id={})", impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx.tcx)); let param_env = &ty::empty_parameter_environment(infcx.tcx); let selcx = &mut SelectionContext::intercrate(infcx, param_env); infcx.probe(|_| { overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selc...
<'tcx> { NoLocalInputType, UncoveredTy(Ty<'tcx>), } /// Checks the coherence orphan rules. `impl_def_id` should be the /// def-id of a trait impl. To pass, either the trait must be local, or else /// two conditions must be satisfied: /// /// 1. All type parameters in `Self` must be "covered" by some local type...
OrphanCheckErr
identifier_name
coherence.rs
_def_id={})", impl1_def_id.repr(infcx.tcx), impl2_def_id.repr(infcx.tcx)); let param_env = &ty::empty_parameter_environment(infcx.tcx); let selcx = &mut SelectionContext::intercrate(infcx, param_env); infcx.probe(|_| { overlap(selcx, impl1_def_id, impl2_def_id) || overlap(selc...
infer::Misc(DUMMY_SP), a_trait_ref.to_poly_trait_ref(), b_trait_ref.to_poly_trait_ref()) { return false; } debug!("overlap: subtraitref check succeeded")...
{ debug!("overlap(a_def_id={}, b_def_id={})", a_def_id.repr(selcx.tcx()), b_def_id.repr(selcx.tcx())); let (a_trait_ref, a_obligations) = impl_trait_ref_and_oblig(selcx, a_def_id, ...
identifier_body
comment.js
var db = require('./db') // create a comments sublevel var comments = db.sublevel('comments') var Comment = module.exports = function(key, attrs) { this.key = key if (attrs) { this.author = attrs.author this.date = attrs.date this.body = attrs.body } } Comment.prototype.save = function(callback) {...
}) } Comment.list = function(postKey, callback) { var results = [] var options = { start: postKey + '!', end: postKey + '!\xff' } comments.createReadStream(options) .on('data', function(data) { results.push(new Comment(data.key, data.value)) }) .on('error', function(err) { if...
if (err && err.notFound) return callback() if (err) return callback(err) callback(null, new Comment(key, value))
random_line_split
diverging_sub_expression.rs
#![warn(clippy::diverging_sub_expression)] #![allow(clippy::match_same_arms, clippy::logic_bug)] #[allow(clippy::empty_loop)] fn diverge() -> ! { loop {} } struct A; impl A { fn foo(&self) -> ! { diverge() } } #[allow(unused_variables, clippy::unnecessary_operation, clippy::short_circuit_statemen...
_ => true || break, }; } }
3 => true || diverge(), 10 => match 42 { 99 => return, _ => true || panic!("boo"), },
random_line_split
diverging_sub_expression.rs
#![warn(clippy::diverging_sub_expression)] #![allow(clippy::match_same_arms, clippy::logic_bug)] #[allow(clippy::empty_loop)] fn diverge() -> ! { loop {} } struct
; impl A { fn foo(&self) -> ! { diverge() } } #[allow(unused_variables, clippy::unnecessary_operation, clippy::short_circuit_statement)] fn main() { let b = true; b || diverge(); b || A.foo(); } #[allow(dead_code, unused_variables)] fn foobar() { loop { let x = match 5 { ...
A
identifier_name
diverging_sub_expression.rs
#![warn(clippy::diverging_sub_expression)] #![allow(clippy::match_same_arms, clippy::logic_bug)] #[allow(clippy::empty_loop)] fn diverge() -> !
struct A; impl A { fn foo(&self) -> ! { diverge() } } #[allow(unused_variables, clippy::unnecessary_operation, clippy::short_circuit_statement)] fn main() { let b = true; b || diverge(); b || A.foo(); } #[allow(dead_code, unused_variables)] fn foobar() { loop { let x = match...
{ loop {} }
identifier_body
__init__.py
from __future__ import print_function
# If we are running from a git repo, generate a more descriptive version number from .util.gitversion import getGitVersion try: gitv = getGitVersion('acq4', os.path.join(os.path.dirname(__file__), '..')) if gitv is not None: __version__ = gitv except Exception: pass # Set up a list of paths to se...
import os, sys __version__ = '0.9.3'
random_line_split
__init__.py
from __future__ import print_function import os, sys __version__ = '0.9.3' # If we are running from a git repo, generate a more descriptive version number from .util.gitversion import getGitVersion try: gitv = getGitVersion('acq4', os.path.join(os.path.dirname(__file__), '..')) if gitv is not None:
except Exception: pass # Set up a list of paths to search for configuration files # (used if no config is explicitly specified) # First we check the parent directory of the current module. # This path is used when running directly from a source checkout modpath = os.path.dirname(os.path.abspath(__file__)) CONFIG...
__version__ = gitv
conditional_block
lzss.rs
const WINDOW_SIZE: usize = 1 << WINDOW_BITS; const HASHTAB_SIZE: usize = 1 << 10; /// Writer for LZSS compressed streams. pub struct Writer<W> { inner: W, window: [u8; WINDOW_SIZE], hashtab: [usize; HASHTAB_SIZE], position: usize, look_ahead_bytes: usize, out_flags: u8, out_count: usize,...
random_line_split
lzss.rs
literals. fn emit_flush(&mut self) -> io::Result<()> { if self.out_count > 0 { if self.out_count < 8 { self.out_flags <<= 8 - self.out_count; } self.out_data[0] = self.out_flags; try!(self.inner.write_all(&self.out_data[..self.out_len])); ...
(&mut self) -> io::Result<()> { let search_pos = self.position; let hsh = self.hash_at(search_pos); let match_pos = self.hashtab[hsh]; let ofs = if match_pos < self.position { self.position - match_pos } else { sel...
process
identifier_name
lzss.rs
/// are looking at. Because hash table entries are overwritten /// blindly, we have to validate whatever we take out of the table /// when calculating the match length. fn hash_at(&self, pos: usize) -> usize { // This might go over the data actually in the window, but as // long as the...
{ cmp_test(b"a", &[128, b'a']); }
identifier_body
lzss.rs
self.out_count = 0; self.out_len = 1; } Ok(()) } /// Emit the literal byte `lit`. fn emit_lit(&mut self, lit: u8) -> io::Result<()> { if self.out_count == 8 { try!(self.emit_flush()); } self.out_count += 1; self.out_flags = (self.out_...
{ Ok(0) }
conditional_block
country_codes.py
'us': 'United States', 'um': 'United States Minor Outlying Islands', 'uy': 'Uruguay', 'uz': 'Uzbekistan', 'vu': 'Vanuatu', 've': 'Venezuela, Bolivarian Republic of', 'vn': 'Viet Nam', 'vg': 'Virgin Islands, British', 'wf': 'Wallis and Futuna', 'eh': 'Western Sahara', 'ye': 'Yemen', 'zm': 'Zambia...
nvert_country_3_to_2(c
identifier_name
country_codes.py
'uy': 'Uruguay', 'uz': 'Uzbekistan', 'vu': 'Vanuatu', 've': 'Venezuela, Bolivarian Republic of', 'vn': 'Viet Nam', 'vg': 'Virgin Islands, British', 'wf': 'Wallis and Futuna', 'eh': 'Western Sahara', 'ye': 'Yemen', 'zm': 'Zambia', 'zw': 'Zimbabwe', } SFDC_COUNTRIES_LIST = list(SFDC_COUNTRIES.keys()...
ode = ccode.lower() return COUNTRY_CODES_MAP.get(ccode, None)
identifier_body
country_codes.py
'cc': 'Cocos (Keeling) Islands', 'co': 'Colombia', 'km': 'Comoros', 'cg': 'Congo', 'cd': 'Congo, the Democratic Republic of the', 'ck': 'Cook Islands', 'cr': 'Costa Rica', 'ci': 'Cote d\'Ivoire', 'hr': 'Croatia', 'cu': 'Cuba', 'cw': 'Curaçao', 'cy': 'Cyprus', 'cz': 'Czech Republic', 'dk': 'D...
'cf': 'Central African Republic', 'td': 'Chad', 'cl': 'Chile', 'cn': 'China', 'cx': 'Christmas Island',
random_line_split
inheritance_integration_spec.ts
/** * @license * Copyright Google LLC 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 {Component, Directive, HostBinding} from '@angular/core'; import {TestBed} from '@angular/core/testing'; @Dir...
@HostBinding('title') title = 'DirectiveB Title'; } @Component({selector: 'component-a', template: 'ComponentA Template'}) class ComponentA { } @Component( {selector: 'component-extends-directive', template: 'ComponentExtendsDirective Template'}) class ComponentExtendsDirective extends DirectiveA { } class Com...
class DirectiveA { } @Directive({selector: '[directiveB]'}) class DirectiveB {
random_line_split
inheritance_integration_spec.ts
/** * @license * Copyright Google LLC 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 {Component, Directive, HostBinding} from '@angular/core'; import {TestBed} from '@angular/core/testing'; @Dir...
extends ComponentA {} @Directive({selector: '[directiveExtendsComponent]'}) class DirectiveExtendsComponent extends ComponentA { @HostBinding('title') title = 'DirectiveExtendsComponent Title'; } class DirectiveWithNoAnnotation extends DirectiveB {} @Component({selector: 'my-app', template: '...'}) class App { } ...
ComponentWithNoAnnotation
identifier_name
functions.py
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
return True def check_update(self): need_update=False for libname in get_libname(self.platform): if libname!='liblibtorrent.so': self.libpath = os.path.join(self.dest_path, libname) self.sizepath=os.path.join(self.root, self.platform['system'], se...
f not filetools.exists(os.path.join(self.dest_path,libname)): return False
conditional_block
functions.py
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
__libbaseurl__ = "https://github.com/DiMartinoXBMC/script.module.libtorrent/raw/master/python_libtorrent" #__settings__ = xbmcaddon.Addon(id='script.module.libtorrent') #__version__ = __settings__.getAddonInfo('version') #__plugin__ = __settings__.getAddonInfo('name') + " v." + __version__ #__icon__=os.path.join(xbmc....
import xbmc, xbmcgui, xbmcaddon from net import HTTP from core import filetools ### Alfa
random_line_split
functions.py
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
self): for libname in get_libname(self.platform): if not filetools.exists(os.path.join(self.dest_path,libname)): return False return True def check_update(self): need_update=False for libname in get_libname(self.platform): if libname!='liblibt...
heck_exist(
identifier_name
functions.py
#-*- coding: utf-8 -*- ''' python-libtorrent for Kodi (script.module.libtorrent) Copyright (C) 2015-2016 DiMartino, srg70, RussakHH, aisman 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 t...
def download(self): __settings__ = xbmcaddon.Addon(id='plugin.video.alfa') ### Alfa filetools.mkdir(self.dest_path) for libname in get_libname(self.platform): dest = os.path.join(self.dest_path, libname) log("try to fetch %s" % libname) u...
f self.check_update(): for libname in get_libname(self.platform): self.libpath = os.path.join(self.dest_path, libname) filetools.remove(self.libpath) self.download()
identifier_body
claims.js
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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....
}; this.getClaims = function (dialect) { return getClaims(dialect); }; })();
{ return []; }
conditional_block
claims.js
/* * Copyright (c) 2014, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you 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....
displayTag: c.getDisplayTag(), isRequired: c.isRequired(), regex: c.getRegEx(), value: c.getValue(), displayOrder: c.getDisplayOrder() }; claims.push(claim); }*/ return claims; }; this.getDefaultClaims = function() { if (DEFAULT_CLAIM_DIALECT) { return getClaims(DEFAULT_CLAIM_DI...
var c = defaultClaims[i].getClaim(); var claim = { claimUri: c.getClaimUri(),
random_line_split
create.py
client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from google.oauth2 import service_account from common.methods import set_progress from infrastructure.models import CustomField, Environment from pathlib import Path import json, tempfile import os import zipfile import ...
(**kwargs): return [("nodejs8", "Node JS 8"), ("nodejs10", "Node JS 10"), ("python37", "Python 3.7"), ("go111", "Node JS 8"), ] def generate_options_for_bucket_to_store_sourcecode(control_value=None, **kwargs): buckets = [] if control_value: environment = Enviro...
generate_options_for_runtime
identifier_name
create.py
client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from google.oauth2 import service_account from common.methods import set_progress from infrastructure.models import CustomField, Environment from pathlib import Path import json, tempfile import os import zipfile import ...
def generate_options_for_enter_sourcecode_or_bucket_url(**kwargs): return ['SourceCode', 'BucketUrl'] def generate_options_for_available_memory_mb(**kwargs): return [ (128, '128 MB'), (256, '256 MB'), (512, '512 MB'), (1024, '1 GB'), (2048, '2 GB'), ] def genera...
buckets = [] if control_value: environment = Environment.objects.get(id=control_value) project_id=environment.gcp_project rh = environment.resource_handler.cast() project=rh.gcp_projects.get(id=project_id).name storage_client = create_build_client(rh,project_id,'storage') ...
identifier_body
create.py
client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from google.oauth2 import service_account from common.methods import set_progress from infrastructure.models import CustomField, Environment from pathlib import Path import json, tempfile import os import zipfile import ...
runtimes = { 'python37': 'main.py', 'nodejs8': 'index.js', 'nodejs10': 'index.js', 'go111': 'function.go' } return (runtimes.get(runtime)==filename) def create_file_with_sourcecode(sourcecode): # Creates a temporary file containing the sourcecode passed. path=source...
""" Every runtime has -specific file that is expected by google cloud functions """
random_line_split
create.py
client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from google.oauth2 import service_account from common.methods import set_progress from infrastructure.models import CustomField, Environment from pathlib import Path import json, tempfile import os import zipfile import ...
path = os.path.join(settings.MEDIA_ROOT, path) archive=io.BytesIO() with zipfile.ZipFile(archive, 'w') as zip_archive: with open(path, 'r') as file: zip_file = zipfile.ZipInfo(filename) zip_archive.writestr(zip_file, file.read()) archive.seek(0) media=MediaIoBaseUplo...
set_progress("Converting relative URL to filesystem path") path = path.replace(settings.MEDIA_URL, settings.MEDIA_ROOT)
conditional_block
loadFile.py
import os import logging import pandas as pd from dataactvalidator.app import createApp from dataactvalidator.scripts.loaderUtils import LoaderUtils from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity from dataactcore.config import CONFIG_BROKE...
num = LoaderUtils.insertDataframe(data, table_name, sess.connection()) sess.commit() logger.info('{} records inserted to {}'.format(num, table_name)) def loadProgramActivity(filename): """Load program activity lookup table.""" model = ProgramActivity with createApp().app_context(): ...
"""Load object class lookup table.""" model = ObjectClass with createApp().app_context(): sess = GlobalDB.db().session # for object class, delete and replace values sess.query(model).delete() data = pd.read_csv(filename, dtype=str) data = LoaderUtils.cleanData( ...
identifier_body
loadFile.py
import os import logging import pandas as pd from dataactvalidator.app import createApp from dataactvalidator.scripts.loaderUtils import LoaderUtils from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity from dataactcore.config import CONFIG_BROKE...
else: loadProgramActivity(os.path.join(basePath, "program_activity.csv")) if __name__ == '__main__': loadDomainValues( os.path.join(CONFIG_BROKER["path"], "dataactvalidator", "config") )
loadProgramActivity(localProgramActivity)
conditional_block
loadFile.py
import os import logging import pandas as pd from dataactvalidator.app import createApp from dataactvalidator.scripts.loaderUtils import LoaderUtils from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity from dataactcore.config import CONFIG_BROKE...
# read CGAC values from csv data = pd.read_csv(filename, dtype=str) # clean data data = LoaderUtils.cleanData( data, model, {"cgac": "cgac_code", "agency": "agency_name"}, {"cgac_code": {"pad_to_length": 3}} ) # de-dupe ...
sess = GlobalDB.db().session # for CGAC, delete and replace values sess.query(model).delete()
random_line_split
loadFile.py
import os import logging import pandas as pd from dataactvalidator.app import createApp from dataactvalidator.scripts.loaderUtils import LoaderUtils from dataactcore.interfaces.db import GlobalDB from dataactcore.models.domainModels import CGAC, ObjectClass, ProgramActivity from dataactcore.config import CONFIG_BROKE...
(basePath, localProgramActivity = None): """Load all domain value files. Parameters ---------- basePath : directory that contains the domain values files. localProgramActivity : optional location of the program activity file (None = use basePath) """ logger.info('Loading CGAC') ...
loadDomainValues
identifier_name
shader.rs
use vecmath::Matrix4; use gfx; use gfx::{Device, DeviceHelper, ToSlice}; use device; use device::draw::CommandBuffer; use render; static VERTEX: gfx::ShaderSource = shaders! { GLSL_120: b" #version 120 uniform mat4 projection, view; attribute vec2 tex_coord; attribute vec3 color, position; varyin...
Renderer { graphics: graphics, params: params, frame: frame, cd: gfx::ClearData { color: [0.81, 0.8, 1.0, 1.0], depth: 1.0, stencil: 0, }, prog: prog, drawstate: drawstate, ...
drawstate.primitive.front_face = gfx::state::Clockwise;
random_line_split
shader.rs
use vecmath::Matrix4; use gfx; use gfx::{Device, DeviceHelper, ToSlice}; use device; use device::draw::CommandBuffer; use render; static VERTEX: gfx::ShaderSource = shaders! { GLSL_120: b" #version 120 uniform mat4 projection, view; attribute vec2 tex_coord; attribute vec3 color, position; varyin...
(&mut self, view_mat: Matrix4<f32>) { self.params.view = view_mat; } pub fn clear(&mut self) { self.graphics.clear(self.cd, gfx::COLOR | gfx::DEPTH, &self.frame); } pub fn create_buffer(&mut self, data: &[Vertex]) -> Buffer { let buf = self.graphics.device.create_buffer(data.le...
set_view
identifier_name
slimey.js
locale = 'pl_pl'; addLangs({ 'enter the url of the image': 'Podaj URL obrazu', 'enter a color': 'Podaj kolor', 'drag the bottom right corner to resize': 'Przeciągnij dolne prawy róg aby rozciągnąć', 'double click to edit content': 'Kliknij dwa razy aby edytować zawartość', 'some text': 'Jakiś tekst', 'new ...
'click to insert a new slide': 'Kliknij aby wstawić nowy slajd', 'bold text': 'Pogrubienie', 'underline text': 'Podkreślenie', 'italic text': 'Kursywa', 'unsaved changes will be lost.': 'Niezapisane zmiany zostaną utracone.', 'align text to the left': 'Do lewej', 'align text to the center': 'Do środka', ...
'no slide to move': 'Brak slajdów do przesunięcia',
random_line_split
debug.py
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2012 Dag Wieers <dag@wieers.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: debug short_...
type: str verbosity: description: - A number that controls when the debug is run, if you set to 3 it will only run debug when -vvv or above type: int default: 0 version_added: '2.1' notes: - This module is also supported for Windows targets. seealso: - module: ansible.builtin.assert - modu...
so you should not be using Jinja2 delimiters unless you are looking for double interpolation.
random_line_split
reader.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
match self.reader.read_at_least(v.len(), v) { Ok(_) => {} Err(e) => panic!("ReaderRng.fill_bytes error: {}", e) } } } #[cfg(test)] mod test { use prelude::*; use super::ReaderRng; use io::MemReader; use num::Int; use rand::Rng; #[test] fn test_...
{ return }
conditional_block
reader.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
fn next_u64(&mut self) -> u64 { // see above for explanation. if cfg!(target_endian="little") { self.reader.read_le_u64().unwrap() } else { self.reader.read_be_u64().unwrap() } } fn fill_bytes(&mut self, v: &mut [u8]) { if v.len() == 0 { retur...
{ // This is designed for speed: reading a LE integer on a LE // platform just involves blitting the bytes into the memory // of the u32, similarly for BE on BE; avoiding byteswapping. if cfg!(target_endian="little") { self.reader.read_le_u32().unwrap() } else { ...
identifier_body
reader.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
(&mut self, v: &mut [u8]) { if v.len() == 0 { return } match self.reader.read_at_least(v.len(), v) { Ok(_) => {} Err(e) => panic!("ReaderRng.fill_bytes error: {}", e) } } } #[cfg(test)] mod test { use prelude::*; use super::ReaderRng; use io::MemReader; ...
fill_bytes
identifier_name
reader.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // 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 ...
} } fn fill_bytes(&mut self, v: &mut [u8]) { if v.len() == 0 { return } match self.reader.read_at_least(v.len(), v) { Ok(_) => {} Err(e) => panic!("ReaderRng.fill_bytes error: {}", e) } } } #[cfg(test)] mod test { use prelude::*; use super::R...
self.reader.read_be_u64().unwrap()
random_line_split
create_messages.py
#!/usr/bin/python3 # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google LLC # # 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...
def load_constants(filename): """Read in constants file, which must be output in every language.""" constant_defs = read_json_file(filename) constants_text = '\n' for key in constant_defs: value = constant_defs[key] value = value.replace('"', '\\"') constants_text += u'\nBlockly.Msg["{0}"] = \"{1}...
try: # This approach is better for compatibility return all(ord(c) < 128 for c in s) except TypeError: return False
identifier_body
create_messages.py
#!/usr/bin/python3 # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google LLC # # 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...
(filename): """Read in constants file, which must be output in every language.""" constant_defs = read_json_file(filename) constants_text = '\n' for key in constant_defs: value = constant_defs[key] value = value.replace('"', '\\"') constants_text += u'\nBlockly.Msg["{0}"] = \"{1}\";'.format( ...
load_constants
identifier_name
create_messages.py
#!/usr/bin/python3 # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google LLC # # 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...
parser.add_argument('files', nargs='+', help='input files') args = parser.parse_args() if not args.output_dir.endswith(os.path.sep): args.output_dir += os.path.sep # Read in source language .json file, which provides any values missing # in target languages' .json files. source_defs = read_json_file(os...
help='relative directory for output files') parser.add_argument('--key_file', default='keys.json', help='relative path to input keys file') parser.add_argument('--quiet', action='store_true', default=False, help='do not write anything to standard out...
random_line_split
create_messages.py
#!/usr/bin/python3 # Generate .js files defining Blockly core and language messages. # # Copyright 2013 Google LLC # # 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...
value = value.replace('"', '\\"') outfile.write(u'Blockly.Msg["{0}"] = "{1}";{2}\n' .format(key, value, comment)) # Announce any keys defined only for target language. if target_defs: extra_keys = [key for key in target_defs if key not in synonym_defs] ...
value = source_defs[key] comment = ' // untranslated'
conditional_block
gdb.py
#!/usr/bin/env python # 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 # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
(Test): def setUp(self): sm = SoftwareManager() dist = distro.detect() packages = ['gcc', 'dejagnu', 'flex', 'bison', 'texinfo', 'make', 'makeinfo'] if dist.name == 'Ubuntu': packages.extend(['g++', 'binutils-dev']) # FIXME: "redhat" as the di...
GDB
identifier_name
gdb.py
#!/usr/bin/env python # 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 # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
package) test_type = self.params.get('type', default='upstream') if test_type == 'upstream': gdb_version = self.params.get('gdb_version', default='10.2') tarball = self.fetch_asset( "http://ftp.gnu.org/gnu/gdb/gdb-%s.tar.gz" % gdb_versi...
sm = SoftwareManager() dist = distro.detect() packages = ['gcc', 'dejagnu', 'flex', 'bison', 'texinfo', 'make', 'makeinfo'] if dist.name == 'Ubuntu': packages.extend(['g++', 'binutils-dev']) # FIXME: "redhat" as the distro name for RHEL is deprecated ...
identifier_body
gdb.py
#!/usr/bin/env python # 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 # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
# FIXME: "redhat" as the distro name for RHEL is deprecated # on Avocado versions >= 50.0. This is a temporary compatibility # enabler for older runners, but should be removed soon elif dist.name in ['rhel', 'fedora', 'redhat']: packages.extend(['gcc-c++', 'binutils-devel', ...
random_line_split
gdb.py
#!/usr/bin/env python # 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 # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that ...
for package in packages: if not sm.check_installed(package) and not sm.install(package): self.cancel("Fail to install %s required for this test." % package) test_type = self.params.get('type', default='upstream') if test_type == 'upstream'...
self.fail('no packages list for your distro.')
conditional_block
ArgumentDeclaration.ts
// Copyright (C) 2015, 2017 Simon Mika <simon@mika.se> // // This file is part of SysPL. // // SysPL 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, or // (at your option) a...
(source: Source): SyntaxTree.ArgumentDeclaration[] { const result: SyntaxTree.ArgumentDeclaration[] = [] if (source.peek()!.isSeparator("(")) { do { source.fetch() // consume: ( or , result.push(parse(source.clone())!) } while (source.peek()!.isSeparator(",")) if (!source.fetch()!.isSeparator(")")) sou...
parseAll
identifier_name
ArgumentDeclaration.ts
// Copyright (C) 2015, 2017 Simon Mika <simon@mika.se> // // This file is part of SysPL. // // SysPL 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, or // (at your option) a...
export function parseAll(source: Source): SyntaxTree.ArgumentDeclaration[] { const result: SyntaxTree.ArgumentDeclaration[] = [] if (source.peek()!.isSeparator("(")) { do { source.fetch() // consume: ( or , result.push(parse(source.clone())!) } while (source.peek()!.isSeparator(",")) if (!source.fetch()!...
{ let result: SyntaxTree.ArgumentDeclaration | undefined if (source.peek()!.isIdentifier()) { // // handles cases "x" and "x: Type" // const symbol = (source.fetch() as Tokens.Identifier).name const type = Type.tryParse(source) result = new SyntaxTree.ArgumentDeclaration(symbol, type, source.mark()) } el...
identifier_body
ArgumentDeclaration.ts
// Copyright (C) 2015, 2017 Simon Mika <simon@mika.se> // // This file is part of SysPL. // // SysPL 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, or // (at your option) a...
// source.fetch() // consume "=" or "." result = new SyntaxTree.ArgumentDeclaration((source.fetch() as Tokens.Identifier).name, undefined, source.mark()) } return result } export function parseAll(source: Source): SyntaxTree.ArgumentDeclaration[] { const result: SyntaxTree.ArgumentDeclaration[] = [] if (sourc...
result = new SyntaxTree.ArgumentDeclaration(symbol, type, source.mark()) } else if (source.peek()!.isOperator("=") || source.peek()!.isSeparator(".")) { // // Handles syntactic sugar cases ".argument" and "=argument" // The type of the argument will have to be resolved later
random_line_split
Error.tsx
import React from 'react'; import { Text } from '@tlon/indigo-react'; enum ErrorTypes { 'cant-pay-ourselves' = 'Cannot pay ourselves', 'no-comets' = 'Cannot pay comets', 'no-dust' = 'Cannot send dust', 'tx-being-signed' = 'Cannot pay when transaction is being signed', 'insufficient-balance' = 'Insufficient c...
error, fontSize, ...rest }: { error: string; fontSize?: string; }) => ( <Text color="red" style={{ fontSize }} {...rest}> { (ErrorTypes as any)[ Object.keys(ErrorTypes).filter((et) => et === error)[0] ] } </Text> ); export default Error;
'invalid-master-ticker' = 'Invalid master ticket', 'invalid-signed' = 'Invalid signed bitcoin transaction', } const Error = ({
random_line_split
SelectByAttribute.py
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
(self): return self.tr('Vector selection') def __init__(self): super().__init__() def initAlgorithm(self, config=None): self.i18n_operators = ['=', '!=', '>', '>=', ...
group
identifier_name
SelectByAttribute.py
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
elif operator == 'does not contain': expression_string = """%s NOT LIKE '%%%s%%'""" % (field_ref, value) else: expression_string = '{} {} {}'.format(field_ref, operator, quoted_val) expression = QgsExpression(expression_string) if expression.hasParserError(): ...
expression_string = """%s LIKE '%%%s%%'""" % (field_ref, value)
conditional_block
SelectByAttribute.py
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
*************************************************************************** """ __author__ = 'Michael Minn' __date__ = 'May 2010' __copyright__ = '(C) 2010, Michael Minn' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from qgis.PyQt.QtCore import QVariant from qgis.c...
* 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 * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * ...
random_line_split
SelectByAttribute.py
# -*- coding: utf-8 -*- """ *************************************************************************** SelectByAttribute.py --------------------- Date : May 2010 Copyright : (C) 2010 by Michael Minn Email : pyqgis at michaelminn dot com *******************...
def __init__(self): super().__init__() def initAlgorithm(self, config=None): self.i18n_operators = ['=', '!=', '>', '>=', '<', '<=', ...
return self.tr('Vector selection')
identifier_body
main.rs
//! # Synacor Challenge //! //! A Rust based runtime for the Synacor challenge architecture. #![warn(missing_docs)] extern crate byteorder; extern crate termion; #[macro_use] extern crate chan; extern crate chan_signal; extern crate libc; extern crate synacor; mod command; mod debugger; use debugger::Debugger; use s...
() { let binary = if let Some(val) = args().nth(1) { let mut buffer = Vec::new(); let mut in_file = File::open(val) .expect("Failed to open challenge binary."); in_file.read_to_end(&mut buffer) .expect("Failed to read in binary contents."); buffer } else {...
main
identifier_name