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
test_error.py
import py import errno def test_error_classes(): for name in errno.errorcode.values(): x = getattr(py.error, name) assert issubclass(x, py.error.Error) assert issubclass(x, EnvironmentError) def test_picklability_issue1(): e1 = py.error.ENOENT() s = py.std.pickle.dumps(e1) e2 ...
import warnings class Case(unittest.TestCase): def test_assertWarns(self): # Clear everything "py.*" from sys.modules and re-import py # as a fresh start for mod in tuple(sys.modules.keys()): if mod and (mod == 'py' or mod.startswith('py.')): ...
random_line_split
test_error.py
import py import errno def test_error_classes(): for name in errno.errorcode.values(): x = getattr(py.error, name) assert issubclass(x, py.error.Error) assert issubclass(x, EnvironmentError) def test_picklability_issue1(): e1 = py.error.ENOENT() s = py.std.pickle.dumps(e1) e2...
def test_error_conversion_ENOTDIR(testdir): p = testdir.makepyfile("") excinfo = py.test.raises(py.error.Error, py.error.checked_call, p.listdir) assert isinstance(excinfo.value, EnvironmentError) assert isinstance(excinfo.value, py.error.Error) assert "ENOTDIR" in repr(excinfo.value) def test_c...
num = 3999 cls = py.error._geterrnoclass(num) assert cls.__name__ == 'UnknownErrno%d' % (num,) assert issubclass(cls, py.error.Error) assert issubclass(cls, EnvironmentError) cls2 = py.error._geterrnoclass(num) assert cls is cls2
identifier_body
test_error.py
import py import errno def test_error_classes(): for name in errno.errorcode.values(): x = getattr(py.error, name) assert issubclass(x, py.error.Error) assert issubclass(x, EnvironmentError) def test_picklability_issue1(): e1 = py.error.ENOENT() s = py.std.pickle.dumps(e1) e2...
(tmpdir): import tempfile py.error.checked_call(tempfile.mkdtemp, dir=str(tmpdir)) try: import unittest unittest.TestCase.assertWarns except (ImportError, AttributeError): pass # required interface not available else: import sys import warnings class Case(unittest.TestCase): ...
test_checked_call_supports_kwargs
identifier_name
test_error.py
import py import errno def test_error_classes(): for name in errno.errorcode.values(): x = getattr(py.error, name) assert issubclass(x, py.error.Error) assert issubclass(x, EnvironmentError) def test_picklability_issue1(): e1 = py.error.ENOENT() s = py.std.pickle.dumps(e1) e2...
import py with self.assertWarns(UserWarning): warnings.warn('this should work')
if mod and (mod == 'py' or mod.startswith('py.')): del sys.modules[mod]
conditional_block
add.py
import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo
def __init__(self, fitID, itemID): wx.Command.__init__(self, True, 'Add Projected Module') self.internalHistory = InternalCommandHistory() self.fitID = fitID self.itemID = itemID def Do(self): cmd = CalcAddProjectedModuleCommand(fitID=self.fitID, modInfo=ModuleInfo(item...
from service.fit import Fit class GuiAddProjectedModuleCommand(wx.Command):
random_line_split
add.py
import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo from service.fit import Fit class GuiAddProjectedModuleCommand(wx.Command):
eos.db.flush() sFit = Fit.getInstance() sFit.recalc(self.fitID) sFit.fill(self.fitID) eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success
def __init__(self, fitID, itemID): wx.Command.__init__(self, True, 'Add Projected Module') self.internalHistory = InternalCommandHistory() self.fitID = fitID self.itemID = itemID def Do(self): cmd = CalcAddProjectedModuleCommand(fitID=self.fitID, modInfo=ModuleInfo(itemID=se...
identifier_body
add.py
import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo from service.fit import Fit class GuiAddProjectedModuleCommand(wx.Command): de...
sFit.fill(self.fitID) eos.db.commit() wx.PostEvent(gui.mainFrame.MainFrame.getInstance(), GE.FitChanged(fitIDs=(self.fitID,))) return success def Undo(self): success = self.internalHistory.undoAll() eos.db.flush() sFit = Fit.getInstance() sFit.recalc...
eos.db.flush() sFit.recalc(self.fitID)
conditional_block
add.py
import wx import eos.db import gui.mainFrame from gui import globalEvents as GE from gui.fitCommands.calc.module.projectedAdd import CalcAddProjectedModuleCommand from gui.fitCommands.helpers import InternalCommandHistory, ModuleInfo from service.fit import Fit class GuiAddProjectedModuleCommand(wx.Command): de...
(self): cmd = CalcAddProjectedModuleCommand(fitID=self.fitID, modInfo=ModuleInfo(itemID=self.itemID)) success = self.internalHistory.submit(cmd) sFit = Fit.getInstance() if cmd.needsGuiRecalc: eos.db.flush() sFit.recalc(self.fitID) sFit.fill(self.fitID) ...
Do
identifier_name
read_manifest.rs
use std::env; use cargo::core::{Package, Source}; use cargo::util::{CliResult, Config}; use cargo::util::important_paths::{find_root_manifest_for_wd}; use cargo::sources::{PathSource}; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_color: Option<String>, } pub const USAGE...
Options: -h, --help Print this message -v, --verbose Use verbose output --manifest-path PATH Path to the manifest --color WHEN Coloring: auto, always, never "; pub fn execute(options: Options, config: &Config) -> CliResult<Option<Package>> { debug!("executin...
Usage: cargo read-manifest [options] cargo read-manifest -h | --help
random_line_split
read_manifest.rs
use std::env; use cargo::core::{Package, Source}; use cargo::util::{CliResult, Config}; use cargo::util::important_paths::{find_root_manifest_for_wd}; use cargo::sources::{PathSource}; #[derive(RustcDecodable)] struct Options { flag_manifest_path: Option<String>, flag_color: Option<String>, } pub const USAGE...
{ debug!("executing; cmd=cargo-read-manifest; args={:?}", env::args().collect::<Vec<_>>()); try!(config.shell().set_color_config(options.flag_color.as_ref().map(|s| &s[..]))); let root = try!(find_root_manifest_for_wd(options.flag_manifest_path, config.cwd())); let mut source = try!(PathSou...
identifier_body
read_manifest.rs
use std::env; use cargo::core::{Package, Source}; use cargo::util::{CliResult, Config}; use cargo::util::important_paths::{find_root_manifest_for_wd}; use cargo::sources::{PathSource}; #[derive(RustcDecodable)] struct
{ flag_manifest_path: Option<String>, flag_color: Option<String>, } pub const USAGE: &'static str = " Print a JSON representation of a Cargo.toml manifest Usage: cargo read-manifest [options] cargo read-manifest -h | --help Options: -h, --help Print this message -v, --verbose ...
Options
identifier_name
coreutils.rs
// This file is part of the uutils coreutils package. // // (c) Michael Gehring <mg@ebfe.org> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use clap::{App, Arg}; use clap_complete::Shell; use std::cmp; use std::ffi::OsStr; use std::ffi...
; // 0th argument equals util name? if let Some(util_os) = util_name { fn not_found(util: &OsStr) -> ! { println!("{}: function/utility not found", util.maybe_quote()); process::exit(1); } let util = match util_os.to_str() { Some(util) => util, ...
{ // unmatched binary name => regard as multi-binary container and advance argument list uucore::set_utility_is_second_arg(); args.next() }
conditional_block
coreutils.rs
// This file is part of the uutils coreutils package. // // (c) Michael Gehring <mg@ebfe.org> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use clap::{App, Arg}; use clap_complete::Shell; use std::cmp; use std::ffi::OsStr; use std::ffi...
let util = match util_os.to_str() { Some(util) => util, None => not_found(&util_os), }; if util == "completion" { gen_completions(args, &utils); } match utils.get(util) { Some(&(uumain, _)) => { process::exit(uum...
{ println!("{}: function/utility not found", util.maybe_quote()); process::exit(1); }
identifier_body
coreutils.rs
// This file is part of the uutils coreutils package. // // (c) Michael Gehring <mg@ebfe.org> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use clap::{App, Arg}; use clap_complete::Shell; use std::cmp; use std::ffi::OsStr;
use std::process; use uucore::display::Quotable; const VERSION: &str = env!("CARGO_PKG_VERSION"); include!(concat!(env!("OUT_DIR"), "/uutils_map.rs")); fn usage<T>(utils: &UtilityMap<T>, name: &str) { println!("{} {} (multi-call binary)\n", name, VERSION); println!("Usage: {} [function [arguments...]]\n", na...
use std::ffi::OsString; use std::io::{self, Write}; use std::path::{Path, PathBuf};
random_line_split
coreutils.rs
// This file is part of the uutils coreutils package. // // (c) Michael Gehring <mg@ebfe.org> // // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. use clap::{App, Arg}; use clap_complete::Shell; use std::cmp; use std::ffi::OsStr; use std::ffi...
() { uucore::panic::mute_sigpipe_panic(); let utils = util_map(); let mut args = uucore::args_os(); let binary = binary_path(&mut args); let binary_as_util = name(&binary); // binary name equals util name? if let Some(&(uumain, _)) = utils.get(binary_as_util) { process::exit(uumai...
main
identifier_name
packet.rs
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, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to wh...
destination_port, payload: vec![], } } pub fn payload(mut self, payload: Vec<u8>) -> Self { self.payload = payload; self } pub fn build(self) -> Vec<u8> { let mut buf = BytesMut::new(); buf.put_u16(self.source_port); buf.put_u16(...
impl TcpBuilder { pub fn new(source_port: u16, destination_port: u16) -> Self { Self { source_port,
random_line_split
packet.rs
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, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to wh...
() { let source: Ipv4Addr = "10.10.10.10".parse().unwrap(); let destination: Ipv4Addr = "127.127.127.127".parse().unwrap(); let tcp = TcpBuilder::new(5555, 6666) .payload(vec![0x41, 0x41, 0x41, 0x41, 0x41]) .build(); let builder = Ip4Builder::new() ....
parse_ip_addr
identifier_name
packet.rs
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, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the ...
pub fn destination(mut self, addr: Ipv4Addr) -> Self { self.dest_addr = addr; self } pub fn ttl(mut self, ttl: u8) -> Self { self.ttl = ttl; self } pub fn protocol(mut self, protocol: Protocol) -> Self { self.protocol = protocol; self } pu...
{ self.source_addr = addr; self }
identifier_body
packet.rs
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, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to wh...
else { result += pdu.get_u16() as u32; } if result > 0xffff { result -= 0xffff; } } return !result as u16; } } #[cfg(test)] mod test { use super::*; use crate::pcap; #[test] fn parse_ip_addr() { let sourc...
{ result += (pdu.get_u8() as u32) << 8; }
conditional_block
__init__.py
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. __all__ = ['pdb'] __version__ = '0.9.0' import sys # backwards compatibility to support `from fairseq.meters import AverageMeter` from fairs...
import fairseq.benchmark # noqa import fairseq.model_parallel # noqa
random_line_split
server.py
# -*- coding: utf-8 -*- import os import asyncio import struct from .logger import get_logger from .protocol import PeerStreamIterator from .message import (MessageID, InterestedMessage, HandshakeMessage, BitFieldMessage, NotInte...
if message: logger.info('Serving {}'.format(message)) self.transport.write(message.encode()) def eof_received(self): logger.debug('eof received') def connection_lost(self, exc): logger.debug('connectin lost') async def run_server(port, torrent): """Run a s...
message = self.request_handler.handle_message(data) logger.debug(message)
random_line_split
server.py
# -*- coding: utf-8 -*- import os import asyncio import struct from .logger import get_logger from .protocol import PeerStreamIterator from .message import (MessageID, InterestedMessage, HandshakeMessage, BitFieldMessage, NotInte...
def handle_message(self, buffer): message = self.parse(buffer) if isinstance(message, NotInterestedMessage): logger.debug('Remove interested state') elif isinstance(message, HandshakeMessage): logger.debug('Received Handshake') elif isinstance(message, Choke...
data = self.file_reader.read(begin=begin, index=index, length=length) return PieceMessage(begin=begin, index=index, block=data)
identifier_body
server.py
# -*- coding: utf-8 -*- import os import asyncio import struct from .logger import get_logger from .protocol import PeerStreamIterator from .message import (MessageID, InterestedMessage, HandshakeMessage, BitFieldMessage, NotInte...
elif message_id is MessageID.NotInterested.value: _consume() return NotInterestedMessage() elif message_id is MessageID.Choke.value: _consume() return ChokeMessage() elif message_id is Messag...
_consume() return InterestedMessage()
conditional_block
server.py
# -*- coding: utf-8 -*- import os import asyncio import struct from .logger import get_logger from .protocol import PeerStreamIterator from .message import (MessageID, InterestedMessage, HandshakeMessage, BitFieldMessage, NotInte...
: def __init__(self, torrent): self.torrent = torrent self.fd = os.open(self.torrent.name, os.O_RDONLY) def read(self, begin, index, length): pos = index * self.torrent.info.piece_length os.lseek(self.fd, pos, os.SEEK_SET) return os.read(self.fd, length) def has_all...
SourceFileReader
identifier_name
universal_fn_syntax_call.rs
pub fn universal_fn_syntax_call() { println!("***Universal Function Syntax Call***"); one(); println!(""); } trait Foo { fn f(&self); } trait Bar { fn f(&self); } struct Baz; impl Foo for Baz { fn f(&self)
} impl Bar for Baz { fn f(&self) { println!("Baz's implementation of bar."); } } trait Foo2 { fn foo() -> i32; } struct Bar2; impl Bar2 { fn foo() -> i32 { 20 } } impl Foo2 for Bar2 { fn foo() -> i32 { 10 } } fn one() { let b = Baz; // b.f(); // can't c...
{ println!("Baz's implementation of foo."); }
identifier_body
universal_fn_syntax_call.rs
pub fn universal_fn_syntax_call() { println!("***Universal Function Syntax Call***"); one(); println!(""); }
fn f(&self); } trait Bar { fn f(&self); } struct Baz; impl Foo for Baz { fn f(&self) { println!("Baz's implementation of foo."); } } impl Bar for Baz { fn f(&self) { println!("Baz's implementation of bar."); } } trait Foo2 { fn foo() -> i32; } struct Bar2; impl Bar2 { ...
trait Foo {
random_line_split
universal_fn_syntax_call.rs
pub fn universal_fn_syntax_call() { println!("***Universal Function Syntax Call***"); one(); println!(""); } trait Foo { fn f(&self); } trait Bar { fn f(&self); } struct Baz; impl Foo for Baz { fn f(&self) { println!("Baz's implementation of foo."); } } impl Bar for Baz { ...
() -> i32 { 10 } } fn one() { let b = Baz; // b.f(); // can't call because of disambiguity Foo::f(&b); // same as f.b(); Bar::f(&b); // same as f.b(); // angle-bracket form assert_eq!(10, <Bar2 as Foo2>::foo()); assert_eq!(20, Bar2::foo()); }
foo
identifier_name
FillTextureCmd.ts
import { Point } from "../../maths/Point" import { Context } from "../../resource/Context" import { Texture } from "../../resource/Texture" import { Pool } from "../../utils/Pool" /** * 填充贴图 */ export class FillTextureCmd { static ID: string = "FillTexture"; /** * 纹理。 */ texture: Texture; ...
/** * 回收到对象池 */ recover(): void { this.texture = null; this.offset = null; this.other = null; Pool.recover("FillTextureCmd", this); } /**@private */ run(context: Context, gx: number, gy: number): void { context.fillTexture(this.texture, this.x + gx,...
cmd.other = other; return cmd; }
random_line_split
FillTextureCmd.ts
import { Point } from "../../maths/Point" import { Context } from "../../resource/Context" import { Texture } from "../../resource/Texture" import { Pool } from "../../utils/Pool" /** * 填充贴图 */ export class FillTextureCmd { static ID: string = "FillTexture"; /** * 纹理。 */ texture: Texture; ...
fset = null; this.other = null; Pool.recover("FillTextureCmd", this); } /**@private */ run(context: Context, gx: number, gy: number): void { context.fillTexture(this.texture, this.x + gx, this.y + gy, this.width, this.height, this.type, this.offset, this.other); } /**@priva...
cmd.texture = texture; cmd.x = x; cmd.y = y; cmd.width = width; cmd.height = height; cmd.type = type; cmd.offset = offset; cmd.other = other; return cmd; } /** * 回收到对象池 */ recover(): void { this.texture = null; this....
identifier_body
FillTextureCmd.ts
import { Point } from "../../maths/Point" import { Context } from "../../resource/Context" import { Texture } from "../../resource/Texture" import { Pool } from "../../utils/Pool" /** * 填充贴图 */ export class FillText
tatic ID: string = "FillTexture"; /** * 纹理。 */ texture: Texture; /** * X轴偏移量。 */ x: number; /** * Y轴偏移量。 */ y: number; /** * (可选)宽度。 */ width: number; /** * (可选)高度。 */ height: number; /** * (可选)填充类型 repeat|repeat-x|repea...
ureCmd { s
identifier_name
plot_undirected_grid_graph_watersheds.py
""" Edge/Node Weighted Watersheds ==================================== Compare edge weighted watersheds and node weighted on a grid graph. """ #################################### # sphinx_gallery_thumbnail_number = 5 from __future__ import print_function import nifty.graph import skimage.data import skimage.segmen...
pylab.title('Edge Weighted Watershed (interpixel weights)') f.add_subplot(2,2, 3) b_img = skimage.segmentation.mark_boundaries(img/255, oversegNodeWeighted.astype('uint32'), mode='inner', color=(0.1,0.1,0.2)) pylab.imshow(b_img) pylab.title('Node Weighted Watershed') pylab.show()
b_img = skimage.segmentation.mark_boundaries(img/255, oversegEdgeWeightedB.astype('uint32'), mode='inner', color=(0.1,0.1,0.2)) pylab.imshow(b_img)
random_line_split
_mocks.py
""" Legalese -------- Copyright (c) 2015, 2016 Genome Research Ltd. Author: Colin Nolan <cn13@sanger.ac.uk>
This file is part of Cookie Monster. Cookie Monster 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. This program is distributed in the hop...
random_line_split
_mocks.py
""" Legalese -------- Copyright (c) 2015, 2016 Genome Research Ltd. Author: Colin Nolan <cn13@sanger.ac.uk> This file is part of Cookie Monster. Cookie Monster 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; ei...
() -> CookieJar: """ Creates a magic mock CookieJar - has the implementation of a CookieJar all methods are implemented using magic mocks and therefore their usage is recorded. :return: the created magic mock """ cookie_jar = InMemoryCookieJar() original_get_next_for_processing = cookie_jar....
create_magic_mock_cookie_jar
identifier_name
_mocks.py
""" Legalese -------- Copyright (c) 2015, 2016 Genome Research Ltd. Author: Colin Nolan <cn13@sanger.ac.uk> This file is part of Cookie Monster. Cookie Monster 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; ei...
""" Creates a magic mock CookieJar - has the implementation of a CookieJar all methods are implemented using magic mocks and therefore their usage is recorded. :return: the created magic mock """ cookie_jar = InMemoryCookieJar() original_get_next_for_processing = cookie_jar.get_next_for_processi...
identifier_body
external_test_py37.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
unittest.main()
conditional_block
external_test_py37.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
return get_payload(DataclassTransform(**values)) if __name__ == '__main__': unittest.main()
URN = 'beam:external:fakeurn:v1' integer_example: int boolean: bool string_example: str list_of_strings: typehints.List[str] optional_kv: typehints.Optional[typehints.KV[str, float]] = None optional_integer: typehints.Optional[int] = None expansion_service: dataclasses.InitVar...
identifier_body
external_test_py37.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
unittest.main()
if __name__ == '__main__':
random_line_split
external_test_py37.py
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
(self, values): @dataclasses.dataclass class DataclassTransform(beam.ExternalTransform): URN = 'beam:external:fakeurn:v1' integer_example: int boolean: bool string_example: str list_of_strings: typehints.List[str] optional_kv: typehints.Optional[typehints.KV[str, float]] = ...
get_payload_from_beam_typehints
identifier_name
stats-country.component.ts
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { Observable } from 'rxjs'; import { MatchService } from '../../services/match.service'; import { IMatch } from '../../services/models/match.model'; import { ICountry } from '../../services/models/country.model'; import { Chart } from 'chart.js';...
ngOnInit(): void { // this.chart = new Chart('canvas', { // type: 'pie', // data: { // datasets: [{ // data: [10, 20, 30] // }], // labels: [ // 'Red', // 'Yellow', // 'Blue' // ] // } // }); const barChartData = ...
{ }
identifier_body
stats-country.component.ts
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { Observable } from 'rxjs'; import { MatchService } from '../../services/match.service'; import { IMatch } from '../../services/models/match.model'; import { ICountry } from '../../services/models/country.model'; import { Chart } from 'chart.js';...
}; this.chart = new Chart('canvas', { type: 'bar', data: barChartData, options: { scales: { xAxes: [{ stacked: true, }], yAxes: [{ stacked: true }] } } }); } ngAfterViewInit(): void { // setTime...
stack: 'Country #1', backgroundColor: 'rgba(255, 99, 132, 0.2)' }]
random_line_split
stats-country.component.ts
import { Component, OnInit, AfterViewInit } from '@angular/core'; import { Observable } from 'rxjs'; import { MatchService } from '../../services/match.service'; import { IMatch } from '../../services/models/match.model'; import { ICountry } from '../../services/models/country.model'; import { Chart } from 'chart.js';...
(private matchService: MatchService) { } ngOnInit(): void { // this.chart = new Chart('canvas', { // type: 'pie', // data: { // datasets: [{ // data: [10, 20, 30] // }], // labels: [ // 'Red', // 'Yellow', // 'Blue' // ] //...
constructor
identifier_name
coro_exc_demo.py
# -*- coding: utf-8 -*- """ Created on Sun May 14 22:13:58 2017 """ #python3 """ >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc_coro.close() >>> from inspect import getgeneratorstate >...
RuntimeError('This line should never run.') if __name__ == "__main__": exc_coro = demo_exc_handling() next(exc_coro) exc_coro.send(11) exc_coro.send(22) exc_coro.close() print(getgeneratorstate(exc_coro))
x = yield except DemoException: print('*** DemoException handled. Continuing...') else: print('-> coroutine received: {!r}'.format(x)) raise
conditional_block
coro_exc_demo.py
# -*- coding: utf-8 -*- """ Created on Sun May 14 22:13:58 2017 """ #python3 """ >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc_coro.close() >>> from inspect import getgeneratorstate >...
_exc_handling(): print('-> coroutine started') while True: try: x = yield except DemoException: print('*** DemoException handled. Continuing...') else: print('-> coroutine received: {!r}'.format(x)) raise RuntimeError('This line should never ru...
"""异常类型。""" def demo
identifier_body
coro_exc_demo.py
# -*- coding: utf-8 -*- """ Created on Sun May 14 22:13:58 2017 """ #python3 """ >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc_coro.close() >>> from inspect import getgeneratorstate >...
(Exception): """异常类型。""" def demo_exc_handling(): print('-> coroutine started') while True: try: x = yield except DemoException: print('*** DemoException handled. Continuing...') else: print('-> coroutine received: {!r}'.format(x)) raise R...
DemoException
identifier_name
coro_exc_demo.py
# -*- coding: utf-8 -*- """ Created on Sun May 14 22:13:58 2017 """ #python3 """ >>> exc_coro = demo_exc_handling() >>> next(exc_coro) -> coroutine started >>> exc_coro.send(11) -> coroutine received: 11 >>> exc_coro.send(22) -> coroutine received: 22 >>> exc_coro.close() >>> from inspect import getgeneratorstate >...
x = yield except DemoException: print('*** DemoException handled. Continuing...') else: print('-> coroutine received: {!r}'.format(x)) raise RuntimeError('This line should never run.') if __name__ == "__main__": exc_coro = demo_exc_handling() next(exc_cor...
def demo_exc_handling(): print('-> coroutine started') while True: try:
random_line_split
__init__.py
#!/usr/bin/python # coding=utf-8 # region License # Findeco is dually licensed under GPLv3 or later and MPLv2.
# ################################################################################ # Copyright (c) 2012 Klaus Greff <klaus.greff@gmx.net> # This file is part of Findeco. # # Findeco 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 So...
random_line_split
navbar.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ROUTER_DIRECTIVES } from '@angular/router'; @Component({ selector: 'fc-navbar', directives: [...ROUTER_DIRECTIVES], styleUrls: ['./navbar.component.scss'], template: ` <nav class="navbar navb...
{ private userName: string; private sub: any; links: any; constructor(private route: ActivatedRoute, private router: Router) { this.links = [ { name: 'Users', link: '' }, { name: 'Posts', link:...
navbarComponent
identifier_name
navbar.component.ts
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { ROUTER_DIRECTIVES } from '@angular/router'; @Component({ selector: 'fc-navbar', directives: [...ROUTER_DIRECTIVES], styleUrls: ['./navbar.component.scss'], template: ` <nav class="navbar navb...
]; } }
link: 'albums' }
random_line_split
ext-lang-zh_CN.js
/* * Simplified Chinese translation * By DavidHu * 09 April 2007 */ Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>'; if(Ext.View){ Ext.View.prototype.emptyText = ""; } if(Ext.grid.Grid){ Ext.grid.Grid.prototype.ddText = "{0} 选择行"; } if(Ext.TabPanelItem){ Ext.Tab...
conditional_block
ext-lang-zh_CN.js
/* * Simplified Chinese translation * By DavidHu * 09 April 2007 */ Ext.UpdateManager.defaults.indicatorText = '<div class="loading-indicator">加载中...</div>'; if(Ext.View){ Ext.View.prototype.emptyText = ""; } if(Ext.grid.Grid){ Ext.grid.Grid.prototype.ddText = "{0} 选择行"; } if(Ext.TabPanelItem){ Ext.Tab...
Ext.apply(Ext.form.NumberField.prototype, { minText : "该输入项的最小值是 {0}", maxText : "该输入项的最大值是 {0}", nanText : "{0} 不是有效数值" }); } if(Ext.form.DateField){ Ext.apply(Ext.form.DateField.prototype, { disabledDaysText : "禁用", disabledDatesText : "禁用", minText : "该输入项的日期必...
if(Ext.form.NumberField){
random_line_split
protectedResource.js
var express = require("express"); var cons = require('consolidate'); var bodyParser = require('body-parser'); var __ = require('underscore'); var cors = require('cors'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); // support form-encoded bodies (for bearer tokens) app.engine('html', cons...
app.use('/', express.static('files/protectedResource')); app.use(cors()); var resource = { "name": "Protected Resource", "description": "This data has been protected by OAuth 2.0" }; var server = app.listen(9002, 'localhost', function () { var host = server.address().address; var port = server.address().port; ...
app.set('views', 'files/protectedResource'); app.set('json spaces', 4);
random_line_split
index.js
/** @license * Copyright 2015 - present The AMP HTML Authors. 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 ...
} /> </Route> </Router> ), document.getElementById('root'));
props => <AMPDocument src={'/content/' + props.params.document} />
random_line_split
platform.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} }
random_line_split
platform.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(id: string): any { return this.data[id] || null; } } export var Registry = <IRegistry>new RegistryImpl(); /** * A base class for registries that leverage the instantiation service to create instances. */ export class BaseRegistry<T> { private toBeInstantiated: IConstructorSignature0<T>[] = []; private instanc...
as
identifier_name
platform.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
else { this.toBeInstantiated.push(ctor); } } _getInstances(): T[] { return this.instances.slice(0); } _setInstances(instances: T[]): void { this.instances = instances; } }
{ this.instantiate(ctor); }
conditional_block
platform.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
_getInstances(): T[] { return this.instances.slice(0); } _setInstances(instances: T[]): void { this.instances = instances; } }
{ if (this.instantiationService) { this.instantiate(ctor); } else { this.toBeInstantiated.push(ctor); } }
identifier_body
basic_usage.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use std::path::Path; use winreg::enums::*; use winreg::RegKey; fn main() ->...
let hkcu = RegKey::predef(HKEY_CURRENT_USER); let path = Path::new("Software").join("WinregRsExample1"); let (key, disp) = hkcu.create_subkey(&path)?; match disp { REG_CREATED_NEW_KEY => println!("A new key has been created"), REG_OPENED_EXISTING_KEY => println!("An existing key has bee...
{ println!("Reading some system info..."); let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?; let pf: String = cur_ver.get_value("ProgramFilesDir")?; let dp: String = cur_ver.get_value("DevicePath")?; println!("ProgramF...
identifier_body
basic_usage.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use std::path::Path; use winreg::enums::*; use winreg::RegKey; fn main() ->...
let multi_sz_val: Vec<String> = key.get_value("TestMultiSZ")?; key.delete_value("TestMultiSZ")?; println!("TestMultiSZ = {:?}", multi_sz_val); key.set_value("TestDWORD", &1_234_567_890u32)?; let dword_val: u32 = key.get_value("TestDWORD")?; println!("TestDWORD = {}", dword_val); key.set_va...
key.delete_value("TestSZ")?; println!("TestSZ = {}", sz_val); key.set_value("TestMultiSZ", &vec!["written", "by", "Rust"])?;
random_line_split
basic_usage.rs
// Copyright 2015, Igor Shaula // Licensed under the MIT License <LICENSE or // http://opensource.org/licenses/MIT>. This file // may not be copied, modified, or distributed // except according to those terms. extern crate winreg; use std::io; use std::path::Path; use winreg::enums::*; use winreg::RegKey; fn
() -> io::Result<()> { println!("Reading some system info..."); let hklm = RegKey::predef(HKEY_LOCAL_MACHINE); let cur_ver = hklm.open_subkey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion")?; let pf: String = cur_ver.get_value("ProgramFilesDir")?; let dp: String = cur_ver.get_value("DevicePath")?; ...
main
identifier_name
button-outline-variant.js
// @flow import { css } from 'styled-components'; import { hover } from '../../utils/hover'; import { sassRgba } from '../../utils/sassRgba'; export function buttonOutlineVariant( color: string, colorHover: string = '#fff' ) { return css` color: ${color}; background-color: transparent; background-i...
&:active, &.active, .show > &.dropdown-toggle { color: ${colorHover}; background-color: ${color}; border-color: ${color}; } `; } export default buttonOutlineVariant;
background-color: transparent; }
random_line_split
button-outline-variant.js
// @flow import { css } from 'styled-components'; import { hover } from '../../utils/hover'; import { sassRgba } from '../../utils/sassRgba'; export function buttonOutlineVariant( color: string, colorHover: string = '#fff' )
color: ${color}; background-color: transparent; } &:active, &.active, .show > &.dropdown-toggle { color: ${colorHover}; background-color: ${color}; border-color: ${color}; } `; } export default buttonOutlineVariant;
{ return css` color: ${color}; background-color: transparent; background-image: none; border-color: ${color}; ${hover(css` color: ${colorHover}; background-color: ${color}; border-color: ${color}; `)}; &:focus, &.focus { box-shadow: 0 0 0 3px ${sassRgba(color,...
identifier_body
button-outline-variant.js
// @flow import { css } from 'styled-components'; import { hover } from '../../utils/hover'; import { sassRgba } from '../../utils/sassRgba'; export function
( color: string, colorHover: string = '#fff' ) { return css` color: ${color}; background-color: transparent; background-image: none; border-color: ${color}; ${hover(css` color: ${colorHover}; background-color: ${color}; border-color: ${color}; `)}; &:focus, &.fo...
buttonOutlineVariant
identifier_name
admin_practitioners.py
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ## ## ...
from lib_openmolar.admin.connect import DemoAdminConnection sc = DemoAdminConnection() sc.connect() builder = DemoGenerator(sc) print builder.demo_queries()
conditional_block
admin_practitioners.py
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ## ## ...
## practitioner 2 self.record.setValue('user_id', 2) self.record.setValue('type',"dentist") self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer") yield self.record.insert_query self.record.clearValues() ## practit...
def __init__(self, database=None): self.length = 4 self.record = InsertableRecord(database, TABLENAME) self.record.remove(self.record.indexOf("time_stamp")) def demo_queries(self): ''' return a list of queries to populate a demo database ''' ## practitioner...
identifier_body
admin_practitioners.py
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ## ## ...
self.record = InsertableRecord(database, TABLENAME) self.record.remove(self.record.indexOf("time_stamp")) def demo_queries(self): ''' return a list of queries to populate a demo database ''' ## practitioner 1 self.record.setValue('user_id', 1) self....
def __init__(self, database=None): self.length = 4
random_line_split
admin_practitioners.py
#! /usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### ## ## ## Copyright 2010-2012, Neil Wallace <neil@openmolar.com> ## ## ...
(self): ''' return a list of queries to populate a demo database ''' ## practitioner 1 self.record.setValue('user_id', 1) self.record.setValue('type',"dentist") self.record.setValue('status', "active") self.record.setValue('modified_by', "demo_installer")...
demo_queries
identifier_name
__main__.py
from sys import exit import argparse import sobol, morris, extended_fast parser = argparse.ArgumentParser(description='Perform sensitivity analysis on model output') parser.add_argument('-m', '--method', type=str, choices=['sobol', 'morris', 'fast'], required=True) parser.add_argument('-p', '--paramfile', type...
extended_fast.analyze(args.paramfile, args.model_output_file, args.column, delim = args.delimiter)
conditional_block
__main__.py
from sys import exit import argparse import sobol, morris, extended_fast parser = argparse.ArgumentParser(description='Perform sensitivity analysis on model output') parser.add_argument('-m', '--method', type=str, choices=['sobol', 'morris', 'fast'], required=True) parser.add_argument('-p', '--paramfile', type...
elif args.method == 'morris': if args.morris_model_input is not None: morris.analyze(args.paramfile, args.morris_model_input, args.model_output_file, args.column, delim = args.delimiter) else: print "Error: model input file is required for Method of Morris. Run with -h flag to see usage." ...
calc_second_order = (args.sobol_max_order == 2) sobol.analyze(args.paramfile, args.model_output_file, args.column, calc_second_order, num_resamples = args.sobol_bootstrap_resamples, delim = args.delimiter)
random_line_split
externalities.rs
<'a, 'a>, tracer: &'a mut T, vm_tracer: &'a mut V, ) -> Self { Externalities { state: state, env_info: env_info, engine: engine, vm_factory: vm_factory, depth: depth, origin_info: origin_info, substate: substate, schedule: engine.schedule(env_info), output: output, tracer: tracer, ...
(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult { // create new contract address let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address)); // prepare the params let params = ActionParams { code_address: address.clone(), address: ad...
create
identifier_name
externalities.rs
} /// Implementation of evm Externalities. pub struct Externalities<'a, T, V> where T: 'a + Tracer, V: 'a + VMTracer { state: &'a mut State, env_info: &'a EnvInfo, engine: &'a Engine, vm_factory: &'a Factory, depth: usize, origin_info: OriginInfo, substate: &'a mut Substate, schedule: Schedule, output: Outpu...
{ OriginInfo { address: params.address.clone(), origin: params.origin.clone(), gas_price: params.gas_price, value: match params.value { ActionValue::Transfer(val) | ActionValue::Apparent(val) => val } } }
identifier_body
externalities.rs
<'a, 'a>, tracer: &'a mut T, vm_tracer: &'a mut V, ) -> Self { Externalities { state: state, env_info: env_info, engine: engine, vm_factory: vm_factory, depth: depth, origin_info: origin_info, substate: substate, schedule: engine.schedule(env_info), output: output, tracer: tracer, ...
, } } fn create(&mut self, gas: &U256, value: &U256, code: &[u8]) -> ContractCreateResult { // create new contract address let address = contract_address(&self.origin_info.address, &self.state.nonce(&self.origin_info.address)); // prepare the params let params = ActionParams { code_address: address.clo...
{ trace!("ext: blockhash({}) -> null self.env_info.number={}\n", number, self.env_info.number); H256::zero() }
conditional_block
externalities.rs
<'a, 'a>, tracer: &'a mut T, vm_tracer: &'a mut V, ) -> Self { Externalities { state: state, env_info: env_info, engine: engine, vm_factory: vm_factory, depth: depth, origin_info: origin_info, substate: substate, schedule: engine.schedule(env_info), output: output, tracer: tracer, ...
true => Err(evm::Error::OutOfGas), false => Ok(*gas) } } handle_copy(copy); let mut code = vec![]; code.extend_from_slice(data); self.state.init_code(&self.origin_info.address, code); Ok(*gas - return_cost) } } } fn log(&mut self, topics: Vec<H256>, data: &[u8]) { u...
random_line_split
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
StaticEnum(..) => { cx.span_err(trait_span, "`Default` cannot be derived for enums, only structs"); // let compilation continue cx.expr_usize(trait_span, 0) } _ => cx.span_bug(trait_span, "Non-static method in `derive(Default)`") }; }
{ match *summary { Unnamed(ref fields) => { if fields.is_empty() { cx.expr_ident(trait_span, substr.type_ident) } else { let exprs = fields.iter().map(|sp| default_call(*sp)).collect(); ...
conditional_block
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
attributes: attrs, is_unsafe: false, combine_substructure: combine_substructure(Box::new(|a, b, c| { default_substructure(a, b, c) })) } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem,...
explicit_self: None, args: Vec::new(), ret_ty: Self_,
random_line_split
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
})) } ), associated_types: Vec::new(), }; trait_def.expand(cx, mitem, item, push) } fn default_substructure(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("de...
{ let inline = cx.meta_word(span, InternedString::new("inline")); let attrs = vec!(cx.attribute(span, inline)); let trait_def = TraitDef { span: span, attributes: Vec::new(), path: path_std!(cx, core::default::Default), additional_bounds: Vec::new(), generics: Lifetim...
identifier_body
default.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
(cx: &mut ExtCtxt, trait_span: Span, substr: &Substructure) -> P<Expr> { let default_ident = vec!( cx.ident_of_std("core"), cx.ident_of("default"), cx.ident_of("Default"), cx.ident_of("default") ); let default_call = |span| cx.expr_call_global(span, default_ident.clone(), Vec...
default_substructure
identifier_name
gecko.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Specified types for legacy Gecko-only properties. use crate::parser::{Parse, ParserContext}; use crate::valu...
<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result where W: fmt::Write, { // We cannot use the ToCss impl of Rect, because that would // merge items when they are equal. We want to list them all. let mut writer = SequenceWriter::new(dest, " "); let rect = &self.0; ...
to_css
identifier_name
gecko.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! Specified types for legacy Gecko-only properties. use crate::parser::{Parse, ParserContext}; use crate::valu...
/// <https://w3c.github.io/IntersectionObserver/#parse-a-root-margin> #[repr(transparent)] pub struct IntersectionObserverRootMargin(pub Rect<LengthPercentage>); impl Parse for IntersectionObserverRootMargin { fn parse<'i, 't>( context: &ParserContext, input: &mut Parser<'i, 't>, ) -> Result<Se...
///
random_line_split
wine.ts
import express = require('express'); import models = require('../models/wine'); import wineMongoDBService = require('../services/wineMongoDBService'); let router = express.Router(); let wineDBService = new wineMongoDBService.WineMongoDBService(); router .get('/', function (req, res, next) { wineDBService...
}) .put('/:id', function(req, res, next){ wineDBService.init(); }) .put('/', function(req, res, next){ wineDBService.init(); wineDBService.save(req.body, function(err, wine){ res.status(201).send(wine); }); }); module.exports = router;
res.status(200).send(wine); });
random_line_split
check_prefixes.py
#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries(): registries = [] directories = os.listdir...
return registries def check_registry(registry_path): with open(registry_path, 'r') as registry_file: original_content = registry_file.read() try: registry = WineRegistry(registry_path) except: sys.stderr.write("Error parsing {}\n".format(registry_path)) raise cont...
if path.endswith(".reg"): registries.append(os.path.join(PREFIXES_PATH, prefix, path))
conditional_block
check_prefixes.py
#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries(): registries = [] directories = os.listdir...
(registry_path): with open(registry_path, 'r') as registry_file: original_content = registry_file.read() try: registry = WineRegistry(registry_path) except: sys.stderr.write("Error parsing {}\n".format(registry_path)) raise content = registry.render() if content != o...
check_registry
identifier_name
check_prefixes.py
#!/usr/bin/python3 import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries():
def check_registry(registry_path): with open(registry_path, 'r') as registry_file: original_content = registry_file.read() try: registry = WineRegistry(registry_path) except: sys.stderr.write("Error parsing {}\n".format(registry_path)) raise content = registry.render(...
registries = [] directories = os.listdir(PREFIXES_PATH) directories.append(os.path.expanduser("~/.wine")) for prefix in directories: for path in os.listdir(os.path.join(PREFIXES_PATH, prefix)): if path.endswith(".reg"): registries.append(os.path.join(PREFIXES_PATH, prefix...
identifier_body
check_prefixes.py
import os import sys import subprocess sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from lutris.util.wineregistry import WineRegistry PREFIXES_PATH = os.path.expanduser("~/Games/wine/prefixes") def get_registries(): registries = [] directories = os.listdir(PREFIXES_PATH) ...
#!/usr/bin/python3
random_line_split
filesystem.py
# coding=utf-8 import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' ...
def isdir(self): return os.path.isdir(self.abspath) @property def exists(self): return os.path.exists(self.abspath) def find(self, pattern='*'): self.dir_required() wd = os.path.realpath(self.abspath) return [File(f) for f in glob.glob(os.path.join(wd, pattern))...
def isfile(self): return os.path.isfile(self.abspath) @property
random_line_split
filesystem.py
# coding=utf-8 import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' ...
(self, without_ext=False): return os.path.basename(self.abspath) @property def name_without_ext(self): basename = os.path.basename(self.abspath) return os.path.splitext(basename)[0] @property def ext(self): return os.path.splitext(self.abspath)[1] @property def...
name
identifier_name
filesystem.py
# coding=utf-8 import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' ...
def file_required(self): if not self.isfile: raise ValueError('Only file is supported for this operation.') @staticmethod def join(path, *paths): return os.path.join(path, *paths) @property def name(self, without_ext=False): return os.path.basename(self.abspat...
if not self.isdir: raise ValueError('Only dir is supported for this operation.')
identifier_body
filesystem.py
# coding=utf-8 import glob import os class File(object): def __init__(self, path): self.original = path self.abspath = os.path.abspath(path) def __str__(self): prefix = '' if self.isfile: prefix = 'file: ' elif self.isdir: prefix = 'dir: ' ...
def file_required(self): if not self.isfile: raise ValueError('Only file is supported for this operation.') @staticmethod def join(path, *paths): return os.path.join(path, *paths) @property def name(self, without_ext=False): return os.path.basename(self.abspat...
raise ValueError('Only dir is supported for this operation.')
conditional_block
TemplateReferenceInterface.d.ts
declare namespace Jymfony.Component.Templating { /** * Internal representation of a template. */ export class TemplateReferenceInterface { public static readonly definition: Newable<TemplateReferenceInterface>; /** * Gets the template parameters. * * @return...
set(name: string, value: any): this; /** * Gets a template parameter. * * @throws {InvalidArgumentException} if the parameter name is not supported */ get(name: string): any; /** * Returns the "logical" template name. * * T...
* Sets a template parameter. * * @throws {InvalidArgumentException} if the parameter name is not supported */
random_line_split
TemplateReferenceInterface.d.ts
declare namespace Jymfony.Component.Templating { /** * Internal representation of a template. */ export class
{ public static readonly definition: Newable<TemplateReferenceInterface>; /** * Gets the template parameters. * * @returns A set of parameters */ all(): Record<string, any>; /** * Sets a template parameter. * * @throws {In...
TemplateReferenceInterface
identifier_name
leechcoin.py
+ '&ret=1' # 1:maison, appart= '&ret=2' #+ '&f=p' # p:particuler c:pro + '&location=' + cp + '&o=' + str(page), None, headers) response = urllib2.urlopen(req) re_id = re.compile('ventes_immobilieres/(?P<id>[0-9]+)\.htm') m = re_id.finditer(response.read()) for m2 in m: ...
n = sqlite3.connect(database) c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS apparts ( '+ 'id text PRIMARY KEY, ' + 'prix int, ' + 'surface int, ' + 'cp int, ville text, ' + 'nom text, ' + 'jour int, mois int, annee int, heure text, ' + 'tel text, ' + 'desc text, ' + ...
identifier_body
leechcoin.py
, heure text, ' + 'tel text, ' + 'desc text, ' + 'siren text, ' + 'enligne int)') req = urllib2.Request( 'http://www.leboncoin.fr/ventes_immobilieres/offres/' #+ 'provence_alpes_cote_d_azur/bouches_du_rhone/' + '?' + 'ps=10&pe=14' # de 250k à 350k + '&ros=4' ...
elif mois[0] == 'f' : mois = 2 elif mois[:4] == 'mars' : mois = 3 elif mois[:4] == 'avri' : mois = 4 elif mois[:3] == 'mai' : mois = 5 elif mois[:4] == 'juin' : mois = 6 elif mois[:4] == 'juil' : mois = 7 elif mois[0] == 'a' : mois = 8 ...
= 1
conditional_block
leechcoin.py
ge, cp): conn = sqlite3.connect(database) c = conn.cursor() c.execute('CREATE TABLE IF NOT EXISTS apparts ( '+ 'id text PRIMARY KEY, ' + 'prix int, ' + 'surface int, ' + 'cp int, ville text, ' + 'nom text, ' + 'jour int, mois int, annee int, heure text, ' + 'tel text, ' + 'de...
chpage(pa
identifier_name
leechcoin.py
4]) print tmp print fdb.format(*tmp) continue try: response = urllib2.urlopen(url) except Exception as e: print 'Error on url', url print e continue rep = response.read().decode('cp1252') try: ...
pass
random_line_split
rot300.py
#7/5/2014 import Image from pytesser import * import telnetlib import base64 import StringIO def main(): tn = telnetlib.Telnet("41.231.53.40",9090) ret = tn.read_until("\n") print ret base64_str = ret.strip() decode = base64.b64decode(base64_str) buff = StringIO.StringIO() buff.write(decod...
new_img = Image.blend(img,img2,0.5) new_img = new_img.convert("RGBA") pixels = new_img.load() width, height = new_img.size for x in range(width): for y in range(height): r, g, b, a = pixels[x, y] #print r,g,b if g==255 and b==127: ...
#construct new image img = img.rotate(90) img2 = img.rotate(180)
random_line_split
rot300.py
#7/5/2014 import Image from pytesser import * import telnetlib import base64 import StringIO def
(): tn = telnetlib.Telnet("41.231.53.40",9090) ret = tn.read_until("\n") print ret base64_str = ret.strip() decode = base64.b64decode(base64_str) buff = StringIO.StringIO() buff.write(decode) buff.seek(0) img = Image.open(buff) #construct new image img = img.rotate(90) ...
main
identifier_name
rot300.py
#7/5/2014 import Image from pytesser import * import telnetlib import base64 import StringIO def main(): tn = telnetlib.Telnet("41.231.53.40",9090) ret = tn.read_until("\n") print ret base64_str = ret.strip() decode = base64.b64decode(base64_str) buff = StringIO.StringIO() buff.write(decod...
new_img.save("newnew.png") text = image_file_to_string("newnew.png")#read text from the image #new_img.show() text = text.split("\n")[1] text = "".join(text.split()) #print text, ret = tn.read_until("Answer:") print ret, print text tn.write(text + "\n") ret = tn.read_all()...
r, g, b, a = pixels[x, y] #print r,g,b if g==255 and b==127: pixels[x,y] = (255,255,255,a)
conditional_block
rot300.py
#7/5/2014 import Image from pytesser import * import telnetlib import base64 import StringIO def main():
r, g, b, a = pixels[x, y] #print r,g,b if g==255 and b==127: pixels[x,y] = (255,255,255,a) new_img.save("newnew.png") text = image_file_to_string("newnew.png")#read text from the image #new_img.show() text = text.split("\n")[1] tex...
tn = telnetlib.Telnet("41.231.53.40",9090) ret = tn.read_until("\n") print ret base64_str = ret.strip() decode = base64.b64decode(base64_str) buff = StringIO.StringIO() buff.write(decode) buff.seek(0) img = Image.open(buff) #construct new image img = img.rotate(90) img2...
identifier_body
user.js
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.rende...
}); }); } /** * Save a user. */ static save(req, res) { let data = _.pick(req.body, _.concat(User.keys, 'password')); User.save(data, req.params.id).then( result => { req.flash('success', 'Saved successfully!'); res.redirect('/admin/users'); }, err =>{ _.pull(data, 'password'); ...
{ res.render(view, {doc: {}, roles}); }
conditional_block
user.js
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.rende...
/** * Delete a user. */ static delete(req, res) { User.delete(req.params.id).then( count => { req.flash('success', 'Deleted successfully!'); res.redirect('/admin/users'); }, err => { req.flash('error', 'An error happened'); res.redirect('back'); }); } }
res.redirect('back'); }); }
random_line_split
user.js
'use strict'; const User = require('../../models/admin/user'), Role = require('../../models/admin/role'), page = require('../../util/page'), _ = require('lodash'); module.exports = class UserController { /** * Display a list of users. */ static index(req, res) { page(User, req).then(data => { res.rende...
(req, res) { let id = req.params.id, view = 'admin/user/form', roles = {'admin': 'Admin'}; Role.where({}).then(cursor => { cursor.project({'name': 1}).forEach(role => { roles[role._id] = role.name; }, err => { if (id) { User.find(id).then(user => { res.render(view, {doc: user.data, ro...
edit
identifier_name