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
evaluator_topics.py
""" This script computes Topic metrics for the end-to-end performance. Precision and recall are micro-averaged. Matching condition: only entities should match. @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ from __future__ import division import sys from collections import defaultdict class EvaluatorTopic...
if __name__ == '__main__': main(sys.argv[1:])
if len(args) < 2: print "\tUsage: <qrel_file> <result_file>" exit(0) print "parsing qrel ..." qrels, null_qrels = parse_file(args[0]) # here qrel does not contain null entities print "parsing results ..." results = parse_file(args[1])[0] print "evaluating ..." score_th = 0 if le...
identifier_body
evaluator_topics.py
""" This script computes Topic metrics for the end-to-end performance. Precision and recall are micro-averaged. Matching condition: only entities should match. @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ from __future__ import division import sys from collections import defaultdict class EvaluatorTopic...
(mention1, mention2): """ Checks if two mentions matches each other. Matching condition: One of the mentions is sub-string of the other one. """ match = ((mention1 in mention2) or (mention2 in mention1)) return match def parse_file(file_name, res=False): """ Parses file and returns the...
mention_match
identifier_name
evaluator_topics.py
""" This script computes Topic metrics for the end-to-end performance. Precision and recall are micro-averaged. Matching condition: only entities should match. @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ from __future__ import division import sys from collections import defaultdict class EvaluatorTopic...
else: fn += 1 # Iterate over results to calculate FP for res_item in results_ens: if not find_item(res_item, qrel_ens): # Finds the result in the qrels fp += 1 stats = {'tp': tp, 'fp': fp, 'fn': fn} return stats def find_item(item_to_find, items_list): ""...
tp += 1
conditional_block
evaluator_topics.py
""" This script computes Topic metrics for the end-to-end performance. Precision and recall are micro-averaged. Matching condition: only entities should match. @author: Faegheh Hasibi (faegheh.hasibi@idi.ntnu.no) """ from __future__ import division import sys from collections import defaultdict class EvaluatorTopic...
def main(args): if len(args) < 2: print "\tUsage: <qrel_file> <result_file>" exit(0) print "parsing qrel ..." qrels, null_qrels = parse_file(args[0]) # here qrel does not contain null entities print "parsing results ..." results = parse_file(args[1])[0] print "evaluating ..." ...
random_line_split
limits.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # 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 requ...
(self, req): return self._index(req, FILTERED_LIMITS_2_36, max_image_meta=False) @wsgi.Controller.api_version('2.57') # noqa @wsgi.expected_errors(()) @validation.query_schema(limits.limits_query_schema_275, '2.75') @validation.query_schema(limits.limits_query_schema, '2.57', '2.74') def i...
index
identifier_name
limits.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # 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 requ...
import MAX_IMAGE_META_PROXY_API_VERSION from nova.api.openstack.api_version_request \ import MAX_PROXY_API_SUPPORT_VERSION from nova.api.openstack.api_version_request \ import MIN_WITHOUT_IMAGE_META_PROXY_API_VERSION from nova.api.openstack.api_version_request \ import MIN_WITHOUT_PROXY_API_SUPPORT_VERS...
# under the License. from nova.api.openstack.api_version_request \
random_line_split
limits.py
# Copyright 2011 OpenStack Foundation # All Rights Reserved. # # 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 requ...
return self._index(req, FILTERED_LIMITS_2_36, max_image_meta=False) @wsgi.Controller.api_version('2.57') # noqa @wsgi.expected_errors(()) @validation.query_schema(limits.limits_query_schema_275, '2.75') @validation.query_schema(limits.limits_query_schema, '2.57', '2.74') def index(self, re...
"""Controller for accessing limits in the OpenStack API.""" @wsgi.Controller.api_version("2.1", MAX_PROXY_API_SUPPORT_VERSION) @wsgi.expected_errors(()) @validation.query_schema(limits.limits_query_schema) def index(self, req): return self._index(req) @wsgi.Controller.api_version(MIN_WITHO...
identifier_body
hookutils.py
[] # Means no imports found or looking for imports failed. #module_imports = filter(lambda x: not x.startswith('distutils'), module_imports) return module_imports def qt4_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtCore import QCoreApplication;" "app=QCoreApplication([...
for d in qt5_plugin_dirs: if os.path.isdir(d): return str(d) # must be 8-bit chars for one-file builds logger.error("Cannot find existing PyQt5 plugin directory") return "" def qt5_phonon_plugins_dir(): qt5_plugin_dirs = eval_statement( "from PyQt5.QtGui import QApplicati...
logger.error("Cannot find PyQt5 plugin directories") return ""
conditional_block
hookutils.py
return [] # Means no imports found or looking for imports failed. #module_imports = filter(lambda x: not x.startswith('distutils'), module_imports) return module_imports def qt4_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtCore import QCoreApplication;" "app=QCoreApplic...
def qt5_menu_nib_dir(): """Return path to Qt resource dir qt_menu.nib. OSX only""" menu_dir = '' # If the QT5DIR env var is set then look there first. It should be set to the # qtbase dir in the Qt5 distribution. dirs = [] if 'QT5DIR' in os.environ: dirs.append(os.path.join(os.envi...
os.path.join('qt5_plugins', plugin_type, os.path.basename(f)), f, 'BINARY')) return binaries
random_line_split
hookutils.py
return [] # Means no imports found or looking for imports failed. #module_imports = filter(lambda x: not x.startswith('distutils'), module_imports) return module_imports def qt4_plugins_dir():
def qt4_phonon_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtGui import QApplication;" "app=QApplication([]); app.setApplicationName('pyinstaller');" "from PyQt4.phonon import Phonon;" "v=Phonon.VideoPlayer(Phonon.VideoCategory);" "print map(unicode,app.li...
qt4_plugin_dirs = eval_statement( "from PyQt4.QtCore import QCoreApplication;" "app=QCoreApplication([]);" "print map(unicode,app.libraryPaths())") if not qt4_plugin_dirs: logger.error("Cannot find PyQt4 plugin directories") return "" for d in qt4_plugin_dirs: if ...
identifier_body
hookutils.py
[] # Means no imports found or looking for imports failed. #module_imports = filter(lambda x: not x.startswith('distutils'), module_imports) return module_imports def qt4_plugins_dir(): qt4_plugin_dirs = eval_statement( "from PyQt4.QtCore import QCoreApplication;" "app=QCoreApplication([...
(): qt5_plugin_dirs = eval_statement( "from PyQt5.QtCore import QCoreApplication;" "app=QCoreApplication([]);" "print map(unicode,app.libraryPaths())") if not qt5_plugin_dirs: logger.error("Cannot find PyQt5 plugin directories") return "" for d in qt5_plugin_dirs: ...
qt5_plugins_dir
identifier_name
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct
<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); for e in e.iter().skip(1) { let this_err: String = e.to_string...
FormattedError
identifier_name
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct FormattedError<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); ...
Ok(()) } } impl Error { pub fn format<'a>(&'a self) -> FormattedError<'a> { FormattedError{value: self} } }
writeln!(f, "")?; writeln!(f, " =>: {:?}", backtrace)?; }
conditional_block
errors.rs
use std::fmt; use std::ops::FnOnce; error_chain! { } pub struct FormattedError<'a> { value: &'a Error } impl<'a> fmt::Display for FormattedError<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let e = self.value; write!(f, "{}", e)?; let mut last_error = e.to_string(); ...
// The backtrace is generated with environment `RUST_BACKTRACE=1`. if let Some(backtrace) = e.backtrace() { writeln!(f, "")?; writeln!(f, " =>: {:?}", backtrace)?; } Ok(()) } } impl Error { pub fn format<'a>(&'a self) -> FormattedError<'a> { For...
random_line_split
noUnnecessaryQualifierRule.js
"use strict"; /** * @license * Copyright 2017 Palantir Technologies, Inc. * * 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 * * Unle...
function symbolIsNamespaceInScope(symbol) { var symbolDeclarations = symbol.getDeclarations(); if (symbolDeclarations == null) { return false; } else if (symbolDeclarations.some(function (decl) { return namespacesInScope.some(function (ns) { return ns === decl; }); })) {...
{ // TODO:PERF `getSymbolsInScope` gets a long list. Is there a better way? var scope = checker.getSymbolsInScope(node, flags); return scope.find(function (scopeSymbol) { return scopeSymbol.name === name; }); }
identifier_body
noUnnecessaryQualifierRule.js
"use strict"; /** * @license * Copyright 2017 Palantir Technologies, Inc. * * 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 * * Unle...
(ctx, checker) { var namespacesInScope = []; ts.forEachChild(ctx.sourceFile, cb); function cb(node) { switch (node.kind) { case ts.SyntaxKind.ModuleDeclaration: case ts.SyntaxKind.EnumDeclaration: namespacesInScope.push(node); ts.forEachChild(n...
walk
identifier_name
noUnnecessaryQualifierRule.js
"use strict"; /** * @license * Copyright 2017 Palantir Technologies, Inc. * * 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 * * Unle...
var alias = tryGetAliasedSymbol(symbol, checker); return alias !== undefined && symbolIsNamespaceInScope(alias); } } function tryGetAliasedSymbol(symbol, checker) { return Lint.isSymbolFlagSet(symbol, ts.SymbolFlags.Alias) ? checker.getAliasedSymbol(symbol) : undefined; }
{ return true; }
conditional_block
noUnnecessaryQualifierRule.js
"use strict"; /** * @license * Copyright 2017 Palantir Technologies, Inc. * * 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 * * Unle...
type: "style", typescriptOnly: true, requiresTypeInfo: true, }; exports.Rule = Rule; function walk(ctx, checker) { var namespacesInScope = []; ts.forEachChild(ctx.sourceFile, cb); function cb(node) { switch (node.kind) { case ts.SyntaxKind.ModuleDeclaration: case ...
optionExamples: [true],
random_line_split
StateChangeEvent.ts
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of c...
*/ public static CURRENT_STATE_CHANGE:string = "currentStateChange"; /** * 当前视图状态即将改变 * @constant egret.gui.StateChangeEvent.CURRENT_STATE_CHANGING */ public static CURRENT_STATE_CHANGING:string = "currentStateChanging"; /** * @method egret.gui.StateChangeEvent#constructor * @param type...
/** * 当前视图状态已经改变 * @constant egret.gui.StateChangeEvent.CURRENT_STATE_CHANGE
random_line_split
StateChangeEvent.ts
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of c...
e; Event._dispatchByTarget(eventClass,target,type,props); } } }
identifier_body
StateChangeEvent.ts
/** * Copyright (c) 2014,Egret-Labs.org * All rights reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of c...
/** * 当前视图状态已经改变 * @constant egret.gui.StateChangeEvent.CURRENT_STATE_CHANGE */ public static CURRENT_STATE_CHANGE:string = "currentStateChange"; /** * 当前视图状态即将改变 * @constant egret.gui.StateChangeEvent.CURRENT_STATE_CHANGING */ public static CURRENT_STATE_CHANGING:string = "currentStateCh...
extends Event{
identifier_name
signalActions.py
import models def borradoPlan(sender, **kwargs): borrada = kwargs['instance'] if borrada.tipo == "pr": aBorrar = models.PlanPrepago.objects.filter(codplan=borrada) else: aBorrar = models.PlanPostpago.objects.filter(codplan=borrada) aBorrar.delete() def insertadoServicio(sender, **kwargs):
nuevoPaq = models.Paquete(codpaq=insertado.codserv,nombrepaq=insertado.nombreserv + ' Paquete',precio=insertado.costo) nuevoPaq.save() nuevoContiene = models.Contiene(codpaq=nuevoPaq,codserv=insertado,cantidad=1) nuevoContiene.save() def borradoServicio(sender, **kwargs): borrado = kwargs['instance'] if b...
insertado = kwargs['instance'] print insertado if insertado.id is not None:
random_line_split
signalActions.py
import models def borradoPlan(sender, **kwargs): borrada = kwargs['instance'] if borrada.tipo == "pr": aBorrar = models.PlanPrepago.objects.filter(codplan=borrada) else: aBorrar = models.PlanPostpago.objects.filter(codplan=borrada) aBorrar.delete() def insertadoServicio(sender, **kwargs): ...
contieneBorrar = models.Contiene.objects.all().filter(codpaq=borrado.codserv) contieneBorrar.delete() paqBorrar = models.Paquete.objects.all().filter(codpaq=borrado.codserv) paqBorrar.delete()
conditional_block
signalActions.py
import models def borradoPlan(sender, **kwargs):
def insertadoServicio(sender, **kwargs): insertado = kwargs['instance'] print insertado if insertado.id is not None: nuevoPaq = models.Paquete(codpaq=insertado.codserv,nombrepaq=insertado.nombreserv + ' Paquete',precio=insertado.costo) nuevoPaq.save() nuevoContiene = models.Contiene(codpaq=nue...
borrada = kwargs['instance'] if borrada.tipo == "pr": aBorrar = models.PlanPrepago.objects.filter(codplan=borrada) else: aBorrar = models.PlanPostpago.objects.filter(codplan=borrada) aBorrar.delete()
identifier_body
signalActions.py
import models def borradoPlan(sender, **kwargs): borrada = kwargs['instance'] if borrada.tipo == "pr": aBorrar = models.PlanPrepago.objects.filter(codplan=borrada) else: aBorrar = models.PlanPostpago.objects.filter(codplan=borrada) aBorrar.delete() def
(sender, **kwargs): insertado = kwargs['instance'] print insertado if insertado.id is not None: nuevoPaq = models.Paquete(codpaq=insertado.codserv,nombrepaq=insertado.nombreserv + ' Paquete',precio=insertado.costo) nuevoPaq.save() nuevoContiene = models.Contiene(codpaq=nuevoPaq,codserv=insertado,can...
insertadoServicio
identifier_name
flatten_dict.py
import inspect try: from collections.abc import Mapping except ImportError: from collections import Mapping import six from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter REDUCER_DICT = { ...
# check max_flatten_depth if max_flatten_depth is not None and max_flatten_depth < 1: raise ValueError("max_flatten_depth should not be less than 1.") if isinstance(reducer, str): reducer = REDUCER_DICT[reducer] try: # Python 3 reducer_accepts_parent_obj = len(inspect.s...
raise ValueError( "argument type %s is not in the flattenalbe types %s" % (type(d), flattenable_types) )
random_line_split
flatten_dict.py
import inspect try: from collections.abc import Mapping except ImportError: from collections import Mapping import six from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter REDUCER_DICT = { ...
`list` indices become keys: ``{'a': ['b', 'c']}`` -> ``{('a', 0): 'b', ('a', 1): 'c'}``. keep_empty_types : Sequence[type] By default, ``flatten({1: 2, 3: {}})`` will give you ``{(1,): 2}``, that is, the key ``3`` will disappear. This is also applied for the types in `enumerate_types...
"""Flatten `Mapping` object. Parameters ---------- d : dict-like object The dict that will be flattened. reducer : {'tuple', 'path', 'underscore', 'dot', Callable} The key joining method. If a `Callable` is given, the `Callable` will be used to reduce. 'tuple': The resul...
identifier_body
flatten_dict.py
import inspect try: from collections.abc import Mapping except ImportError: from collections import Mapping import six from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter REDUCER_DICT = { ...
( d, reducer="tuple", inverse=False, max_flatten_depth=None, enumerate_types=(), keep_empty_types=(), ): """Flatten `Mapping` object. Parameters ---------- d : dict-like object The dict that will be flattened. reducer : {'tuple', 'path', 'underscore', 'dot', Callable...
flatten
identifier_name
flatten_dict.py
import inspect try: from collections.abc import Mapping except ImportError: from collections import Mapping import six from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter REDUCER_DICT = { ...
# add an item to the result if inverse: flat_key, value = value, flat_key if flat_key in flat_dict: raise ValueError("duplicated key '{}'".format(flat_key)) flat_dict[flat_key] = value return has_item _flatten(d, depth=1) ...
has_child = _flatten(value, depth=depth + 1, parent=flat_key) if has_child or not isinstance(value, keep_empty_types): # ignore the key in this level because it already has child key # or its value is empty continue
conditional_block
combine_logs.py
#!/usr/bin/env python3 """Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os i...
log_events = read_logs(unknown_args[0]) print_logs(log_events, color=args.color, html=args.html) def read_logs(tmp_dir): """Reads log files. Delegates to generator function get_log_events() to provide individual log events for each of the input log files.""" files = [("test", "%s/test_frame...
"""Main function. Parses args, reads the log files and renders them as text or html.""" parser = argparse.ArgumentParser(usage='%(prog)s [options] <test temporary directory>', description=__doc__) parser.add_argument('-c', '--color', dest='color', action='store_true', help='outputs the combined log with events...
identifier_body
combine_logs.py
#!/usr/bin/env python3 """Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os i...
colors["node2"] = "\033[0;31m" # RED colors["node3"] = "\033[0;33m" # YELLOW colors["reset"] = "\033[0m" # Reset font color for event in log_events: print("{0} {1: <5} {2} {3}".format(colors[event.source.rstrip()], event.source, event.event, colors["reset"]...
if color: colors["test"] = "\033[0;36m" # CYAN colors["node0"] = "\033[0;34m" # BLUE colors["node1"] = "\033[0;32m" # GREEN
random_line_split
combine_logs.py
#!/usr/bin/env python3 """Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os i...
(source, logfile): """Generator function that returns individual log events. Log events may be split over multiple lines. We use the timestamp regex match as the marker for a new log event.""" try: with open(logfile, 'r') as infile: event = '' timestamp = '' ...
get_log_events
identifier_name
combine_logs.py
#!/usr/bin/env python3 """Combine logs from multiple bitcore nodes as well as the test_framework log. This streams the combined log output to stdout. Use combine_logs.py > outputfile to write to an outputfile.""" import argparse from collections import defaultdict, namedtuple import heapq import itertools import os i...
else: try: import jinja2 except ImportError: print("jinja2 not found. Try `pip install jinja2`") sys.exit(1) print(jinja2.Environment(loader=jinja2.FileSystemLoader('./')) .get_template('combined_log_template.html') ...
print("{0} {1: <5} {2} {3}".format(colors[event.source.rstrip()], event.source, event.event, colors["reset"]))
conditional_block
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * 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 restriction, including without limitation the * rights t...
>(var: T) { unsafe { forget(var); } } /* cast::ktransmute::<L, G> Convert a variable from one type to another. => var = variable of type L to convert <= returns variable as type G */ #[inline] pub fn ktransmute<L, G>(var: L) -> G { unsafe { transmute(var) } }
orget<T
identifier_name
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * 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 restriction, including without limitation the * rights t...
/* cast::ktransmute::<L, G> Convert a variable from one type to another. => var = variable of type L to convert <= returns variable as type G */ #[inline] pub fn ktransmute<L, G>(var: L) -> G { unsafe { transmute(var) } }
unsafe { forget(var); } }
identifier_body
cast.rs
/* kernel/cast.rs * * Copyright (c) 2014, Chris Williams (diosix.org) * * 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 restriction, including without limitation the * rights t...
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ /* allow the kernel to recast variables */ /* grab the compiler's built-in functions */ extern "rust-intrinsic" { pub fn forget<T>(_: T) ...
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
random_line_split
generate_label_testvectors.py
import numpy as np from scipy.ndimage import label def generate_test_vecs(infile, strelfile, resultfile):
bitimage(["010", "111", "010"]), bitimage(["101", "010", "101"]), bitimage(["100", "010", "001"]), bitimage(["000", "111", "000"]), bitimage(["110", "010", "011"]), bitimage(["110", "111", "011"])] strels = strels + [np.flipud(s) fo...
"test label with different structuring element neighborhoods" def bitimage(l): return np.array([[c for c in s] for s in l]) == '1' data = [np.ones((7, 7)), bitimage(["1110111", "1100011", "1010101", "0001000", ...
identifier_body
generate_label_testvectors.py
import numpy as np from scipy.ndimage import label def generate_test_vecs(infile, strelfile, resultfile): "test label with different structuring element neighborhoods" def
(l): return np.array([[c for c in s] for s in l]) == '1' data = [np.ones((7, 7)), bitimage(["1110111", "1100011", "1010101", "0001000", "1010101", "1100011", "11101...
bitimage
identifier_name
generate_label_testvectors.py
import numpy as np from scipy.ndimage import label def generate_test_vecs(infile, strelfile, resultfile): "test label with different structuring element neighborhoods" def bitimage(l): return np.array([[c for c in s] for s in l]) == '1' data = [np.ones((7, 7)), bitimage(["1110111", ...
generate_test_vecs("label_inputs.txt", "label_strels.txt", "label_results.txt")
random_line_split
sync3kReducer.ts
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in...
import { Sync3kLocalState } from '../states/sync3kState'; export const sync3kReducer = (state: Sync3kLocalState = {latest:'', specs:{}, keyRequests: {}, head: {}, watermark: -1}, action: AnyAction) => { switch (action.type) { case '@@sync3k/SYNC3K_INITIALIZE': return {...state, initialized: !action.askForK...
random_line_split
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error>...
let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_err(|e| error::ErrorInternalServerError(format!("Database error: {}", e)))?; let _deleted = web::block(move || { let conn = pool...
{ return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); }
conditional_block
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result};
use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> { if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this pa...
use crate::DbPool;
random_line_split
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn
(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error> { if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); } let pool_ = pool.clone(); let like = web::block(move || { let conn = ...
delete
identifier_name
delete.rs
use actix_identity::Identity; use actix_web::{error, http::header, post, web, Error, HttpResponse, Result}; use crate::DbPool; use super::actions; use crate::uri_helpers::*; #[post("/likes/{id}/delete")] pub async fn delete(ident: Identity, pool: web::Data<DbPool>, id: web::Path<i32>) -> Result<HttpResponse, Error>...
Ok(HttpResponse::Found() .append_header((header::LOCATION, likes_uri())) .finish()) }
{ if ident.identity().is_none() { return Result::Err(error::ErrorForbidden("You have to be logged in to see this page")); } let pool_ = pool.clone(); let like = web::block(move || { let conn = pool_.get()?; actions::get_like(id.into_inner(), &conn) }) .await? .map_er...
identifier_body
bounds.py
import sys from PyFBA import lp, log_and_message def reaction_bounds(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False): """ Set the bounds for each reaction. We set the reactions to run between either lower/mid, mid/upper, or lower/upper depending on whether the ...
in_media = False override = False # if we have external compounds that are not in the media, we don't want to run this as a media reaction for c in reactions[r].left_compounds: if c.location == 'e': if c in media: in_media =...
perhaps we should add a test for that. """ if False and (reactions[r].is_uptake_secretion or reactions[r].is_transport or reactions[r].is_input_reaction()):
random_line_split
bounds.py
import sys from PyFBA import lp, log_and_message def reaction_bounds(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False): """ Set the bounds for each reaction. We set the reactions to run between either lower/mid, mid/upper, or lower/upper depending on whether the ...
elif direction == "<": # This is what I think it should be: # rbvals[r] = (lower, mid) rbvals[r] = (lower, upper) else: sys.stderr.write("DO NOT UNDERSTAND DIRECTION " + direction + " for " + r + "\n") rbvals[r] = (mid, upper) if verbose:...
rbvals[r] = (mid, upper) # rbvals[r] = (lower, upper)
conditional_block
bounds.py
import sys from PyFBA import lp, log_and_message def reaction_bounds(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False):
rbvals = {} media_uptake_secretion_count = 0 other_uptake_secretion_count = 0 for r in reactions_with_upsr: if r == 'BIOMASS_EQN': rbvals[r] = (mid, upper) continue # if we already know the bounds, eg from an SBML file or from our uptake/secretion reactions ...
""" Set the bounds for each reaction. We set the reactions to run between either lower/mid, mid/upper, or lower/upper depending on whether the reaction runs <=, =>, or <=> respectively. :param reactions: The dict of all reactions we know about :type reactions: dict of metabolism.Reaction :param...
identifier_body
bounds.py
import sys from PyFBA import lp, log_and_message def
(reactions, reactions_with_upsr, media, lower=-1000.0, mid=0.0, upper=1000.0, verbose=False): """ Set the bounds for each reaction. We set the reactions to run between either lower/mid, mid/upper, or lower/upper depending on whether the reaction runs <=, =>, or <=> respectively. :param reactions: T...
reaction_bounds
identifier_name
ethstore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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) any later version....
} try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl SecretStore for EthStore { fn insert_account(&self, secret: Secret, password: &str) -> Result<Address, Error> { let keypair = try!(KeyPair::from_secret(secret).map_err(|_| Error...
{ return Ok(account.clone()) }
conditional_block
ethstore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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) any later version....
import::import_geth_accounts(&*self.dir, desired.into_iter().collect(), testnet) } }
random_line_split
ethstore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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) any later version....
fn get(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } ...
{ let mut cache = self.cache.write(); let accounts = try!(self.dir.load()); let new_accounts: BTreeMap<_, _> = accounts.into_iter().map(|account| (account.address.clone(), account)).collect(); mem::replace(&mut *cache, new_accounts); Ok(()) }
identifier_body
ethstore.rs
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity 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) any later version....
(&self, address: &Address) -> Result<SafeAccount, Error> { { let cache = self.cache.read(); if let Some(account) = cache.get(address) { return Ok(account.clone()) } } try!(self.reload_accounts()); let cache = self.cache.read(); cache.get(address).cloned().ok_or(Error::InvalidAccount) } } impl S...
get
identifier_name
ClientHintIssue.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as i18n from '../../core/i18n/i18n.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as Protocol from '../../generated/protocol.js...
getCategory(): IssueCategory { return IssueCategory.Other; } details(): Protocol.Audits.ClientHintIssueDetails { return this.issueDetails; } getDescription(): MarkdownIssueDescription|null { const description = issueDescriptions.get(this.issueDetails.clientHintIssueReason); if (!descriptio...
{ super( { code: Protocol.Audits.InspectorIssueCode.ClientHintIssue, umaCode: [Protocol.Audits.InspectorIssueCode.ClientHintIssue, issueDetails.clientHintIssueReason].join('::'), }, issuesModel); this.issueDetails = issueDetails; }
identifier_body
ClientHintIssue.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as i18n from '../../core/i18n/i18n.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as Protocol from '../../generated/protocol.js...
if (!description) { return null; } return resolveLazyDescription(description); } sources(): Iterable<Protocol.Audits.SourceCodeLocation> { return [this.issueDetails.sourceCodeLocation]; } primaryKey(): string { return JSON.stringify(this.issueDetails); } getKind(): IssueKind { ...
return this.issueDetails; } getDescription(): MarkdownIssueDescription|null { const description = issueDescriptions.get(this.issueDetails.clientHintIssueReason);
random_line_split
ClientHintIssue.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as i18n from '../../core/i18n/i18n.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as Protocol from '../../generated/protocol.js...
return [new ClientHintIssue(details, issuesModel)]; } } const issueDescriptions: Map<Protocol.Audits.ClientHintIssueReason, LazyMarkdownIssueDescription> = new Map([ [ Protocol.Audits.ClientHintIssueReason.MetaTagAllowListInvalidOrigin, { file: 'clientHintMetaTagAllowListInvalidOrigin.md', ...
{ console.warn('Client Hint issue without details received.'); return []; }
conditional_block
ClientHintIssue.ts
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. import * as i18n from '../../core/i18n/i18n.js'; import type * as SDK from '../../core/sdk/sdk.js'; import * as Protocol from '../../generated/protocol.js...
(): IssueCategory { return IssueCategory.Other; } details(): Protocol.Audits.ClientHintIssueDetails { return this.issueDetails; } getDescription(): MarkdownIssueDescription|null { const description = issueDescriptions.get(this.issueDetails.clientHintIssueReason); if (!description) { retu...
getCategory
identifier_name
UIService.ts
import _ from '../utils/underscore'; type axis = string | boolean; type state = { clientRect?: ClientRect, documentWidth?: number, documentHeight?: number, startStyleLeft?: number, startStyleTop?: number, startStyleRight?: number, startStyleBottom?: number, startClientY?: number, s...
return Array.from(div.children); } static createElementFromHTML(htmlString: string, context?: Object): Element { return this.createElementsFromHTML(htmlString, context)[0]; } }
div.innerHTML = innerHTML;
random_line_split
UIService.ts
import _ from '../utils/underscore'; type axis = string | boolean; type state = { clientRect?: ClientRect, documentWidth?: number, documentHeight?: number, startStyleLeft?: number, startStyleTop?: number, startStyleRight?: number, startStyleBottom?: number, startClientY?: number, s...
(axis: axis): Array<string> { return !axis ? ['left', 'top'] : (axis === 'x' ? ['left'] : (axis === 'y' ? ['top'] : (console.warn('Unexpected value of axis'), ['left', 'top']))); } static draggable( { el, start, sto...
__getDefaultsSetProperties
identifier_name
UIService.ts
import _ from '../utils/underscore'; type axis = string | boolean; type state = { clientRect?: ClientRect, documentWidth?: number, documentHeight?: number, startStyleLeft?: number, startStyleTop?: number, startStyleRight?: number, startStyleBottom?: number, startClientY?: number, s...
static getTransitionDurationMilliseconds(el: HTMLElement): number { const transitionDuration = getComputedStyle(el).transitionDuration; const isSeconds = /^(\d)+\.*(\d)*s$/.test(transitionDuration); const isMilliseconds = /^(\d)+ms$/.test(transitionDuration); if (isSeconds && !isM...
{ if (onStart) { el.removeEventListener('pointerdown', onStart); } }
identifier_body
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, ...
// to prevent orphaned processes. let pgid = unsafe { libc::getpgid(self.pid) }; if self.pid == pgid { debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to t...
// if it is the root process of the process group // we send our signals to the entire process group
random_line_split
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, ...
// JW TODO: Determine if the error represents a case where the // process was already exited before we return out and assume // so. trace!("Sending {:?} signal to process {}", shutdown_signal, pid_to_kill); #[allow(clippy::question_mark)] i...
{ debug!("pid to kill {} is the process group root. Sending signal to process group.", self.pid); // sending a signal to the negative pid sends it to the // entire process group instead just the single pid pid_to_kill = self.pid.neg(); }
conditional_block
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, ...
{ pid: pid_t, } impl Process { fn new(pid: Pid) -> Self { Process { pid } } /// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { si...
Process
identifier_name
service.rs
// NOTE: All this code is basically copied verbatim from its previous home in // the Launcher module. Once all the service-related functionality that we're // going to move over to the Supervisor has been moved, we can take a look at // perhaps refactoring some of this a bit. use crate::{manager::ShutdownConfig, ...
/// Attempt to gracefully terminate a proccess and then forcefully /// kill it after 8 seconds if it has not terminated. fn kill(&self, shutdown_config: &ShutdownConfig) -> ShutdownMethod { let ShutdownConfig { signal: shutdown_signal, timeout, } = *shutdown_config; ...
{ Process { pid } }
identifier_body
imageLoader.ts
import {celm} from "./canvas"; type Data = [number, number, () => void]; const datas: Data[] = []; export const images: HTMLImageElement[] = []; export function loadPrerender(id: number, w: number, h: number, cb: () => void) { datas[id] = [w, h, cb]; } // export function loadImageSrc(id: number, dataURL: string) ...
}; for (let i = 0; i < datas.length; ++i) { const d = datas[i]; if (!d) { images[i] = null; ++numloaded; continue; } images[i] = new Image(); images[i].onload = imageOnloadCallback; celm.width = d[0]; celm.height = d[1]; d[2](); images[i].src = celm.toDataURL()...
{ cb(); }
conditional_block
imageLoader.ts
import {celm} from "./canvas"; type Data = [number, number, () => void]; const datas: Data[] = []; export const images: HTMLImageElement[] = []; export function loadPrerender(id: number, w: number, h: number, cb: () => void) { datas[id] = [w, h, cb]; } // export function loadImageSrc(id: number, dataURL: string) ...
(cb: () => void) { let numloaded = 0; const imageOnloadCallback = () => { ++numloaded; if (numloaded === datas.length) { cb(); } }; for (let i = 0; i < datas.length; ++i) { const d = datas[i]; if (!d) { images[i] = null; ++numloaded; continue; } images[i] = ne...
onload
identifier_name
imageLoader.ts
import {celm} from "./canvas"; type Data = [number, number, () => void]; const datas: Data[] = []; export const images: HTMLImageElement[] = []; export function loadPrerender(id: number, w: number, h: number, cb: () => void) { datas[id] = [w, h, cb]; } // export function loadImageSrc(id: number, dataURL: string) ...
playerGun, gunlv1, gunlv2, gunlv3, UFOHit, UFO, last_UFO = UFO + 20, // there are around 10-20 kind of UFO BigHFOHit, BigUFO, last_BigUFO = BigUFO + 20, earthSurface, // moonSurface, // alienPlanetSurface, alienPlanetSurfaceWithShield, neptuneSurface, uranusSurface, saturnSurface, ju...
export const enum ImagesId {
random_line_split
imageLoader.ts
import {celm} from "./canvas"; type Data = [number, number, () => void]; const datas: Data[] = []; export const images: HTMLImageElement[] = []; export function loadPrerender(id: number, w: number, h: number, cb: () => void)
// export function loadImageSrc(id: number, dataURL: string) { // datas[id] = dataURL; // } export function onload(cb: () => void) { let numloaded = 0; const imageOnloadCallback = () => { ++numloaded; if (numloaded === datas.length) { cb(); } }; for (let i = 0; i < datas.length; ++i) { ...
{ datas[id] = [w, h, cb]; }
identifier_body
WebpackOptionsDefaulter.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var OptionsDefaulter = require("./OptionsDefaulter"); var Template = require("./Template"); function WebpackOptionsDefaulter() { OptionsDefaulter.call(this); this.set("devtool", false); this.set("cache", tr...
WebpackOptionsDefaulter.prototype = Object.create(OptionsDefaulter.prototype); WebpackOptionsDefaulter.prototype.constructor = WebpackOptionsDefaulter;
random_line_split
WebpackOptionsDefaulter.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var OptionsDefaulter = require("./OptionsDefaulter"); var Template = require("./Template"); function
() { OptionsDefaulter.call(this); this.set("devtool", false); this.set("cache", true); this.set("context", process.cwd()); this.set("target", "web"); this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRecursive", true); thi...
WebpackOptionsDefaulter
identifier_name
WebpackOptionsDefaulter.js
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Tobias Koppers @sokra */ var OptionsDefaulter = require("./OptionsDefaulter"); var Template = require("./Template"); function WebpackOptionsDefaulter()
this.set("module.unsafeCache", true); this.set("output", "call", function(value, options) { if(typeof value === "string") { return { filename: value }; } else if(typeof value !== "object") { return {}; } else { return value; } }); this.set("output.filename", "[name].js"); thi...
{ OptionsDefaulter.call(this); this.set("devtool", false); this.set("cache", true); this.set("context", process.cwd()); this.set("target", "web"); this.set("module.unknownContextRequest", "."); this.set("module.unknownContextRegExp", false); this.set("module.unknownContextRecursive", true); this.s...
identifier_body
autotest-tw-solver.py
#!/usr/bin/env python3 """ Automatically test a given treewidth solver: ./autotest-tw-solver.py path/to/my/solver The test is run on some corner cases, and on graphs were past PACE submissions exhibited bugs. Optional argument: --full run test on all graphs with min-degree 3 and at most 8 vertices Require...
# More test cases where some tw-solvers were buggy in the past tests = ["test/tw-solver-bugs.graph6"] if full: tests.append("test/n_upto_8.graph6") for fname in tests: with open(fname) as tests: for line in tests: line = line.strip().split(" ") ...
treewidth = None with open(grfile[:-3] + ".td") as td_stream: treewidth = read_tw_from_td(td_stream) yield grfile, open(grfile, "r"), treewidth
conditional_block
autotest-tw-solver.py
#!/usr/bin/env python3 """ Automatically test a given treewidth solver: ./autotest-tw-solver.py path/to/my/solver The test is run on some corner cases, and on graphs were past PACE submissions exhibited bugs. Optional argument: --full run test on all graphs with min-degree 3 and at most 8 vertices Require...
ifstream.seek(0) tmp_td.flush() tmp_td.seek(0) print(name) valid = td_validate(ifstream, tmp_td) ifstream.close() tmp_td.seek(0) computed_tw = read_tw_from_td(tmp_td) if treewidth != None and computed_tw != None: if treewidth > comput...
try: p.wait(timeout=5) except subprocess.TimeoutExpired: p.kill()
random_line_split
autotest-tw-solver.py
#!/usr/bin/env python3 """ Automatically test a given treewidth solver: ./autotest-tw-solver.py path/to/my/solver The test is run on some corner cases, and on graphs were past PACE submissions exhibited bugs. Optional argument: --full run test on all graphs with min-degree 3 and at most 8 vertices Require...
(grstream, tdstream): with tempfile.NamedTemporaryFile("w+") as tmp_td: for line in tdstream: tmp_td.write(line) tmp_td.flush() tmp_td.seek(0) with tempfile.NamedTemporaryFile("w+") as tmp_gr: for line in grstream: tmp_gr.write(line) ...
td_validate
identifier_name
autotest-tw-solver.py
#!/usr/bin/env python3 """ Automatically test a given treewidth solver: ./autotest-tw-solver.py path/to/my/solver The test is run on some corner cases, and on graphs were past PACE submissions exhibited bugs. Optional argument: --full run test on all graphs with min-degree 3 and at most 8 vertices Require...
ifstream.seek(0) tmp_td.flush() tmp_td.seek(0) print(name) valid = td_validate(ifstream, tmp_td) ifstream.close() tmp_td.seek(0) computed_tw = read_tw_from_td(tmp_td) if treewidth != None and computed_tw != None: if treewidth > comput...
"""given the name of a testcase, the input stream for a .gr file, and the correct treewidth, this function runs the test""" global tw_executable name, ifstream, treewidth = arg with tempfile.TemporaryFile("w+") as tmp_td: p = subprocess.Popen( [tw_executable], stdin=ifstream, stdou...
identifier_body
utils.rs
_f64(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]) -> R...
assert!(parse_iso_8601_duration(b"T3S").err().is_some()); assert!(parse_iso_8601_duration(b"P3S").err().is_some()); }
random_line_split
utils.rs
(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]) -> Resul...
parse_f64
identifier_name
utils.rs
parse_f64(value : &[u8]) -> Result<f64> { let res = std::str::from_utf8(value)?; let res_f64 = res.parse::<f64>()?; Ok(res_f64 as f64) } /// Try to parse the given array of bytes into an i64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_i64(value : &[u8]...
/// Try to parse the given array of bytes into an u64, by first converting /// it to the corresponding ASCII (or even here, UTF-8) values. pub fn parse_u64(value : &[u8]) -> Result<u64> { let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<u64>()?; Ok(res_u64) } /// Try to parse the given ar...
{ let res = std::str::from_utf8(value)?; let res_u64 = res.parse::<i64>()?; Ok(res_u64) }
identifier_body
repository_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os import sys import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.buildbot import rep...
cros_test_lib.main()
conditional_block
repository_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os import sys import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.buildbot import rep...
if __name__ == '__main__': cros_test_lib.main()
"""Test that Re-init works with the chrome-bot account. In testing, repo init behavior on the buildbots is different from a local run, because there is some logic in 'repo' that filters changes based on GIT_COMMITTER_IDENT. So for sanity's sake, try to emulate running on the buildbots. """ def setUp(self)...
identifier_body
repository_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os import sys import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.buildbot import rep...
(cros_test_lib.MoxTestCase): def RunCommand_Mock(self, result, *args, **kwargs): output = self.mox.CreateMockAnything() output.output = result return output def testExternalRepoCheckout(self): """Test we detect external checkouts properly.""" self.mox.StubOutWithMock(cros_build_lib, 'RunComman...
RepositoryTests
identifier_name
repository_unittest.py
#!/usr/bin/python # Copyright (c) 2012 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import functools import os import sys
from chromite.lib import cros_test_lib # pylint: disable=W0212,R0904,E1101,W0613 class RepositoryTests(cros_test_lib.MoxTestCase): def RunCommand_Mock(self, result, *args, **kwargs): output = self.mox.CreateMockAnything() output.output = result return output def testExternalRepoCheckout(self): ""...
import constants sys.path.insert(0, constants.SOURCE_ROOT) from chromite.buildbot import repository from chromite.lib import cros_build_lib
random_line_split
regions-glb-free-free.rs
// Copyright 2012 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 ...
<'r>(name: &'r str, desc: &'r str) -> Flag<'r> { Flag { name: name, desc: desc, max_count: 1, value: 0 } } pub impl<'self> Flag<'self> { fn set_desc(self, s: &str) -> Flag<'self> { Flag { //~ ERROR cannot infer an appropriate lifetime name: self.name, ...
flag
identifier_name
regions-glb-free-free.rs
// Copyright 2012 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 ...
{ let f : argparse::Flag = argparse::flag(~"flag", ~"My flag"); let updated_flag = f.set_desc(~"My new flag"); assert!(updated_flag.desc == "My new flag"); }
identifier_body
regions-glb-free-free.rs
// Copyright 2012 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 ...
Flag { name: name, desc: desc, max_count: 1, value: 0 } } pub impl<'self> Flag<'self> { fn set_desc(self, s: &str) -> Flag<'self> { Flag { //~ ERROR cannot infer an appropriate lifetime name: self.name, desc: s, max_count: self.max_cou...
} pub fn flag<'r>(name: &'r str, desc: &'r str) -> Flag<'r> {
random_line_split
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
{ match res { Ok(None) => Err(Error::NotFoundErr), Ok(Some(o)) => Ok(o), Err(e) => Err(e), } }
identifier_body
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
<'a> { store: &'a Store, batch: WriteBatch, } impl<'a> Batch<'a> { /// Writes a single key and its `Writeable` value to the batch. The write /// function must be called to "commit" the batch to storage. pub fn put_ser<W: ser::Writeable>(mut self, key: &[u8], value: &W) -> Result<Batch<'a>, Error> { let ser_valu...
Batch
identifier_name
lib.rs
// Copyright 2016 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agree...
// limitations under the License. //! Storage of core types using RocksDB. #![deny(non_upper_case_globals)] #![deny(non_camel_case_types)] #![deny(non_snake_case)] #![deny(unused_mut)] #![warn(missing_docs)] extern crate byteorder; extern crate grin_core as core; extern crate rocksdb; const SEP: u8 = ':' as u8; us...
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and
random_line_split
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Fo...
(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unsupported bit flag value 0b{:b} (unknown flags: 0b{:b})", self.actual(), self.unknown()) } } impl fmt::Debug for UnknownFlags { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "UnknownFlags {{ actual: ...
fmt
identifier_name
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Fo...
pub fn known(&self) -> guint { self.actual & self.known_mask } } pub mod prelude { pub use super::{IntrospectedFlags, FlagsType, UnknownFlags}; pub use gtype::GType; pub use types::guint; } impl ErrorTrait for UnknownFlags { fn description(&self) -> &str { "unknown bit flags encountered" ...
{ self.actual & !self.known_mask }
identifier_body
flags.rs
// This file is part of Grust, GObject introspection bindings for Rust // // Copyright (C) 2015 Mikhail Zabaluev <mikhail.zabaluev@gmail.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Fo...
#[derive(Copy, Clone)] pub struct UnknownFlags { actual: guint, known_mask: guint } impl UnknownFlags { pub fn new(flags: guint, known_mask: guint) -> UnknownFlags { UnknownFlags { actual: flags, known_mask: known_mask } } pub fn actual(&self) -> guint { self.actual } pub fn unknown(&s...
random_line_split
case_list.py
from django.utils.translation import ugettext as _ from memoized import memoized from corehq.apps.locations.permissions import location_safe from .users import EmwfUtils, ExpandedMobileWorkerFilter class CaseListFilterUtils(EmwfUtils): def sharing_group_tuple(self, g): return ("sg__%s" % g['_id'], '%s...
return reporting + sharing def get_default_selections(self): if self.request.can_access_all_locations: return self.default_selections else: return self._get_assigned_locations_default()
sharing.append(self.utils.sharing_group_tuple(group))
conditional_block
case_list.py
from django.utils.translation import ugettext as _ from memoized import memoized from corehq.apps.locations.permissions import location_safe from .users import EmwfUtils, ExpandedMobileWorkerFilter class CaseListFilterUtils(EmwfUtils): def sharing_group_tuple(self, g): return ("sg__%s" % g['_id'], '%s...
from corehq.apps.reports.models import HQUserType return "t__{}".format(HQUserType.DEACTIVATED) in mobile_user_and_group_slugs @staticmethod def selected_sharing_group_ids(mobile_user_and_group_slugs): return [g[4:] for g in mobile_user_and_group_slugs if g.startswith("sg__")] @cla...
return 'project_data' in mobile_user_and_group_slugs @staticmethod def show_deactivated_data(mobile_user_and_group_slugs):
random_line_split
case_list.py
from django.utils.translation import ugettext as _ from memoized import memoized from corehq.apps.locations.permissions import location_safe from .users import EmwfUtils, ExpandedMobileWorkerFilter class CaseListFilterUtils(EmwfUtils): def sharing_group_tuple(self, g): return ("sg__%s" % g['_id'], '%s...
(self, mobile_user_and_group_slugs): query_results = self._selected_groups_query(mobile_user_and_group_slugs) reporting_group_ids = self.selected_reporting_group_ids(mobile_user_and_group_slugs) sharing_group_ids = self.selected_sharing_group_ids(mobile_user_and_group_slugs) reporting =...
_selected_group_entries
identifier_name
case_list.py
from django.utils.translation import ugettext as _ from memoized import memoized from corehq.apps.locations.permissions import location_safe from .users import EmwfUtils, ExpandedMobileWorkerFilter class CaseListFilterUtils(EmwfUtils): def sharing_group_tuple(self, g): return ("sg__%s" % g['_id'], '%s...
@staticmethod def show_all_data(mobile_user_and_group_slugs): return 'all_data' in mobile_user_and_group_slugs @staticmethod def show_project_data(mobile_user_and_group_slugs): return 'project_data' in mobile_user_and_group_slugs @staticmethod def show_deactivated_data(mobile...
return CaseListFilterUtils(self.domain)
identifier_body
cloudstack.py
renemoser.net> # # This file is part of Ansible, # # Ansible 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) any later version. # # Ansible is distributed...
self, domain): domains = self.cs.listDomains(listall=True) if domains: for d in domains['domain']: if d['path'].lower() == domain.lower(): return d['id'] print("Error: Domain %s not found." % domain, file=sys.stderr) sys.exit(1) def ge...
et_domain_id(
identifier_name
cloudstack.py
renemoser.net> # # This file is part of Ansible, # # Ansible 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) any later version. # # Ansible is distributed...
print("Error: Project %s not found." % project, file=sys.stderr) sys.exit(1) def get_host(self, name, project_id=None, domain_id=None): hosts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id) data = {} if not hosts: return data for ...
eturn p['id']
conditional_block
cloudstack.py
renemoser.net> # # This file is part of Ansible, # # Ansible 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) any later version. # # Ansible is distributed...
data['hypervisor'] = host['hypervisor'] data['created'] = host['created'] data['nic'] = [] for nic in host['nic']: data['nic'].append({ 'ip': nic['ipaddress'], 'mac': nic['macaddress'], ...
osts = self.cs.listVirtualMachines(projectid=project_id, domainid=domain_id) data = {} if not hosts: return data for host in hosts['virtualmachine']: host_name = host['displayname'] if name == host_name: data['zone'] = host['zonename'] ...
identifier_body
cloudstack.py
renemoser.net> # # This file is part of Ansible, # # Ansible 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) any later version. # # Ansible is distributed...
if 'group' in host: data['_meta']['hostvars'][host_name]['group'] = host['group'] data['_meta']['hostvars'][host_name]['state'] = host['state'] data['_meta']['hostvars'][host_name]['service_offering'] = host['serviceofferingname'] data['_meta']['hostvars'...
if group_name not in data: data[group_name] = { 'hosts': [] } data[group_name]['hosts'].append(host_name)
random_line_split
test_copy_package_category.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test copying a package category in the library editor """ def test(library_editor, helpers):
# Check metadata widget_properties = { ('NameEdit', 'text'): 'C-SMT', ('DescriptionEdit', 'plainText'): '', ('KeywordsEdit', 'text'): '', ('VersionEdit', 'text'): '0.1', } for (widget, property), value in widget_properties.items(): props = le.widget('libraryEdito...
""" Copy package category with "New Library Element" wizard """ le = library_editor # Open "New Library Element" wizard le.action('libraryEditorActionNewElement').trigger(blocking=False) # Choose "Copy existing element" le.widget('libraryEditorNewElementWizardChooseTypeCopyRadioButton').se...
identifier_body
test_copy_package_category.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test copying a package category in the library editor """ def test(library_editor, helpers): """ Copy package category with "New Library Element" wizard """ le = library_editor # Open "New Library Element" wizard le.action('libraryEditorActio...
# Finish dialog = le.widget('libraryEditorNewElementWizard') le.widget('libraryEditorNewElementWizardFinishButton').click() helpers.wait_until_widget_hidden(dialog) # Check if a new tab is opened (indicates that the element was created) tab_props = le.widget('libraryEditorStackedWidget').prop...
props = le.widget('libraryEditorNewElementWizardMetadata' + widget).properties() assert props[property] == value
conditional_block