file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
canvas.py
#!/usr/bin/python2.4 # vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab # # $Id$ # # Copyright (C) 1999-2006 Keith Dart <keith@kdart.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...
win.set_title('Canvas test') canvas = GnomeCanvas() canvas.set_size(300, 300) win.add(canvas) canvas.show() canvas.root().add('line', points=(10,10, 90,10, 90,90, 10,90), width_pixels=10, fill_color='blue') win.show() mainloop()
win.connect('destroy', mainquit)
random_line_split
if_match.rs
use header::EntityTag; header! { #[doc="`If-Match` header, defined in"] #[doc="[RFC7232](https://tools.ietf.org/html/rfc7232#section-3.1)"] #[doc=""] #[doc="The `If-Match` header field makes the request method conditional on"] #[doc="the recipient origin server either having at least one current"] ...
test_header!( test2, vec![b"\"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\""], Some(HeaderField::Items( vec![EntityTag::new(false, "xyzzy".to_owned()), EntityTag::new(false, "r2d2xxxx".to_owned()), EntityTag::new(false, "c3pioz...
test_header!( test1, vec![b"\"xyzzy\""], Some(HeaderField::Items( vec![EntityTag::new(false, "xyzzy".to_owned())])));
random_line_split
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use hsts::{HSTSList, secure_u...
{ let (progress_chan, mut chunk) = { let buf = match read_block(reader) { Ok(ReadResult::Payload(buf)) => buf, _ => vec!(), }; let p = match start_sending_sniffed_opt(start_chan, metadata, classifier, &buf) { Ok(p) => p, _ => return }; ...
identifier_body
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use hsts::{HSTSList, secure_u...
// See https://bugzilla.mozilla.org/show_bug.cgi?id=401564 and // https://bugzilla.mozilla.org/show_bug.cgi?id=216828 . // Only preserve ones which have been explicitly marked as such. if iters == 1 { let mut combined_headers = load_data.headers.clone(); combined_...
// Avoid automatically preserving request headers when redirects occur.
random_line_split
http_loader.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use devtools_traits::{ChromeToDevtoolsControlMsg, DevtoolsControlMsg, NetworkEvent}; use hsts::{HSTSList, secure_u...
(url: Url, err: String, start_chan: LoadConsumer) { let mut metadata: Metadata = Metadata::default(url); metadata.status = None; match start_sending_opt(start_chan, metadata) { Ok(p) => p.send(Done(Err(err))).unwrap(), _ => {} }; } enum ReadResult { Payload(Vec<u8>), EOF, } fn...
send_error
identifier_name
lt.js
var convert = require('./convert'), func = convert('lt', require('../lt')); func.placeholder = require('./placeholder'); module.exports = func; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL2NsaWVudC9saWIvbG9kYXNoL2ZwL2x0LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O...
'use strict';
random_line_split
touch_helper.py
# Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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 3 of the License, or # (at your option) any later vers...
""" Launch short func if needed @param widget as Gtk.Widget @param event as Gdk.Event """ # Ignore this release event, long func called if self.__timeout_id == Type.NONE: self.__timeout_id = None return True elif self.__timeout_...
identifier_body
touch_helper.py
# Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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 3 of the License, or # (at your option) any later vers...
if event is None or event.button == 1: self.__short_func(self.__short_args) else: self.__long_func(self.__long_args) return True
GLib.source_remove(self.__timeout_id) self.__timeout_id = None
conditional_block
touch_helper.py
# Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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 3 of the License, or # (at your option) any later vers...
def __on_button_press(self, widget, event): """ Launch long func @param widget as Gtk.Widget @param event as Gdk.Event """ self.__timeout_id = GLib.timeout_add(500, self.__launch_long_func) return True ...
@param action as Gio.SimpleAction @param param as GLib.Variant """ self.__short_func(self.__short_args)
random_line_split
touch_helper.py
# Copyright (c) 2014-2017 Cedric Bellegarde <cedric.bellegarde@adishatz.org> # 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 3 of the License, or # (at your option) any later vers...
(self, action, param): """ Launch short func @param action as Gio.SimpleAction @param param as GLib.Variant """ self.__short_func(self.__short_args) def __on_button_press(self, widget, event): """ Launch long func @param wi...
__on_action_activate
identifier_name
lib.rs
extern crate hyper; extern crate url; extern crate serde; extern crate serde_json; extern crate hyper_native_tls; #[macro_use] extern crate lazy_static; use hyper::client::{Client}; use hyper::header::{ContentType}; use hyper::client::response::{Response}; use hyper::error::Error as HyperError; use url::form_urlencode...
let opt_result = json.get("status"); let result = match opt_result { Some(result) => result, None => return Err(CleverbotError::MissingValue(String::from("status"))), }; match result.as_ref() { "success" => { let json_nick = json.get("n...
}; let mut body = String::new(); try!(response.read_to_string(&mut body)); let json: BTreeMap<String, String> = try!(serde_json::from_str(&body));
random_line_split
lib.rs
extern crate hyper; extern crate url; extern crate serde; extern crate serde_json; extern crate hyper_native_tls; #[macro_use] extern crate lazy_static; use hyper::client::{Client}; use hyper::header::{ContentType}; use hyper::client::response::{Response}; use hyper::error::Error as HyperError; use url::form_urlencode...
} impl From<JsonError> for CleverbotError { fn from(err: JsonError) -> CleverbotError { CleverbotError::Json(err) } } pub struct Cleverbot { user: String, key: String, pub nick: String, } lazy_static! { static ref CLIENT: Client = Client::with_connector(HttpsConnector::new(NativeTlsC...
{ CleverbotError::Std(err) }
identifier_body
lib.rs
extern crate hyper; extern crate url; extern crate serde; extern crate serde_json; extern crate hyper_native_tls; #[macro_use] extern crate lazy_static; use hyper::client::{Client}; use hyper::header::{ContentType}; use hyper::client::response::{Response}; use hyper::error::Error as HyperError; use url::form_urlencode...
(err: JsonError) -> CleverbotError { CleverbotError::Json(err) } } pub struct Cleverbot { user: String, key: String, pub nick: String, } lazy_static! { static ref CLIENT: Client = Client::with_connector(HttpsConnector::new(NativeTlsClient::new().unwrap())); } impl Cleverbot { /// Crea...
from
identifier_name
cursors.py
"""MySQLdb Cursors This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ import re import sys try: from types import ListType, TupleType, UnicodeType except ImportError: # Python 3 ListType = list TupleType = tuple UnicodeType = str restr = r...
return args def _do_query(self, q): db = self._get_db() self._last_executed = q db.query(q) self._do_get_result() return self.rowcount def _query(self, q): return self._do_query(q) def _fetch_row(self, size=1): if not self._result: ...
self._warning_check()
conditional_block
cursors.py
"""MySQLdb Cursors This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ import re import sys try: from types import ListType, TupleType, UnicodeType except ImportError: # Python 3 ListType = list TupleType = tuple UnicodeType = str restr = r...
class DictCursor(CursorStoreResultMixIn, CursorDictRowsMixIn, BaseCursor): """This is a Cursor class that returns rows as dictionaries and stores the result set in the client.""" class SSCursor(CursorUseResultMixIn, CursorTupleRowsMixIn, BaseCursor): """This is a C...
"""This is the standard Cursor class that returns rows as tuples and stores the result set in the client."""
identifier_body
cursors.py
"""MySQLdb Cursors This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ import re import sys try: from types import ListType, TupleType, UnicodeType except ImportError: # Python 3 ListType = list TupleType = tuple UnicodeType = str restr = r...
(self, size=None): """Fetch up to size rows from the cursor. Result set may be smaller than size. If size is not defined, cursor.arraysize is used.""" self._check_executed() end = self.rownumber + (size or self.arraysize) result = self._rows[self.rownumber:end] self.rownu...
fetchmany
identifier_name
cursors.py
"""MySQLdb Cursors This module implements Cursors of various types for MySQLdb. By default, MySQLdb uses the Cursor class. """ import re import sys try: from types import ListType, TupleType, UnicodeType except ImportError: # Python 3 ListType = list TupleType = tuple UnicodeType = str restr = r...
procname -- string, name of procedure to execute on server args -- Sequence of parameters to use with procedure Returns the original args. Compatibility warning: PEP-249 specifies that any modified parameters must be returned. This is currently impossible as they are o...
"""Execute stored procedure procname with args
random_line_split
mod.rs
// Root Module // // This file is part of AEx. // Copyright (C) 2017 Jeffrey Sharp // // AEx 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 ...
pub mod fmt; pub mod io; //pub mod source; pub mod target; //pub mod types;
pub mod ast;
random_line_split
index.js
//Execution function $('document').ready(function () { "use strict"; //introduction jeu intro.js intro(); $('.sound').click(function () { if (sonOn) { sonOn = false; $(this).html('Sound off') } else { sonOn = true; $(this).html('Sound on'...
}, 400) // Chargement du terrain field.creation().animate(); //Chargement des nuages creationNuage(); //chagement des objets Background creationBackground(); // crer un nouvel hero à l'aide de la fonction constructeur ! var perso = new ObjetRyu(); // Positionnement généra...
{ main.pause() }
conditional_block
index.js
//Execution function $('document').ready(function () { "use strict"; //introduction jeu intro.js intro(); $('.sound').click(function () { if (sonOn) { sonOn = false; $(this).html('Sound off') } else { sonOn = true; $(this).html('Sound on'...
// var Obstacle = [usineObstacle(0), usineObstacle(1), usineObstacle()]; creationObstacle(perso); ///// //Déplacement // ///// var container = document.getElementById('container'); var hammer = Hammer(container, { transform_always_block: true, tap_always: false, ...
random_line_split
autolink.ts
const videoConversion = [ // Videos [ /(?:(?:http|https):\/\/)?(?:www\.)?((?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\s&]+)([^\s]*))/g, '<a href="https://$1" target="_blank">$1</a><br /><div class="youtube-container"><div class="youtube-player" data-id="$2"><img class="youtube-thumb autoLi...
(match, link, protocol, www, domain, regexDotGroup, tld, port, filepath, fileExtension, getParams, endChar): string { const videoSearchLength = videoConversion.length; const videoSites = ["youtube", "youtu", "dailymotion", "vimeo"]; let output = link + endChar; if (videoSites.indexOf...
autoLinkFormat
identifier_name
autolink.ts
const videoConversion = [ // Videos [ /(?:(?:http|https):\/\/)?(?:www\.)?((?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\s&]+)([^\s]*))/g, '<a href="https://$1" target="_blank">$1</a><br /><div class="youtube-container"><div class="youtube-player" data-id="$2"><img class="youtube-thumb autoLi...
function parseMediaLink(output: string, link: string, endChar: string) { const imageExpression = /((\b((https?|ftp|file):\/\/)?[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\.(?:jpe?g|gif|png))/ig; const soundExpression = /((\b((https?|ftp|file):\/\/)?[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\.(?...
{ const videoSearchLength = videoConversion.length; const videoSites = ["youtube", "youtu", "dailymotion", "vimeo"]; let output = link + endChar; if (videoSites.indexOf(domain) > -1 && (typeof getParams !== "undefined" && getParams.length > 0 || domain === "youtu" && tld === ".be")) ...
identifier_body
autolink.ts
const videoConversion = [ // Videos [ /(?:(?:http|https):\/\/)?(?:www\.)?((?:youtube\.com|youtu\.be)\/(?:watch\?v=)?([^\s&]+)([^\s]*))/g, '<a href="https://$1" target="_blank">$1</a><br /><div class="youtube-container"><div class="youtube-player" data-id="$2"><img class="youtube-thumb autoLi...
output = link.replace(imageExpression, function(url) { if (url.indexOf("https") === -1) { return `<img class="autoLinkedImage" src="https://t.dark-gaming.com:3001/route/${encodeURIComponent(url)}"/>${endChar}`; } else { return `<img class="autoLinkedImage" src="${url}"/...
} function parseMediaLink(output: string, link: string, endChar: string) { const imageExpression = /((\b((https?|ftp|file):\/\/)?[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\.(?:jpe?g|gif|png))/ig; const soundExpression = /((\b((https?|ftp|file):\/\/)?[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])\.(...
random_line_split
message.py
"""Extension argument processing code """ __all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias', 'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvf...
return args def toArgs(self): """Return all namespaced arguments, failing if any non-namespaced arguments exist.""" # FIXME - undocumented exception post_args = self.toPostArgs() kvargs = {} for k, v in post_args.iteritems(): if not k.startswith(...
for (ns_uri, ns_key), value in self.args.iteritems(): key = self.getKey(ns_uri, ns_key) # Ensure the resulting value is an UTF-8 encoded bytestring. args[key] = oidutil.toUnicode(value).encode('UTF-8')
random_line_split
message.py
"""Extension argument processing code """ __all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias', 'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvf...
(self, namespace_uri): return self.isDefined(namespace_uri) def isImplicit(self, namespace_uri): return namespace_uri in self.implicit_namespaces
__contains__
identifier_name
message.py
"""Extension argument processing code """ __all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias', 'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvf...
if alias == NULL_NAMESPACE: ns_key = 'openid.ns' else: ns_key = 'openid.ns.' + alias args[ns_key] = oidutil.toUnicode(ns_uri).encode('UTF-8') for (ns_uri, ns_key), value in self.args.iteritems(): key = self.getKey(ns_uri, ns_key) ...
continue
conditional_block
message.py
"""Extension argument processing code """ __all__ = ['Message', 'NamespaceMap', 'no_default', 'registerNamespaceAlias', 'OPENID_NS', 'BARE_NS', 'OPENID1_NS', 'OPENID2_NS', 'SREG_URI', 'IDENTIFIER_SELECT'] import copy import warnings import urllib from openid import oidutil from openid import kvf...
def getArgs(self, namespace): """Get the arguments that are defined for this namespace URI @returns: mapping from namespaced keys to values @returntype: dict """ namespace = self._fixNS(namespace) return dict([ (ns_key, value) for ((pair_ns,...
"""Get a value for a namespaced key. @param namespace: The namespace in the message for this key @type namespace: str @param key: The key to get within this namespace @type key: str @param default: The value to use if this key is absent from this message. Using the...
identifier_body
filters.js
"use strict"; (function (Filter) { Filter[Filter["all"] = 9000] = "all"; Filter[Filter["audio"] = 1000] = "audio"; Filter[Filter["lossless"] = 1101] = "lossless"; Filter[Filter["mp3"] = 1102] = "mp3"; Filter[Filter["video"] = 2000] = "video"; Filter[Filter["tv"] = 2101] = "tv"; Filter[Filter...
return FilterCategory; }()); exports.FilterCategory = FilterCategory; //# sourceMappingURL=filters.js.map
{ this.filter = filter; this.checked = checked; }
identifier_body
filters.js
"use strict"; (function (Filter) { Filter[Filter["all"] = 9000] = "all"; Filter[Filter["audio"] = 1000] = "audio"; Filter[Filter["lossless"] = 1101] = "lossless"; Filter[Filter["mp3"] = 1102] = "mp3"; Filter[Filter["video"] = 2000] = "video"; Filter[Filter["tv"] = 2101] = "tv"; Filter[Filter...
(filter, checked) { this.filter = filter; this.checked = checked; } return FilterCategory; }()); exports.FilterCategory = FilterCategory; //# sourceMappingURL=filters.js.map
FilterCategory
identifier_name
filters.js
"use strict"; (function (Filter) { Filter[Filter["all"] = 9000] = "all";
Filter[Filter["dvdrip"] = 2102] = "dvdrip"; Filter[Filter["hdrip"] = 2103] = "hdrip"; Filter[Filter["dvd"] = 2104] = "dvd"; Filter[Filter["lq"] = 2105] = "lq"; Filter[Filter["ebooks"] = 3000] = "ebooks"; Filter[Filter["comics"] = 3101] = "comics"; Filter[Filter["magazines"] = 3102] = "magazi...
Filter[Filter["audio"] = 1000] = "audio"; Filter[Filter["lossless"] = 1101] = "lossless"; Filter[Filter["mp3"] = 1102] = "mp3"; Filter[Filter["video"] = 2000] = "video"; Filter[Filter["tv"] = 2101] = "tv";
random_line_split
sales-pipeline.js
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and...
* but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with EspoCRM. If not, see http://www.gnu.org/licenses/. ***...
random_line_split
sales-pipeline.js
/************************************************************************ * This file is part of EspoCRM. * * EspoCRM - Open Source CRM application. * Copyright (C) 2014 Yuri Kuznetsov, Taras Machyshyn, Oleksiy Avramenko * Website: http://www.espocrm.com * * EspoCRM is free software: you can redistribute it and...
} } return data; }, setup: function () { this.currency = this.getConfig().get('defaultCurrency'); this.currencySymbol = ''; var data = [ { value: 12000, stage: 'Prospecting' }, { value: 5050, stage: 'Qualification' }, { value: ...
{ this.maxY = y; }
conditional_block
loop-proper-liveness.rs
// Copyright 2015 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 ...
() { }
main
identifier_name
loop-proper-liveness.rs
// Copyright 2015 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 test3() { let x: i32; // Similarly, the use of variable `x` is unreachable. 'a: loop { x = loop { return }; } println!("{:?}", x); } fn main() { }
{ // In this test the `'a` loop will never terminate thus making the use of `x` unreachable. let x: i32; 'a: loop { x = loop { continue 'a }; } println!("{:?}", x); }
identifier_body
loop-proper-liveness.rs
// Copyright 2015 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 ...
}
} println!("{:?}", x); } fn main() {
random_line_split
SrvUnreadMessageCountCommandSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvUnreadMessageCountCommand } from "../commands/SrvUnreadMess...
public static deserialize(buffer: ArrayBufferBuilder, command: SrvUnreadMessageCountCommand ): void { PokerCommandHeaderSerializer.deserialize(buffer, command.header); command.data = new SrvUnreadMessageCountData(); SrvUnreadMessageCountDataSerializer.deserialize(buffer, command.data); } }
{ buffer.pointer += PokerCommandHeader.HEADER_SIZE_BYTES; SrvUnreadMessageCountDataSerializer.serialize(buffer, command.data); PokerCommandHeaderSerializer.serialize(buffer, command.header); }
identifier_body
SrvUnreadMessageCountCommandSerializer.ts
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvUnreadMessageCountCommand } from "../commands/SrvUnreadMess...
(buffer: ArrayBufferBuilder, command: SrvUnreadMessageCountCommand ): void { buffer.pointer += PokerCommandHeader.HEADER_SIZE_BYTES; SrvUnreadMessageCountDataSerializer.serialize(buffer, command.data); PokerCommandHeaderSerializer.serialize(buffer, command.header); } public static deserialize(buffer: Array...
serialize
identifier_name
SrvUnreadMessageCountCommandSerializer.ts
import { SrvUnreadMessageCountData } from "../data/SrvUnreadMessageCountData"; import { SrvUnreadMessageCountDataSerializer } from "./SrvUnreadMessageCountDataSerializer"; export class SrvUnreadMessageCountCommandSerializer { public static serialize(buffer: ArrayBufferBuilder, command: SrvUnreadMessageCountCommand )...
import { ArrayBufferBuilder } from "../../../../utils/ArrayBufferBuilder"; import { PokerCommandHeaderSerializer } from "../../core/serializers/PokerCommandHeaderSerializer"; import { PokerCommandHeader } from "../../core/data/PokerCommandHeader"; import { SrvUnreadMessageCountCommand } from "../commands/SrvUnreadMessa...
random_line_split
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::Status; fn test(uri: &str, expected: &str) { let client = Client::new(rocket()).unwrap(); let mut res = client.get(uri).dispatch(); assert_eq!(res.body_string(), Some(expected.into())); } fn test_404(uri: &str) { let client = Client::new(...
{ test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy"); test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob"); test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George"); test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd", "Person not found for U...
identifier_body
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::Status; fn test(uri: &str, expected: &str) { let client = Client::new(rocket()).unwrap(); let mut res = client.get(uri).dispatch(); assert_eq!(res.body_string(), Some(expected.into())); } fn test_404(uri: &str) {
assert_eq!(res.status(), Status::NotFound); } #[test] fn test_people() { test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy"); test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob"); test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George"); test("/pe...
let client = Client::new(rocket()).unwrap(); let res = client.get(uri).dispatch();
random_line_split
tests.rs
use super::rocket; use rocket::local::Client; use rocket::http::Status; fn test(uri: &str, expected: &str) { let client = Client::new(rocket()).unwrap(); let mut res = client.get(uri).dispatch(); assert_eq!(res.body_string(), Some(expected.into())); } fn test_404(uri: &str) { let client = Client::new(...
() { test("/people/7f205202-7ba1-4c39-b2fc-3e630722bf9f", "We found: Lacy"); test("/people/4da34121-bc7d-4fc1-aee6-bf8de0795333", "We found: Bob"); test("/people/ad962969-4e3d-4de7-ac4a-2d86d6d10839", "We found: George"); test("/people/e18b3a5c-488f-4159-a240-2101e0da19fd", "Person not found fo...
test_people
identifier_name
cvs.py
# CVS conversion code inspired by hg-cvs-import and git-cvsimport import os, locale, re, socket from cStringIO import StringIO from mercurial import util from common import NoRepo, commit, converter_source, checktool class convert_cvs(converter_source): def __init__(self, ui, path, rev=None): super(conve...
def _connect(self): root = self.cvsroot conntype = None user, host = None, None cmd = ['cvs', 'server'] self.ui.status("connecting to %s\n" % root) if root.startswith(":pserver:"): root = root[9:] m = re.match(r'(?:(.*?)(?::(.*?))?@)?([^:\/...
if self.changeset: return maxrev = 0 cmd = self.cmd if self.rev: # TODO: handle tags try: # patchset number? maxrev = int(self.rev) except ValueError: try: # date ...
identifier_body
cvs.py
# CVS conversion code inspired by hg-cvs-import and git-cvsimport import os, locale, re, socket from cStringIO import StringIO from mercurial import util from common import NoRepo, commit, converter_source, checktool class convert_cvs(converter_source): def __init__(self, ui, path, rev=None): super(conve...
return files
return self.tags def getchangedfiles(self, rev, i): files = self.files[rev].keys() files.sort()
random_line_split
cvs.py
# CVS conversion code inspired by hg-cvs-import and git-cvsimport import os, locale, re, socket from cStringIO import StringIO from mercurial import util from common import NoRepo, commit, converter_source, checktool class convert_cvs(converter_source): def __init__(self, ui, path, rev=None): super(conve...
(self): return self.tags def getchangedfiles(self, rev, i): files = self.files[rev].keys() files.sort() return files
gettags
identifier_name
cvs.py
# CVS conversion code inspired by hg-cvs-import and git-cvsimport import os, locale, re, socket from cStringIO import StringIO from mercurial import util from common import NoRepo, commit, converter_source, checktool class convert_cvs(converter_source): def __init__(self, ui, path, rev=None): super(conve...
def getfile(self, file, rev): data, mode = self._getfile(file, rev) self.modecache[(file, rev)] = mode return data def getmode(self, file, rev): return self.modecache[(file, rev)] def getchanges(self, rev): self.modecache = {} files = self.files[rev] ...
if line == "ok\n": return (data, "x" in mode and "x" or "") elif line.startswith("E "): self.ui.warn("cvs server: %s\n" % line[2:]) elif line.startswith("Remove"): l = self.readp.readline() l = self.readp.rea...
conditional_block
arcgis_press.js
/* * grunt-arcgis-press * https://github.com/agrc/grunt-arcgis-press * * Copyright (c) 2015 Steve Gourley & Scott Davis * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var PythonShell = require('python-shell'); var chalk = require('chalk'); var mixin = require('...
'A grunt task for covering your ArcGIS service publishing needs. Hot off the press!', function() { var done = this.async(); // create temp folder if needed var tempFolder = path.join(process.cwd(), '.grunt', 'grunt-arcgis-press'); if (!grunt.file.exists(t...
var Promise = require('promise'); var path = require('path'); grunt.registerMultiTask('arcgis_press',
random_line_split
arcgis_press.js
/* * grunt-arcgis-press * https://github.com/agrc/grunt-arcgis-press * * Copyright (c) 2015 Steve Gourley & Scott Davis * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { var PythonShell = require('python-shell'); var chalk = require('chalk'); var mixin = require('...
} Promise.all(promises).then(function() { done(); }, function() { done(false); }); }); };
{ promises.push(publishService(config.services[prop])); }
conditional_block
map.js
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
*/ jspb.Map.prototype.serializeBinary = function( fieldNumber, writer, keyWriterFn, valueWriterFn, opt_valueWriterCallback) { var strKeys = this.stringKeys_(); strKeys.sort(); for (var i = 0; i < strKeys.length; i++) { var entry = this.map_[strKeys[i]]; writer.beginSubMessage(fieldNumber); keyWri...
* The method on BinaryWriter that writes type V to the stream. May be * writeMessage, in which case the second callback arg form is used. * @param {?function(V,!jspb.BinaryWriter)=} opt_valueWriterCallback * The BinaryWriter serialization callback for type V, if V is a message * type.
random_line_split
map.js
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // ...
else { valueWriterFn.call(writer, 2, entry.value); } writer.endSubMessage(); } }; /** * Read one key/value message from the given BinaryReader. Compatible as the * `reader` callback parameter to jspb.BinaryReader.readMessage, to be called * when a key/value pair submessage is encountered. * @para...
{ valueWriterFn.call(writer, 2, this.wrapEntry_(entry), opt_valueWriterCallback); }
conditional_block
lexical_chains.py
""" lexical chain module for text tiling """ from tile_reader import TileReader from scoring import boundarize, depth_scoring, window_diff # ====================================================================================================================== # Main # ================================================...
(self, sents, window=4, pos_filter=('PUNCT', 'SYM', 'SPACE', 'DET'), boundary_type='liberal'): """ Set attributes :param sents: (list) spacy-analyzed sentences :param window: (int) distance threshold within which chains are considered active :param boundary_type: (str) 'liberal' ...
analyze
identifier_name
lexical_chains.py
""" lexical chain module for text tiling """ from tile_reader import TileReader from scoring import boundarize, depth_scoring, window_diff # ====================================================================================================================== # Main # ================================================...
ymin, ymax = plt.ylim() xmin, xmax = plt.xlim() wdiff_rounded = round(Decimal(wdiff), 3) plt.text(xmax-(xmax-xmin)/4,ymax+0.5, "window diff: {}".format(wdiff_rounded)) plt.show()
plt.axvline(x=index, color = 'gray')
conditional_block
lexical_chains.py
""" lexical chain module for text tiling """ from tile_reader import TileReader from scoring import boundarize, depth_scoring, window_diff # ====================================================================================================================== # Main # ================================================...
# loop over all sentences for sent in sents: # get index and unique tokens from current sentence i = sents.index(sent) uniques_i = set(sent) # loop over all sentences within dist thresh of current for diff in xrange(window, 0, -1): ...
actives = {} for i in xrange(len(sents)-1): actives[i] = set()
random_line_split
lexical_chains.py
""" lexical chain module for text tiling """ from tile_reader import TileReader from scoring import boundarize, depth_scoring, window_diff # ====================================================================================================================== # Main # ================================================...
@staticmethod def _preproc(sentences, pos_filter): """ Filters out stop POSs and lemmatizes sentences :param sentences: list of tokenized sentences in doc :param pos_filter: tuple of spacy pos_ labels to filter out :return: list """ filtered = [[tok for ...
""" Set attributes :param sents: (list) spacy-analyzed sentences :param window: (int) distance threshold within which chains are considered active :param boundary_type: (str) 'liberal' or 'conservative' boundary scoring :param pos_filter: (tuple) spacy pos_ labels to exclude (i.e...
identifier_body
playlist.js
var playlist = function () { var videoPlaylist = [];
var audio = document.getElementsByTagName("audio")[0]; //audio.play(); var video = document.getElementsByTagName("video")[0]; $('#video-mp4').prop('src', videoPlaylist[videoIndex]+'.mp4'); $('#video-ogg').prop('src', videoPlaylist[videoIndex]+'.ogg'); $('#video-swf').prop('src', videoPlaylist[...
var videoIndex = 0; $('#video-playlist li').each(function(index) { videoPlaylist.push($(this).data('url')); });
random_line_split
playlist.js
var playlist = function () { var videoPlaylist = []; var videoIndex = 0; $('#video-playlist li').each(function(index) { videoPlaylist.push($(this).data('url')); }); var audio = document.getElementsByTagName("audio")[0]; //audio.play(); var video = document.getElementsByTagName("vi...
}; audio.onended = function(e) { $('#lastCreation').show(); } video.onpause = function(e) { audio.pause(); }; video.onplay = function(e) { audio.play(); }; }
{ $('#video-mp4').prop('src', videoPlaylist[videoIndex]+'.mp4'); $('#video-ogg').prop('src', videoPlaylist[videoIndex]+'.ogg'); $('#video-swf').prop('data', videoPlaylist[videoIndex]+'.swf'); $('#video-swf').find('param').prop('value', videoPlaylist[videoIndex]+'.swf'); ...
conditional_block
tax_summary_edit.py
make sure that the file has default sorting (by rankID) Copyright: tax_summary_edit edits mothur taxonomy summary file Copyright (C) 2016 William Brazelton 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 ...
#! /usr/bin/env python """ edits mothur taxonomy summary file transfers last name that is not "unclassified" or "uncultured" to "unclassified" or "uncultured" assignment
random_line_split
tax_summary_edit.py
#! /usr/bin/env python """ edits mothur taxonomy summary file transfers last name that is not "unclassified" or "uncultured" to "unclassified" or "uncultured" assignment make sure that the file has default sorting (by rankID) Copyright: tax_summary_edit edits mothur taxonomy summary file Copyright (C) 2016...
infile.close() outfile.close()
if "unclassified" in line: columns = line.split('\t') tax = columns[2] newtax = tax + ' ' + lasttax outfile.write(columns[0]) outfile.write('\t') outfile.write(columns[1]) outfile.write('\t') outfile.write(newtax) for tab in columns[3:]: outfile.write('\t') outfile.write(tab) elif "uncultured" ...
conditional_block
function-arguments.rs
// Copyright 2013-2014 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-MI...
() {()}
zzz
identifier_name
function-arguments.rs
// Copyright 2013-2014 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-MI...
fn zzz() {()}
{ zzz(); (x, y) }
identifier_body
api.js
import backgroundImages from '@const/background-images'; import * as actions from './actions.js'; import Background from './class.js'; // const getObj = (indexString) => { /* const [type, index] = indexString.split('-') if (typeof index === 'undefined') return {} return store.getState().bgimgState.list[type][index]...
current, //, // currentIndex, // currentPath }) ); }; }; export const add = (/*filename*/) => {}; export const remove = (/*indexCustom*/) => {}; export const change = (obj) => { return (dispatch) => { dispatch(actions.change(obj)); ...
random_line_split
api.js
import backgroundImages from '@const/background-images'; import * as actions from './actions.js'; import Background from './class.js'; // const getObj = (indexString) => { /* const [type, index] = indexString.split('-') if (typeof index === 'undefined') return {} return store.getState().bgimgState.list[type][index]...
/* const dir = type == 'custom' ? thePath.bgimgs_custom : thePath.bgimgs const parseData = (name) => { return { name: name } } if (self.nw) { const fs = require('fs') const path = require('path') const getList = (dir) => { return fs...
{ list = backgroundImages.map( (filename, index) => new Background(filename, type + '-' + index) ); }
conditional_block
context.ts
// Copyright 2021 The LUCI Authors. // // 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
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import { createContextLink } from '../../libs/context'; import { TestVariant } from '../../services/resultdb'; export interface VariantGr...
// // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS,
random_line_split
errors.rs
use super::ast::AstLocation; use tok::Tok; use tok::Location as TokenLocation; error_chain! { types { Error, ErrorKind, ResultExt, Result; } foreign_links { Io(::std::io::Error); Parse(::lalrpop_util::ParseError<TokenLocation, Tok, char>); } errors { TypeMismatch(e...
} }
display("Invalid import expression: {:?} at {}", node, location) }
random_line_split
__init__.py
from PySide2.QtWidgets import QApplication __title__ = "Wordsets editor" __description__ = "A plugin to manage word sets" __long_description__ = """ <p>This plugin allows to create sets of words that can be matched with the attributes of the project's variants.</p> <p> Once the addition of a word set is started, a man...
__version__ = "1.0.0"
random_line_split
factoids.py
import string import asyncio import re from sqlalchemy import Table, Column, String import requests from cloudbot import hook from cloudbot.util import botvars, colors, web re_lineends = re.compile(r'[\r\n]*') FACTOID_CHAR = "?" # TODO: config table = Table( "mem", botvars.metadata, Column("word", St...
"""- lists all available factoids""" reply_text = [] reply_text_length = 0 for word in factoid_cache.keys(): added_length = len(word) + 2 if reply_text_length + added_length > 400: notice(", ".join(reply_text)) reply_text = [] reply_text_length = 0 ...
identifier_body
factoids.py
import string import asyncio import re from sqlalchemy import Table, Column, String import requests from cloudbot import hook from cloudbot.util import botvars, colors, web re_lineends = re.compile(r'[\r\n]*') FACTOID_CHAR = "?" # TODO: config table = Table( "mem", botvars.metadata, Column("word", St...
@hook.command("r", "remember", permissions=["addfactoid"]) def remember(text, nick, db, notice, async): """<word> [+]<data> - remembers <data> with <word> - add + to <data> to append""" try: word, data = text.split(None, 1) except ValueError: return remember.__doc__ old_data = factoid_...
yield from async(db.commit) yield from load_cache(async, db) @asyncio.coroutine
random_line_split
factoids.py
import string import asyncio import re from sqlalchemy import Table, Column, String import requests from cloudbot import hook from cloudbot.util import botvars, colors, web re_lineends = re.compile(r'[\r\n]*') FACTOID_CHAR = "?" # TODO: config table = Table( "mem", botvars.metadata, Column("word", St...
else: notice("I don't know about that.") return @asyncio.coroutine @hook.command() def info(text, notice): """<factoid> - shows the source of a factoid""" text = text.strip() if text in factoid_cache: notice(factoid_cache[text]) else: notice("Unknown Factoid.") ...
yield from del_factoid(async, db, text) notice('"{}" has been forgotten.'.format(data.replace('`', "'"))) return
conditional_block
factoids.py
import string import asyncio import re from sqlalchemy import Table, Column, String import requests from cloudbot import hook from cloudbot.util import botvars, colors, web re_lineends = re.compile(r'[\r\n]*') FACTOID_CHAR = "?" # TODO: config table = Table( "mem", botvars.metadata, Column("word", St...
(db): query = db.execute(table.select()) return [(row["word"], row["data"]) for row in query] @asyncio.coroutine @hook.on_start() def load_cache(async, db): """ :type db: sqlalchemy.orm.Session """ global factoid_cache factoid_cache = {} for word, data in (yield from async(_load_cache_...
_load_cache_db
identifier_name
build.js.e2e.ts
import * as gulp from 'gulp'; import * as gulpLoadPlugins from 'gulp-load-plugins'; import { join } from 'path'; import { APP_SRC, APP_DEST, TOOLS_DIR } from '../../config'; import { templateLocals, makeTsProject } from '../../utils'; const plugins = <any>gulpLoadPlugins(); export = () => { let tsProject = makeTsPr...
.pipe(gulp.dest(APP_DEST)); }
random_line_split
main.rs
#![feature(slicing_syntax)] use std::io::{File,BufferedReader}; use std::num::SignedInt; // abs method use std::io::fs; fn filesize(size: int) -> String { let units = "KMGT"; let mut left = size.abs() as f64; let mut unit = -1i; while left > 1100. && unit < 3 { left /= 1024.; unit += 1; } if unit...
fn get_swap() -> Vec<(uint, int, String)> { fs::readdir(&Path::new("/proc")).unwrap().iter().filter_map( |d| d.filename_str().unwrap().parse().and_then(|pid| match get_swap_for(pid) { 0 => None, swap => Some((pid, swap, get_comm_for(pid))), } ) ).collect() } fn main() { // let...
{ let smaps_path = format!("/proc/{}/smaps", pid); let mut file = BufferedReader::new(File::open(&Path::new(smaps_path))); let mut s = 0; for l in file.lines() { let line = match l { Ok(s) => s, Err(_) => return 0, }; if line.starts_with("Swap:") { s += line.words().nth(1).unwrap(...
identifier_body
main.rs
#![feature(slicing_syntax)] use std::io::{File,BufferedReader}; use std::num::SignedInt; // abs method use std::io::fs; fn filesize(size: int) -> String { let units = "KMGT"; let mut left = size.abs() as f64; let mut unit = -1i; while left > 1100. && unit < 3 { left /= 1024.; unit += 1; } if unit...
(pid: uint) -> String { let cmdline_path = format!("/proc/{}/cmdline", pid); match File::open(&Path::new(&cmdline_path)).read_to_string() { // s may be empty for kernel threads Ok(s) => chop_null(s), Err(_) => String::new(), } } fn get_swap_for(pid: uint) -> int { let smaps_path = format!("/proc/{}...
get_comm_for
identifier_name
main.rs
#![feature(slicing_syntax)] use std::io::{File,BufferedReader}; use std::num::SignedInt; // abs method use std::io::fs; fn filesize(size: int) -> String { let units = "KMGT"; let mut left = size.abs() as f64; let mut unit = -1i;
while left > 1100. && unit < 3 { left /= 1024.; unit += 1; } if unit == -1 { format!("{}B", size) } else { if size < 0 { left = -left; } format!("{:.1}{}iB", left, units.char_at(unit as uint)) } } fn chop_null(s: String) -> String { let last = s.len() - 1; let mut s = s; ...
random_line_split
line_nav_iframes_in_inline_block.py
#!/usr/bin/python """Test of line navigation output of Firefox.""" from macaroon.playback import * import utils sequence = MacroSequence() #sequence.append(WaitForDocLoad()) sequence.append(PauseAction(5000)) # Work around some new quirk in Gecko that causes this test to fail if # run via the test harness rather t...
sequence.append(utils.AssertionSummaryAction()) sequence.start()
["BRAILLE LINE: 'Line 1'", " VISIBLE: 'Line 1', cursor=1", "SPEECH OUTPUT: 'Line 1'"]))
random_line_split
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::DomRefCell; use crate::dom:...
(bubbles: EventBubbles) -> Self { match bubbles { EventBubbles::Bubbles => true, EventBubbles::DoesNotBubble => false, } } } #[derive(Clone, Copy, MallocSizeOf, PartialEq)] pub enum EventCancelable { Cancelable, NotCancelable, } impl From<bool> for EventCancelable {...
from
identifier_name
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::DomRefCell; use crate::dom:...
pub fn new_uninitialized(global: &GlobalScope) -> DomRoot<Event> { reflect_dom_object(Box::new(Event::new_inherited()), global, EventBinding::Wrap) } pub fn new( global: &GlobalScope, type_: Atom, bubbles: EventBubbles, cancelable: EventCancelable, ) -> DomRoot...
{ Event { reflector_: Reflector::new(), current_target: Default::default(), target: Default::default(), type_: DomRefCell::new(atom!("")), phase: Cell::new(EventPhase::None), canceled: Cell::new(EventDefault::Allowed), stop_prop...
identifier_body
event.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use crate::dom::bindings::callback::ExceptionHandling; use crate::dom::bindings::cell::DomRefCell; use crate::dom:...
self.status() } pub fn status(&self) -> EventStatus { match self.DefaultPrevented() { true => EventStatus::Canceled, false => EventStatus::NotCanceled, } } #[inline] pub fn dispatching(&self) -> bool { self.dispatching.get() } #[inli...
// Step 10-12. self.clear_dispatching_flags(); // Step 14.
random_line_split
completion.py
# -*- coding: utf-8 -*- # # This tool helps you to rebase package to the latest version # Copyright (C) 2013-2014 Red Hat, Inc. # # 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...
(): archives = Archive.get_supported_archives() return [a.lstrip('.') for a in archives] @staticmethod def options(): def get_delimiter(parser, action): if action.nargs == 0: return None fmt = parser._get_formatter() # pylint: disable=protected-a...
extensions
identifier_name
completion.py
# -*- coding: utf-8 -*- # # This tool helps you to rebase package to the latest version # Copyright (C) 2013-2014 Red Hat, Inc. # # 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...
def replace_placeholders(s, **kwargs): placeholder_re = re.compile(r'@(\w+)@') matches = list(placeholder_re.finditer(s)) result = s for match in reversed(matches): replacement = kwargs.get(match.group(1), '') result = result[:match.start(0)] + replacement + result[match.end(0):] ...
options = cls.options() return { # pattern list of extensions 'RH_EXTENSIONS': '@({})'.format('|'.join(cls.extensions())), # array of options 'RH_OPTIONS': '({})'.format(' '.join(['"{}"'.format(' '.join(o['options'])) for o in options])), # array of ch...
identifier_body
completion.py
# -*- coding: utf-8 -*- # # This tool helps you to rebase package to the latest version # Copyright (C) 2013-2014 Red Hat, Inc. # # 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...
delimiter = get_delimiter(parser, action) or '' result.append(dict( options=[o + delimiter.strip() for o in action.option_strings], choices=action.choices or [])) return result @classmethod def dump(cls): options = cls.options() r...
continue
conditional_block
completion.py
# -*- coding: utf-8 -*- # # This tool helps you to rebase package to the latest version # Copyright (C) 2013-2014 Red Hat, Inc. # # 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...
placeholder_re = re.compile(r'@(\w+)@') matches = list(placeholder_re.finditer(s)) result = s for match in reversed(matches): replacement = kwargs.get(match.group(1), '') result = result[:match.start(0)] + replacement + result[match.end(0):] return result def main(): if len(sys...
def replace_placeholders(s, **kwargs):
random_line_split
lib.rs
/* * Copyright 2015-2019 Ben Ashford * * 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...
/// /// This function is exposed to allow extensions to certain operations, it is /// not expected to be used by consumers of the library fn do_req(resp: reqwest::Response) -> Result<reqwest::Response, EsError> { let mut resp = resp; let status = resp.status(); match status { StatusCode::OK | Status...
random_line_split
lib.rs
/* * Copyright 2015-2019 Ben Ashford * * 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...
(client: &mut Client, index_name: &str) { // TODO - this should use the Bulk API let documents = vec![ TestDocument::new() .with_str_field("Document A123") .with_int_field(1), TestDocument::new() .with_str_field("Document B456") ...
setup_test_data
identifier_name
index.js
/* eslint-disable no-underscore-dangle */ const Invoker = require('./invoker'); const Server = require('./server'); class Provider { static init(serviceInfo) { if (Provider.instances) { throw new Error(`service ${Invoker.getDescription(serviceInfo)} has been registered`); } Provider.called = true;...
funcNames.forEach((name) => { this.addMethod(name, functions[name]); }); return this; } addMethod(functionName, handler) { if (!functionName || !handler) { throw new Error('function name or handler should not be empty'); } this.invoker.addMethod(functionName); this.server...
{ throw new Error('methods should have handlers'); }
conditional_block
index.js
/* eslint-disable no-underscore-dangle */ const Invoker = require('./invoker'); const Server = require('./server'); class Provider { static init(serviceInfo) { if (Provider.instances) { throw new Error(`service ${Invoker.getDescription(serviceInfo)} has been registered`); } Provider.called = true;...
(functionName, handler) { if (!functionName || !handler) { throw new Error('function name or handler should not be empty'); } this.invoker.addMethod(functionName); this.server.addHandler(functionName, handler); return this; } /** * dispose provider * should remove invoker from zook...
addMethod
identifier_name
index.js
/* eslint-disable no-underscore-dangle */ const Invoker = require('./invoker'); const Server = require('./server'); class Provider { static init(serviceInfo) { if (Provider.instances) { throw new Error(`service ${Invoker.getDescription(serviceInfo)} has been registered`); } Provider.called = true;...
* @return {Promise.<void>} */ dispose() { return this.invoker.dispose(); } } module.exports = Provider;
* dispose provider * should remove invoker from zookeeper before server closed
random_line_split
index.js
/* eslint-disable no-underscore-dangle */ const Invoker = require('./invoker'); const Server = require('./server'); class Provider { static init(serviceInfo)
constructor(serviceInfo) { this.invoker = Invoker.createInstance(serviceInfo); this.server = Server.createInstance(); } configServer(options) { this.server.config(options); return this; } listen(port) { this.invoker.setPort(port); return this .server .listen(port) ...
{ if (Provider.instances) { throw new Error(`service ${Invoker.getDescription(serviceInfo)} has been registered`); } Provider.called = true; Provider.instances = new Provider(serviceInfo); return Provider.instances; }
identifier_body
group_tags.py
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, g...
(template.Node): def __init__(self, group_var, model_name_var, context_var): self.group_var = template.Variable(group_var) self.model_name_var = template.Variable(model_name_var) self.context_var = context_var def render(self, context): group = self.group_var.resolve(context...
ContentObjectsNode
identifier_name
group_tags.py
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, g...
if len(bits) != 5: raise template.TemplateSyntaxError("'%s' requires five arguments." % bits[0]) return ContentObjectsNode(bits[1], bits[2], bits[4])
random_line_split
group_tags.py
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, g...
@register.tag def groupurl(parser, token): bits = token.contents.split() tag_name = bits[0] if len(bits) < 3: raise template.TemplateSyntaxError("'%s' takes at least two arguments" " (path to a view and a group)" % tag_name) view_name = bits[1] group = parser.compile_filt...
def __init__(self, group_var, model_name_var, context_var): self.group_var = template.Variable(group_var) self.model_name_var = template.Variable(model_name_var) self.context_var = context_var def render(self, context): group = self.group_var.resolve(context) model_name ...
identifier_body
group_tags.py
from django import template from django.utils.encoding import smart_str from django.core.urlresolvers import reverse, NoReverseMatch from django.db.models import get_model from django.db.models.query import QuerySet register = template.Library() class GroupURLNode(template.Node): def __init__(self, view_name, g...
return GroupURLNode(view_name, group, kwargs, asvar) @register.tag def content_objects(parser, token): """ {% content_objects group "tasks.Task" as tasks %} """ bits = token.split_contents() if len(bits) != 5: raise template.TemplateSyntaxError("'%s' requires five arguments."...
raise template.TemplateSyntaxError("'%s' does not support non-kwargs arguments." % tag_name)
conditional_block
clipread.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##Copyright (c) 2017 Benoit Valot and Panisa Treepong ##benoit.valot@univ-fcomte.fr ##UMR 6249 Chrono-Environnement, Besançon, France ##Licence GPL from . import variables class ClipRead(): """Clip read object""" def __init__(self, alignedsegment): self.read_...
def getclipseq(self): """return clip part of the read, except for hard clip return None""" if len(self.read_seq) == self.read_len: return None if self.isstartclip(): return self.read_seq[:self.read_start] else: return self.read_seq[self.read_end:]...
""Return the position of the clip""" if self.isstartclip(): return self.ref_start else: return self.ref_end
identifier_body
clipread.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##Copyright (c) 2017 Benoit Valot and Panisa Treepong ##benoit.valot@univ-fcomte.fr ##UMR 6249 Chrono-Environnement, Besançon, France ##Licence GPL from . import variables class ClipRead(): """Clip read object""" def __init__(self, alignedsegment): self.read_...
elif self.cigartuples[-1][0] in variables.cigarclip: return False else: raise Exception("ClipRead must contain clip part at start or end") def getdr(self, drstart, drend): """Return the dr sequence if complete or return None""" s = self.read_start + (drstart ...
eturn True
conditional_block
clipread.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##Copyright (c) 2017 Benoit Valot and Panisa Treepong ##benoit.valot@univ-fcomte.fr ##UMR 6249 Chrono-Environnement, Besançon, France ##Licence GPL from . import variables class ClipRead(): """Clip read object""" def __init__(self, alignedsegment): self.read_...
self): return str(self.ref_start) + ": " + str(self.read_start) + self.read_seq + \ str(self.read_end) + " :" + str(self.ref_end) if __name__=='__main__': import doctest doctest.testmod()
_str__(
identifier_name
clipread.py
#!/usr/bin/python # -*- coding: utf-8 -*- ##Copyright (c) 2017 Benoit Valot and Panisa Treepong ##benoit.valot@univ-fcomte.fr ##UMR 6249 Chrono-Environnement, Besançon, France ##Licence GPL from . import variables class ClipRead(): """Clip read object""" def __init__(self, alignedsegment): self.read_...
else: return self.ref_end def getclipseq(self): """return clip part of the read, except for hard clip return None""" if len(self.read_seq) == self.read_len: return None if self.isstartclip(): return self.read_seq[:self.read_start] else: ...
def getclippos(self): """Return the position of the clip""" if self.isstartclip(): return self.ref_start
random_line_split
injectr.js
"use strict";
fs = require('fs'), path = require('path'), vm = require('vm'); module.exports = function (file, mocks, context) { var script; mocks = mocks || {}; context = context || {}; file = path.join(path.dirname(module.parent.filename), file); cache[file] = cache[file] || module.exports.onload(f...
var cache = {},
random_line_split
injectr.js
"use strict"; var cache = {}, fs = require('fs'), path = require('path'), vm = require('vm'); module.exports = function (file, mocks, context) { var script; mocks = mocks || {}; context = context || {}; file = path.join(path.dirname(module.parent.filename), file); cache[file] = cache[f...
if (a.indexOf('.') === 0) { a = path.join(path.dirname(file), a); } return require(a); }; context.module = context.module || {}; context.module.exports = {}; context.exports = context.module.exports; script.runInNewContext(context); return context.module.exp...
{ return mocks[a]; }
conditional_block
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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 // to use, copy, modify...
fn get_from_pointer(builder: PointerBuilder<'a>, default: Option<&'a [crate::Word]>) -> Result<Builder<'a, T>> { Ok(Builder { marker: PhantomData, builder: builder.get_list(Pointer, default)? }) } } impl <'a, T> Builder<'a, T> where T: FromClientHook { pub fn get(se...
{ Builder { marker: PhantomData, builder: builder.init_list(Pointer, size), } }
identifier_body
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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 // to use, copy, modify...
(reader: &PointerReader<'a>, default: Option<&'a [crate::Word]>) -> Result<Reader<'a, T>> { Ok(Reader { reader: reader.get_list(Pointer, default)?, marker: PhantomData }) } } impl <'a, T> Reader<'a, T> where T: FromClientHook { pub fn get(self, index: u32) -> Result<T> { ass...
get_from_pointer
identifier_name
capability_list.rs
// Copyright (c) 2017 David Renshaw and contributors // // 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 // to use, copy, modify...
// // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILI...
random_line_split
capsule.rs
//! Work wih Python capsules //! use libc::c_void; use std::ffi::{CStr, CString, NulError}; use std::mem; use super::object::PyObject; use crate::err::{self, PyErr, PyResult}; use crate::ffi::{PyCapsule_GetPointer, PyCapsule_Import, PyCapsule_New}; use crate::python::{Python, ToPythonPointer}; /// Capsules are the pr...
Ok(caps_ptr) } /// Convenience method to create a capsule for some data /// /// The encapsuled data may be an array of functions, but it can't be itself a /// function directly. /// /// May panic when running out of memory. /// pub fn new_data<T, N>(py: Python, data: &'stat...
{ return Err(PyErr::fetch(py)); }
conditional_block